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