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