1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.stream.Collectors;
  31 
  32 import javax.lang.model.element.ElementKind;
  33 import javax.tools.JavaFileObject;
  34 
  35 import com.sun.source.tree.CaseTree.CaseKind;
  36 import com.sun.source.tree.IdentifierTree;
  37 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  38 import com.sun.source.tree.MemberSelectTree;
  39 import com.sun.source.tree.TreeVisitor;
  40 import com.sun.source.util.SimpleTreeVisitor;
  41 import com.sun.tools.javac.code.*;
  42 import com.sun.tools.javac.code.Lint.LintCategory;
  43 import com.sun.tools.javac.code.Scope.WriteableScope;
  44 import com.sun.tools.javac.code.Source.Feature;
  45 import com.sun.tools.javac.code.Symbol.*;
  46 import com.sun.tools.javac.code.Type.*;
  47 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  50 import com.sun.tools.javac.comp.Check.CheckContext;
  51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  52 import com.sun.tools.javac.jvm.*;
  53 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  54 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  56 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  57 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  58 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  59 import com.sun.tools.javac.tree.*;
  60 import com.sun.tools.javac.tree.JCTree.*;
  61 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  62 import com.sun.tools.javac.util.*;
  63 import com.sun.tools.javac.util.DefinedBy.Api;
  64 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  65 import com.sun.tools.javac.util.JCDiagnostic.Error;
  66 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  67 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  68 import com.sun.tools.javac.util.List;
  69 
  70 import static com.sun.tools.javac.code.Flags.*;
  71 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  72 import static com.sun.tools.javac.code.Flags.BLOCK;
  73 import static com.sun.tools.javac.code.Kinds.*;
  74 import static com.sun.tools.javac.code.Kinds.Kind.*;
  75 import static com.sun.tools.javac.code.TypeTag.*;
  76 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  77 import com.sun.tools.javac.comp.Analyzer.AnalyzerMode;
  78 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  79 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  80 import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler;
  81 import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
  82 
  83 /** This is the main context-dependent analysis phase in GJC. It
  84  *  encompasses name resolution, type checking and constant folding as
  85  *  subtasks. Some subtasks involve auxiliary classes.
  86  *  @see Check
  87  *  @see Resolve
  88  *  @see ConstFold
  89  *  @see Infer
  90  *
  91  *  <p><b>This is NOT part of any supported API.
  92  *  If you write code that depends on this, you do so at your own risk.
  93  *  This code and its internal interfaces are subject to change or
  94  *  deletion without notice.</b>
  95  */
  96 public class Attr extends JCTree.Visitor {
  97     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
  98 
  99     final Names names;
 100     final Log log;
 101     final Symtab syms;
 102     final Resolve rs;
 103     final Operators operators;
 104     final Infer infer;
 105     final Analyzer analyzer;
 106     final DeferredAttr deferredAttr;
 107     final Check chk;
 108     final Flow flow;
 109     final MemberEnter memberEnter;
 110     final TypeEnter typeEnter;
 111     final TreeMaker make;
 112     final ConstFold cfolder;
 113     final Enter enter;
 114     final Target target;
 115     final Types types;
 116     final JCDiagnostic.Factory diags;
 117     final TypeAnnotations typeAnnotations;
 118     final DeferredLintHandler deferredLintHandler;
 119     final TypeEnvs typeEnvs;
 120     final Dependencies dependencies;
 121     final Annotate annotate;
 122     final ArgumentAttr argumentAttr;
 123 
 124     public static Attr instance(Context context) {
 125         Attr instance = context.get(attrKey);
 126         if (instance == null)
 127             instance = new Attr(context);
 128         return instance;
 129     }
 130 
 131     protected Attr(Context context) {
 132         context.put(attrKey, this);
 133 
 134         names = Names.instance(context);
 135         log = Log.instance(context);
 136         syms = Symtab.instance(context);
 137         rs = Resolve.instance(context);
 138         operators = Operators.instance(context);
 139         chk = Check.instance(context);
 140         flow = Flow.instance(context);
 141         memberEnter = MemberEnter.instance(context);
 142         typeEnter = TypeEnter.instance(context);
 143         make = TreeMaker.instance(context);
 144         enter = Enter.instance(context);
 145         infer = Infer.instance(context);
 146         analyzer = Analyzer.instance(context);
 147         deferredAttr = DeferredAttr.instance(context);
 148         cfolder = ConstFold.instance(context);
 149         target = Target.instance(context);
 150         types = Types.instance(context);
 151         diags = JCDiagnostic.Factory.instance(context);
 152         annotate = Annotate.instance(context);
 153         typeAnnotations = TypeAnnotations.instance(context);
 154         deferredLintHandler = DeferredLintHandler.instance(context);
 155         typeEnvs = TypeEnvs.instance(context);
 156         dependencies = Dependencies.instance(context);
 157         argumentAttr = ArgumentAttr.instance(context);
 158 
 159         Options options = Options.instance(context);
 160 
 161         Source source = Source.instance(context);
 162         allowPoly = Feature.POLY.allowedInSource(source);
 163         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 164         allowLambda = Feature.LAMBDA.allowedInSource(source);
 165         allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
 166         allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);
 167         sourceName = source.name;
 168         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 169 
 170         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 171         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 172         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 173         methodAttrInfo = new MethodAttrInfo();
 174         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 175         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 176         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 177     }
 178 
 179     /** Switch: support target-typing inference
 180      */
 181     boolean allowPoly;
 182 
 183     /** Switch: support type annotations.
 184      */
 185     boolean allowTypeAnnos;
 186 
 187     /** Switch: support lambda expressions ?
 188      */
 189     boolean allowLambda;
 190 
 191     /** Switch: support default methods ?
 192      */
 193     boolean allowDefaultMethods;
 194 
 195     /** Switch: static interface methods enabled?
 196      */
 197     boolean allowStaticInterfaceMethods;
 198 
 199     /**
 200      * Switch: warn about use of variable before declaration?
 201      * RFE: 6425594
 202      */
 203     boolean useBeforeDeclarationWarning;
 204 
 205     /**
 206      * Switch: name of source level; used for error reporting.
 207      */
 208     String sourceName;
 209 
 210     /** Check kind and type of given tree against protokind and prototype.
 211      *  If check succeeds, store type in tree and return it.
 212      *  If check fails, store errType in tree and return it.
 213      *  No checks are performed if the prototype is a method type.
 214      *  It is not necessary in this case since we know that kind and type
 215      *  are correct.
 216      *
 217      *  @param tree     The tree whose kind and type is checked
 218      *  @param found    The computed type of the tree
 219      *  @param ownkind  The computed kind of the tree
 220      *  @param resultInfo  The expected result of the tree
 221      */
 222     Type check(final JCTree tree,
 223                final Type found,
 224                final KindSelector ownkind,
 225                final ResultInfo resultInfo) {
 226         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 227         Type owntype;
 228         boolean shouldCheck = !found.hasTag(ERROR) &&
 229                 !resultInfo.pt.hasTag(METHOD) &&
 230                 !resultInfo.pt.hasTag(FORALL);
 231         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 232             log.error(tree.pos(),
 233                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 234                                             ownkind.kindNames()));
 235             owntype = types.createErrorType(found);
 236         } else if (allowPoly && inferenceContext.free(found)) {
 237             //delay the check if there are inference variables in the found type
 238             //this means we are dealing with a partially inferred poly expression
 239             owntype = shouldCheck ? resultInfo.pt : found;
 240             if (resultInfo.checkMode.installPostInferenceHook()) {
 241                 inferenceContext.addFreeTypeListener(List.of(found),
 242                         instantiatedContext -> {
 243                             ResultInfo pendingResult =
 244                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 245                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 246                         });
 247             }
 248         } else {
 249             owntype = shouldCheck ?
 250             resultInfo.check(tree, found) :
 251             found;
 252         }
 253         if (resultInfo.checkMode.updateTreeType()) {
 254             tree.type = owntype;
 255         }
 256         return owntype;
 257     }
 258 
 259     /** Is given blank final variable assignable, i.e. in a scope where it
 260      *  may be assigned to even though it is final?
 261      *  @param v      The blank final variable.
 262      *  @param env    The current environment.
 263      */
 264     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 265         Symbol owner = env.info.scope.owner;
 266            // owner refers to the innermost variable, method or
 267            // initializer block declaration at this point.
 268         return
 269             v.owner == owner
 270             ||
 271             ((owner.name == names.init ||    // i.e. we are in a constructor
 272               owner.kind == VAR ||           // i.e. we are in a variable initializer
 273               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 274              &&
 275              v.owner == owner.owner
 276              &&
 277              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 278     }
 279 
 280     /** Check that variable can be assigned to.
 281      *  @param pos    The current source code position.
 282      *  @param v      The assigned variable
 283      *  @param base   If the variable is referred to in a Select, the part
 284      *                to the left of the `.', null otherwise.
 285      *  @param env    The current environment.
 286      */
 287     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 288         if (v.name == names._this) {
 289             log.error(pos, Errors.CantAssignValToThis);
 290         } else if ((v.flags() & FINAL) != 0 &&
 291             ((v.flags() & HASINIT) != 0
 292              ||
 293              !((base == null ||
 294                TreeInfo.isThisQualifier(base)) &&
 295                isAssignableAsBlankFinal(v, env)))) {
 296             if (v.isResourceVariable()) { //TWR resource
 297                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 298             } else {
 299                 log.error(pos, Errors.CantAssignValToFinalVar(v));
 300             }
 301         }
 302     }
 303 
 304     /** Does tree represent a static reference to an identifier?
 305      *  It is assumed that tree is either a SELECT or an IDENT.
 306      *  We have to weed out selects from non-type names here.
 307      *  @param tree    The candidate tree.
 308      */
 309     boolean isStaticReference(JCTree tree) {
 310         if (tree.hasTag(SELECT)) {
 311             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 312             if (lsym == null || lsym.kind != TYP) {
 313                 return false;
 314             }
 315         }
 316         return true;
 317     }
 318 
 319     /** Is this symbol a type?
 320      */
 321     static boolean isType(Symbol sym) {
 322         return sym != null && sym.kind == TYP;
 323     }
 324 
 325     /** The current `this' symbol.
 326      *  @param env    The current environment.
 327      */
 328     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
 329         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
 330     }
 331 
 332     /** Attribute a parsed identifier.
 333      * @param tree Parsed identifier name
 334      * @param topLevel The toplevel to use
 335      */
 336     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 337         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 338         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 339                                            syms.errSymbol.name,
 340                                            null, null, null, null);
 341         localEnv.enclClass.sym = syms.errSymbol;
 342         return attribIdent(tree, localEnv);
 343     }
 344 
 345     /** Attribute a parsed identifier.
 346      * @param tree Parsed identifier name
 347      * @param env The env to use
 348      */
 349     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
 350         return tree.accept(identAttributer, env);
 351     }
 352     // where
 353         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 354         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 355             @Override @DefinedBy(Api.COMPILER_TREE)
 356             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 357                 Symbol site = visit(node.getExpression(), env);
 358                 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
 359                     return site;
 360                 Name name = (Name)node.getIdentifier();
 361                 if (site.kind == PCK) {
 362                     env.toplevel.packge = (PackageSymbol)site;
 363                     return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
 364                             KindSelector.TYP_PCK);
 365                 } else {
 366                     env.enclClass.sym = (ClassSymbol)site;
 367                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 368                 }
 369             }
 370 
 371             @Override @DefinedBy(Api.COMPILER_TREE)
 372             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 373                 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
 374             }
 375         }
 376 
 377     public Type coerce(Type etype, Type ttype) {
 378         return cfolder.coerce(etype, ttype);
 379     }
 380 
 381     public Type attribType(JCTree node, TypeSymbol sym) {
 382         Env<AttrContext> env = typeEnvs.get(sym);
 383         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 384         return attribTree(node, localEnv, unknownTypeInfo);
 385     }
 386 
 387     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
 388         // Attribute qualifying package or class.
 389         JCFieldAccess s = (JCFieldAccess)tree.qualid;
 390         return attribTree(s.selected, env,
 391                           new ResultInfo(tree.staticImport ?
 392                                          KindSelector.TYP : KindSelector.TYP_PCK,
 393                        Type.noType));
 394     }
 395 
 396     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 397         breakTree = tree;
 398         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 399         EnumSet<AnalyzerMode> analyzerModes = EnumSet.copyOf(analyzer.analyzerModes);
 400         try {
 401             analyzer.analyzerModes.clear();
 402             attribExpr(expr, env);
 403         } catch (BreakAttr b) {
 404             return b.env;
 405         } catch (AssertionError ae) {
 406             if (ae.getCause() instanceof BreakAttr) {
 407                 return ((BreakAttr)(ae.getCause())).env;
 408             } else {
 409                 throw ae;
 410             }
 411         } finally {
 412             breakTree = null;
 413             log.useSource(prev);
 414             analyzer.analyzerModes.addAll(analyzerModes);
 415         }
 416         return env;
 417     }
 418 
 419     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 420         breakTree = tree;
 421         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 422         EnumSet<AnalyzerMode> analyzerModes = EnumSet.copyOf(analyzer.analyzerModes);
 423         try {
 424             analyzer.analyzerModes.clear();
 425             attribStat(stmt, env);
 426         } catch (BreakAttr b) {
 427             return b.env;
 428         } catch (AssertionError ae) {
 429             if (ae.getCause() instanceof BreakAttr) {
 430                 return ((BreakAttr)(ae.getCause())).env;
 431             } else {
 432                 throw ae;
 433             }
 434         } finally {
 435             breakTree = null;
 436             log.useSource(prev);
 437             analyzer.analyzerModes.addAll(analyzerModes);
 438         }
 439         return env;
 440     }
 441 
 442     private JCTree breakTree = null;
 443 
 444     private static class BreakAttr extends RuntimeException {
 445         static final long serialVersionUID = -6924771130405446405L;
 446         private Env<AttrContext> env;
 447         private BreakAttr(Env<AttrContext> env) {
 448             this.env = env;
 449         }
 450     }
 451 
 452     /**
 453      * Mode controlling behavior of Attr.Check
 454      */
 455     enum CheckMode {
 456 
 457         NORMAL,
 458 
 459         /**
 460          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
 461          * that the captured var cache in {@code InferenceContext} will be used in read-only
 462          * mode when performing inference checks.
 463          */
 464         NO_TREE_UPDATE {
 465             @Override
 466             public boolean updateTreeType() {
 467                 return false;
 468             }
 469         },
 470         /**
 471          * Mode signalling that caller will manage free types in tree decorations.
 472          */
 473         NO_INFERENCE_HOOK {
 474             @Override
 475             public boolean installPostInferenceHook() {
 476                 return false;
 477             }
 478         };
 479 
 480         public boolean updateTreeType() {
 481             return true;
 482         }
 483         public boolean installPostInferenceHook() {
 484             return true;
 485         }
 486     }
 487 
 488 
 489     class ResultInfo {
 490         final KindSelector pkind;
 491         final Type pt;
 492         final CheckContext checkContext;
 493         final CheckMode checkMode;
 494 
 495         ResultInfo(KindSelector pkind, Type pt) {
 496             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
 497         }
 498 
 499         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
 500             this(pkind, pt, chk.basicHandler, checkMode);
 501         }
 502 
 503         protected ResultInfo(KindSelector pkind,
 504                              Type pt, CheckContext checkContext) {
 505             this(pkind, pt, checkContext, CheckMode.NORMAL);
 506         }
 507 
 508         protected ResultInfo(KindSelector pkind,
 509                              Type pt, CheckContext checkContext, CheckMode checkMode) {
 510             this.pkind = pkind;
 511             this.pt = pt;
 512             this.checkContext = checkContext;
 513             this.checkMode = checkMode;
 514         }
 515 
 516         /**
 517          * Should {@link Attr#attribTree} use the {@ArgumentAttr} visitor instead of this one?
 518          * @param tree The tree to be type-checked.
 519          * @return true if {@ArgumentAttr} should be used.
 520          */
 521         protected boolean needsArgumentAttr(JCTree tree) { return false; }
 522 
 523         protected Type check(final DiagnosticPosition pos, final Type found) {
 524             return chk.checkType(pos, found, pt, checkContext);
 525         }
 526 
 527         protected ResultInfo dup(Type newPt) {
 528             return new ResultInfo(pkind, newPt, checkContext, checkMode);
 529         }
 530 
 531         protected ResultInfo dup(CheckContext newContext) {
 532             return new ResultInfo(pkind, pt, newContext, checkMode);
 533         }
 534 
 535         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 536             return new ResultInfo(pkind, newPt, newContext, checkMode);
 537         }
 538 
 539         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 540             return new ResultInfo(pkind, newPt, newContext, newMode);
 541         }
 542 
 543         protected ResultInfo dup(CheckMode newMode) {
 544             return new ResultInfo(pkind, pt, checkContext, newMode);
 545         }
 546 
 547         @Override
 548         public String toString() {
 549             if (pt != null) {
 550                 return pt.toString();
 551             } else {
 552                 return "";
 553             }
 554         }
 555     }
 556 
 557     class MethodAttrInfo extends ResultInfo {
 558         public MethodAttrInfo() {
 559             this(chk.basicHandler);
 560         }
 561 
 562         public MethodAttrInfo(CheckContext checkContext) {
 563             super(KindSelector.VAL, Infer.anyPoly, checkContext);
 564         }
 565 
 566         @Override
 567         protected boolean needsArgumentAttr(JCTree tree) {
 568             return true;
 569         }
 570 
 571         protected ResultInfo dup(Type newPt) {
 572             throw new IllegalStateException();
 573         }
 574 
 575         protected ResultInfo dup(CheckContext newContext) {
 576             return new MethodAttrInfo(newContext);
 577         }
 578 
 579         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 580             throw new IllegalStateException();
 581         }
 582 
 583         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 584             throw new IllegalStateException();
 585         }
 586 
 587         protected ResultInfo dup(CheckMode newMode) {
 588             throw new IllegalStateException();
 589         }
 590     }
 591 
 592     class RecoveryInfo extends ResultInfo {
 593 
 594         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
 595             this(deferredAttrContext, Type.recoveryType);
 596         }
 597 
 598         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
 599             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
 600                 @Override
 601                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
 602                     return deferredAttrContext;
 603                 }
 604                 @Override
 605                 public boolean compatible(Type found, Type req, Warner warn) {
 606                     return true;
 607                 }
 608                 @Override
 609                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 610                     if (pt == Type.recoveryType) {
 611                         chk.basicHandler.report(pos, details);
 612                     }
 613                 }
 614             });
 615         }
 616     }
 617 
 618     final ResultInfo statInfo;
 619     final ResultInfo varAssignmentInfo;
 620     final ResultInfo methodAttrInfo;
 621     final ResultInfo unknownExprInfo;
 622     final ResultInfo unknownTypeInfo;
 623     final ResultInfo unknownTypeExprInfo;
 624     final ResultInfo recoveryInfo;
 625 
 626     Type pt() {
 627         return resultInfo.pt;
 628     }
 629 
 630     KindSelector pkind() {
 631         return resultInfo.pkind;
 632     }
 633 
 634 /* ************************************************************************
 635  * Visitor methods
 636  *************************************************************************/
 637 
 638     /** Visitor argument: the current environment.
 639      */
 640     Env<AttrContext> env;
 641 
 642     /** Visitor argument: the currently expected attribution result.
 643      */
 644     ResultInfo resultInfo;
 645 
 646     /** Visitor result: the computed type.
 647      */
 648     Type result;
 649 
 650     /** Visitor method: attribute a tree, catching any completion failure
 651      *  exceptions. Return the tree's type.
 652      *
 653      *  @param tree    The tree to be visited.
 654      *  @param env     The environment visitor argument.
 655      *  @param resultInfo   The result info visitor argument.
 656      */
 657     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
 658         Env<AttrContext> prevEnv = this.env;
 659         ResultInfo prevResult = this.resultInfo;
 660         try {
 661             this.env = env;
 662             this.resultInfo = resultInfo;
 663             if (resultInfo.needsArgumentAttr(tree)) {
 664                 result = argumentAttr.attribArg(tree, env);
 665             } else {
 666                 tree.accept(this);
 667             }
 668             if (tree == breakTree &&
 669                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
 670                 breakTreeFound(copyEnv(env));
 671             }
 672             return result;
 673         } catch (CompletionFailure ex) {
 674             tree.type = syms.errType;
 675             return chk.completionError(tree.pos(), ex);
 676         } finally {
 677             this.env = prevEnv;
 678             this.resultInfo = prevResult;
 679         }
 680     }
 681 
 682     protected void breakTreeFound(Env<AttrContext> env) {
 683         throw new BreakAttr(env);
 684     }
 685 
 686     Env<AttrContext> copyEnv(Env<AttrContext> env) {
 687         Env<AttrContext> newEnv =
 688                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
 689         if (newEnv.outer != null) {
 690             newEnv.outer = copyEnv(newEnv.outer);
 691         }
 692         return newEnv;
 693     }
 694 
 695     WriteableScope copyScope(WriteableScope sc) {
 696         WriteableScope newScope = WriteableScope.create(sc.owner);
 697         List<Symbol> elemsList = List.nil();
 698         for (Symbol sym : sc.getSymbols()) {
 699             elemsList = elemsList.prepend(sym);
 700         }
 701         for (Symbol s : elemsList) {
 702             newScope.enter(s);
 703         }
 704         return newScope;
 705     }
 706 
 707     /** Derived visitor method: attribute an expression tree.
 708      */
 709     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 710         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
 711     }
 712 
 713     /** Derived visitor method: attribute an expression tree with
 714      *  no constraints on the computed type.
 715      */
 716     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
 717         return attribTree(tree, env, unknownExprInfo);
 718     }
 719 
 720     /** Derived visitor method: attribute a type tree.
 721      */
 722     public Type attribType(JCTree tree, Env<AttrContext> env) {
 723         Type result = attribType(tree, env, Type.noType);
 724         return result;
 725     }
 726 
 727     /** Derived visitor method: attribute a type tree.
 728      */
 729     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 730         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
 731         return result;
 732     }
 733 
 734     /** Derived visitor method: attribute a statement or definition tree.
 735      */
 736     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 737         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
 738         try {
 739             return attribTree(tree, env, statInfo);
 740         } finally {
 741             analyzer.analyzeIfNeeded(tree, analyzeEnv);
 742         }
 743     }
 744 
 745     /** Attribute a list of expressions, returning a list of types.
 746      */
 747     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 748         ListBuffer<Type> ts = new ListBuffer<>();
 749         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 750             ts.append(attribExpr(l.head, env, pt));
 751         return ts.toList();
 752     }
 753 
 754     /** Attribute a list of statements, returning nothing.
 755      */
 756     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 757         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 758             attribStat(l.head, env);
 759     }
 760 
 761     /** Attribute the arguments in a method call, returning the method kind.
 762      */
 763     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
 764         KindSelector kind = initialKind;
 765         for (JCExpression arg : trees) {
 766             Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
 767             if (argtype.hasTag(DEFERRED)) {
 768                 kind = KindSelector.of(KindSelector.POLY, kind);
 769             }
 770             argtypes.append(argtype);
 771         }
 772         return kind;
 773     }
 774 
 775     /** Attribute a type argument list, returning a list of types.
 776      *  Caller is responsible for calling checkRefTypes.
 777      */
 778     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 779         ListBuffer<Type> argtypes = new ListBuffer<>();
 780         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 781             argtypes.append(attribType(l.head, env));
 782         return argtypes.toList();
 783     }
 784 
 785     /** Attribute a type argument list, returning a list of types.
 786      *  Check that all the types are references.
 787      */
 788     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 789         List<Type> types = attribAnyTypes(trees, env);
 790         return chk.checkRefTypes(trees, types);
 791     }
 792 
 793     /**
 794      * Attribute type variables (of generic classes or methods).
 795      * Compound types are attributed later in attribBounds.
 796      * @param typarams the type variables to enter
 797      * @param env      the current environment
 798      */
 799     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 800         for (JCTypeParameter tvar : typarams) {
 801             TypeVar a = (TypeVar)tvar.type;
 802             a.tsym.flags_field |= UNATTRIBUTED;
 803             a.setUpperBound(Type.noType);
 804             if (!tvar.bounds.isEmpty()) {
 805                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 806                 for (JCExpression bound : tvar.bounds.tail)
 807                     bounds = bounds.prepend(attribType(bound, env));
 808                 types.setBounds(a, bounds.reverse());
 809             } else {
 810                 // if no bounds are given, assume a single bound of
 811                 // java.lang.Object.
 812                 types.setBounds(a, List.of(syms.objectType));
 813             }
 814             a.tsym.flags_field &= ~UNATTRIBUTED;
 815         }
 816         if (checkCyclic) {
 817             for (JCTypeParameter tvar : typarams) {
 818                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 819             }
 820         }
 821     }
 822 
 823     /**
 824      * Attribute the type references in a list of annotations.
 825      */
 826     void attribAnnotationTypes(List<JCAnnotation> annotations,
 827                                Env<AttrContext> env) {
 828         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 829             JCAnnotation a = al.head;
 830             attribType(a.annotationType, env);
 831         }
 832     }
 833 
 834     /**
 835      * Attribute a "lazy constant value".
 836      *  @param env         The env for the const value
 837      *  @param variable    The initializer for the const value
 838      *  @param type        The expected type, or null
 839      *  @see VarSymbol#setLazyConstValue
 840      */
 841     public Object attribLazyConstantValue(Env<AttrContext> env,
 842                                       JCVariableDecl variable,
 843                                       Type type) {
 844 
 845         DiagnosticPosition prevLintPos
 846                 = deferredLintHandler.setPos(variable.pos());
 847 
 848         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 849         try {
 850             Type itype = attribExpr(variable.init, env, type);
 851             if (variable.isImplicitlyTyped()) {
 852                 //fixup local variable type
 853                 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype.baseType(), variable.name);
 854             }
 855             if (itype.constValue() != null) {
 856                 return coerce(itype, type).constValue();
 857             } else {
 858                 return null;
 859             }
 860         } finally {
 861             log.useSource(prevSource);
 862             deferredLintHandler.setPos(prevLintPos);
 863         }
 864     }
 865 
 866     /** Attribute type reference in an `extends' or `implements' clause.
 867      *  Supertypes of anonymous inner classes are usually already attributed.
 868      *
 869      *  @param tree              The tree making up the type reference.
 870      *  @param env               The environment current at the reference.
 871      *  @param classExpected     true if only a class is expected here.
 872      *  @param interfaceExpected true if only an interface is expected here.
 873      */
 874     Type attribBase(JCTree tree,
 875                     Env<AttrContext> env,
 876                     boolean classExpected,
 877                     boolean interfaceExpected,
 878                     boolean checkExtensible) {
 879         Type t = tree.type != null ?
 880             tree.type :
 881             attribType(tree, env);
 882         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 883     }
 884     Type checkBase(Type t,
 885                    JCTree tree,
 886                    Env<AttrContext> env,
 887                    boolean classExpected,
 888                    boolean interfaceExpected,
 889                    boolean checkExtensible) {
 890         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
 891                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
 892         if (t.tsym.isAnonymous()) {
 893             log.error(pos, Errors.CantInheritFromAnon);
 894             return types.createErrorType(t);
 895         }
 896         if (t.isErroneous())
 897             return t;
 898         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
 899             // check that type variable is already visible
 900             if (t.getUpperBound() == null) {
 901                 log.error(pos, Errors.IllegalForwardRef);
 902                 return types.createErrorType(t);
 903             }
 904         } else {
 905             t = chk.checkClassType(pos, t, checkExtensible);
 906         }
 907         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 908             log.error(pos, Errors.IntfExpectedHere);
 909             // return errType is necessary since otherwise there might
 910             // be undetected cycles which cause attribution to loop
 911             return types.createErrorType(t);
 912         } else if (checkExtensible &&
 913                    classExpected &&
 914                    (t.tsym.flags() & INTERFACE) != 0) {
 915             log.error(pos, Errors.NoIntfExpectedHere);
 916             return types.createErrorType(t);
 917         }
 918         if (checkExtensible &&
 919             ((t.tsym.flags() & FINAL) != 0)) {
 920             log.error(pos,
 921                       Errors.CantInheritFromFinal(t.tsym));
 922         }
 923         chk.checkNonCyclic(pos, t);
 924         return t;
 925     }
 926 
 927     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
 928         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
 929         id.type = env.info.scope.owner.enclClass().type;
 930         id.sym = env.info.scope.owner.enclClass();
 931         return id.type;
 932     }
 933 
 934     public void visitClassDef(JCClassDecl tree) {
 935         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
 936                 Optional.ofNullable(env.info.isSpeculative ?
 937                         argumentAttr.withLocalCacheContext() : null);
 938         try {
 939             // Local and anonymous classes have not been entered yet, so we need to
 940             // do it now.
 941             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
 942                 enter.classEnter(tree, env);
 943             } else {
 944                 // If this class declaration is part of a class level annotation,
 945                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
 946                 // order to simplify later steps and allow for sensible error
 947                 // messages.
 948                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
 949                     enter.classEnter(tree, env);
 950             }
 951 
 952             ClassSymbol c = tree.sym;
 953             if (c == null) {
 954                 // exit in case something drastic went wrong during enter.
 955                 result = null;
 956             } else {
 957                 // make sure class has been completed:
 958                 c.complete();
 959 
 960                 // If this class appears as an anonymous class
 961                 // in a superclass constructor call
 962                 // disable implicit outer instance from being passed.
 963                 // (This would be an illegal access to "this before super").
 964                 if (env.info.isSelfCall &&
 965                         env.tree.hasTag(NEWCLASS)) {
 966                     c.flags_field |= NOOUTERTHIS;
 967                 }
 968                 attribClass(tree.pos(), c);
 969                 result = tree.type = c.type;
 970             }
 971         } finally {
 972             localCacheContext.ifPresent(LocalCacheContext::leave);
 973         }
 974     }
 975 
 976     public void visitMethodDef(JCMethodDecl tree) {
 977         MethodSymbol m = tree.sym;
 978         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
 979 
 980         Lint lint = env.info.lint.augment(m);
 981         Lint prevLint = chk.setLint(lint);
 982         MethodSymbol prevMethod = chk.setMethod(m);
 983         try {
 984             deferredLintHandler.flush(tree.pos());
 985             chk.checkDeprecatedAnnotation(tree.pos(), m);
 986 
 987 
 988             // Create a new environment with local scope
 989             // for attributing the method.
 990             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
 991             localEnv.info.lint = lint;
 992 
 993             attribStats(tree.typarams, localEnv);
 994 
 995             // If we override any other methods, check that we do so properly.
 996             // JLS ???
 997             if (m.isStatic()) {
 998                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
 999             } else {
1000                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1001             }
1002             chk.checkOverride(env, tree, m);
1003 
1004             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1005                 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1006             }
1007 
1008             // Enter all type parameters into the local method scope.
1009             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1010                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1011 
1012             ClassSymbol owner = env.enclClass.sym;
1013             if ((owner.flags() & ANNOTATION) != 0 &&
1014                     (tree.params.nonEmpty() ||
1015                     tree.recvparam != null))
1016                 log.error(tree.params.nonEmpty() ?
1017                         tree.params.head.pos() :
1018                         tree.recvparam.pos(),
1019                         Errors.IntfAnnotationMembersCantHaveParams);
1020 
1021             // Attribute all value parameters.
1022             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1023                 attribStat(l.head, localEnv);
1024             }
1025 
1026             chk.checkVarargsMethodDecl(localEnv, tree);
1027 
1028             // Check that type parameters are well-formed.
1029             chk.validate(tree.typarams, localEnv);
1030 
1031             // Check that result type is well-formed.
1032             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
1033                 chk.validate(tree.restype, localEnv);
1034 
1035             // Check that receiver type is well-formed.
1036             if (tree.recvparam != null) {
1037                 // Use a new environment to check the receiver parameter.
1038                 // Otherwise I get "might not have been initialized" errors.
1039                 // Is there a better way?
1040                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1041                 attribType(tree.recvparam, newEnv);
1042                 chk.validate(tree.recvparam, newEnv);
1043             }
1044 
1045             // annotation method checks
1046             if ((owner.flags() & ANNOTATION) != 0) {
1047                 // annotation method cannot have throws clause
1048                 if (tree.thrown.nonEmpty()) {
1049                     log.error(tree.thrown.head.pos(),
1050                               Errors.ThrowsNotAllowedInIntfAnnotation);
1051                 }
1052                 // annotation method cannot declare type-parameters
1053                 if (tree.typarams.nonEmpty()) {
1054                     log.error(tree.typarams.head.pos(),
1055                               Errors.IntfAnnotationMembersCantHaveTypeParams);
1056                 }
1057                 // validate annotation method's return type (could be an annotation type)
1058                 chk.validateAnnotationType(tree.restype);
1059                 // ensure that annotation method does not clash with members of Object/Annotation
1060                 chk.validateAnnotationMethod(tree.pos(), m);
1061             }
1062 
1063             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1064                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1065 
1066             if (tree.body == null) {
1067                 // Empty bodies are only allowed for
1068                 // abstract, native, or interface methods, or for methods
1069                 // in a retrofit signature class.
1070                 if (tree.defaultValue != null) {
1071                     if ((owner.flags() & ANNOTATION) == 0)
1072                         log.error(tree.pos(),
1073                                   Errors.DefaultAllowedInIntfAnnotationMember);
1074                 }
1075                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1076                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1077             } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1078                 if ((owner.flags() & INTERFACE) != 0) {
1079                     log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1080                 } else {
1081                     log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1082                 }
1083             } else if ((tree.mods.flags & NATIVE) != 0) {
1084                 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1085             } else {
1086                 // Add an implicit super() call unless an explicit call to
1087                 // super(...) or this(...) is given
1088                 // or we are compiling class java.lang.Object.
1089                 if (tree.name == names.init && owner.type != syms.objectType) {
1090                     JCBlock body = tree.body;
1091                     if (body.stats.isEmpty() ||
1092                             !TreeInfo.isSelfCall(body.stats.head)) {
1093                         body.stats = body.stats.
1094                                 prepend(typeEnter.SuperCall(make.at(body.pos),
1095                                         List.nil(),
1096                                         List.nil(),
1097                                         false));
1098                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1099                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1100                             TreeInfo.isSuperCall(body.stats.head)) {
1101                         // enum constructors are not allowed to call super
1102                         // directly, so make sure there aren't any super calls
1103                         // in enum constructors, except in the compiler
1104                         // generated one.
1105                         log.error(tree.body.stats.head.pos(),
1106                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1107                     }
1108                 }
1109 
1110                 // Attribute all type annotations in the body
1111                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1112                 annotate.flush();
1113 
1114                 // Attribute method body.
1115                 attribStat(tree.body, localEnv);
1116             }
1117 
1118             localEnv.info.scope.leave();
1119             result = tree.type = m.type;
1120         } finally {
1121             chk.setLint(prevLint);
1122             chk.setMethod(prevMethod);
1123         }
1124     }
1125 
1126     public void visitVarDef(JCVariableDecl tree) {
1127         // Local variables have not been entered yet, so we need to do it now:
1128         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1129             if (tree.sym != null) {
1130                 // parameters have already been entered
1131                 env.info.scope.enter(tree.sym);
1132             } else {
1133                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1134                     if (tree.init == null) {
1135                         //cannot use 'var' without initializer
1136                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1137                         tree.vartype = make.Erroneous();
1138                     } else {
1139                         Fragment msg = canInferLocalVarType(tree);
1140                         if (msg != null) {
1141                             //cannot use 'var' with initializer which require an explicit target
1142                             //(e.g. lambda, method reference, array initializer).
1143                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1144                             tree.vartype = make.Erroneous();
1145                         }
1146                     }
1147                 }
1148                 try {
1149                     annotate.blockAnnotations();
1150                     memberEnter.memberEnter(tree, env);
1151                 } finally {
1152                     annotate.unblockAnnotations();
1153                 }
1154             }
1155         } else {
1156             if (tree.init != null) {
1157                 // Field initializer expression need to be entered.
1158                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1159                 annotate.flush();
1160             }
1161         }
1162 
1163         VarSymbol v = tree.sym;
1164         Lint lint = env.info.lint.augment(v);
1165         Lint prevLint = chk.setLint(lint);
1166 
1167         // Check that the variable's declared type is well-formed.
1168         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1169                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1170                 (tree.sym.flags() & PARAMETER) != 0;
1171         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1172 
1173         try {
1174             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1175             deferredLintHandler.flush(tree.pos());
1176             chk.checkDeprecatedAnnotation(tree.pos(), v);
1177 
1178             if (tree.init != null) {
1179                 if ((v.flags_field & FINAL) == 0 ||
1180                     !memberEnter.needsLazyConstValue(tree.init)) {
1181                     // Not a compile-time constant
1182                     // Attribute initializer in a new environment
1183                     // with the declared variable as owner.
1184                     // Check that initializer conforms to variable's declared type.
1185                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1186                     initEnv.info.lint = lint;
1187                     // In order to catch self-references, we set the variable's
1188                     // declaration position to maximal possible value, effectively
1189                     // marking the variable as undefined.
1190                     initEnv.info.enclVar = v;
1191                     attribExpr(tree.init, initEnv, v.type);
1192                     if (tree.isImplicitlyTyped()) {
1193                         //fixup local variable type
1194                         v.type = chk.checkLocalVarType(tree, tree.init.type.baseType(), tree.name);
1195                     }
1196                 }
1197                 if (tree.isImplicitlyTyped()) {
1198                     setSyntheticVariableType(tree, v.type);
1199                 }
1200             }
1201             result = tree.type = v.type;
1202         }
1203         finally {
1204             chk.setLint(prevLint);
1205         }
1206     }
1207 
1208     Fragment canInferLocalVarType(JCVariableDecl tree) {
1209         LocalInitScanner lis = new LocalInitScanner();
1210         lis.scan(tree.init);
1211         return lis.badInferenceMsg;
1212     }
1213 
1214     static class LocalInitScanner extends TreeScanner {
1215         Fragment badInferenceMsg = null;
1216         boolean needsTarget = true;
1217 
1218         @Override
1219         public void visitNewArray(JCNewArray tree) {
1220             if (tree.elemtype == null && needsTarget) {
1221                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1222             }
1223         }
1224 
1225         @Override
1226         public void visitLambda(JCLambda tree) {
1227             if (needsTarget) {
1228                 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1229             }
1230         }
1231 
1232         @Override
1233         public void visitTypeCast(JCTypeCast tree) {
1234             boolean prevNeedsTarget = needsTarget;
1235             try {
1236                 needsTarget = false;
1237                 super.visitTypeCast(tree);
1238             } finally {
1239                 needsTarget = prevNeedsTarget;
1240             }
1241         }
1242 
1243         @Override
1244         public void visitReference(JCMemberReference tree) {
1245             if (needsTarget) {
1246                 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1247             }
1248         }
1249 
1250         @Override
1251         public void visitNewClass(JCNewClass tree) {
1252             boolean prevNeedsTarget = needsTarget;
1253             try {
1254                 needsTarget = false;
1255                 super.visitNewClass(tree);
1256             } finally {
1257                 needsTarget = prevNeedsTarget;
1258             }
1259         }
1260 
1261         @Override
1262         public void visitApply(JCMethodInvocation tree) {
1263             boolean prevNeedsTarget = needsTarget;
1264             try {
1265                 needsTarget = false;
1266                 super.visitApply(tree);
1267             } finally {
1268                 needsTarget = prevNeedsTarget;
1269             }
1270         }
1271     }
1272 
1273     public void visitSkip(JCSkip tree) {
1274         result = null;
1275     }
1276 
1277     public void visitBlock(JCBlock tree) {
1278         if (env.info.scope.owner.kind == TYP) {
1279             // Block is a static or instance initializer;
1280             // let the owner of the environment be a freshly
1281             // created BLOCK-method.
1282             Symbol fakeOwner =
1283                 new MethodSymbol(tree.flags | BLOCK |
1284                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1285                     env.info.scope.owner);
1286             final Env<AttrContext> localEnv =
1287                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1288 
1289             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1290             // Attribute all type annotations in the block
1291             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1292             annotate.flush();
1293             attribStats(tree.stats, localEnv);
1294 
1295             {
1296                 // Store init and clinit type annotations with the ClassSymbol
1297                 // to allow output in Gen.normalizeDefs.
1298                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1299                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1300                 if ((tree.flags & STATIC) != 0) {
1301                     cs.appendClassInitTypeAttributes(tas);
1302                 } else {
1303                     cs.appendInitTypeAttributes(tas);
1304                 }
1305             }
1306         } else {
1307             // Create a new local environment with a local scope.
1308             Env<AttrContext> localEnv =
1309                 env.dup(tree, env.info.dup(env.info.scope.dup()));
1310             try {
1311                 attribStats(tree.stats, localEnv);
1312             } finally {
1313                 localEnv.info.scope.leave();
1314             }
1315         }
1316         result = null;
1317     }
1318 
1319     public void visitDoLoop(JCDoWhileLoop tree) {
1320         attribStat(tree.body, env.dup(tree));
1321         attribExpr(tree.cond, env, syms.booleanType);
1322         result = null;
1323     }
1324 
1325     public void visitWhileLoop(JCWhileLoop tree) {
1326         attribExpr(tree.cond, env, syms.booleanType);
1327         attribStat(tree.body, env.dup(tree));
1328         result = null;
1329     }
1330 
1331     public void visitForLoop(JCForLoop tree) {
1332         Env<AttrContext> loopEnv =
1333             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1334         try {
1335             attribStats(tree.init, loopEnv);
1336             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1337             loopEnv.tree = tree; // before, we were not in loop!
1338             attribStats(tree.step, loopEnv);
1339             attribStat(tree.body, loopEnv);
1340             result = null;
1341         }
1342         finally {
1343             loopEnv.info.scope.leave();
1344         }
1345     }
1346 
1347     public void visitForeachLoop(JCEnhancedForLoop tree) {
1348         Env<AttrContext> loopEnv =
1349             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1350         try {
1351             //the Formal Parameter of a for-each loop is not in the scope when
1352             //attributing the for-each expression; we mimick this by attributing
1353             //the for-each expression first (against original scope).
1354             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1355             chk.checkNonVoid(tree.pos(), exprType);
1356             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1357             if (elemtype == null) {
1358                 // or perhaps expr implements Iterable<T>?
1359                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1360                 if (base == null) {
1361                     log.error(tree.expr.pos(),
1362                               Errors.ForeachNotApplicableToType(exprType,
1363                                                                 Fragments.TypeReqArrayOrIterable));
1364                     elemtype = types.createErrorType(exprType);
1365                 } else {
1366                     List<Type> iterableParams = base.allparams();
1367                     elemtype = iterableParams.isEmpty()
1368                         ? syms.objectType
1369                         : types.wildUpperBound(iterableParams.head);
1370                 }
1371             }
1372             if (tree.var.isImplicitlyTyped()) {
1373                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1374                 setSyntheticVariableType(tree.var, inferredType);
1375             }
1376             attribStat(tree.var, loopEnv);
1377             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1378             loopEnv.tree = tree; // before, we were not in loop!
1379             attribStat(tree.body, loopEnv);
1380             result = null;
1381         }
1382         finally {
1383             loopEnv.info.scope.leave();
1384         }
1385     }
1386 
1387     public void visitLabelled(JCLabeledStatement tree) {
1388         // Check that label is not used in an enclosing statement
1389         Env<AttrContext> env1 = env;
1390         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1391             if (env1.tree.hasTag(LABELLED) &&
1392                 ((JCLabeledStatement) env1.tree).label == tree.label) {
1393                 log.error(tree.pos(),
1394                           Errors.LabelAlreadyInUse(tree.label));
1395                 break;
1396             }
1397             env1 = env1.next;
1398         }
1399 
1400         attribStat(tree.body, env.dup(tree));
1401         result = null;
1402     }
1403 
1404     public void visitSwitch(JCSwitch tree) {
1405         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1406             attribStats(c.stats, caseEnv);
1407         });
1408         result = null;
1409     }
1410 
1411     public void visitSwitchExpression(JCSwitchExpression tree) {
1412         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
1413                 PolyKind.STANDALONE : PolyKind.POLY;
1414 
1415         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1416             //this means we are returning a poly conditional from void-compatible lambda expression
1417             resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
1418             result = tree.type = types.createErrorType(resultInfo.pt);
1419             return;
1420         }
1421 
1422         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1423                 unknownExprInfo :
1424                 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
1425 
1426         ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
1427         ListBuffer<Type> caseTypes = new ListBuffer<>();
1428 
1429         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1430             caseEnv.info.yieldResult = condInfo;
1431             attribStats(c.stats, caseEnv);
1432             new TreeScanner() {
1433                 @Override
1434                 public void visitYield(JCYield brk) {
1435                     if (brk.target == tree) {
1436                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
1437                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
1438                     }
1439                     super.visitYield(brk);
1440                 }
1441 
1442                 @Override public void visitClassDef(JCClassDecl tree) {}
1443                 @Override public void visitLambda(JCLambda tree) {}
1444             }.scan(c.stats);
1445         });
1446 
1447         if (tree.cases.isEmpty()) {
1448             log.error(tree.pos(),
1449                       Errors.SwitchExpressionEmpty);
1450         }
1451 
1452         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
1453 
1454         result = tree.type = check(tree, owntype, KindSelector.VAL, resultInfo);
1455     }
1456     //where:
1457         CheckContext switchExpressionContext(CheckContext checkContext) {
1458             return new Check.NestedCheckContext(checkContext) {
1459                 //this will use enclosing check context to check compatibility of
1460                 //subexpression against target type; if we are in a method check context,
1461                 //depending on whether boxing is allowed, we could have incompatibilities
1462                 @Override
1463                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1464                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
1465                 }
1466             };
1467         }
1468 
1469     private void handleSwitch(JCTree switchTree,
1470                               JCExpression selector,
1471                               List<JCCase> cases,
1472                               BiConsumer<JCCase, Env<AttrContext>> attribCase) {
1473         Type seltype = attribExpr(selector, env);
1474 
1475         Env<AttrContext> switchEnv =
1476             env.dup(switchTree, env.info.dup(env.info.scope.dup()));
1477 
1478         try {
1479             boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1480             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
1481             if (!enumSwitch && !stringSwitch)
1482                 seltype = chk.checkType(selector.pos(), seltype, syms.intType);
1483 
1484             // Attribute all cases and
1485             // check that there are no duplicate case labels or default clauses.
1486             Set<Object> labels = new HashSet<>(); // The set of case labels.
1487             boolean hasDefault = false;      // Is there a default label?
1488             @SuppressWarnings("removal")
1489             CaseKind caseKind = null;
1490             boolean wasError = false;
1491             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
1492                 JCCase c = l.head;
1493                 if (caseKind == null) {
1494                     caseKind = c.caseKind;
1495                 } else if (caseKind != c.caseKind && !wasError) {
1496                     log.error(c.pos(),
1497                               Errors.SwitchMixingCaseTypes);
1498                     wasError = true;
1499                 }
1500                 if (c.getExpressions().nonEmpty()) {
1501                     for (JCExpression pat : c.getExpressions()) {
1502                         if (TreeInfo.isNull(pat)) {
1503                             log.error(pat.pos(),
1504                                       Errors.SwitchNullNotAllowed);
1505                         } else if (enumSwitch) {
1506                             Symbol sym = enumConstant(pat, seltype);
1507                             if (sym == null) {
1508                                 log.error(pat.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
1509                             } else if (!labels.add(sym)) {
1510                                 log.error(c.pos(), Errors.DuplicateCaseLabel);
1511                             }
1512                         } else {
1513                             Type pattype = attribExpr(pat, switchEnv, seltype);
1514                             if (!pattype.hasTag(ERROR)) {
1515                                 if (pattype.constValue() == null) {
1516                                     log.error(pat.pos(),
1517                                               (stringSwitch ? Errors.StringConstReq : Errors.ConstExprReq));
1518                                 } else if (!labels.add(pattype.constValue())) {
1519                                     log.error(c.pos(), Errors.DuplicateCaseLabel);
1520                                 }
1521                             }
1522                         }
1523                     }
1524                 } else if (hasDefault) {
1525                     log.error(c.pos(), Errors.DuplicateDefaultLabel);
1526                 } else {
1527                     hasDefault = true;
1528                 }
1529                 Env<AttrContext> caseEnv =
1530                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1531                 try {
1532                     attribCase.accept(c, caseEnv);
1533                 } finally {
1534                     caseEnv.info.scope.leave();
1535                     addVars(c.stats, switchEnv.info.scope);
1536                 }
1537             }
1538         } finally {
1539             switchEnv.info.scope.leave();
1540         }
1541     }
1542     // where
1543         /** Add any variables defined in stats to the switch scope. */
1544         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1545             for (;stats.nonEmpty(); stats = stats.tail) {
1546                 JCTree stat = stats.head;
1547                 if (stat.hasTag(VARDEF))
1548                     switchScope.enter(((JCVariableDecl) stat).sym);
1549             }
1550         }
1551     // where
1552     /** Return the selected enumeration constant symbol, or null. */
1553     private Symbol enumConstant(JCTree tree, Type enumType) {
1554         if (tree.hasTag(IDENT)) {
1555             JCIdent ident = (JCIdent)tree;
1556             Name name = ident.name;
1557             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1558                 if (sym.kind == VAR) {
1559                     Symbol s = ident.sym = sym;
1560                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1561                     ident.type = s.type;
1562                     return ((s.flags_field & Flags.ENUM) == 0)
1563                         ? null : s;
1564                 }
1565             }
1566         }
1567         return null;
1568     }
1569 
1570     public void visitSynchronized(JCSynchronized tree) {
1571         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1572         attribStat(tree.body, env);
1573         result = null;
1574     }
1575 
1576     public void visitTry(JCTry tree) {
1577         // Create a new local environment with a local
1578         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1579         try {
1580             boolean isTryWithResource = tree.resources.nonEmpty();
1581             // Create a nested environment for attributing the try block if needed
1582             Env<AttrContext> tryEnv = isTryWithResource ?
1583                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1584                 localEnv;
1585             try {
1586                 // Attribute resource declarations
1587                 for (JCTree resource : tree.resources) {
1588                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1589                         @Override
1590                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1591                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1592                         }
1593                     };
1594                     ResultInfo twrResult =
1595                         new ResultInfo(KindSelector.VAR,
1596                                        syms.autoCloseableType,
1597                                        twrContext);
1598                     if (resource.hasTag(VARDEF)) {
1599                         attribStat(resource, tryEnv);
1600                         twrResult.check(resource, resource.type);
1601 
1602                         //check that resource type cannot throw InterruptedException
1603                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
1604 
1605                         VarSymbol var = ((JCVariableDecl) resource).sym;
1606                         var.setData(ElementKind.RESOURCE_VARIABLE);
1607                     } else {
1608                         attribTree(resource, tryEnv, twrResult);
1609                     }
1610                 }
1611                 // Attribute body
1612                 attribStat(tree.body, tryEnv);
1613             } finally {
1614                 if (isTryWithResource)
1615                     tryEnv.info.scope.leave();
1616             }
1617 
1618             // Attribute catch clauses
1619             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1620                 JCCatch c = l.head;
1621                 Env<AttrContext> catchEnv =
1622                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1623                 try {
1624                     Type ctype = attribStat(c.param, catchEnv);
1625                     if (TreeInfo.isMultiCatch(c)) {
1626                         //multi-catch parameter is implicitly marked as final
1627                         c.param.sym.flags_field |= FINAL | UNION;
1628                     }
1629                     if (c.param.sym.kind == VAR) {
1630                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1631                     }
1632                     chk.checkType(c.param.vartype.pos(),
1633                                   chk.checkClassType(c.param.vartype.pos(), ctype),
1634                                   syms.throwableType);
1635                     attribStat(c.body, catchEnv);
1636                 } finally {
1637                     catchEnv.info.scope.leave();
1638                 }
1639             }
1640 
1641             // Attribute finalizer
1642             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1643             result = null;
1644         }
1645         finally {
1646             localEnv.info.scope.leave();
1647         }
1648     }
1649 
1650     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1651         if (!resource.isErroneous() &&
1652             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1653             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1654             Symbol close = syms.noSymbol;
1655             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1656             try {
1657                 close = rs.resolveQualifiedMethod(pos,
1658                         env,
1659                         types.skipTypeVars(resource, false),
1660                         names.close,
1661                         List.nil(),
1662                         List.nil());
1663             }
1664             finally {
1665                 log.popDiagnosticHandler(discardHandler);
1666             }
1667             if (close.kind == MTH &&
1668                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1669                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1670                     env.info.lint.isEnabled(LintCategory.TRY)) {
1671                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
1672             }
1673         }
1674     }
1675 
1676     public void visitConditional(JCConditional tree) {
1677         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1678 
1679         tree.polyKind = (!allowPoly ||
1680                 pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
1681                 isBooleanOrNumeric(env, tree)) ?
1682                 PolyKind.STANDALONE : PolyKind.POLY;
1683 
1684         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1685             //this means we are returning a poly conditional from void-compatible lambda expression
1686             resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
1687             result = tree.type = types.createErrorType(resultInfo.pt);
1688             return;
1689         }
1690 
1691         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1692                 unknownExprInfo :
1693                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
1694 
1695         Type truetype = attribTree(tree.truepart, env, condInfo);
1696         Type falsetype = attribTree(tree.falsepart, env, condInfo);
1697 
1698         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
1699                 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
1700                          List.of(truetype, falsetype)) : pt();
1701         if (condtype.constValue() != null &&
1702                 truetype.constValue() != null &&
1703                 falsetype.constValue() != null &&
1704                 !owntype.hasTag(NONE)) {
1705             //constant folding
1706             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1707         }
1708         result = check(tree, owntype, KindSelector.VAL, resultInfo);
1709     }
1710     //where
1711         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1712             switch (tree.getTag()) {
1713                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1714                               ((JCLiteral)tree).typetag == BOOLEAN ||
1715                               ((JCLiteral)tree).typetag == BOT;
1716                 case LAMBDA: case REFERENCE: return false;
1717                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1718                 case CONDEXPR:
1719                     JCConditional condTree = (JCConditional)tree;
1720                     return isBooleanOrNumeric(env, condTree.truepart) &&
1721                             isBooleanOrNumeric(env, condTree.falsepart);
1722                 case APPLY:
1723                     JCMethodInvocation speculativeMethodTree =
1724                             (JCMethodInvocation)deferredAttr.attribSpeculative(
1725                                     tree, env, unknownExprInfo,
1726                                     argumentAttr.withLocalCacheContext());
1727                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
1728                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
1729                             env.enclClass.type :
1730                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
1731                     Type owntype = types.memberType(receiverType, msym).getReturnType();
1732                     return primitiveOrBoxed(owntype);
1733                 case NEWCLASS:
1734                     JCExpression className =
1735                             removeClassParams.translate(((JCNewClass)tree).clazz);
1736                     JCExpression speculativeNewClassTree =
1737                             (JCExpression)deferredAttr.attribSpeculative(
1738                                     className, env, unknownTypeInfo,
1739                                     argumentAttr.withLocalCacheContext());
1740                     return primitiveOrBoxed(speculativeNewClassTree.type);
1741                 default:
1742                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
1743                             argumentAttr.withLocalCacheContext()).type;
1744                     return primitiveOrBoxed(speculativeType);
1745             }
1746         }
1747         //where
1748             boolean primitiveOrBoxed(Type t) {
1749                 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
1750             }
1751 
1752             TreeTranslator removeClassParams = new TreeTranslator() {
1753                 @Override
1754                 public void visitTypeApply(JCTypeApply tree) {
1755                     result = translate(tree.clazz);
1756                 }
1757             };
1758 
1759         CheckContext conditionalContext(CheckContext checkContext) {
1760             return new Check.NestedCheckContext(checkContext) {
1761                 //this will use enclosing check context to check compatibility of
1762                 //subexpression against target type; if we are in a method check context,
1763                 //depending on whether boxing is allowed, we could have incompatibilities
1764                 @Override
1765                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1766                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
1767                 }
1768             };
1769         }
1770 
1771         /** Compute the type of a conditional expression, after
1772          *  checking that it exists.  See JLS 15.25. Does not take into
1773          *  account the special case where condition and both arms
1774          *  are constants.
1775          *
1776          *  @param pos      The source position to be used for error
1777          *                  diagnostics.
1778          *  @param thentype The type of the expression's then-part.
1779          *  @param elsetype The type of the expression's else-part.
1780          */
1781         Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
1782             if (condTypes.isEmpty()) {
1783                 return syms.objectType; //TODO: how to handle?
1784             }
1785             Type first = condTypes.head;
1786             // If same type, that is the result
1787             if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
1788                 return first.baseType();
1789 
1790             List<Type> unboxedTypes = condTypes.stream()
1791                                                .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
1792                                                .collect(List.collector());
1793 
1794             // Otherwise, if both arms can be converted to a numeric
1795             // type, return the least numeric type that fits both arms
1796             // (i.e. return larger of the two, or return int if one
1797             // arm is short, the other is char).
1798             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
1799                 // If one arm has an integer subrange type (i.e., byte,
1800                 // short, or char), and the other is an integer constant
1801                 // that fits into the subrange, return the subrange type.
1802                 for (Type type : unboxedTypes) {
1803                     if (!type.getTag().isStrictSubRangeOf(INT)) {
1804                         continue;
1805                     }
1806                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
1807                         return type.baseType();
1808                 }
1809 
1810                 for (TypeTag tag : primitiveTags) {
1811                     Type candidate = syms.typeOfTag[tag.ordinal()];
1812                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
1813                         return candidate;
1814                     }
1815                 }
1816             }
1817 
1818             // Those were all the cases that could result in a primitive
1819             condTypes = condTypes.stream()
1820                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
1821                                  .collect(List.collector());
1822 
1823             for (Type type : condTypes) {
1824                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
1825                     return type.baseType();
1826             }
1827 
1828             Iterator<DiagnosticPosition> posIt = positions.iterator();
1829 
1830             condTypes = condTypes.stream()
1831                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
1832                                  .collect(List.collector());
1833 
1834             // both are known to be reference types.  The result is
1835             // lub(thentype,elsetype). This cannot fail, as it will
1836             // always be possible to infer "Object" if nothing better.
1837             return types.lub(condTypes.stream().map(t -> t.baseType()).collect(List.collector()));
1838         }
1839 
1840     final static TypeTag[] primitiveTags = new TypeTag[]{
1841         BYTE,
1842         CHAR,
1843         SHORT,
1844         INT,
1845         LONG,
1846         FLOAT,
1847         DOUBLE,
1848         BOOLEAN,
1849     };
1850 
1851     public void visitIf(JCIf tree) {
1852         attribExpr(tree.cond, env, syms.booleanType);
1853         attribStat(tree.thenpart, env);
1854         if (tree.elsepart != null)
1855             attribStat(tree.elsepart, env);
1856         chk.checkEmptyIf(tree);
1857         result = null;
1858     }
1859 
1860     public void visitExec(JCExpressionStatement tree) {
1861         //a fresh environment is required for 292 inference to work properly ---
1862         //see Infer.instantiatePolymorphicSignatureInstance()
1863         Env<AttrContext> localEnv = env.dup(tree);
1864         attribExpr(tree.expr, localEnv);
1865         result = null;
1866     }
1867 
1868     public void visitBreak(JCBreak tree) {
1869         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1870         result = null;
1871     }
1872 
1873     public void visitYield(JCYield tree) {
1874         if (env.info.yieldResult != null) {
1875             attribTree(tree.value, env, env.info.yieldResult);
1876             tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
1877         } else {
1878             log.error(tree.pos(), tree.value.hasTag(PARENS)
1879                     ? Errors.NoSwitchExpressionQualify
1880                     : Errors.NoSwitchExpression);
1881             attribTree(tree.value, env, unknownExprInfo);
1882         }
1883         result = null;
1884     }
1885 
1886     public void visitContinue(JCContinue tree) {
1887         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1888         result = null;
1889     }
1890     //where
1891         /** Return the target of a break, continue or yield statement,
1892          *  if it exists, report an error if not.
1893          *  Note: The target of a labelled break or continue is the
1894          *  (non-labelled) statement tree referred to by the label,
1895          *  not the tree representing the labelled statement itself.
1896          *
1897          *  @param pos     The position to be used for error diagnostics
1898          *  @param tag     The tag of the jump statement. This is either
1899          *                 Tree.BREAK or Tree.CONTINUE.
1900          *  @param label   The label of the jump statement, or null if no
1901          *                 label is given.
1902          *  @param env     The environment current at the jump statement.
1903          */
1904         private JCTree findJumpTarget(DiagnosticPosition pos,
1905                                                    JCTree.Tag tag,
1906                                                    Name label,
1907                                                    Env<AttrContext> env) {
1908             Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
1909 
1910             if (jumpTarget.snd != null) {
1911                 log.error(pos, jumpTarget.snd);
1912             }
1913 
1914             return jumpTarget.fst;
1915         }
1916         /** Return the target of a break or continue statement, if it exists,
1917          *  report an error if not.
1918          *  Note: The target of a labelled break or continue is the
1919          *  (non-labelled) statement tree referred to by the label,
1920          *  not the tree representing the labelled statement itself.
1921          *
1922          *  @param tag     The tag of the jump statement. This is either
1923          *                 Tree.BREAK or Tree.CONTINUE.
1924          *  @param label   The label of the jump statement, or null if no
1925          *                 label is given.
1926          *  @param env     The environment current at the jump statement.
1927          */
1928         private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
1929                                                                        Name label,
1930                                                                        Env<AttrContext> env) {
1931             // Search environments outwards from the point of jump.
1932             Env<AttrContext> env1 = env;
1933             JCDiagnostic.Error pendingError = null;
1934             LOOP:
1935             while (env1 != null) {
1936                 switch (env1.tree.getTag()) {
1937                     case LABELLED:
1938                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1939                         if (label == labelled.label) {
1940                             // If jump is a continue, check that target is a loop.
1941                             if (tag == CONTINUE) {
1942                                 if (!labelled.body.hasTag(DOLOOP) &&
1943                                         !labelled.body.hasTag(WHILELOOP) &&
1944                                         !labelled.body.hasTag(FORLOOP) &&
1945                                         !labelled.body.hasTag(FOREACHLOOP)) {
1946                                     pendingError = Errors.NotLoopLabel(label);
1947                                 }
1948                                 // Found labelled statement target, now go inwards
1949                                 // to next non-labelled tree.
1950                                 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
1951                             } else {
1952                                 return Pair.of(labelled, pendingError);
1953                             }
1954                         }
1955                         break;
1956                     case DOLOOP:
1957                     case WHILELOOP:
1958                     case FORLOOP:
1959                     case FOREACHLOOP:
1960                         if (label == null) return Pair.of(env1.tree, pendingError);
1961                         break;
1962                     case SWITCH:
1963                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
1964                         break;
1965                     case SWITCH_EXPRESSION:
1966                         if (tag == YIELD) {
1967                             return Pair.of(env1.tree, null);
1968                         } else if (tag == BREAK) {
1969                             pendingError = Errors.BreakOutsideSwitchExpression;
1970                         } else {
1971                             pendingError = Errors.ContinueOutsideSwitchExpression;
1972                         }
1973                         break;
1974                     case LAMBDA:
1975                     case METHODDEF:
1976                     case CLASSDEF:
1977                         break LOOP;
1978                     default:
1979                 }
1980                 env1 = env1.next;
1981             }
1982             if (label != null)
1983                 return Pair.of(null, Errors.UndefLabel(label));
1984             else if (pendingError != null)
1985                 return Pair.of(null, pendingError);
1986             else if (tag == CONTINUE)
1987                 return Pair.of(null, Errors.ContOutsideLoop);
1988             else
1989                 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
1990         }
1991 
1992     public void visitReturn(JCReturn tree) {
1993         // Check that there is an enclosing method which is
1994         // nested within than the enclosing class.
1995         if (env.info.returnResult == null) {
1996             log.error(tree.pos(), Errors.RetOutsideMeth);
1997         } else if (env.info.yieldResult != null) {
1998             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
1999         } else {
2000             // Attribute return expression, if it exists, and check that
2001             // it conforms to result type of enclosing method.
2002             if (tree.expr != null) {
2003                 if (env.info.returnResult.pt.hasTag(VOID)) {
2004                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2005                               diags.fragment(Fragments.UnexpectedRetVal));
2006                 }
2007                 attribTree(tree.expr, env, env.info.returnResult);
2008             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2009                     !env.info.returnResult.pt.hasTag(NONE)) {
2010                 env.info.returnResult.checkContext.report(tree.pos(),
2011                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2012             }
2013         }
2014         result = null;
2015     }
2016 
2017     public void visitThrow(JCThrow tree) {
2018         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
2019         if (allowPoly) {
2020             chk.checkType(tree, owntype, syms.throwableType);
2021         }
2022         result = null;
2023     }
2024 
2025     public void visitAssert(JCAssert tree) {
2026         attribExpr(tree.cond, env, syms.booleanType);
2027         if (tree.detail != null) {
2028             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2029         }
2030         result = null;
2031     }
2032 
2033      /** Visitor method for method invocations.
2034      *  NOTE: The method part of an application will have in its type field
2035      *        the return type of the method, not the method's type itself!
2036      */
2037     public void visitApply(JCMethodInvocation tree) {
2038         // The local environment of a method application is
2039         // a new environment nested in the current one.
2040         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2041 
2042         // The types of the actual method arguments.
2043         List<Type> argtypes;
2044 
2045         // The types of the actual method type arguments.
2046         List<Type> typeargtypes = null;
2047 
2048         Name methName = TreeInfo.name(tree.meth);
2049 
2050         boolean isConstructorCall =
2051             methName == names._this || methName == names._super;
2052 
2053         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2054         if (isConstructorCall) {
2055             // We are seeing a ...this(...) or ...super(...) call.
2056             // Check that this is the first statement in a constructor.
2057             if (checkFirstConstructorStat(tree, env)) {
2058 
2059                 // Record the fact
2060                 // that this is a constructor call (using isSelfCall).
2061                 localEnv.info.isSelfCall = true;
2062 
2063                 // Attribute arguments, yielding list of argument types.
2064                 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2065                 argtypes = argtypesBuf.toList();
2066                 typeargtypes = attribTypes(tree.typeargs, localEnv);
2067 
2068                 // Variable `site' points to the class in which the called
2069                 // constructor is defined.
2070                 Type site = env.enclClass.sym.type;
2071                 if (methName == names._super) {
2072                     if (site == syms.objectType) {
2073                         log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2074                         site = types.createErrorType(syms.objectType);
2075                     } else {
2076                         site = types.supertype(site);
2077                     }
2078                 }
2079 
2080                 if (site.hasTag(CLASS)) {
2081                     Type encl = site.getEnclosingType();
2082                     while (encl != null && encl.hasTag(TYPEVAR))
2083                         encl = encl.getUpperBound();
2084                     if (encl.hasTag(CLASS)) {
2085                         // we are calling a nested class
2086 
2087                         if (tree.meth.hasTag(SELECT)) {
2088                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2089 
2090                             // We are seeing a prefixed call, of the form
2091                             //     <expr>.super(...).
2092                             // Check that the prefix expression conforms
2093                             // to the outer instance type of the class.
2094                             chk.checkRefType(qualifier.pos(),
2095                                              attribExpr(qualifier, localEnv,
2096                                                         encl));
2097                         } else if (methName == names._super) {
2098                             // qualifier omitted; check for existence
2099                             // of an appropriate implicit qualifier.
2100                             rs.resolveImplicitThis(tree.meth.pos(),
2101                                                    localEnv, site, true);
2102                         }
2103                     } else if (tree.meth.hasTag(SELECT)) {
2104                         log.error(tree.meth.pos(),
2105                                   Errors.IllegalQualNotIcls(site.tsym));
2106                     }
2107 
2108                     // if we're calling a java.lang.Enum constructor,
2109                     // prefix the implicit String and int parameters
2110                     if (site.tsym == syms.enumSym)
2111                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
2112 
2113                     // Resolve the called constructor under the assumption
2114                     // that we are referring to a superclass instance of the
2115                     // current instance (JLS ???).
2116                     boolean selectSuperPrev = localEnv.info.selectSuper;
2117                     localEnv.info.selectSuper = true;
2118                     localEnv.info.pendingResolutionPhase = null;
2119                     Symbol sym = rs.resolveConstructor(
2120                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
2121                     localEnv.info.selectSuper = selectSuperPrev;
2122 
2123                     // Set method symbol to resolved constructor...
2124                     TreeInfo.setSymbol(tree.meth, sym);
2125 
2126                     // ...and check that it is legal in the current context.
2127                     // (this will also set the tree's type)
2128                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2129                     checkId(tree.meth, site, sym, localEnv,
2130                             new ResultInfo(kind, mpt));
2131                 }
2132                 // Otherwise, `site' is an error type and we do nothing
2133             }
2134             result = tree.type = syms.voidType;
2135         } else {
2136             // Otherwise, we are seeing a regular method call.
2137             // Attribute the arguments, yielding list of argument types, ...
2138             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2139             argtypes = argtypesBuf.toList();
2140             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
2141 
2142             // ... and attribute the method using as a prototype a methodtype
2143             // whose formal argument types is exactly the list of actual
2144             // arguments (this will also set the method symbol).
2145             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2146             localEnv.info.pendingResolutionPhase = null;
2147             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2148 
2149             // Compute the result type.
2150             Type restype = mtype.getReturnType();
2151             if (restype.hasTag(WILDCARD))
2152                 throw new AssertionError(mtype);
2153 
2154             Type qualifier = (tree.meth.hasTag(SELECT))
2155                     ? ((JCFieldAccess) tree.meth).selected.type
2156                     : env.enclClass.sym.type;
2157             Symbol msym = TreeInfo.symbol(tree.meth);
2158             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2159 
2160             chk.checkRefTypes(tree.typeargs, typeargtypes);
2161 
2162             // Check that value of resulting type is admissible in the
2163             // current context.  Also, capture the return type
2164             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2165             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2166         }
2167         chk.validate(tree.typeargs, localEnv);
2168     }
2169     //where
2170         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2171             if (msym != null &&
2172                     msym.owner == syms.objectType.tsym &&
2173                     methodName == names.getClass &&
2174                     argtypes.isEmpty()) {
2175                 // as a special case, x.getClass() has type Class<? extends |X|>
2176                 return new ClassType(restype.getEnclosingType(),
2177                         List.of(new WildcardType(types.erasure(qualifierType),
2178                                 BoundKind.EXTENDS,
2179                                 syms.boundClass)),
2180                         restype.tsym,
2181                         restype.getMetadata());
2182             } else if (msym != null &&
2183                     msym.owner == syms.arrayClass &&
2184                     methodName == names.clone &&
2185                     types.isArray(qualifierType)) {
2186                 // as a special case, array.clone() has a result that is
2187                 // the same as static type of the array being cloned
2188                 return qualifierType;
2189             } else {
2190                 return restype;
2191             }
2192         }
2193 
2194         /** Check that given application node appears as first statement
2195          *  in a constructor call.
2196          *  @param tree   The application node
2197          *  @param env    The environment current at the application.
2198          */
2199         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
2200             JCMethodDecl enclMethod = env.enclMethod;
2201             if (enclMethod != null && enclMethod.name == names.init) {
2202                 JCBlock body = enclMethod.body;
2203                 if (body.stats.head.hasTag(EXEC) &&
2204                     ((JCExpressionStatement) body.stats.head).expr == tree)
2205                     return true;
2206             }
2207             log.error(tree.pos(),
2208                       Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2209             return false;
2210         }
2211 
2212         /** Obtain a method type with given argument types.
2213          */
2214         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2215             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2216             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2217         }
2218 
2219     public void visitNewClass(final JCNewClass tree) {
2220         Type owntype = types.createErrorType(tree.type);
2221 
2222         // The local environment of a class creation is
2223         // a new environment nested in the current one.
2224         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2225 
2226         // The anonymous inner class definition of the new expression,
2227         // if one is defined by it.
2228         JCClassDecl cdef = tree.def;
2229 
2230         // If enclosing class is given, attribute it, and
2231         // complete class name to be fully qualified
2232         JCExpression clazz = tree.clazz; // Class field following new
2233         JCExpression clazzid;            // Identifier in class field
2234         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
2235         annoclazzid = null;
2236 
2237         if (clazz.hasTag(TYPEAPPLY)) {
2238             clazzid = ((JCTypeApply) clazz).clazz;
2239             if (clazzid.hasTag(ANNOTATED_TYPE)) {
2240                 annoclazzid = (JCAnnotatedType) clazzid;
2241                 clazzid = annoclazzid.underlyingType;
2242             }
2243         } else {
2244             if (clazz.hasTag(ANNOTATED_TYPE)) {
2245                 annoclazzid = (JCAnnotatedType) clazz;
2246                 clazzid = annoclazzid.underlyingType;
2247             } else {
2248                 clazzid = clazz;
2249             }
2250         }
2251 
2252         JCExpression clazzid1 = clazzid; // The same in fully qualified form
2253 
2254         if (tree.encl != null) {
2255             // We are seeing a qualified new, of the form
2256             //    <expr>.new C <...> (...) ...
2257             // In this case, we let clazz stand for the name of the
2258             // allocated class C prefixed with the type of the qualifier
2259             // expression, so that we can
2260             // resolve it with standard techniques later. I.e., if
2261             // <expr> has type T, then <expr>.new C <...> (...)
2262             // yields a clazz T.C.
2263             Type encltype = chk.checkRefType(tree.encl.pos(),
2264                                              attribExpr(tree.encl, env));
2265             // TODO 308: in <expr>.new C, do we also want to add the type annotations
2266             // from expr to the combined type, or not? Yes, do this.
2267             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
2268                                                  ((JCIdent) clazzid).name);
2269 
2270             EndPosTable endPosTable = this.env.toplevel.endPositions;
2271             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
2272             if (clazz.hasTag(ANNOTATED_TYPE)) {
2273                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
2274                 List<JCAnnotation> annos = annoType.annotations;
2275 
2276                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
2277                     clazzid1 = make.at(tree.pos).
2278                         TypeApply(clazzid1,
2279                                   ((JCTypeApply) clazz).arguments);
2280                 }
2281 
2282                 clazzid1 = make.at(tree.pos).
2283                     AnnotatedType(annos, clazzid1);
2284             } else if (clazz.hasTag(TYPEAPPLY)) {
2285                 clazzid1 = make.at(tree.pos).
2286                     TypeApply(clazzid1,
2287                               ((JCTypeApply) clazz).arguments);
2288             }
2289 
2290             clazz = clazzid1;
2291         }
2292 
2293         // Attribute clazz expression and store
2294         // symbol + type back into the attributed tree.
2295         Type clazztype;
2296 
2297         try {
2298             env.info.isNewClass = true;
2299             clazztype = TreeInfo.isEnumInit(env.tree) ?
2300                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2301                 attribType(clazz, env);
2302         } finally {
2303             env.info.isNewClass = false;
2304         }
2305 
2306         clazztype = chk.checkDiamond(tree, clazztype);
2307         chk.validate(clazz, localEnv);
2308         if (tree.encl != null) {
2309             // We have to work in this case to store
2310             // symbol + type back into the attributed tree.
2311             tree.clazz.type = clazztype;
2312             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2313             clazzid.type = ((JCIdent) clazzid).sym.type;
2314             if (annoclazzid != null) {
2315                 annoclazzid.type = clazzid.type;
2316             }
2317             if (!clazztype.isErroneous()) {
2318                 if (cdef != null && clazztype.tsym.isInterface()) {
2319                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2320                 } else if (clazztype.tsym.isStatic()) {
2321                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
2322                 }
2323             }
2324         } else if (!clazztype.tsym.isInterface() &&
2325                    clazztype.getEnclosingType().hasTag(CLASS)) {
2326             // Check for the existence of an apropos outer instance
2327             rs.resolveImplicitThis(tree.pos(), env, clazztype);
2328         }
2329 
2330         // Attribute constructor arguments.
2331         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2332         final KindSelector pkind =
2333             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2334         List<Type> argtypes = argtypesBuf.toList();
2335         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2336 
2337         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2338             // Enums may not be instantiated except implicitly
2339             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2340                 (!env.tree.hasTag(VARDEF) ||
2341                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2342                  ((JCVariableDecl) env.tree).init != tree))
2343                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2344 
2345             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2346                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2347             boolean skipNonDiamondPath = false;
2348             // Check that class is not abstract
2349             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2350                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2351                 log.error(tree.pos(),
2352                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2353                 skipNonDiamondPath = true;
2354             } else if (cdef != null && clazztype.tsym.isInterface()) {
2355                 // Check that no constructor arguments are given to
2356                 // anonymous classes implementing an interface
2357                 if (!argtypes.isEmpty())
2358                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2359 
2360                 if (!typeargtypes.isEmpty())
2361                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2362 
2363                 // Error recovery: pretend no arguments were supplied.
2364                 argtypes = List.nil();
2365                 typeargtypes = List.nil();
2366                 skipNonDiamondPath = true;
2367             }
2368             if (TreeInfo.isDiamond(tree)) {
2369                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2370                             clazztype.tsym.type.getTypeArguments(),
2371                                                clazztype.tsym,
2372                                                clazztype.getMetadata());
2373 
2374                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2375                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2376                 diamondEnv.info.pendingResolutionPhase = null;
2377 
2378                 //if the type of the instance creation expression is a class type
2379                 //apply method resolution inference (JLS 15.12.2.7). The return type
2380                 //of the resolved constructor will be a partially instantiated type
2381                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2382                             diamondEnv,
2383                             site,
2384                             argtypes,
2385                             typeargtypes);
2386                 tree.constructor = constructor.baseSymbol();
2387 
2388                 final TypeSymbol csym = clazztype.tsym;
2389                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2390                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2391                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2392                 constructorType = checkId(tree, site,
2393                         constructor,
2394                         diamondEnv,
2395                         diamondResult);
2396 
2397                 tree.clazz.type = types.createErrorType(clazztype);
2398                 if (!constructorType.isErroneous()) {
2399                     tree.clazz.type = clazz.type = constructorType.getReturnType();
2400                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2401                 }
2402                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2403             }
2404 
2405             // Resolve the called constructor under the assumption
2406             // that we are referring to a superclass instance of the
2407             // current instance (JLS ???).
2408             else if (!skipNonDiamondPath) {
2409                 //the following code alters some of the fields in the current
2410                 //AttrContext - hence, the current context must be dup'ed in
2411                 //order to avoid downstream failures
2412                 Env<AttrContext> rsEnv = localEnv.dup(tree);
2413                 rsEnv.info.selectSuper = cdef != null;
2414                 rsEnv.info.pendingResolutionPhase = null;
2415                 tree.constructor = rs.resolveConstructor(
2416                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2417                 if (cdef == null) { //do not check twice!
2418                     tree.constructorType = checkId(tree,
2419                             clazztype,
2420                             tree.constructor,
2421                             rsEnv,
2422                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2423                     if (rsEnv.info.lastResolveVarargs())
2424                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2425                 }
2426             }
2427 
2428             if (cdef != null) {
2429                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2430                 return;
2431             }
2432 
2433             if (tree.constructor != null && tree.constructor.kind == MTH)
2434                 owntype = clazztype;
2435         }
2436         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2437         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2438         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2439             //we need to wait for inference to finish and then replace inference vars in the constructor type
2440             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2441                     instantiatedContext -> {
2442                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2443                     });
2444         }
2445         chk.validate(tree.typeargs, localEnv);
2446     }
2447 
2448         // where
2449         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2450                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
2451                                                    List<Type> argtypes, List<Type> typeargtypes,
2452                                                    KindSelector pkind) {
2453             // We are seeing an anonymous class instance creation.
2454             // In this case, the class instance creation
2455             // expression
2456             //
2457             //    E.new <typeargs1>C<typargs2>(args) { ... }
2458             //
2459             // is represented internally as
2460             //
2461             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2462             //
2463             // This expression is then *transformed* as follows:
2464             //
2465             // (1) add an extends or implements clause
2466             // (2) add a constructor.
2467             //
2468             // For instance, if C is a class, and ET is the type of E,
2469             // the expression
2470             //
2471             //    E.new <typeargs1>C<typargs2>(args) { ... }
2472             //
2473             // is translated to (where X is a fresh name and typarams is the
2474             // parameter list of the super constructor):
2475             //
2476             //   new <typeargs1>X(<*nullchk*>E, args) where
2477             //     X extends C<typargs2> {
2478             //       <typarams> X(ET e, args) {
2479             //         e.<typeargs1>super(args)
2480             //       }
2481             //       ...
2482             //     }
2483             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2484             final boolean isDiamond = TreeInfo.isDiamond(tree);
2485             if (isDiamond
2486                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2487                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2488                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2489                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2490                         instantiatedContext -> {
2491                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2492                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
2493                             ResultInfo prevResult = this.resultInfo;
2494                             try {
2495                                 this.resultInfo = resultInfoForClassDefinition;
2496                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
2497                                                             localEnv, argtypes, typeargtypes, pkind);
2498                             } finally {
2499                                 this.resultInfo = prevResult;
2500                             }
2501                         });
2502             } else {
2503                 if (isDiamond && clazztype.hasTag(CLASS)) {
2504                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2505                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2506                         // One or more types inferred in the previous steps is non-denotable.
2507                         Fragment fragment = Diamond(clazztype.tsym);
2508                         log.error(tree.clazz.pos(),
2509                                 Errors.CantApplyDiamond1(
2510                                         fragment,
2511                                         invalidDiamondArgs.size() > 1 ?
2512                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2513                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2514                     }
2515                     // For <>(){}, inferred types must also be accessible.
2516                     for (Type t : clazztype.getTypeArguments()) {
2517                         rs.checkAccessibleType(env, t);
2518                     }
2519                 }
2520 
2521                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2522                 // false for isInterface call even when the original type is an interface.
2523                 boolean implementing = clazztype.tsym.isInterface() ||
2524                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2525                         clazztype.getOriginalType().tsym.isInterface();
2526 
2527                 if (implementing) {
2528                     cdef.implementing = List.of(clazz);
2529                 } else {
2530                     cdef.extending = clazz;
2531                 }
2532 
2533                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2534                     isSerializable(clazztype)) {
2535                     localEnv.info.isSerializable = true;
2536                 }
2537 
2538                 attribStat(cdef, localEnv);
2539 
2540                 List<Type> finalargtypes;
2541                 // If an outer instance is given,
2542                 // prefix it to the constructor arguments
2543                 // and delete it from the new expression
2544                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2545                     finalargtypes = argtypes.prepend(tree.encl.type);
2546                 } else {
2547                     finalargtypes = argtypes;
2548                 }
2549 
2550                 // Reassign clazztype and recompute constructor. As this necessarily involves
2551                 // another attribution pass for deferred types in the case of <>, replicate
2552                 // them. Original arguments have right decorations already.
2553                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
2554                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
2555                 }
2556 
2557                 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
2558                                                     : cdef.sym.type;
2559                 Symbol sym = tree.constructor = rs.resolveConstructor(
2560                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
2561                 Assert.check(!sym.kind.isResolutionError());
2562                 tree.constructor = sym;
2563                 tree.constructorType = checkId(tree,
2564                         clazztype,
2565                         tree.constructor,
2566                         localEnv,
2567                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2568             }
2569             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
2570                                 clazztype : types.createErrorType(tree.type);
2571             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
2572             chk.validate(tree.typeargs, localEnv);
2573         }
2574 
2575         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
2576             return new Check.NestedCheckContext(checkContext) {
2577                 @Override
2578                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2579                     enclosingContext.report(clazz.clazz,
2580                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
2581                 }
2582             };
2583         }
2584 
2585     /** Make an attributed null check tree.
2586      */
2587     public JCExpression makeNullCheck(JCExpression arg) {
2588         // optimization: new Outer() can never be null; skip null check
2589         if (arg.getTag() == NEWCLASS)
2590             return arg;
2591         // optimization: X.this is never null; skip null check
2592         Name name = TreeInfo.name(arg);
2593         if (name == names._this || name == names._super) return arg;
2594 
2595         JCTree.Tag optag = NULLCHK;
2596         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2597         tree.operator = operators.resolveUnary(arg, optag, arg.type);
2598         tree.type = arg.type;
2599         return tree;
2600     }
2601 
2602     public void visitNewArray(JCNewArray tree) {
2603         Type owntype = types.createErrorType(tree.type);
2604         Env<AttrContext> localEnv = env.dup(tree);
2605         Type elemtype;
2606         if (tree.elemtype != null) {
2607             elemtype = attribType(tree.elemtype, localEnv);
2608             chk.validate(tree.elemtype, localEnv);
2609             owntype = elemtype;
2610             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2611                 attribExpr(l.head, localEnv, syms.intType);
2612                 owntype = new ArrayType(owntype, syms.arrayClass);
2613             }
2614         } else {
2615             // we are seeing an untyped aggregate { ... }
2616             // this is allowed only if the prototype is an array
2617             if (pt().hasTag(ARRAY)) {
2618                 elemtype = types.elemtype(pt());
2619             } else {
2620                 if (!pt().hasTag(ERROR) &&
2621                         (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
2622                     log.error(tree.pos(),
2623                               Errors.IllegalInitializerForType(pt()));
2624                 }
2625                 elemtype = types.createErrorType(pt());
2626             }
2627         }
2628         if (tree.elems != null) {
2629             attribExprs(tree.elems, localEnv, elemtype);
2630             owntype = new ArrayType(elemtype, syms.arrayClass);
2631         }
2632         if (!types.isReifiable(elemtype))
2633             log.error(tree.pos(), Errors.GenericArrayCreation);
2634         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2635     }
2636 
2637     /*
2638      * A lambda expression can only be attributed when a target-type is available.
2639      * In addition, if the target-type is that of a functional interface whose
2640      * descriptor contains inference variables in argument position the lambda expression
2641      * is 'stuck' (see DeferredAttr).
2642      */
2643     @Override
2644     public void visitLambda(final JCLambda that) {
2645         boolean wrongContext = false;
2646         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2647             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
2648                 //lambda only allowed in assignment or method invocation/cast context
2649                 log.error(that.pos(), Errors.UnexpectedLambda);
2650             }
2651             resultInfo = recoveryInfo;
2652             wrongContext = true;
2653         }
2654         //create an environment for attribution of the lambda expression
2655         final Env<AttrContext> localEnv = lambdaEnv(that, env);
2656         boolean needsRecovery =
2657                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2658         try {
2659             if (needsRecovery && isSerializable(pt())) {
2660                 localEnv.info.isSerializable = true;
2661                 localEnv.info.isLambda = true;
2662             }
2663             List<Type> explicitParamTypes = null;
2664             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2665                 //attribute lambda parameters
2666                 attribStats(that.params, localEnv);
2667                 explicitParamTypes = TreeInfo.types(that.params);
2668             }
2669 
2670             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
2671             Type currentTarget = targetInfo.target;
2672             Type lambdaType = targetInfo.descriptor;
2673 
2674             if (currentTarget.isErroneous()) {
2675                 result = that.type = currentTarget;
2676                 return;
2677             }
2678 
2679             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2680 
2681             if (lambdaType.hasTag(FORALL)) {
2682                 //lambda expression target desc cannot be a generic method
2683                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
2684                                                                     kindName(currentTarget.tsym),
2685                                                                     currentTarget.tsym);
2686                 resultInfo.checkContext.report(that, diags.fragment(msg));
2687                 result = that.type = types.createErrorType(pt());
2688                 return;
2689             }
2690 
2691             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2692                 //add param type info in the AST
2693                 List<Type> actuals = lambdaType.getParameterTypes();
2694                 List<JCVariableDecl> params = that.params;
2695 
2696                 boolean arityMismatch = false;
2697 
2698                 while (params.nonEmpty()) {
2699                     if (actuals.isEmpty()) {
2700                         //not enough actuals to perform lambda parameter inference
2701                         arityMismatch = true;
2702                     }
2703                     //reset previously set info
2704                     Type argType = arityMismatch ?
2705                             syms.errType :
2706                             actuals.head;
2707                     if (params.head.isImplicitlyTyped()) {
2708                         setSyntheticVariableType(params.head, argType);
2709                     }
2710                     params.head.sym = null;
2711                     actuals = actuals.isEmpty() ?
2712                             actuals :
2713                             actuals.tail;
2714                     params = params.tail;
2715                 }
2716 
2717                 //attribute lambda parameters
2718                 attribStats(that.params, localEnv);
2719 
2720                 if (arityMismatch) {
2721                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
2722                         result = that.type = types.createErrorType(currentTarget);
2723                         return;
2724                 }
2725             }
2726 
2727             //from this point on, no recovery is needed; if we are in assignment context
2728             //we will be able to attribute the whole lambda body, regardless of errors;
2729             //if we are in a 'check' method context, and the lambda is not compatible
2730             //with the target-type, it will be recovered anyway in Attr.checkId
2731             needsRecovery = false;
2732 
2733             ResultInfo bodyResultInfo = localEnv.info.returnResult =
2734                     lambdaBodyResult(that, lambdaType, resultInfo);
2735 
2736             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2737                 attribTree(that.getBody(), localEnv, bodyResultInfo);
2738             } else {
2739                 JCBlock body = (JCBlock)that.body;
2740                 if (body == breakTree &&
2741                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2742                     breakTreeFound(copyEnv(localEnv));
2743                 }
2744                 attribStats(body.stats, localEnv);
2745             }
2746 
2747             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2748 
2749             boolean isSpeculativeRound =
2750                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2751 
2752             preFlow(that);
2753             flow.analyzeLambda(env, that, make, isSpeculativeRound);
2754 
2755             that.type = currentTarget; //avoids recovery at this stage
2756             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2757 
2758             if (!isSpeculativeRound) {
2759                 //add thrown types as bounds to the thrown types free variables if needed:
2760                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2761                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2762                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
2763                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
2764                     }
2765                 }
2766 
2767                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2768             }
2769             result = wrongContext ? that.type = types.createErrorType(pt())
2770                                   : check(that, currentTarget, KindSelector.VAL, resultInfo);
2771         } catch (Types.FunctionDescriptorLookupError ex) {
2772             JCDiagnostic cause = ex.getDiagnostic();
2773             resultInfo.checkContext.report(that, cause);
2774             result = that.type = types.createErrorType(pt());
2775             return;
2776         } catch (Throwable t) {
2777             //when an unexpected exception happens, avoid attempts to attribute the same tree again
2778             //as that would likely cause the same exception again.
2779             needsRecovery = false;
2780             throw t;
2781         } finally {
2782             localEnv.info.scope.leave();
2783             if (needsRecovery) {
2784                 attribTree(that, env, recoveryInfo);
2785             }
2786         }
2787     }
2788     //where
2789         class TargetInfo {
2790             Type target;
2791             Type descriptor;
2792 
2793             public TargetInfo(Type target, Type descriptor) {
2794                 this.target = target;
2795                 this.descriptor = descriptor;
2796             }
2797         }
2798 
2799         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
2800             Type lambdaType;
2801             Type currentTarget = resultInfo.pt;
2802             if (resultInfo.pt != Type.recoveryType) {
2803                 /* We need to adjust the target. If the target is an
2804                  * intersection type, for example: SAM & I1 & I2 ...
2805                  * the target will be updated to SAM
2806                  */
2807                 currentTarget = targetChecker.visit(currentTarget, that);
2808                 if (!currentTarget.isIntersection()) {
2809                     if (explicitParamTypes != null) {
2810                         currentTarget = infer.instantiateFunctionalInterface(that,
2811                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
2812                     }
2813                     currentTarget = types.removeWildcards(currentTarget);
2814                     lambdaType = types.findDescriptorType(currentTarget);
2815                 } else {
2816                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
2817                     ListBuffer<Type> components = new ListBuffer<>();
2818                     for (Type bound : ict.getExplicitComponents()) {
2819                         if (explicitParamTypes != null) {
2820                             try {
2821                                 bound = infer.instantiateFunctionalInterface(that,
2822                                         bound, explicitParamTypes, resultInfo.checkContext);
2823                             } catch (FunctionDescriptorLookupError t) {
2824                                 // do nothing
2825                             }
2826                         }
2827                         bound = types.removeWildcards(bound);
2828                         components.add(bound);
2829                     }
2830                     currentTarget = types.makeIntersectionType(components.toList());
2831                     currentTarget.tsym.flags_field |= INTERFACE;
2832                     lambdaType = types.findDescriptorType(currentTarget);
2833                 }
2834 
2835             } else {
2836                 currentTarget = Type.recoveryType;
2837                 lambdaType = fallbackDescriptorType(that);
2838             }
2839             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
2840                 //lambda expression target desc cannot be a generic method
2841                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
2842                                                                     kindName(currentTarget.tsym),
2843                                                                     currentTarget.tsym);
2844                 resultInfo.checkContext.report(that, diags.fragment(msg));
2845                 currentTarget = types.createErrorType(pt());
2846             }
2847             return new TargetInfo(currentTarget, lambdaType);
2848         }
2849 
2850         void preFlow(JCLambda tree) {
2851             new PostAttrAnalyzer() {
2852                 @Override
2853                 public void scan(JCTree tree) {
2854                     if (tree == null ||
2855                             (tree.type != null &&
2856                             tree.type == Type.stuckType)) {
2857                         //don't touch stuck expressions!
2858                         return;
2859                     }
2860                     super.scan(tree);
2861                 }
2862 
2863                 @Override
2864                 public void visitClassDef(JCClassDecl that) {
2865                     // or class declaration trees!
2866                 }
2867 
2868                 public void visitLambda(JCLambda that) {
2869                     // or lambda expressions!
2870                 }
2871             }.scan(tree.body);
2872         }
2873 
2874         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2875 
2876             @Override
2877             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2878                 return t.isIntersection() ?
2879                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2880             }
2881 
2882             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2883                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
2884                 return ict;
2885             }
2886 
2887             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
2888                 ListBuffer<Type> targs = new ListBuffer<>();
2889                 ListBuffer<Type> supertypes = new ListBuffer<>();
2890                 for (Type i : ict.interfaces_field) {
2891                     if (i.isParameterized()) {
2892                         targs.appendList(i.tsym.type.allparams());
2893                     }
2894                     supertypes.append(i.tsym.type);
2895                 }
2896                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
2897                 notionalIntf.allparams_field = targs.toList();
2898                 notionalIntf.tsym.flags_field |= INTERFACE;
2899                 return notionalIntf.tsym;
2900             }
2901         };
2902 
2903         private Type fallbackDescriptorType(JCExpression tree) {
2904             switch (tree.getTag()) {
2905                 case LAMBDA:
2906                     JCLambda lambda = (JCLambda)tree;
2907                     List<Type> argtypes = List.nil();
2908                     for (JCVariableDecl param : lambda.params) {
2909                         argtypes = param.vartype != null && param.vartype.type != null ?
2910                                 argtypes.append(param.vartype.type) :
2911                                 argtypes.append(syms.errType);
2912                     }
2913                     return new MethodType(argtypes, Type.recoveryType,
2914                             List.of(syms.throwableType), syms.methodClass);
2915                 case REFERENCE:
2916                     return new MethodType(List.nil(), Type.recoveryType,
2917                             List.of(syms.throwableType), syms.methodClass);
2918                 default:
2919                     Assert.error("Cannot get here!");
2920             }
2921             return null;
2922         }
2923 
2924         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2925                 final InferenceContext inferenceContext, final Type... ts) {
2926             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2927         }
2928 
2929         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2930                 final InferenceContext inferenceContext, final List<Type> ts) {
2931             if (inferenceContext.free(ts)) {
2932                 inferenceContext.addFreeTypeListener(ts,
2933                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
2934             } else {
2935                 for (Type t : ts) {
2936                     rs.checkAccessibleType(env, t);
2937                 }
2938             }
2939         }
2940 
2941         /**
2942          * Lambda/method reference have a special check context that ensures
2943          * that i.e. a lambda return type is compatible with the expected
2944          * type according to both the inherited context and the assignment
2945          * context.
2946          */
2947         class FunctionalReturnContext extends Check.NestedCheckContext {
2948 
2949             FunctionalReturnContext(CheckContext enclosingContext) {
2950                 super(enclosingContext);
2951             }
2952 
2953             @Override
2954             public boolean compatible(Type found, Type req, Warner warn) {
2955                 //return type must be compatible in both current context and assignment context
2956                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
2957             }
2958 
2959             @Override
2960             public void report(DiagnosticPosition pos, JCDiagnostic details) {
2961                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
2962             }
2963         }
2964 
2965         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2966 
2967             JCExpression expr;
2968             boolean expStmtExpected;
2969 
2970             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2971                 super(enclosingContext);
2972                 this.expr = expr;
2973             }
2974 
2975             @Override
2976             public void report(DiagnosticPosition pos, JCDiagnostic details) {
2977                 if (expStmtExpected) {
2978                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
2979                 } else {
2980                     super.report(pos, details);
2981                 }
2982             }
2983 
2984             @Override
2985             public boolean compatible(Type found, Type req, Warner warn) {
2986                 //a void return is compatible with an expression statement lambda
2987                 if (req.hasTag(VOID)) {
2988                     expStmtExpected = true;
2989                     return TreeInfo.isExpressionStatement(expr);
2990                 } else {
2991                     return super.compatible(found, req, warn);
2992                 }
2993             }
2994         }
2995 
2996         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
2997             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2998                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2999                     new FunctionalReturnContext(resultInfo.checkContext);
3000 
3001             return descriptor.getReturnType() == Type.recoveryType ?
3002                     recoveryInfo :
3003                     new ResultInfo(KindSelector.VAL,
3004                             descriptor.getReturnType(), funcContext);
3005         }
3006 
3007         /**
3008         * Lambda compatibility. Check that given return types, thrown types, parameter types
3009         * are compatible with the expected functional interface descriptor. This means that:
3010         * (i) parameter types must be identical to those of the target descriptor; (ii) return
3011         * types must be compatible with the return type of the expected descriptor.
3012         */
3013         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3014             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3015 
3016             //return values have already been checked - but if lambda has no return
3017             //values, we must ensure that void/value compatibility is correct;
3018             //this amounts at checking that, if a lambda body can complete normally,
3019             //the descriptor's return type must be void
3020             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3021                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3022                 Fragment msg =
3023                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3024                 checkContext.report(tree,
3025                                     diags.fragment(msg));
3026             }
3027 
3028             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3029             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3030                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3031             }
3032         }
3033 
3034         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
3035          * static field and that lambda has type annotations, these annotations will
3036          * also be stored at these fake clinit methods.
3037          *
3038          * LambdaToMethod also use fake clinit methods so they can be reused.
3039          * Also as LTM is a phase subsequent to attribution, the methods from
3040          * clinits can be safely removed by LTM to save memory.
3041          */
3042         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
3043 
3044         public MethodSymbol removeClinit(ClassSymbol sym) {
3045             return clinits.remove(sym);
3046         }
3047 
3048         /* This method returns an environment to be used to attribute a lambda
3049          * expression.
3050          *
3051          * The owner of this environment is a method symbol. If the current owner
3052          * is not a method, for example if the lambda is used to initialize
3053          * a field, then if the field is:
3054          *
3055          * - an instance field, we use the first constructor.
3056          * - a static field, we create a fake clinit method.
3057          */
3058         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3059             Env<AttrContext> lambdaEnv;
3060             Symbol owner = env.info.scope.owner;
3061             if (owner.kind == VAR && owner.owner.kind == TYP) {
3062                 //field initializer
3063                 ClassSymbol enclClass = owner.enclClass();
3064                 Symbol newScopeOwner = env.info.scope.owner;
3065                 /* if the field isn't static, then we can get the first constructor
3066                  * and use it as the owner of the environment. This is what
3067                  * LTM code is doing to look for type annotations so we are fine.
3068                  */
3069                 if ((owner.flags() & STATIC) == 0) {
3070                     for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
3071                         newScopeOwner = s;
3072                         break;
3073                     }
3074                 } else {
3075                     /* if the field is static then we need to create a fake clinit
3076                      * method, this method can later be reused by LTM.
3077                      */
3078                     MethodSymbol clinit = clinits.get(enclClass);
3079                     if (clinit == null) {
3080                         Type clinitType = new MethodType(List.nil(),
3081                                 syms.voidType, List.nil(), syms.methodClass);
3082                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3083                                 names.clinit, clinitType, enclClass);
3084                         clinit.params = List.nil();
3085                         clinits.put(enclClass, clinit);
3086                     }
3087                     newScopeOwner = clinit;
3088                 }
3089                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3090             } else {
3091                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3092             }
3093             lambdaEnv.info.yieldResult = null;
3094             return lambdaEnv;
3095         }
3096 
3097     @Override
3098     public void visitReference(final JCMemberReference that) {
3099         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3100             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3101                 //method reference only allowed in assignment or method invocation/cast context
3102                 log.error(that.pos(), Errors.UnexpectedMref);
3103             }
3104             result = that.type = types.createErrorType(pt());
3105             return;
3106         }
3107         final Env<AttrContext> localEnv = env.dup(that);
3108         try {
3109             //attribute member reference qualifier - if this is a constructor
3110             //reference, the expected kind must be a type
3111             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3112 
3113             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3114                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3115                 if (!exprType.isErroneous() &&
3116                     exprType.isRaw() &&
3117                     that.typeargs != null) {
3118                     log.error(that.expr.pos(),
3119                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3120                                                  Fragments.MrefInferAndExplicitParams));
3121                     exprType = types.createErrorType(exprType);
3122                 }
3123             }
3124 
3125             if (exprType.isErroneous()) {
3126                 //if the qualifier expression contains problems,
3127                 //give up attribution of method reference
3128                 result = that.type = exprType;
3129                 return;
3130             }
3131 
3132             if (TreeInfo.isStaticSelector(that.expr, names)) {
3133                 //if the qualifier is a type, validate it; raw warning check is
3134                 //omitted as we don't know at this stage as to whether this is a
3135                 //raw selector (because of inference)
3136                 chk.validate(that.expr, env, false);
3137             } else {
3138                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3139                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3140             }
3141             //attrib type-arguments
3142             List<Type> typeargtypes = List.nil();
3143             if (that.typeargs != null) {
3144                 typeargtypes = attribTypes(that.typeargs, localEnv);
3145             }
3146 
3147             boolean isTargetSerializable =
3148                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3149                     isSerializable(pt());
3150             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3151             Type currentTarget = targetInfo.target;
3152             Type desc = targetInfo.descriptor;
3153 
3154             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3155             List<Type> argtypes = desc.getParameterTypes();
3156             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3157 
3158             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3159                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3160             }
3161 
3162             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3163             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3164             try {
3165                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3166                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3167                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3168             } finally {
3169                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3170             }
3171 
3172             Symbol refSym = refResult.fst;
3173             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3174 
3175             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3176              *  JDK-8075541
3177              */
3178             if (refSym.kind != MTH) {
3179                 boolean targetError;
3180                 switch (refSym.kind) {
3181                     case ABSENT_MTH:
3182                     case MISSING_ENCL:
3183                         targetError = false;
3184                         break;
3185                     case WRONG_MTH:
3186                     case WRONG_MTHS:
3187                     case AMBIGUOUS:
3188                     case HIDDEN:
3189                     case STATICERR:
3190                         targetError = true;
3191                         break;
3192                     default:
3193                         Assert.error("unexpected result kind " + refSym.kind);
3194                         targetError = false;
3195                 }
3196 
3197                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3198                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3199                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3200 
3201                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3202                         targetError ?
3203                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3204                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3205 
3206                 if (targetError && currentTarget == Type.recoveryType) {
3207                     //a target error doesn't make sense during recovery stage
3208                     //as we don't know what actual parameter types are
3209                     result = that.type = currentTarget;
3210                     return;
3211                 } else {
3212                     if (targetError) {
3213                         resultInfo.checkContext.report(that, diag);
3214                     } else {
3215                         log.report(diag);
3216                     }
3217                     result = that.type = types.createErrorType(currentTarget);
3218                     return;
3219                 }
3220             }
3221 
3222             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3223             that.kind = lookupHelper.referenceKind(that.sym);
3224             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3225 
3226             if (desc.getReturnType() == Type.recoveryType) {
3227                 // stop here
3228                 result = that.type = currentTarget;
3229                 return;
3230             }
3231 
3232             if (!env.info.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3233                 Type enclosingType = exprType.getEnclosingType();
3234                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3235                     // Check for the existence of an apropriate outer instance
3236                     rs.resolveImplicitThis(that.pos(), env, exprType);
3237                 }
3238             }
3239 
3240             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3241 
3242                 if (that.getMode() == ReferenceMode.INVOKE &&
3243                         TreeInfo.isStaticSelector(that.expr, names) &&
3244                         that.kind.isUnbound() &&
3245                         lookupHelper.site.isRaw()) {
3246                     chk.checkRaw(that.expr, localEnv);
3247                 }
3248 
3249                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3250                         exprType.getTypeArguments().nonEmpty()) {
3251                     //static ref with class type-args
3252                     log.error(that.expr.pos(),
3253                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3254                                                  Fragments.StaticMrefWithTargs));
3255                     result = that.type = types.createErrorType(currentTarget);
3256                     return;
3257                 }
3258 
3259                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3260                     // Check that super-qualified symbols are not abstract (JLS)
3261                     rs.checkNonAbstract(that.pos(), that.sym);
3262                 }
3263 
3264                 if (isTargetSerializable) {
3265                     chk.checkAccessFromSerializableElement(that, true);
3266                 }
3267             }
3268 
3269             ResultInfo checkInfo =
3270                     resultInfo.dup(newMethodTemplate(
3271                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3272                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3273                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3274 
3275             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3276 
3277             if (that.kind.isUnbound() &&
3278                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3279                 //re-generate inference constraints for unbound receiver
3280                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3281                     //cannot happen as this has already been checked - we just need
3282                     //to regenerate the inference constraints, as that has been lost
3283                     //as a result of the call to inferenceContext.save()
3284                     Assert.error("Can't get here");
3285                 }
3286             }
3287 
3288             if (!refType.isErroneous()) {
3289                 refType = types.createMethodTypeWithReturn(refType,
3290                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3291             }
3292 
3293             //go ahead with standard method reference compatibility check - note that param check
3294             //is a no-op (as this has been taken care during method applicability)
3295             boolean isSpeculativeRound =
3296                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3297 
3298             that.type = currentTarget; //avoids recovery at this stage
3299             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3300             if (!isSpeculativeRound) {
3301                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3302             }
3303             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3304         } catch (Types.FunctionDescriptorLookupError ex) {
3305             JCDiagnostic cause = ex.getDiagnostic();
3306             resultInfo.checkContext.report(that, cause);
3307             result = that.type = types.createErrorType(pt());
3308             return;
3309         }
3310     }
3311     //where
3312         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3313             //if this is a constructor reference, the expected kind must be a type
3314             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3315                                   KindSelector.VAL_TYP : KindSelector.TYP,
3316                                   Type.noType);
3317         }
3318 
3319 
3320     @SuppressWarnings("fallthrough")
3321     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3322         InferenceContext inferenceContext = checkContext.inferenceContext();
3323         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3324 
3325         Type resType;
3326         switch (tree.getMode()) {
3327             case NEW:
3328                 if (!tree.expr.type.isRaw()) {
3329                     resType = tree.expr.type;
3330                     break;
3331                 }
3332             default:
3333                 resType = refType.getReturnType();
3334         }
3335 
3336         Type incompatibleReturnType = resType;
3337 
3338         if (returnType.hasTag(VOID)) {
3339             incompatibleReturnType = null;
3340         }
3341 
3342         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3343             if (resType.isErroneous() ||
3344                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3345                             checkContext.checkWarner(tree, resType, returnType))) {
3346                 incompatibleReturnType = null;
3347             }
3348         }
3349 
3350         if (incompatibleReturnType != null) {
3351             Fragment msg =
3352                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3353             checkContext.report(tree, diags.fragment(msg));
3354         } else {
3355             if (inferenceContext.free(refType)) {
3356                 // we need to wait for inference to finish and then replace inference vars in the referent type
3357                 inferenceContext.addFreeTypeListener(List.of(refType),
3358                         instantiatedContext -> {
3359                             tree.referentType = instantiatedContext.asInstType(refType);
3360                         });
3361             } else {
3362                 tree.referentType = refType;
3363             }
3364         }
3365 
3366         if (!speculativeAttr) {
3367             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3368                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3369             }
3370         }
3371     }
3372 
3373     boolean checkExConstraints(
3374             List<Type> thrownByFuncExpr,
3375             List<Type> thrownAtFuncType,
3376             InferenceContext inferenceContext) {
3377         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3378          *  are not proper types
3379          */
3380         List<Type> nonProperList = thrownAtFuncType.stream()
3381                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3382         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3383 
3384         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3385          *  in the throws clause of the invocation type of the method reference's compile-time
3386          *  declaration
3387          */
3388         List<Type> checkedList = thrownByFuncExpr.stream()
3389                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3390 
3391         /** If n = 0 (the function type's throws clause consists only of proper types), then
3392          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3393          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3394          *  reduces to true
3395          */
3396         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3397         for (Type checked : checkedList) {
3398             boolean isSubtype = false;
3399             for (Type proper : properList) {
3400                 if (types.isSubtype(checked, proper)) {
3401                     isSubtype = true;
3402                     break;
3403                 }
3404             }
3405             if (!isSubtype) {
3406                 uncaughtByProperTypes.add(checked);
3407             }
3408         }
3409 
3410         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3411             return false;
3412         }
3413 
3414         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3415          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3416          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3417          */
3418         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3419         uncaughtByProperTypes.forEach(checkedEx -> {
3420             nonProperAsUndet.forEach(nonProper -> {
3421                 types.isSubtype(checkedEx, nonProper);
3422             });
3423         });
3424 
3425         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3426          */
3427         nonProperAsUndet.stream()
3428                 .filter(t -> t.hasTag(UNDETVAR))
3429                 .forEach(t -> ((UndetVar)t).setThrow());
3430         return true;
3431     }
3432 
3433     /**
3434      * Set functional type info on the underlying AST. Note: as the target descriptor
3435      * might contain inference variables, we might need to register an hook in the
3436      * current inference context.
3437      */
3438     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3439             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3440         if (checkContext.inferenceContext().free(descriptorType)) {
3441             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3442                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3443                     inferenceContext.asInstType(primaryTarget), checkContext));
3444         } else {
3445             if (pt.hasTag(CLASS)) {
3446                 fExpr.target = primaryTarget;
3447             }
3448             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3449                     pt != Type.recoveryType) {
3450                 //check that functional interface class is well-formed
3451                 try {
3452                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3453                      * when it's executed post-inference. See the listener code
3454                      * above.
3455                      */
3456                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3457                             names.empty, fExpr.target, ABSTRACT);
3458                     if (csym != null) {
3459                         chk.checkImplementations(env.tree, csym, csym);
3460                         try {
3461                             //perform an additional functional interface check on the synthetic class,
3462                             //as there may be spurious errors for raw targets - because of existing issues
3463                             //with membership and inheritance (see JDK-8074570).
3464                             csym.flags_field |= INTERFACE;
3465                             types.findDescriptorType(csym.type);
3466                         } catch (FunctionDescriptorLookupError err) {
3467                             resultInfo.checkContext.report(fExpr,
3468                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3469                         }
3470                     }
3471                 } catch (Types.FunctionDescriptorLookupError ex) {
3472                     JCDiagnostic cause = ex.getDiagnostic();
3473                     resultInfo.checkContext.report(env.tree, cause);
3474                 }
3475             }
3476         }
3477     }
3478 
3479     public void visitParens(JCParens tree) {
3480         Type owntype = attribTree(tree.expr, env, resultInfo);
3481         result = check(tree, owntype, pkind(), resultInfo);
3482         Symbol sym = TreeInfo.symbol(tree);
3483         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3484             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3485     }
3486 
3487     public void visitAssign(JCAssign tree) {
3488         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3489         Type capturedType = capture(owntype);
3490         attribExpr(tree.rhs, env, owntype);
3491         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3492     }
3493 
3494     public void visitAssignop(JCAssignOp tree) {
3495         // Attribute arguments.
3496         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3497         Type operand = attribExpr(tree.rhs, env);
3498         // Find operator.
3499         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3500         if (operator != operators.noOpSymbol &&
3501                 !owntype.isErroneous() &&
3502                 !operand.isErroneous()) {
3503             chk.checkDivZero(tree.rhs.pos(), operator, operand);
3504             chk.checkCastable(tree.rhs.pos(),
3505                               operator.type.getReturnType(),
3506                               owntype);
3507         }
3508         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3509     }
3510 
3511     public void visitUnary(JCUnary tree) {
3512         // Attribute arguments.
3513         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3514             ? attribTree(tree.arg, env, varAssignmentInfo)
3515             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3516 
3517         // Find operator.
3518         Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3519         Type owntype = types.createErrorType(tree.type);
3520         if (operator != operators.noOpSymbol &&
3521                 !argtype.isErroneous()) {
3522             owntype = (tree.getTag().isIncOrDecUnaryOp())
3523                 ? tree.arg.type
3524                 : operator.type.getReturnType();
3525             int opc = ((OperatorSymbol)operator).opcode;
3526 
3527             // If the argument is constant, fold it.
3528             if (argtype.constValue() != null) {
3529                 Type ctype = cfolder.fold1(opc, argtype);
3530                 if (ctype != null) {
3531                     owntype = cfolder.coerce(ctype, owntype);
3532                 }
3533             }
3534         }
3535         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3536     }
3537 
3538     public void visitBinary(JCBinary tree) {
3539         // Attribute arguments.
3540         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3541         Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
3542         // Find operator.
3543         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3544         Type owntype = types.createErrorType(tree.type);
3545         if (operator != operators.noOpSymbol &&
3546                 !left.isErroneous() &&
3547                 !right.isErroneous()) {
3548             owntype = operator.type.getReturnType();
3549             int opc = ((OperatorSymbol)operator).opcode;
3550             // If both arguments are constants, fold them.
3551             if (left.constValue() != null && right.constValue() != null) {
3552                 Type ctype = cfolder.fold2(opc, left, right);
3553                 if (ctype != null) {
3554                     owntype = cfolder.coerce(ctype, owntype);
3555                 }
3556             }
3557 
3558             // Check that argument types of a reference ==, != are
3559             // castable to each other, (JLS 15.21).  Note: unboxing
3560             // comparisons will not have an acmp* opc at this point.
3561             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3562                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3563                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
3564                 }
3565             }
3566 
3567             chk.checkDivZero(tree.rhs.pos(), operator, right);
3568         }
3569         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3570     }
3571 
3572     public void visitTypeCast(final JCTypeCast tree) {
3573         Type clazztype = attribType(tree.clazz, env);
3574         chk.validate(tree.clazz, env, false);
3575         //a fresh environment is required for 292 inference to work properly ---
3576         //see Infer.instantiatePolymorphicSignatureInstance()
3577         Env<AttrContext> localEnv = env.dup(tree);
3578         //should we propagate the target type?
3579         final ResultInfo castInfo;
3580         JCExpression expr = TreeInfo.skipParens(tree.expr);
3581         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3582         if (isPoly) {
3583             //expression is a poly - we need to propagate target type info
3584             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3585                                       new Check.NestedCheckContext(resultInfo.checkContext) {
3586                 @Override
3587                 public boolean compatible(Type found, Type req, Warner warn) {
3588                     return types.isCastable(found, req, warn);
3589                 }
3590             });
3591         } else {
3592             //standalone cast - target-type info is not propagated
3593             castInfo = unknownExprInfo;
3594         }
3595         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3596         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3597         if (exprtype.constValue() != null)
3598             owntype = cfolder.coerce(exprtype, owntype);
3599         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3600         if (!isPoly)
3601             chk.checkRedundantCast(localEnv, tree);
3602     }
3603 
3604     public void visitTypeTest(JCInstanceOf tree) {
3605         Type exprtype = chk.checkNullOrRefType(
3606                 tree.expr.pos(), attribExpr(tree.expr, env));
3607         Type clazztype = attribType(tree.clazz, env);
3608         if (!clazztype.hasTag(TYPEVAR)) {
3609             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3610         }
3611         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3612             log.error(tree.clazz.pos(), Errors.IllegalGenericTypeForInstof);
3613             clazztype = types.createErrorType(clazztype);
3614         }
3615         chk.validate(tree.clazz, env, false);
3616         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3617         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3618     }
3619 
3620     public void visitIndexed(JCArrayAccess tree) {
3621         Type owntype = types.createErrorType(tree.type);
3622         Type atype = attribExpr(tree.indexed, env);
3623         attribExpr(tree.index, env, syms.intType);
3624         if (types.isArray(atype))
3625             owntype = types.elemtype(atype);
3626         else if (!atype.hasTag(ERROR))
3627             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
3628         if (!pkind().contains(KindSelector.VAL))
3629             owntype = capture(owntype);
3630         result = check(tree, owntype, KindSelector.VAR, resultInfo);
3631     }
3632 
3633     public void visitIdent(JCIdent tree) {
3634         Symbol sym;
3635 
3636         // Find symbol
3637         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3638             // If we are looking for a method, the prototype `pt' will be a
3639             // method type with the type of the call's arguments as parameters.
3640             env.info.pendingResolutionPhase = null;
3641             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3642         } else if (tree.sym != null && tree.sym.kind != VAR) {
3643             sym = tree.sym;
3644         } else {
3645             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3646         }
3647         tree.sym = sym;
3648 
3649         // (1) Also find the environment current for the class where
3650         //     sym is defined (`symEnv').
3651         // Only for pre-tiger versions (1.4 and earlier):
3652         // (2) Also determine whether we access symbol out of an anonymous
3653         //     class in a this or super call.  This is illegal for instance
3654         //     members since such classes don't carry a this$n link.
3655         //     (`noOuterThisPath').
3656         Env<AttrContext> symEnv = env;
3657         boolean noOuterThisPath = false;
3658         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3659             sym.kind.matches(KindSelector.VAL_MTH) &&
3660             sym.owner.kind == TYP &&
3661             tree.name != names._this && tree.name != names._super) {
3662 
3663             // Find environment in which identifier is defined.
3664             while (symEnv.outer != null &&
3665                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3666                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3667                     noOuterThisPath = false;
3668                 symEnv = symEnv.outer;
3669             }
3670         }
3671 
3672         // If symbol is a variable, ...
3673         if (sym.kind == VAR) {
3674             VarSymbol v = (VarSymbol)sym;
3675 
3676             // ..., evaluate its initializer, if it has one, and check for
3677             // illegal forward reference.
3678             checkInit(tree, env, v, false);
3679 
3680             // If we are expecting a variable (as opposed to a value), check
3681             // that the variable is assignable in the current environment.
3682             if (KindSelector.ASG.subset(pkind()))
3683                 checkAssignable(tree.pos(), v, null, env);
3684         }
3685 
3686         // In a constructor body,
3687         // if symbol is a field or instance method, check that it is
3688         // not accessed before the supertype constructor is called.
3689         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3690             sym.kind.matches(KindSelector.VAL_MTH) &&
3691             sym.owner.kind == TYP &&
3692             (sym.flags() & STATIC) == 0) {
3693             chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3694                                           sym : thisSym(tree.pos(), env));
3695         }
3696         Env<AttrContext> env1 = env;
3697         if (sym.kind != ERR && sym.kind != TYP &&
3698             sym.owner != null && sym.owner != env1.enclClass.sym) {
3699             // If the found symbol is inaccessible, then it is
3700             // accessed through an enclosing instance.  Locate this
3701             // enclosing instance:
3702             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3703                 env1 = env1.outer;
3704         }
3705 
3706         if (env.info.isSerializable) {
3707             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3708         }
3709 
3710         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3711     }
3712 
3713     public void visitSelect(JCFieldAccess tree) {
3714         // Determine the expected kind of the qualifier expression.
3715         KindSelector skind = KindSelector.NIL;
3716         if (tree.name == names._this || tree.name == names._super ||
3717                 tree.name == names._class)
3718         {
3719             skind = KindSelector.TYP;
3720         } else {
3721             if (pkind().contains(KindSelector.PCK))
3722                 skind = KindSelector.of(skind, KindSelector.PCK);
3723             if (pkind().contains(KindSelector.TYP))
3724                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3725             if (pkind().contains(KindSelector.VAL_MTH))
3726                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3727         }
3728 
3729         // Attribute the qualifier expression, and determine its symbol (if any).
3730         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3731         if (!pkind().contains(KindSelector.TYP_PCK))
3732             site = capture(site); // Capture field access
3733 
3734         // don't allow T.class T[].class, etc
3735         if (skind == KindSelector.TYP) {
3736             Type elt = site;
3737             while (elt.hasTag(ARRAY))
3738                 elt = ((ArrayType)elt).elemtype;
3739             if (elt.hasTag(TYPEVAR)) {
3740                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
3741                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3742                 tree.sym = tree.type.tsym;
3743                 return ;
3744             }
3745         }
3746 
3747         // If qualifier symbol is a type or `super', assert `selectSuper'
3748         // for the selection. This is relevant for determining whether
3749         // protected symbols are accessible.
3750         Symbol sitesym = TreeInfo.symbol(tree.selected);
3751         boolean selectSuperPrev = env.info.selectSuper;
3752         env.info.selectSuper =
3753             sitesym != null &&
3754             sitesym.name == names._super;
3755 
3756         // Determine the symbol represented by the selection.
3757         env.info.pendingResolutionPhase = null;
3758         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3759         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3760             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
3761             sym = syms.errSymbol;
3762         }
3763         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3764             site = capture(site);
3765             sym = selectSym(tree, sitesym, site, env, resultInfo);
3766         }
3767         boolean varArgs = env.info.lastResolveVarargs();
3768         tree.sym = sym;
3769 
3770         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3771             site = types.skipTypeVars(site, true);
3772         }
3773 
3774         // If that symbol is a variable, ...
3775         if (sym.kind == VAR) {
3776             VarSymbol v = (VarSymbol)sym;
3777 
3778             // ..., evaluate its initializer, if it has one, and check for
3779             // illegal forward reference.
3780             checkInit(tree, env, v, true);
3781 
3782             // If we are expecting a variable (as opposed to a value), check
3783             // that the variable is assignable in the current environment.
3784             if (KindSelector.ASG.subset(pkind()))
3785                 checkAssignable(tree.pos(), v, tree.selected, env);
3786         }
3787 
3788         if (sitesym != null &&
3789                 sitesym.kind == VAR &&
3790                 ((VarSymbol)sitesym).isResourceVariable() &&
3791                 sym.kind == MTH &&
3792                 sym.name.equals(names.close) &&
3793                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3794                 env.info.lint.isEnabled(LintCategory.TRY)) {
3795             log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall);
3796         }
3797 
3798         // Disallow selecting a type from an expression
3799         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3800             tree.type = check(tree.selected, pt(),
3801                               sitesym == null ?
3802                                       KindSelector.VAL : sitesym.kind.toSelector(),
3803                               new ResultInfo(KindSelector.TYP_PCK, pt()));
3804         }
3805 
3806         if (isType(sitesym)) {
3807             if (sym.name == names._this) {
3808                 // If `C' is the currently compiled class, check that
3809                 // C.this' does not appear in a call to a super(...)
3810                 if (env.info.isSelfCall &&
3811                     site.tsym == env.enclClass.sym) {
3812                     chk.earlyRefError(tree.pos(), sym);
3813                 }
3814             } else {
3815                 // Check if type-qualified fields or methods are static (JLS)
3816                 if ((sym.flags() & STATIC) == 0 &&
3817                     sym.name != names._super &&
3818                     (sym.kind == VAR || sym.kind == MTH)) {
3819                     rs.accessBase(rs.new StaticError(sym),
3820                               tree.pos(), site, sym.name, true);
3821                 }
3822             }
3823             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3824                     sym.isStatic() && sym.kind == MTH) {
3825                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), Feature.STATIC_INTERFACE_METHODS_INVOKE.error(sourceName));
3826             }
3827         } else if (sym.kind != ERR &&
3828                    (sym.flags() & STATIC) != 0 &&
3829                    sym.name != names._class) {
3830             // If the qualified item is not a type and the selected item is static, report
3831             // a warning. Make allowance for the class of an array type e.g. Object[].class)
3832             chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
3833         }
3834 
3835         // If we are selecting an instance member via a `super', ...
3836         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3837 
3838             // Check that super-qualified symbols are not abstract (JLS)
3839             rs.checkNonAbstract(tree.pos(), sym);
3840 
3841             if (site.isRaw()) {
3842                 // Determine argument types for site.
3843                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3844                 if (site1 != null) site = site1;
3845             }
3846         }
3847 
3848         if (env.info.isSerializable) {
3849             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3850         }
3851 
3852         env.info.selectSuper = selectSuperPrev;
3853         result = checkId(tree, site, sym, env, resultInfo);
3854     }
3855     //where
3856         /** Determine symbol referenced by a Select expression,
3857          *
3858          *  @param tree   The select tree.
3859          *  @param site   The type of the selected expression,
3860          *  @param env    The current environment.
3861          *  @param resultInfo The current result.
3862          */
3863         private Symbol selectSym(JCFieldAccess tree,
3864                                  Symbol location,
3865                                  Type site,
3866                                  Env<AttrContext> env,
3867                                  ResultInfo resultInfo) {
3868             DiagnosticPosition pos = tree.pos();
3869             Name name = tree.name;
3870             switch (site.getTag()) {
3871             case PACKAGE:
3872                 return rs.accessBase(
3873                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
3874                     pos, location, site, name, true);
3875             case ARRAY:
3876             case CLASS:
3877                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3878                     return rs.resolveQualifiedMethod(
3879                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3880                 } else if (name == names._this || name == names._super) {
3881                     return rs.resolveSelf(pos, env, site.tsym, name);
3882                 } else if (name == names._class) {
3883                     // In this case, we have already made sure in
3884                     // visitSelect that qualifier expression is a type.
3885                     return syms.getClassField(site, types);
3886                 } else {
3887                     // We are seeing a plain identifier as selector.
3888                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
3889                         sym = rs.accessBase(sym, pos, location, site, name, true);
3890                     return sym;
3891                 }
3892             case WILDCARD:
3893                 throw new AssertionError(tree);
3894             case TYPEVAR:
3895                 // Normally, site.getUpperBound() shouldn't be null.
3896                 // It should only happen during memberEnter/attribBase
3897                 // when determining the super type which *must* beac
3898                 // done before attributing the type variables.  In
3899                 // other words, we are seeing this illegal program:
3900                 // class B<T> extends A<T.foo> {}
3901                 Symbol sym = (site.getUpperBound() != null)
3902                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3903                     : null;
3904                 if (sym == null) {
3905                     log.error(pos, Errors.TypeVarCantBeDeref);
3906                     return syms.errSymbol;
3907                 } else {
3908                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3909                         rs.new AccessError(env, site, sym) :
3910                                 sym;
3911                     rs.accessBase(sym2, pos, location, site, name, true);
3912                     return sym;
3913                 }
3914             case ERROR:
3915                 // preserve identifier names through errors
3916                 return types.createErrorType(name, site.tsym, site).tsym;
3917             default:
3918                 // The qualifier expression is of a primitive type -- only
3919                 // .class is allowed for these.
3920                 if (name == names._class) {
3921                     // In this case, we have already made sure in Select that
3922                     // qualifier expression is a type.
3923                     return syms.getClassField(site, types);
3924                 } else {
3925                     log.error(pos, Errors.CantDeref(site));
3926                     return syms.errSymbol;
3927                 }
3928             }
3929         }
3930 
3931         /** Determine type of identifier or select expression and check that
3932          *  (1) the referenced symbol is not deprecated
3933          *  (2) the symbol's type is safe (@see checkSafe)
3934          *  (3) if symbol is a variable, check that its type and kind are
3935          *      compatible with the prototype and protokind.
3936          *  (4) if symbol is an instance field of a raw type,
3937          *      which is being assigned to, issue an unchecked warning if its
3938          *      type changes under erasure.
3939          *  (5) if symbol is an instance method of a raw type, issue an
3940          *      unchecked warning if its argument types change under erasure.
3941          *  If checks succeed:
3942          *    If symbol is a constant, return its constant type
3943          *    else if symbol is a method, return its result type
3944          *    otherwise return its type.
3945          *  Otherwise return errType.
3946          *
3947          *  @param tree       The syntax tree representing the identifier
3948          *  @param site       If this is a select, the type of the selected
3949          *                    expression, otherwise the type of the current class.
3950          *  @param sym        The symbol representing the identifier.
3951          *  @param env        The current environment.
3952          *  @param resultInfo    The expected result
3953          */
3954         Type checkId(JCTree tree,
3955                      Type site,
3956                      Symbol sym,
3957                      Env<AttrContext> env,
3958                      ResultInfo resultInfo) {
3959             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3960                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
3961                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3962         }
3963 
3964         Type checkMethodIdInternal(JCTree tree,
3965                      Type site,
3966                      Symbol sym,
3967                      Env<AttrContext> env,
3968                      ResultInfo resultInfo) {
3969             if (resultInfo.pkind.contains(KindSelector.POLY)) {
3970                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3971                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3972                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3973                 return owntype;
3974             } else {
3975                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3976             }
3977         }
3978 
3979         Type checkIdInternal(JCTree tree,
3980                      Type site,
3981                      Symbol sym,
3982                      Type pt,
3983                      Env<AttrContext> env,
3984                      ResultInfo resultInfo) {
3985             if (pt.isErroneous()) {
3986                 return types.createErrorType(site);
3987             }
3988             Type owntype; // The computed type of this identifier occurrence.
3989             switch (sym.kind) {
3990             case TYP:
3991                 // For types, the computed type equals the symbol's type,
3992                 // except for two situations:
3993                 owntype = sym.type;
3994                 if (owntype.hasTag(CLASS)) {
3995                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3996                     Type ownOuter = owntype.getEnclosingType();
3997 
3998                     // (a) If the symbol's type is parameterized, erase it
3999                     // because no type parameters were given.
4000                     // We recover generic outer type later in visitTypeApply.
4001                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4002                         owntype = types.erasure(owntype);
4003                     }
4004 
4005                     // (b) If the symbol's type is an inner class, then
4006                     // we have to interpret its outer type as a superclass
4007                     // of the site type. Example:
4008                     //
4009                     // class Tree<A> { class Visitor { ... } }
4010                     // class PointTree extends Tree<Point> { ... }
4011                     // ...PointTree.Visitor...
4012                     //
4013                     // Then the type of the last expression above is
4014                     // Tree<Point>.Visitor.
4015                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4016                         Type normOuter = site;
4017                         if (normOuter.hasTag(CLASS)) {
4018                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4019                         }
4020                         if (normOuter == null) // perhaps from an import
4021                             normOuter = types.erasure(ownOuter);
4022                         if (normOuter != ownOuter)
4023                             owntype = new ClassType(
4024                                 normOuter, List.nil(), owntype.tsym,
4025                                 owntype.getMetadata());
4026                     }
4027                 }
4028                 break;
4029             case VAR:
4030                 VarSymbol v = (VarSymbol)sym;
4031 
4032                 if (env.info.enclVar != null
4033                         && v.type.hasTag(NONE)) {
4034                     //self reference to implicitly typed variable declaration
4035                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4036                     return v.type = types.createErrorType(v.type);
4037                 }
4038 
4039                 // Test (4): if symbol is an instance field of a raw type,
4040                 // which is being assigned to, issue an unchecked warning if
4041                 // its type changes under erasure.
4042                 if (KindSelector.ASG.subset(pkind()) &&
4043                     v.owner.kind == TYP &&
4044                     (v.flags() & STATIC) == 0 &&
4045                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4046                     Type s = types.asOuterSuper(site, v.owner);
4047                     if (s != null &&
4048                         s.isRaw() &&
4049                         !types.isSameType(v.type, v.erasure(types))) {
4050                         chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s));
4051                     }
4052                 }
4053                 // The computed type of a variable is the type of the
4054                 // variable symbol, taken as a member of the site type.
4055                 owntype = (sym.owner.kind == TYP &&
4056                            sym.name != names._this && sym.name != names._super)
4057                     ? types.memberType(site, sym)
4058                     : sym.type;
4059 
4060                 // If the variable is a constant, record constant value in
4061                 // computed type.
4062                 if (v.getConstValue() != null && isStaticReference(tree))
4063                     owntype = owntype.constType(v.getConstValue());
4064 
4065                 if (resultInfo.pkind == KindSelector.VAL) {
4066                     owntype = capture(owntype); // capture "names as expressions"
4067                 }
4068                 break;
4069             case MTH: {
4070                 owntype = checkMethod(site, sym,
4071                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4072                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4073                         resultInfo.pt.getTypeArguments());
4074                 break;
4075             }
4076             case PCK: case ERR:
4077                 owntype = sym.type;
4078                 break;
4079             default:
4080                 throw new AssertionError("unexpected kind: " + sym.kind +
4081                                          " in tree " + tree);
4082             }
4083 
4084             // Emit a `deprecation' warning if symbol is deprecated.
4085             // (for constructors (but not for constructor references), the error
4086             // was given when the constructor was resolved)
4087 
4088             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4089                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4090                 chk.checkSunAPI(tree.pos(), sym);
4091                 chk.checkProfile(tree.pos(), sym);
4092             }
4093 
4094             // If symbol is a variable, check that its type and
4095             // kind are compatible with the prototype and protokind.
4096             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4097         }
4098 
4099         /** Check that variable is initialized and evaluate the variable's
4100          *  initializer, if not yet done. Also check that variable is not
4101          *  referenced before it is defined.
4102          *  @param tree    The tree making up the variable reference.
4103          *  @param env     The current environment.
4104          *  @param v       The variable's symbol.
4105          */
4106         private void checkInit(JCTree tree,
4107                                Env<AttrContext> env,
4108                                VarSymbol v,
4109                                boolean onlyWarning) {
4110             // A forward reference is diagnosed if the declaration position
4111             // of the variable is greater than the current tree position
4112             // and the tree and variable definition occur in the same class
4113             // definition.  Note that writes don't count as references.
4114             // This check applies only to class and instance
4115             // variables.  Local variables follow different scope rules,
4116             // and are subject to definite assignment checking.
4117             Env<AttrContext> initEnv = enclosingInitEnv(env);
4118             if (initEnv != null &&
4119                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4120                 v.owner.kind == TYP &&
4121                 v.owner == env.info.scope.owner.enclClass() &&
4122                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4123                 (!env.tree.hasTag(ASSIGN) ||
4124                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4125                 if (!onlyWarning || isStaticEnumField(v)) {
4126                     Error errkey = (initEnv.info.enclVar == v) ?
4127                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4128                     log.error(tree.pos(), errkey);
4129                 } else if (useBeforeDeclarationWarning) {
4130                     Warning warnkey = (initEnv.info.enclVar == v) ?
4131                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4132                     log.warning(tree.pos(), warnkey);
4133                 }
4134             }
4135 
4136             v.getConstValue(); // ensure initializer is evaluated
4137 
4138             checkEnumInitializer(tree, env, v);
4139         }
4140 
4141         /**
4142          * Returns the enclosing init environment associated with this env (if any). An init env
4143          * can be either a field declaration env or a static/instance initializer env.
4144          */
4145         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4146             while (true) {
4147                 switch (env.tree.getTag()) {
4148                     case VARDEF:
4149                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4150                         if (vdecl.sym.owner.kind == TYP) {
4151                             //field
4152                             return env;
4153                         }
4154                         break;
4155                     case BLOCK:
4156                         if (env.next.tree.hasTag(CLASSDEF)) {
4157                             //instance/static initializer
4158                             return env;
4159                         }
4160                         break;
4161                     case METHODDEF:
4162                     case CLASSDEF:
4163                     case TOPLEVEL:
4164                         return null;
4165                 }
4166                 Assert.checkNonNull(env.next);
4167                 env = env.next;
4168             }
4169         }
4170 
4171         /**
4172          * Check for illegal references to static members of enum.  In
4173          * an enum type, constructors and initializers may not
4174          * reference its static members unless they are constant.
4175          *
4176          * @param tree    The tree making up the variable reference.
4177          * @param env     The current environment.
4178          * @param v       The variable's symbol.
4179          * @jls 8.9 Enum Types
4180          */
4181         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4182             // JLS:
4183             //
4184             // "It is a compile-time error to reference a static field
4185             // of an enum type that is not a compile-time constant
4186             // (15.28) from constructors, instance initializer blocks,
4187             // or instance variable initializer expressions of that
4188             // type. It is a compile-time error for the constructors,
4189             // instance initializer blocks, or instance variable
4190             // initializer expressions of an enum constant e to refer
4191             // to itself or to an enum constant of the same type that
4192             // is declared to the right of e."
4193             if (isStaticEnumField(v)) {
4194                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4195 
4196                 if (enclClass == null || enclClass.owner == null)
4197                     return;
4198 
4199                 // See if the enclosing class is the enum (or a
4200                 // subclass thereof) declaring v.  If not, this
4201                 // reference is OK.
4202                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4203                     return;
4204 
4205                 // If the reference isn't from an initializer, then
4206                 // the reference is OK.
4207                 if (!Resolve.isInitializer(env))
4208                     return;
4209 
4210                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4211             }
4212         }
4213 
4214         /** Is the given symbol a static, non-constant field of an Enum?
4215          *  Note: enum literals should not be regarded as such
4216          */
4217         private boolean isStaticEnumField(VarSymbol v) {
4218             return Flags.isEnum(v.owner) &&
4219                    Flags.isStatic(v) &&
4220                    !Flags.isConstant(v) &&
4221                    v.name != names._class;
4222         }
4223 
4224     /**
4225      * Check that method arguments conform to its instantiation.
4226      **/
4227     public Type checkMethod(Type site,
4228                             final Symbol sym,
4229                             ResultInfo resultInfo,
4230                             Env<AttrContext> env,
4231                             final List<JCExpression> argtrees,
4232                             List<Type> argtypes,
4233                             List<Type> typeargtypes) {
4234         // Test (5): if symbol is an instance method of a raw type, issue
4235         // an unchecked warning if its argument types change under erasure.
4236         if ((sym.flags() & STATIC) == 0 &&
4237             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4238             Type s = types.asOuterSuper(site, sym.owner);
4239             if (s != null && s.isRaw() &&
4240                 !types.isSameTypes(sym.type.getParameterTypes(),
4241                                    sym.erasure(types).getParameterTypes())) {
4242                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s));
4243             }
4244         }
4245 
4246         if (env.info.defaultSuperCallSite != null) {
4247             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4248                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4249                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4250                 List<MethodSymbol> icand_sup =
4251                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4252                 if (icand_sup.nonEmpty() &&
4253                         icand_sup.head != sym &&
4254                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4255                     log.error(env.tree.pos(),
4256                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4257                     break;
4258                 }
4259             }
4260             env.info.defaultSuperCallSite = null;
4261         }
4262 
4263         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4264             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4265             if (app.meth.hasTag(SELECT) &&
4266                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4267                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4268             }
4269         }
4270 
4271         // Compute the identifier's instantiated type.
4272         // For methods, we need to compute the instance type by
4273         // Resolve.instantiate from the symbol's type as well as
4274         // any type arguments and value arguments.
4275         Warner noteWarner = new Warner();
4276         try {
4277             Type owntype = rs.checkMethod(
4278                     env,
4279                     site,
4280                     sym,
4281                     resultInfo,
4282                     argtypes,
4283                     typeargtypes,
4284                     noteWarner);
4285 
4286             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4287                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4288 
4289             argtypes = argtypes.map(checkDeferredMap);
4290 
4291             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4292                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym),
4293                         sym.name,
4294                         rs.methodArguments(sym.type.getParameterTypes()),
4295                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4296                         kindName(sym.location()),
4297                         sym.location()));
4298                 if (resultInfo.pt != Infer.anyPoly ||
4299                         !owntype.hasTag(METHOD) ||
4300                         !owntype.isPartial()) {
4301                     //if this is not a partially inferred method type, erase return type. Otherwise,
4302                     //erasure is carried out in PartiallyInferredMethodType.check().
4303                     owntype = new MethodType(owntype.getParameterTypes(),
4304                             types.erasure(owntype.getReturnType()),
4305                             types.erasure(owntype.getThrownTypes()),
4306                             syms.methodClass);
4307                 }
4308             }
4309 
4310             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4311                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4312                  PolyKind.POLY : PolyKind.STANDALONE;
4313             TreeInfo.setPolyKind(env.tree, pkind);
4314 
4315             return (resultInfo.pt == Infer.anyPoly) ?
4316                     owntype :
4317                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4318                             resultInfo.checkContext.inferenceContext());
4319         } catch (Infer.InferenceException ex) {
4320             //invalid target type - propagate exception outwards or report error
4321             //depending on the current check context
4322             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4323             return types.createErrorType(site);
4324         } catch (Resolve.InapplicableMethodException ex) {
4325             final JCDiagnostic diag = ex.getDiagnostic();
4326             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4327                 @Override
4328                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4329                     return new Pair<>(sym, diag);
4330                 }
4331             };
4332             List<Type> argtypes2 = argtypes.map(
4333                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4334             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4335                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4336             log.report(errDiag);
4337             return types.createErrorType(site);
4338         }
4339     }
4340 
4341     public void visitLiteral(JCLiteral tree) {
4342         result = check(tree, litType(tree.typetag).constType(tree.value),
4343                 KindSelector.VAL, resultInfo);
4344     }
4345     //where
4346     /** Return the type of a literal with given type tag.
4347      */
4348     Type litType(TypeTag tag) {
4349         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4350     }
4351 
4352     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4353         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4354     }
4355 
4356     public void visitTypeArray(JCArrayTypeTree tree) {
4357         Type etype = attribType(tree.elemtype, env);
4358         Type type = new ArrayType(etype, syms.arrayClass);
4359         result = check(tree, type, KindSelector.TYP, resultInfo);
4360     }
4361 
4362     /** Visitor method for parameterized types.
4363      *  Bound checking is left until later, since types are attributed
4364      *  before supertype structure is completely known
4365      */
4366     public void visitTypeApply(JCTypeApply tree) {
4367         Type owntype = types.createErrorType(tree.type);
4368 
4369         // Attribute functor part of application and make sure it's a class.
4370         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
4371 
4372         // Attribute type parameters
4373         List<Type> actuals = attribTypes(tree.arguments, env);
4374 
4375         if (clazztype.hasTag(CLASS)) {
4376             List<Type> formals = clazztype.tsym.type.getTypeArguments();
4377             if (actuals.isEmpty()) //diamond
4378                 actuals = formals;
4379 
4380             if (actuals.length() == formals.length()) {
4381                 List<Type> a = actuals;
4382                 List<Type> f = formals;
4383                 while (a.nonEmpty()) {
4384                     a.head = a.head.withTypeVar(f.head);
4385                     a = a.tail;
4386                     f = f.tail;
4387                 }
4388                 // Compute the proper generic outer
4389                 Type clazzOuter = clazztype.getEnclosingType();
4390                 if (clazzOuter.hasTag(CLASS)) {
4391                     Type site;
4392                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4393                     if (clazz.hasTag(IDENT)) {
4394                         site = env.enclClass.sym.type;
4395                     } else if (clazz.hasTag(SELECT)) {
4396                         site = ((JCFieldAccess) clazz).selected.type;
4397                     } else throw new AssertionError(""+tree);
4398                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4399                         if (site.hasTag(CLASS))
4400                             site = types.asOuterSuper(site, clazzOuter.tsym);
4401                         if (site == null)
4402                             site = types.erasure(clazzOuter);
4403                         clazzOuter = site;
4404                     }
4405                 }
4406                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4407                                         clazztype.getMetadata());
4408             } else {
4409                 if (formals.length() != 0) {
4410                     log.error(tree.pos(),
4411                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
4412                 } else {
4413                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
4414                 }
4415                 owntype = types.createErrorType(tree.type);
4416             }
4417         }
4418         result = check(tree, owntype, KindSelector.TYP, resultInfo);
4419     }
4420 
4421     public void visitTypeUnion(JCTypeUnion tree) {
4422         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4423         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4424         for (JCExpression typeTree : tree.alternatives) {
4425             Type ctype = attribType(typeTree, env);
4426             ctype = chk.checkType(typeTree.pos(),
4427                           chk.checkClassType(typeTree.pos(), ctype),
4428                           syms.throwableType);
4429             if (!ctype.isErroneous()) {
4430                 //check that alternatives of a union type are pairwise
4431                 //unrelated w.r.t. subtyping
4432                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
4433                     for (Type t : multicatchTypes) {
4434                         boolean sub = types.isSubtype(ctype, t);
4435                         boolean sup = types.isSubtype(t, ctype);
4436                         if (sub || sup) {
4437                             //assume 'a' <: 'b'
4438                             Type a = sub ? ctype : t;
4439                             Type b = sub ? t : ctype;
4440                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
4441                         }
4442                     }
4443                 }
4444                 multicatchTypes.append(ctype);
4445                 if (all_multicatchTypes != null)
4446                     all_multicatchTypes.append(ctype);
4447             } else {
4448                 if (all_multicatchTypes == null) {
4449                     all_multicatchTypes = new ListBuffer<>();
4450                     all_multicatchTypes.appendList(multicatchTypes);
4451                 }
4452                 all_multicatchTypes.append(ctype);
4453             }
4454         }
4455         Type t = check(tree, types.lub(multicatchTypes.toList()),
4456                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
4457         if (t.hasTag(CLASS)) {
4458             List<Type> alternatives =
4459                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
4460             t = new UnionClassType((ClassType) t, alternatives);
4461         }
4462         tree.type = result = t;
4463     }
4464 
4465     public void visitTypeIntersection(JCTypeIntersection tree) {
4466         attribTypes(tree.bounds, env);
4467         tree.type = result = checkIntersection(tree, tree.bounds);
4468     }
4469 
4470     public void visitTypeParameter(JCTypeParameter tree) {
4471         TypeVar typeVar = (TypeVar) tree.type;
4472 
4473         if (tree.annotations != null && tree.annotations.nonEmpty()) {
4474             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
4475         }
4476 
4477         if (!typeVar.getUpperBound().isErroneous()) {
4478             //fixup type-parameter bound computed in 'attribTypeVariables'
4479             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
4480         }
4481     }
4482 
4483     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
4484         Set<Type> boundSet = new HashSet<>();
4485         if (bounds.nonEmpty()) {
4486             // accept class or interface or typevar as first bound.
4487             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
4488             boundSet.add(types.erasure(bounds.head.type));
4489             if (bounds.head.type.isErroneous()) {
4490                 return bounds.head.type;
4491             }
4492             else if (bounds.head.type.hasTag(TYPEVAR)) {
4493                 // if first bound was a typevar, do not accept further bounds.
4494                 if (bounds.tail.nonEmpty()) {
4495                     log.error(bounds.tail.head.pos(),
4496                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
4497                     return bounds.head.type;
4498                 }
4499             } else {
4500                 // if first bound was a class or interface, accept only interfaces
4501                 // as further bounds.
4502                 for (JCExpression bound : bounds.tail) {
4503                     bound.type = checkBase(bound.type, bound, env, false, true, false);
4504                     if (bound.type.isErroneous()) {
4505                         bounds = List.of(bound);
4506                     }
4507                     else if (bound.type.hasTag(CLASS)) {
4508                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4509                     }
4510                 }
4511             }
4512         }
4513 
4514         if (bounds.length() == 0) {
4515             return syms.objectType;
4516         } else if (bounds.length() == 1) {
4517             return bounds.head.type;
4518         } else {
4519             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
4520             // ... the variable's bound is a class type flagged COMPOUND
4521             // (see comment for TypeVar.bound).
4522             // In this case, generate a class tree that represents the
4523             // bound class, ...
4524             JCExpression extending;
4525             List<JCExpression> implementing;
4526             if (!bounds.head.type.isInterface()) {
4527                 extending = bounds.head;
4528                 implementing = bounds.tail;
4529             } else {
4530                 extending = null;
4531                 implementing = bounds;
4532             }
4533             JCClassDecl cd = make.at(tree).ClassDef(
4534                 make.Modifiers(PUBLIC | ABSTRACT),
4535                 names.empty, List.nil(),
4536                 extending, implementing, List.nil());
4537 
4538             ClassSymbol c = (ClassSymbol)owntype.tsym;
4539             Assert.check((c.flags() & COMPOUND) != 0);
4540             cd.sym = c;
4541             c.sourcefile = env.toplevel.sourcefile;
4542 
4543             // ... and attribute the bound class
4544             c.flags_field |= UNATTRIBUTED;
4545             Env<AttrContext> cenv = enter.classEnv(cd, env);
4546             typeEnvs.put(c, cenv);
4547             attribClass(c);
4548             return owntype;
4549         }
4550     }
4551 
4552     public void visitWildcard(JCWildcard tree) {
4553         //- System.err.println("visitWildcard("+tree+");");//DEBUG
4554         Type type = (tree.kind.kind == BoundKind.UNBOUND)
4555             ? syms.objectType
4556             : attribType(tree.inner, env);
4557         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4558                                               tree.kind.kind,
4559                                               syms.boundClass),
4560                 KindSelector.TYP, resultInfo);
4561     }
4562 
4563     public void visitAnnotation(JCAnnotation tree) {
4564         Assert.error("should be handled in annotate");
4565     }
4566 
4567     public void visitAnnotatedType(JCAnnotatedType tree) {
4568         attribAnnotationTypes(tree.annotations, env);
4569         Type underlyingType = attribType(tree.underlyingType, env);
4570         Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
4571 
4572         if (!env.info.isNewClass)
4573             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
4574         result = tree.type = annotatedType;
4575     }
4576 
4577     public void visitErroneous(JCErroneous tree) {
4578         if (tree.errs != null)
4579             for (JCTree err : tree.errs)
4580                 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4581         result = tree.type = syms.errType;
4582     }
4583 
4584     /** Default visitor method for all other trees.
4585      */
4586     public void visitTree(JCTree tree) {
4587         throw new AssertionError();
4588     }
4589 
4590     /**
4591      * Attribute an env for either a top level tree or class or module declaration.
4592      */
4593     public void attrib(Env<AttrContext> env) {
4594         switch (env.tree.getTag()) {
4595             case MODULEDEF:
4596                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
4597                 break;
4598             case TOPLEVEL:
4599                 attribTopLevel(env);
4600                 break;
4601             case PACKAGEDEF:
4602                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
4603                 break;
4604             default:
4605                 attribClass(env.tree.pos(), env.enclClass.sym);
4606         }
4607     }
4608 
4609     /**
4610      * Attribute a top level tree. These trees are encountered when the
4611      * package declaration has annotations.
4612      */
4613     public void attribTopLevel(Env<AttrContext> env) {
4614         JCCompilationUnit toplevel = env.toplevel;
4615         try {
4616             annotate.flush();
4617         } catch (CompletionFailure ex) {
4618             chk.completionError(toplevel.pos(), ex);
4619         }
4620     }
4621 
4622     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
4623         try {
4624             annotate.flush();
4625             attribPackage(p);
4626         } catch (CompletionFailure ex) {
4627             chk.completionError(pos, ex);
4628         }
4629     }
4630 
4631     void attribPackage(PackageSymbol p) {
4632         Env<AttrContext> env = typeEnvs.get(p);
4633         chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p);
4634     }
4635 
4636     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
4637         try {
4638             annotate.flush();
4639             attribModule(m);
4640         } catch (CompletionFailure ex) {
4641             chk.completionError(pos, ex);
4642         }
4643     }
4644 
4645     void attribModule(ModuleSymbol m) {
4646         // Get environment current at the point of module definition.
4647         Env<AttrContext> env = enter.typeEnvs.get(m);
4648         attribStat(env.tree, env);
4649     }
4650 
4651     /** Main method: attribute class definition associated with given class symbol.
4652      *  reporting completion failures at the given position.
4653      *  @param pos The source position at which completion errors are to be
4654      *             reported.
4655      *  @param c   The class symbol whose definition will be attributed.
4656      */
4657     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4658         try {
4659             annotate.flush();
4660             attribClass(c);
4661         } catch (CompletionFailure ex) {
4662             chk.completionError(pos, ex);
4663         }
4664     }
4665 
4666     /** Attribute class definition associated with given class symbol.
4667      *  @param c   The class symbol whose definition will be attributed.
4668      */
4669     void attribClass(ClassSymbol c) throws CompletionFailure {
4670         if (c.type.hasTag(ERROR)) return;
4671 
4672         // Check for cycles in the inheritance graph, which can arise from
4673         // ill-formed class files.
4674         chk.checkNonCyclic(null, c.type);
4675 
4676         Type st = types.supertype(c.type);
4677         if ((c.flags_field & Flags.COMPOUND) == 0) {
4678             // First, attribute superclass.
4679             if (st.hasTag(CLASS))
4680                 attribClass((ClassSymbol)st.tsym);
4681 
4682             // Next attribute owner, if it is a class.
4683             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4684                 attribClass((ClassSymbol)c.owner);
4685         }
4686 
4687         // The previous operations might have attributed the current class
4688         // if there was a cycle. So we test first whether the class is still
4689         // UNATTRIBUTED.
4690         if ((c.flags_field & UNATTRIBUTED) != 0) {
4691             c.flags_field &= ~UNATTRIBUTED;
4692 
4693             // Get environment current at the point of class definition.
4694             Env<AttrContext> env = typeEnvs.get(c);
4695 
4696             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4697             // because the annotations were not available at the time the env was created. Therefore,
4698             // we look up the environment chain for the first enclosing environment for which the
4699             // lint value is set. Typically, this is the parent env, but might be further if there
4700             // are any envs created as a result of TypeParameter nodes.
4701             Env<AttrContext> lintEnv = env;
4702             while (lintEnv.info.lint == null)
4703                 lintEnv = lintEnv.next;
4704 
4705             // Having found the enclosing lint value, we can initialize the lint value for this class
4706             env.info.lint = lintEnv.info.lint.augment(c);
4707 
4708             Lint prevLint = chk.setLint(env.info.lint);
4709             JavaFileObject prev = log.useSource(c.sourcefile);
4710             ResultInfo prevReturnRes = env.info.returnResult;
4711 
4712             try {
4713                 deferredLintHandler.flush(env.tree);
4714                 env.info.returnResult = null;
4715                 // java.lang.Enum may not be subclassed by a non-enum
4716                 if (st.tsym == syms.enumSym &&
4717                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4718                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
4719 
4720                 // Enums may not be extended by source-level classes
4721                 if (st.tsym != null &&
4722                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4723                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4724                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
4725                 }
4726 
4727                 if (isSerializable(c.type)) {
4728                     env.info.isSerializable = true;
4729                 }
4730 
4731                 attribClassBody(env, c);
4732 
4733                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4734                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4735                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4736                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
4737             } finally {
4738                 env.info.returnResult = prevReturnRes;
4739                 log.useSource(prev);
4740                 chk.setLint(prevLint);
4741             }
4742 
4743         }
4744     }
4745 
4746     public void visitImport(JCImport tree) {
4747         // nothing to do
4748     }
4749 
4750     public void visitModuleDef(JCModuleDecl tree) {
4751         tree.sym.completeUsesProvides();
4752         ModuleSymbol msym = tree.sym;
4753         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
4754         Lint prevLint = chk.setLint(lint);
4755         chk.checkModuleName(tree);
4756         chk.checkDeprecatedAnnotation(tree, msym);
4757 
4758         try {
4759             deferredLintHandler.flush(tree.pos());
4760         } finally {
4761             chk.setLint(prevLint);
4762         }
4763     }
4764 
4765     /** Finish the attribution of a class. */
4766     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4767         JCClassDecl tree = (JCClassDecl)env.tree;
4768         Assert.check(c == tree.sym);
4769 
4770         // Validate type parameters, supertype and interfaces.
4771         attribStats(tree.typarams, env);
4772         if (!c.isAnonymous()) {
4773             //already checked if anonymous
4774             chk.validate(tree.typarams, env);
4775             chk.validate(tree.extending, env);
4776             chk.validate(tree.implementing, env);
4777         }
4778 
4779         c.markAbstractIfNeeded(types);
4780 
4781         // If this is a non-abstract class, check that it has no abstract
4782         // methods or unimplemented methods of an implemented interface.
4783         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4784             chk.checkAllDefined(tree.pos(), c);
4785         }
4786 
4787         if ((c.flags() & ANNOTATION) != 0) {
4788             if (tree.implementing.nonEmpty())
4789                 log.error(tree.implementing.head.pos(),
4790                           Errors.CantExtendIntfAnnotation);
4791             if (tree.typarams.nonEmpty()) {
4792                 log.error(tree.typarams.head.pos(),
4793                           Errors.IntfAnnotationCantHaveTypeParams(c));
4794             }
4795 
4796             // If this annotation type has a @Repeatable, validate
4797             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
4798             // If this annotation type has a @Repeatable, validate
4799             if (repeatable != null) {
4800                 // get diagnostic position for error reporting
4801                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4802                 Assert.checkNonNull(cbPos);
4803 
4804                 chk.validateRepeatable(c, repeatable, cbPos);
4805             }
4806         } else {
4807             // Check that all extended classes and interfaces
4808             // are compatible (i.e. no two define methods with same arguments
4809             // yet different return types).  (JLS 8.4.6.3)
4810             chk.checkCompatibleSupertypes(tree.pos(), c.type);
4811             if (allowDefaultMethods) {
4812                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4813             }
4814         }
4815 
4816         // Check that class does not import the same parameterized interface
4817         // with two different argument lists.
4818         chk.checkClassBounds(tree.pos(), c.type);
4819 
4820         tree.type = c.type;
4821 
4822         for (List<JCTypeParameter> l = tree.typarams;
4823              l.nonEmpty(); l = l.tail) {
4824              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4825         }
4826 
4827         // Check that a generic class doesn't extend Throwable
4828         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4829             log.error(tree.extending.pos(), Errors.GenericThrowable);
4830 
4831         // Check that all methods which implement some
4832         // method conform to the method they implement.
4833         chk.checkImplementations(tree);
4834 
4835         //check that a resource implementing AutoCloseable cannot throw InterruptedException
4836         checkAutoCloseable(tree.pos(), env, c.type);
4837 
4838         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4839             // Attribute declaration
4840             attribStat(l.head, env);
4841             // Check that declarations in inner classes are not static (JLS 8.1.2)
4842             // Make an exception for static constants.
4843             if (c.owner.kind != PCK &&
4844                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4845                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4846                 Symbol sym = null;
4847                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4848                 if (sym == null ||
4849                     sym.kind != VAR ||
4850                     ((VarSymbol) sym).getConstValue() == null)
4851                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
4852             }
4853         }
4854 
4855         // Check for cycles among non-initial constructors.
4856         chk.checkCyclicConstructors(tree);
4857 
4858         // Check for cycles among annotation elements.
4859         chk.checkNonCyclicElements(tree);
4860 
4861         // Check for proper use of serialVersionUID
4862         if (env.info.lint.isEnabled(LintCategory.SERIAL)
4863                 && isSerializable(c.type)
4864                 && (c.flags() & (Flags.ENUM | Flags.INTERFACE)) == 0
4865                 && !c.isAnonymous()) {
4866             checkSerialVersionUID(tree, c);
4867         }
4868         if (allowTypeAnnos) {
4869             // Correctly organize the postions of the type annotations
4870             typeAnnotations.organizeTypeAnnotationsBodies(tree);
4871 
4872             // Check type annotations applicability rules
4873             validateTypeAnnotations(tree, false);
4874         }
4875     }
4876         // where
4877         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4878         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4879             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4880                 if (types.isSameType(al.head.annotationType.type, t))
4881                     return al.head.pos();
4882             }
4883 
4884             return null;
4885         }
4886 
4887         /** check if a type is a subtype of Serializable, if that is available. */
4888         boolean isSerializable(Type t) {
4889             try {
4890                 syms.serializableType.complete();
4891             }
4892             catch (CompletionFailure e) {
4893                 return false;
4894             }
4895             return types.isSubtype(t, syms.serializableType);
4896         }
4897 
4898         /** Check that an appropriate serialVersionUID member is defined. */
4899         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4900 
4901             // check for presence of serialVersionUID
4902             VarSymbol svuid = null;
4903             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4904                 if (sym.kind == VAR) {
4905                     svuid = (VarSymbol)sym;
4906                     break;
4907                 }
4908             }
4909 
4910             if (svuid == null) {
4911                 log.warning(LintCategory.SERIAL,
4912                         tree.pos(), Warnings.MissingSVUID(c));
4913                 return;
4914             }
4915 
4916             // check that it is static final
4917             if ((svuid.flags() & (STATIC | FINAL)) !=
4918                 (STATIC | FINAL))
4919                 log.warning(LintCategory.SERIAL,
4920                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ImproperSVUID(c));
4921 
4922             // check that it is long
4923             else if (!svuid.type.hasTag(LONG))
4924                 log.warning(LintCategory.SERIAL,
4925                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.LongSVUID(c));
4926 
4927             // check constant
4928             else if (svuid.getConstValue() == null)
4929                 log.warning(LintCategory.SERIAL,
4930                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ConstantSVUID(c));
4931         }
4932 
4933     private Type capture(Type type) {
4934         return types.capture(type);
4935     }
4936 
4937     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
4938         if (type.isErroneous()) {
4939             tree.vartype = make.at(Position.NOPOS).Erroneous();
4940         } else {
4941             tree.vartype = make.at(Position.NOPOS).Type(type);
4942         }
4943     }
4944 
4945     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4946         tree.accept(new TypeAnnotationsValidator(sigOnly));
4947     }
4948     //where
4949     private final class TypeAnnotationsValidator extends TreeScanner {
4950 
4951         private final boolean sigOnly;
4952         public TypeAnnotationsValidator(boolean sigOnly) {
4953             this.sigOnly = sigOnly;
4954         }
4955 
4956         public void visitAnnotation(JCAnnotation tree) {
4957             chk.validateTypeAnnotation(tree, false);
4958             super.visitAnnotation(tree);
4959         }
4960         public void visitAnnotatedType(JCAnnotatedType tree) {
4961             if (!tree.underlyingType.type.isErroneous()) {
4962                 super.visitAnnotatedType(tree);
4963             }
4964         }
4965         public void visitTypeParameter(JCTypeParameter tree) {
4966             chk.validateTypeAnnotations(tree.annotations, true);
4967             scan(tree.bounds);
4968             // Don't call super.
4969             // This is needed because above we call validateTypeAnnotation with
4970             // false, which would forbid annotations on type parameters.
4971             // super.visitTypeParameter(tree);
4972         }
4973         public void visitMethodDef(JCMethodDecl tree) {
4974             if (tree.recvparam != null &&
4975                     !tree.recvparam.vartype.type.isErroneous()) {
4976                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4977                         tree.recvparam.vartype.type.tsym);
4978             }
4979             if (tree.restype != null && tree.restype.type != null) {
4980                 validateAnnotatedType(tree.restype, tree.restype.type);
4981             }
4982             if (sigOnly) {
4983                 scan(tree.mods);
4984                 scan(tree.restype);
4985                 scan(tree.typarams);
4986                 scan(tree.recvparam);
4987                 scan(tree.params);
4988                 scan(tree.thrown);
4989             } else {
4990                 scan(tree.defaultValue);
4991                 scan(tree.body);
4992             }
4993         }
4994         public void visitVarDef(final JCVariableDecl tree) {
4995             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4996             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
4997                 validateAnnotatedType(tree.vartype, tree.sym.type);
4998             scan(tree.mods);
4999             scan(tree.vartype);
5000             if (!sigOnly) {
5001                 scan(tree.init);
5002             }
5003         }
5004         public void visitTypeCast(JCTypeCast tree) {
5005             if (tree.clazz != null && tree.clazz.type != null)
5006                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5007             super.visitTypeCast(tree);
5008         }
5009         public void visitTypeTest(JCInstanceOf tree) {
5010             if (tree.clazz != null && tree.clazz.type != null)
5011                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5012             super.visitTypeTest(tree);
5013         }
5014         public void visitNewClass(JCNewClass tree) {
5015             if (tree.clazz != null && tree.clazz.type != null) {
5016                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5017                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5018                             tree.clazz.type.tsym);
5019                 }
5020                 if (tree.def != null) {
5021                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5022                 }
5023 
5024                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5025             }
5026             super.visitNewClass(tree);
5027         }
5028         public void visitNewArray(JCNewArray tree) {
5029             if (tree.elemtype != null && tree.elemtype.type != null) {
5030                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5031                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5032                             tree.elemtype.type.tsym);
5033                 }
5034                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5035             }
5036             super.visitNewArray(tree);
5037         }
5038         public void visitClassDef(JCClassDecl tree) {
5039             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5040             if (sigOnly) {
5041                 scan(tree.mods);
5042                 scan(tree.typarams);
5043                 scan(tree.extending);
5044                 scan(tree.implementing);
5045             }
5046             for (JCTree member : tree.defs) {
5047                 if (member.hasTag(Tag.CLASSDEF)) {
5048                     continue;
5049                 }
5050                 scan(member);
5051             }
5052         }
5053         public void visitBlock(JCBlock tree) {
5054             if (!sigOnly) {
5055                 scan(tree.stats);
5056             }
5057         }
5058 
5059         /* I would want to model this after
5060          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5061          * and override visitSelect and visitTypeApply.
5062          * However, we only set the annotated type in the top-level type
5063          * of the symbol.
5064          * Therefore, we need to override each individual location where a type
5065          * can occur.
5066          */
5067         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5068             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5069 
5070             if (type.isPrimitiveOrVoid()) {
5071                 return;
5072             }
5073 
5074             JCTree enclTr = errtree;
5075             Type enclTy = type;
5076 
5077             boolean repeat = true;
5078             while (repeat) {
5079                 if (enclTr.hasTag(TYPEAPPLY)) {
5080                     List<Type> tyargs = enclTy.getTypeArguments();
5081                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5082                     if (trargs.length() > 0) {
5083                         // Nothing to do for diamonds
5084                         if (tyargs.length() == trargs.length()) {
5085                             for (int i = 0; i < tyargs.length(); ++i) {
5086                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5087                             }
5088                         }
5089                         // If the lengths don't match, it's either a diamond
5090                         // or some nested type that redundantly provides
5091                         // type arguments in the tree.
5092                     }
5093 
5094                     // Look at the clazz part of a generic type
5095                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5096                 }
5097 
5098                 if (enclTr.hasTag(SELECT)) {
5099                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5100                     if (enclTy != null &&
5101                             !enclTy.hasTag(NONE)) {
5102                         enclTy = enclTy.getEnclosingType();
5103                     }
5104                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5105                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5106                     if (enclTy == null || enclTy.hasTag(NONE)) {
5107                         if (at.getAnnotations().size() == 1) {
5108                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping1(at.getAnnotations().head.attribute));
5109                         } else {
5110                             ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
5111                             for (JCAnnotation an : at.getAnnotations()) {
5112                                 comps.add(an.attribute);
5113                             }
5114                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping(comps.toList()));
5115                         }
5116                         repeat = false;
5117                     }
5118                     enclTr = at.underlyingType;
5119                     // enclTy doesn't need to be changed
5120                 } else if (enclTr.hasTag(IDENT)) {
5121                     repeat = false;
5122                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5123                     JCWildcard wc = (JCWildcard) enclTr;
5124                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5125                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5126                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5127                     } else {
5128                         // Nothing to do for UNBOUND
5129                     }
5130                     repeat = false;
5131                 } else if (enclTr.hasTag(TYPEARRAY)) {
5132                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5133                     validateAnnotatedType(art.getType(), art.elemtype.type);
5134                     repeat = false;
5135                 } else if (enclTr.hasTag(TYPEUNION)) {
5136                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5137                     for (JCTree t : ut.getTypeAlternatives()) {
5138                         validateAnnotatedType(t, t.type);
5139                     }
5140                     repeat = false;
5141                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5142                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5143                     for (JCTree t : it.getBounds()) {
5144                         validateAnnotatedType(t, t.type);
5145                     }
5146                     repeat = false;
5147                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5148                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5149                     repeat = false;
5150                 } else {
5151                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5152                             " within: "+ errtree + " with kind: " + errtree.getKind());
5153                 }
5154             }
5155         }
5156 
5157         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5158                 Symbol sym) {
5159             // Ensure that no declaration annotations are present.
5160             // Note that a tree type might be an AnnotatedType with
5161             // empty annotations, if only declaration annotations were given.
5162             // This method will raise an error for such a type.
5163             for (JCAnnotation ai : annotations) {
5164                 if (!ai.type.isErroneous() &&
5165                         typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5166                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5167                 }
5168             }
5169         }
5170     }
5171 
5172     // <editor-fold desc="post-attribution visitor">
5173 
5174     /**
5175      * Handle missing types/symbols in an AST. This routine is useful when
5176      * the compiler has encountered some errors (which might have ended up
5177      * terminating attribution abruptly); if the compiler is used in fail-over
5178      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5179      * prevents NPE to be progagated during subsequent compilation steps.
5180      */
5181     public void postAttr(JCTree tree) {
5182         new PostAttrAnalyzer().scan(tree);
5183     }
5184 
5185     class PostAttrAnalyzer extends TreeScanner {
5186 
5187         private void initTypeIfNeeded(JCTree that) {
5188             if (that.type == null) {
5189                 if (that.hasTag(METHODDEF)) {
5190                     that.type = dummyMethodType((JCMethodDecl)that);
5191                 } else {
5192                     that.type = syms.unknownType;
5193                 }
5194             }
5195         }
5196 
5197         /* Construct a dummy method type. If we have a method declaration,
5198          * and the declared return type is void, then use that return type
5199          * instead of UNKNOWN to avoid spurious error messages in lambda
5200          * bodies (see:JDK-8041704).
5201          */
5202         private Type dummyMethodType(JCMethodDecl md) {
5203             Type restype = syms.unknownType;
5204             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5205                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5206                 if (prim.typetag == VOID)
5207                     restype = syms.voidType;
5208             }
5209             return new MethodType(List.nil(), restype,
5210                                   List.nil(), syms.methodClass);
5211         }
5212         private Type dummyMethodType() {
5213             return dummyMethodType(null);
5214         }
5215 
5216         @Override
5217         public void scan(JCTree tree) {
5218             if (tree == null) return;
5219             if (tree instanceof JCExpression) {
5220                 initTypeIfNeeded(tree);
5221             }
5222             super.scan(tree);
5223         }
5224 
5225         @Override
5226         public void visitIdent(JCIdent that) {
5227             if (that.sym == null) {
5228                 that.sym = syms.unknownSymbol;
5229             }
5230         }
5231 
5232         @Override
5233         public void visitSelect(JCFieldAccess that) {
5234             if (that.sym == null) {
5235                 that.sym = syms.unknownSymbol;
5236             }
5237             super.visitSelect(that);
5238         }
5239 
5240         @Override
5241         public void visitClassDef(JCClassDecl that) {
5242             initTypeIfNeeded(that);
5243             if (that.sym == null) {
5244                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
5245             }
5246             super.visitClassDef(that);
5247         }
5248 
5249         @Override
5250         public void visitMethodDef(JCMethodDecl that) {
5251             initTypeIfNeeded(that);
5252             if (that.sym == null) {
5253                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
5254             }
5255             super.visitMethodDef(that);
5256         }
5257 
5258         @Override
5259         public void visitVarDef(JCVariableDecl that) {
5260             initTypeIfNeeded(that);
5261             if (that.sym == null) {
5262                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
5263                 that.sym.adr = 0;
5264             }
5265             if (that.vartype == null) {
5266                 that.vartype = make.at(Position.NOPOS).Erroneous();
5267             }
5268             super.visitVarDef(that);
5269         }
5270 
5271         @Override
5272         public void visitNewClass(JCNewClass that) {
5273             if (that.constructor == null) {
5274                 that.constructor = new MethodSymbol(0, names.init,
5275                         dummyMethodType(), syms.noSymbol);
5276             }
5277             if (that.constructorType == null) {
5278                 that.constructorType = syms.unknownType;
5279             }
5280             super.visitNewClass(that);
5281         }
5282 
5283         @Override
5284         public void visitAssignop(JCAssignOp that) {
5285             if (that.operator == null) {
5286                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5287                         -1, syms.noSymbol);
5288             }
5289             super.visitAssignop(that);
5290         }
5291 
5292         @Override
5293         public void visitBinary(JCBinary that) {
5294             if (that.operator == null) {
5295                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5296                         -1, syms.noSymbol);
5297             }
5298             super.visitBinary(that);
5299         }
5300 
5301         @Override
5302         public void visitUnary(JCUnary that) {
5303             if (that.operator == null) {
5304                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5305                         -1, syms.noSymbol);
5306             }
5307             super.visitUnary(that);
5308         }
5309 
5310         @Override
5311         public void visitReference(JCMemberReference that) {
5312             super.visitReference(that);
5313             if (that.sym == null) {
5314                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
5315                         syms.noSymbol);
5316             }
5317         }
5318     }
5319     // </editor-fold>
5320 
5321     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
5322         new TreeScanner() {
5323             Symbol packge = pkg;
5324             @Override
5325             public void visitIdent(JCIdent that) {
5326                 that.sym = packge;
5327             }
5328 
5329             @Override
5330             public void visitSelect(JCFieldAccess that) {
5331                 that.sym = packge;
5332                 packge = packge.owner;
5333                 super.visitSelect(that);
5334             }
5335         }.scan(pid);
5336     }
5337 
5338 }