1 /*
   2  * Copyright (c) 1999, 2026, 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.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                         } else if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR &&
1396                                 TreeInfo.isThisOrSelectorDotThis(subtree) &&
1397                                 TreeInfo.isExplicitThisReference(
1398                                         types,
1399                                         (ClassType)localEnv.enclClass.sym.type,
1400                                         subtree)) {
1401                             reportPrologueError(tree, sym);
1402                             return;
1403                         }
1404                     }
1405                 }
1406                 analyzeSymbol(tree);
1407             } else {
1408                 boolean prevLhs = isInLHS;
1409                 try {
1410                     isInLHS = false;
1411                     scan(ss.scanLater);
1412                 } finally {
1413                     isInLHS = prevLhs;
1414                 }
1415             }
1416             if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1417                 for (JCTree subtree : ss.selectorTrees) {
1418                     if (isInstanceField(subtree)) {
1419                         // we need to add a proxy for this one
1420                         localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(subtree));
1421                     }
1422                 }
1423             }
1424         }
1425 
1426         private boolean isInstanceField(JCTree tree) {
1427             Symbol sym = TreeInfo.symbolFor(tree);
1428             return (sym != null &&
1429                     !sym.isStatic() &&
1430                     sym.kind == VAR &&
1431                     sym.owner.kind == TYP &&
1432                     sym.name != names._this &&
1433                     sym.name != names._super &&
1434                     isEarlyReference(localEnv, tree, sym));
1435         }
1436 
1437         @Override
1438         public void visitNewClass(JCNewClass tree) {
1439             super.visitNewClass(tree);
1440             checkNewClassAndMethRefs(tree, tree.type);
1441         }
1442 
1443         @Override
1444         public void visitReference(JCMemberReference tree) {
1445             super.visitReference(tree);
1446             if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1447                 checkNewClassAndMethRefs(tree, tree.expr.type);
1448             }
1449         }
1450 
1451         void checkNewClassAndMethRefs(JCTree tree, Type t) {
1452             if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1453                     !t.tsym.isStatic() &&
1454                     !t.tsym.isDirectlyOrIndirectlyLocal()) {
1455                 reportPrologueError(tree, t.getEnclosingType().tsym);
1456             }
1457         }
1458 
1459         /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1460          * for a proxy local variable later on
1461          */
1462         boolean isInLHS = false;
1463 
1464         @Override
1465         public void visitAssign(JCAssign tree) {
1466             boolean previousIsInLHS = isInLHS;
1467             try {
1468                 isInLHS = true;
1469                 scan(tree.lhs);
1470             } finally {
1471                 isInLHS = previousIsInLHS;
1472             }
1473             scan(tree.rhs);
1474         }
1475 
1476         @Override
1477         public void visitMethodDef(JCMethodDecl tree) {
1478             // ignore any declarative part, mainly to avoid scanning receiver parameters
1479             scan(tree.body);
1480         }
1481 
1482         void analyzeSymbol(JCTree tree) {
1483             Symbol sym = TreeInfo.symbolFor(tree);
1484             // make sure that there is a symbol and it is not static
1485             if (sym == null || sym.isStatic()) {
1486                 return;
1487             }
1488             if (isInLHS && !insideLambdaOrClassDef) {
1489                 // Check instance field assignments that appear in constructor prologues
1490                 if (isEarlyReference(localEnv, tree, sym)) {
1491                     // Field may not be inherited from a superclass
1492                     if (sym.owner != localEnv.enclClass.sym) {
1493                         reportPrologueError(tree, sym);
1494                         return;
1495                     }
1496                     // Field may not have an initializer
1497                     if ((sym.flags() & HASINIT) != 0) {
1498                         if (!localEnv.enclClass.sym.isValueClass() || !sym.type.hasTag(ARRAY) || !isIndexed) {
1499                             reportPrologueError(tree, sym, true);
1500                         }
1501                         return;
1502                     }
1503                     // cant reference an instance field before a this constructor
1504                     if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1505                         reportPrologueError(tree, sym);
1506                         return;
1507                     }
1508                 }
1509                 return;
1510             }
1511             tree = TreeInfo.skipParens(tree);
1512             if (sym.kind == VAR && sym.owner.kind == TYP) {
1513                 if (sym.name == names._this || sym.name == names._super) {
1514                     // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1515                     if (TreeInfo.isExplicitThisReference(
1516                             types,
1517                             (ClassType)localEnv.enclClass.sym.type,
1518                             tree)) {
1519                         reportPrologueError(tree, sym);
1520                     }
1521                 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1522                     if (sym.owner != localEnv.enclClass.sym) {
1523                         if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1524                                 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1525                             /* if we are dealing with a field that doesn't belong to the current class, but the
1526                              * field is inherited, this is an error. Unless, the super class is also an outer
1527                              * class and the field's qualifier refers to the outer class
1528                              */
1529                             if (tree.hasTag(IDENT) ||
1530                                 TreeInfo.isExplicitThisReference(
1531                                         types,
1532                                         (ClassType)localEnv.enclClass.sym.type,
1533                                         ((JCFieldAccess)tree).selected)) {
1534                                 reportPrologueError(tree, sym);
1535                             }
1536                         }
1537                     } else if (isEarlyReference(localEnv, tree, sym)) {
1538                         /* now this is a `proper` instance field of the current class
1539                          * references to fields of identity classes which happen to have initializers are
1540                          * not allowed in the prologue.
1541                          * But it is OK for a field with initializer to refer to another field with initializer,
1542                          * so no warning or error if we are analyzing a field initializer.
1543                          */
1544                         if (insideLambdaOrClassDef ||
1545                             (!localEnv.enclClass.sym.isValueClass() &&
1546                              (sym.flags_field & HASINIT) != 0 &&
1547                              !isInitializer))
1548                             reportPrologueError(tree, sym);
1549                         // we will need to generate a proxy for this field later on
1550                         if (!isInLHS) {
1551                             if (!allowValueClasses) {
1552                                 reportPrologueError(tree, sym);
1553                             } else {
1554                                 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1555                                     reportPrologueError(tree, sym);
1556                                 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR && isInstanceField(tree)) {
1557                                     localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1558                                 }
1559                                 /* we do nothing in warnings only mode, as in that mode we are simulating what
1560                                  * the compiler would do in case the constructor code would be in the prologue
1561                                  * phase
1562                                  */
1563                             }
1564                         }
1565                     }
1566                 }
1567             }
1568         }
1569 
1570         /**
1571          * Determine if the symbol appearance constitutes an early reference to the current class.
1572          *
1573          * <p>
1574          * This means the symbol is an instance field, or method, of the current class and it appears
1575          * in an early initialization context of it (i.e., one of its constructor prologues).
1576          *
1577          * @param env    The current environment
1578          * @param tree   the AST referencing the variable
1579          * @param sym    The symbol
1580          */
1581         private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1582             if ((sym.kind == VAR || sym.kind == MTH) &&
1583                     sym.isMemberOf(env.enclClass.sym, types) &&
1584                     ((sym.flags() & STATIC) == 0 ||
1585                     (sym.kind == MTH && tree instanceof JCFieldAccess))) {
1586                 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1587                 if (tree instanceof JCFieldAccess fa) {
1588                     return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1589                 } else if (currentClassSym != env.enclClass.sym) {
1590                     /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1591                      * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1592                      * otherwise it is not.
1593                      * It could be that the reference to CI's member happens inside CI's own prologue, but that
1594                      * will be checked separately, when CI's prologue is analyzed.
1595                      */
1596                     return !sym.isMemberOf(currentClassSym, types);
1597                 }
1598                 return true;
1599             }
1600             return false;
1601         }
1602 
1603         /* scanner for a select expression, anything that is not a select or identifier
1604          * will be stored for further analysis
1605          */
1606         class SelectScanner extends DeferredAttr.FilterScanner {
1607             JCTree scanLater;
1608             java.util.List<JCTree> selectorTrees = new ArrayList<>();
1609 
1610             SelectScanner() {
1611                 super(Set.of(IDENT, SELECT, PARENS));
1612             }
1613 
1614             @Override
1615             public void visitSelect(JCFieldAccess tree) {
1616                 super.visitSelect(tree);
1617                 selectorTrees.add(tree.selected);
1618             }
1619 
1620             @Override
1621             void skip(JCTree tree) {
1622                 scanLater = tree;
1623             }
1624         }
1625     }
1626 
1627     public void visitVarDef(JCVariableDecl tree) {
1628         // Local variables have not been entered yet, so we need to do it now:
1629         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1630             if (tree.sym != null) {
1631                 // parameters have already been entered
1632                 env.info.scope.enter(tree.sym);
1633             } else {
1634                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1635                     if (tree.init == null) {
1636                         //cannot use 'var' without initializer
1637                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1638                         tree.vartype = make.at(tree.pos()).Erroneous();
1639                     } else {
1640                         Fragment msg = canInferLocalVarType(tree);
1641                         if (msg != null) {
1642                             //cannot use 'var' with initializer which require an explicit target
1643                             //(e.g. lambda, method reference, array initializer).
1644                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1645                             tree.vartype = make.at(tree.pos()).Erroneous();
1646                         }
1647                     }
1648                 }
1649                 try {
1650                     annotate.blockAnnotations();
1651                     memberEnter.memberEnter(tree, env);
1652                 } finally {
1653                     annotate.unblockAnnotations();
1654                 }
1655             }
1656         } else {
1657             doQueueScanTreeAndTypeAnnotateForVarInit(tree, env);
1658         }
1659 
1660         VarSymbol v = tree.sym;
1661         Lint lint = env.info.lint.augment(v);
1662         Lint prevLint = chk.setLint(lint);
1663 
1664         // Check that the variable's declared type is well-formed.
1665         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1666                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1667                 (tree.sym.flags() & PARAMETER) != 0;
1668         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1669 
1670         try {
1671             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1672             chk.checkDeprecatedAnnotation(tree.pos(), v);
1673 
1674             if (tree.init != null) {
1675                 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1676                 if ((v.flags_field & FINAL) == 0 ||
1677                     !memberEnter.needsLazyConstValue(tree.init)) {
1678                     // Not a compile-time constant
1679                     // Attribute initializer in a new environment
1680                     // with the declared variable as owner.
1681                     // Check that initializer conforms to variable's declared type.

1682                     initEnv.info.lint = lint;
1683                     // In order to catch self-references, we set the variable's
1684                     // declaration position to maximal possible value, effectively
1685                     // marking the variable as undefined.
1686                     initEnv.info.enclVar = v;
1687                     boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1688                     try {
1689                         if (v.owner.kind == TYP && !v.isStatic() && v.isStrict()) {
1690                             // strict instance initializer in a value class
1691                             initEnv.info.ctorPrologue = true;
1692                         }
1693                         attribExpr(tree.init, initEnv, v.type);
1694                         if (tree.isImplicitlyTyped()) {
1695                             //fixup local variable type
1696                             v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1697                         }
1698                     } finally {
1699                         initEnv.info.ctorPrologue = previousCtorPrologue;
1700                     }
1701                 }
1702                 if (allowValueClasses && v.owner.kind == TYP && !v.isStatic()) {
1703                     // strict field initializers are inlined in constructor's prologues
1704                     CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(initEnv,
1705                             !v.isStrict() ? PrologueVisitorMode.WARNINGS_ONLY : PrologueVisitorMode.SUPER_CONSTRUCTOR,
1706                             true);
1707                     ctorPrologueVisitor.scan(tree.init);
1708                 }
1709                 if (tree.isImplicitlyTyped()) {
1710                     setSyntheticVariableType(tree, v.type);
1711                 }
1712             }
1713             result = tree.type = v.type;
1714             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1715                 if (isNonArgsMethodInObject(v.name)) {
1716                     log.error(tree, Errors.IllegalRecordComponentName(v));
1717                 }
1718             }
1719             chk.checkRequiresIdentity(tree, env.info.lint);
1720         }
1721         finally {
1722             chk.setLint(prevLint);
1723         }
1724     }
1725 
1726     private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1727         if (tree.init != null &&
1728             (tree.mods.flags & Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED) == 0 &&
1729             env.info.scope.owner.kind != MTH && env.info.scope.owner.kind != VAR) {
1730             tree.mods.flags |= Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED;
1731             // Field initializer expression need to be entered.
1732             annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym);
1733             annotate.flush();
1734         }
1735     }
1736 
1737     private boolean isNonArgsMethodInObject(Name name) {
1738         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1739             if (s.type.getParameterTypes().isEmpty()) {
1740                 return true;
1741             }
1742         }
1743         return false;
1744     }
1745 
1746     Fragment canInferLocalVarType(JCVariableDecl tree) {
1747         LocalInitScanner lis = new LocalInitScanner();
1748         lis.scan(tree.init);
1749         return lis.badInferenceMsg;
1750     }
1751 
1752     static class LocalInitScanner extends TreeScanner {
1753         Fragment badInferenceMsg = null;
1754         boolean needsTarget = true;
1755 
1756         @Override
1757         public void visitNewArray(JCNewArray tree) {
1758             if (tree.elemtype == null && needsTarget) {
1759                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1760             }
1761         }
1762 
1763         @Override
1764         public void visitLambda(JCLambda tree) {
1765             if (needsTarget) {
1766                 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1767             }
1768         }
1769 
1770         @Override
1771         public void visitTypeCast(JCTypeCast tree) {
1772             boolean prevNeedsTarget = needsTarget;
1773             try {
1774                 needsTarget = false;
1775                 super.visitTypeCast(tree);
1776             } finally {
1777                 needsTarget = prevNeedsTarget;
1778             }
1779         }
1780 
1781         @Override
1782         public void visitReference(JCMemberReference tree) {
1783             if (needsTarget) {
1784                 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1785             }
1786         }
1787 
1788         @Override
1789         public void visitNewClass(JCNewClass tree) {
1790             boolean prevNeedsTarget = needsTarget;
1791             try {
1792                 needsTarget = false;
1793                 super.visitNewClass(tree);
1794             } finally {
1795                 needsTarget = prevNeedsTarget;
1796             }
1797         }
1798 
1799         @Override
1800         public void visitApply(JCMethodInvocation tree) {
1801             boolean prevNeedsTarget = needsTarget;
1802             try {
1803                 needsTarget = false;
1804                 super.visitApply(tree);
1805             } finally {
1806                 needsTarget = prevNeedsTarget;
1807             }
1808         }
1809     }
1810 
1811     public void visitSkip(JCSkip tree) {
1812         result = null;
1813     }
1814 
1815     public void visitBlock(JCBlock tree) {
1816         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1817             // Block is a static or instance initializer;
1818             // let the owner of the environment be a freshly
1819             // created BLOCK-method.
1820             Symbol fakeOwner =
1821                 new MethodSymbol(tree.flags | BLOCK |
1822                     env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1823                     env.info.scope.owner);
1824             final Env<AttrContext> localEnv =
1825                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1826 
1827             if ((tree.flags & STATIC) != 0) {
1828                 localEnv.info.staticLevel++;
1829             } else {
1830                 localEnv.info.instanceInitializerBlock = true;
1831             }
1832             // Attribute all type annotations in the block
1833             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1834             annotate.flush();
1835             attribStats(tree.stats, localEnv);
1836 
1837             {
1838                 // Store init and clinit type annotations with the ClassSymbol
1839                 // to allow output in Gen.normalizeDefs.
1840                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1841                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1842                 if ((tree.flags & STATIC) != 0) {
1843                     cs.appendClassInitTypeAttributes(tas);
1844                 } else {
1845                     cs.appendInitTypeAttributes(tas);
1846                 }
1847             }
1848         } else {
1849             // Create a new local environment with a local scope.
1850             Env<AttrContext> localEnv =
1851                 env.dup(tree, env.info.dup(env.info.scope.dup()));
1852             try {
1853                 attribStats(tree.stats, localEnv);
1854             } finally {
1855                 localEnv.info.scope.leave();
1856             }
1857         }
1858         result = null;
1859     }
1860 
1861     public void visitDoLoop(JCDoWhileLoop tree) {
1862         attribStat(tree.body, env.dup(tree));
1863         attribExpr(tree.cond, env, syms.booleanType);
1864         handleLoopConditionBindings(matchBindings, tree, tree.body);
1865         result = null;
1866     }
1867 
1868     public void visitWhileLoop(JCWhileLoop tree) {
1869         attribExpr(tree.cond, env, syms.booleanType);
1870         MatchBindings condBindings = matchBindings;
1871         // include condition's bindings when true in the body:
1872         Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1873         try {
1874             attribStat(tree.body, whileEnv.dup(tree));
1875         } finally {
1876             whileEnv.info.scope.leave();
1877         }
1878         handleLoopConditionBindings(condBindings, tree, tree.body);
1879         result = null;
1880     }
1881 
1882     public void visitForLoop(JCForLoop tree) {
1883         Env<AttrContext> loopEnv =
1884             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1885         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1886         try {
1887             attribStats(tree.init, loopEnv);
1888             if (tree.cond != null) {
1889                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1890                 // include condition's bindings when true in the body and step:
1891                 condBindings = matchBindings;
1892             }
1893             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1894             try {
1895                 bodyEnv.tree = tree; // before, we were not in loop!
1896                 attribStats(tree.step, bodyEnv);
1897                 attribStat(tree.body, bodyEnv);
1898             } finally {
1899                 bodyEnv.info.scope.leave();
1900             }
1901             result = null;
1902         }
1903         finally {
1904             loopEnv.info.scope.leave();
1905         }
1906         handleLoopConditionBindings(condBindings, tree, tree.body);
1907     }
1908 
1909     /**
1910      * Include condition's bindings when false after the loop, if cannot get out of the loop
1911      */
1912     private void handleLoopConditionBindings(MatchBindings condBindings,
1913                                              JCStatement loop,
1914                                              JCStatement loopBody) {
1915         if (condBindings.bindingsWhenFalse.nonEmpty() &&
1916             !breaksTo(env, loop, loopBody)) {
1917             addBindings2Scope(loop, condBindings.bindingsWhenFalse);
1918         }
1919     }
1920 
1921     private boolean breaksTo(Env<AttrContext> env, JCTree loop, JCTree body) {
1922         preFlow(body);
1923         return flow.breaksToTree(env, loop, body, make);
1924     }
1925 
1926     /**
1927      * Add given bindings to the current scope, unless there's a break to
1928      * an immediately enclosing labeled statement.
1929      */
1930     private void addBindings2Scope(JCStatement introducingStatement,
1931                                    List<BindingSymbol> bindings) {
1932         if (bindings.isEmpty()) {
1933             return ;
1934         }
1935 
1936         var searchEnv = env;
1937         while (searchEnv.tree instanceof JCLabeledStatement labeled &&
1938                labeled.body == introducingStatement) {
1939             if (breaksTo(env, labeled, labeled.body)) {
1940                 //breaking to an immediately enclosing labeled statement
1941                 return ;
1942             }
1943             searchEnv = searchEnv.next;
1944             introducingStatement = labeled;
1945         }
1946 
1947         //include condition's body when false after the while, if cannot get out of the loop
1948         bindings.forEach(env.info.scope::enter);
1949         bindings.forEach(BindingSymbol::preserveBinding);
1950     }
1951 
1952     public void visitForeachLoop(JCEnhancedForLoop tree) {
1953         Env<AttrContext> loopEnv =
1954             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1955         try {
1956             //the Formal Parameter of a for-each loop is not in the scope when
1957             //attributing the for-each expression; we mimic this by attributing
1958             //the for-each expression first (against original scope).
1959             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1960             chk.checkNonVoid(tree.pos(), exprType);
1961             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1962             if (elemtype == null) {
1963                 // or perhaps expr implements Iterable<T>?
1964                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1965                 if (base == null) {
1966                     log.error(tree.expr.pos(),
1967                               Errors.ForeachNotApplicableToType(exprType,
1968                                                                 Fragments.TypeReqArrayOrIterable));
1969                     elemtype = types.createErrorType(exprType);
1970                 } else {
1971                     List<Type> iterableParams = base.allparams();
1972                     elemtype = iterableParams.isEmpty()
1973                         ? syms.objectType
1974                         : types.wildUpperBound(iterableParams.head);
1975 
1976                     // Check the return type of the method iterator().
1977                     // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1978                     Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1979                             loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1980                     if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1981                         log.error(tree.pos(),
1982                                 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1983                     }
1984                 }
1985             }
1986             if (tree.var.isImplicitlyTyped()) {
1987                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1988                 setSyntheticVariableType(tree.var, inferredType);
1989             }
1990             attribStat(tree.var, loopEnv);
1991             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1992             loopEnv.tree = tree; // before, we were not in loop!
1993             attribStat(tree.body, loopEnv);
1994             result = null;
1995         }
1996         finally {
1997             loopEnv.info.scope.leave();
1998         }
1999     }
2000 
2001     public void visitLabelled(JCLabeledStatement tree) {
2002         // Check that label is not used in an enclosing statement
2003         Env<AttrContext> env1 = env;
2004         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
2005             if (env1.tree.hasTag(LABELLED) &&
2006                 ((JCLabeledStatement) env1.tree).label == tree.label) {
2007                 log.error(tree.pos(),
2008                           Errors.LabelAlreadyInUse(tree.label));
2009                 break;
2010             }
2011             env1 = env1.next;
2012         }
2013 
2014         attribStat(tree.body, env.dup(tree));
2015         result = null;
2016     }
2017 
2018     public void visitSwitch(JCSwitch tree) {
2019         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
2020             attribStats(c.stats, caseEnv);
2021         });
2022         result = null;
2023     }
2024 
2025     public void visitSwitchExpression(JCSwitchExpression tree) {
2026         boolean wrongContext = false;
2027 
2028         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
2029                 PolyKind.STANDALONE : PolyKind.POLY;
2030 
2031         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2032             //this means we are returning a poly conditional from void-compatible lambda expression
2033             resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
2034             resultInfo = recoveryInfo;
2035             wrongContext = true;
2036         }
2037 
2038         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2039                 unknownExprInfo :
2040                 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
2041 
2042         ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
2043         ListBuffer<Type> caseTypes = new ListBuffer<>();
2044 
2045         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
2046             caseEnv.info.yieldResult = condInfo;
2047             attribStats(c.stats, caseEnv);
2048             new TreeScanner() {
2049                 @Override
2050                 public void visitYield(JCYield brk) {
2051                     if (brk.target == tree) {
2052                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
2053                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
2054                     }
2055                     super.visitYield(brk);
2056                 }
2057 
2058                 @Override public void visitClassDef(JCClassDecl tree) {}
2059                 @Override public void visitLambda(JCLambda tree) {}
2060             }.scan(c.stats);
2061         });
2062 
2063         if (tree.cases.isEmpty()) {
2064             log.error(tree.pos(),
2065                       Errors.SwitchExpressionEmpty);
2066         } else if (caseTypes.isEmpty()) {
2067             log.error(tree.pos(),
2068                       Errors.SwitchExpressionNoResultExpressions);
2069         }
2070 
2071         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
2072 
2073         result = tree.type = wrongContext? types.createErrorType(pt()) : check(tree, owntype, KindSelector.VAL, resultInfo);
2074     }
2075     //where:
2076         CheckContext switchExpressionContext(CheckContext checkContext) {
2077             return new Check.NestedCheckContext(checkContext) {
2078                 //this will use enclosing check context to check compatibility of
2079                 //subexpression against target type; if we are in a method check context,
2080                 //depending on whether boxing is allowed, we could have incompatibilities
2081                 @Override
2082                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2083                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
2084                 }
2085             };
2086         }
2087 
2088     private void handleSwitch(JCTree switchTree,
2089                               JCExpression selector,
2090                               List<JCCase> cases,
2091                               BiConsumer<JCCase, Env<AttrContext>> attribCase) {
2092         Type seltype = attribExpr(selector, env);
2093         Type seltypeUnboxed = types.unboxedTypeOrType(seltype);
2094 
2095         Env<AttrContext> switchEnv =
2096             env.dup(switchTree, env.info.dup(env.info.scope.dup()));
2097 
2098         try {
2099             boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
2100             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
2101             boolean booleanSwitch = types.isSameType(seltypeUnboxed, syms.booleanType);
2102             boolean errorEnumSwitch = TreeInfo.isErrorEnumSwitch(selector, cases);
2103             boolean intSwitch = types.isAssignable(seltype, syms.intType);
2104             boolean patternSwitch;
2105             if (seltype.isPrimitive() && !intSwitch) {
2106                 preview.checkSourceLevel(selector.pos(), Feature.PRIMITIVE_PATTERNS);
2107                 patternSwitch = true;
2108             }
2109             if (!enumSwitch && !stringSwitch && !errorEnumSwitch &&
2110                 !intSwitch) {
2111                 preview.checkSourceLevel(selector.pos(), Feature.PATTERN_SWITCH);
2112                 patternSwitch = true;
2113             } else {
2114                 patternSwitch = cases.stream()
2115                                      .flatMap(c -> c.labels.stream())
2116                                      .anyMatch(l -> l.hasTag(PATTERNCASELABEL) ||
2117                                                     TreeInfo.isNullCaseLabel(l));
2118             }
2119 
2120             // Attribute all cases and
2121             // check that there are no duplicate case labels or default clauses.
2122             Set<Object> constants = new HashSet<>(); // The set of case constants.
2123             boolean hasDefault = false;           // Is there a default label?
2124             boolean hasUnconditionalPattern = false; // Is there a unconditional pattern?
2125             boolean lastPatternErroneous = false; // Has the last pattern erroneous type?
2126             boolean hasNullPattern = false;       // Is there a null pattern?
2127             CaseTree.CaseKind caseKind = null;
2128             boolean wasError = false;
2129             JCCaseLabel unconditionalCaseLabel = null;
2130             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
2131                 JCCase c = l.head;
2132                 if (caseKind == null) {
2133                     caseKind = c.caseKind;
2134                 } else if (caseKind != c.caseKind && !wasError) {
2135                     log.error(c.pos(),
2136                               Errors.SwitchMixingCaseTypes);
2137                     wasError = true;
2138                 }
2139                 MatchBindings currentBindings = null;
2140                 MatchBindings guardBindings = null;
2141                 for (List<JCCaseLabel> labels = c.labels; labels.nonEmpty(); labels = labels.tail) {
2142                     JCCaseLabel label = labels.head;
2143                     if (label instanceof JCConstantCaseLabel constLabel) {
2144                         JCExpression expr = constLabel.expr;
2145                         if (TreeInfo.isNull(expr)) {
2146                             preview.checkSourceLevel(expr.pos(), Feature.CASE_NULL);
2147                             if (hasNullPattern) {
2148                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
2149                             }
2150                             hasNullPattern = true;
2151                             attribExpr(expr, switchEnv, seltype);
2152                             matchBindings = new MatchBindings(matchBindings.bindingsWhenTrue, matchBindings.bindingsWhenFalse, true);
2153                         } else if (enumSwitch) {
2154                             Symbol sym = enumConstant(expr, seltype);
2155                             if (sym == null) {
2156                                 if (allowPatternSwitch) {
2157                                     attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
2158                                     Symbol enumSym = TreeInfo.symbol(expr);
2159                                     if (enumSym == null || !enumSym.isEnum() || enumSym.kind != VAR) {
2160                                         log.error(expr.pos(), Errors.EnumLabelMustBeEnumConstant);
2161                                     } else if (!constants.add(enumSym)) {
2162                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
2163                                     }
2164                                 } else {
2165                                     log.error(expr.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
2166                                 }
2167                             } else if (!constants.add(sym)) {
2168                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
2169                             }
2170                         } else if (errorEnumSwitch) {
2171                             //error recovery: the selector is erroneous, and all the case labels
2172                             //are identifiers. This could be an enum switch - don't report resolve
2173                             //error for the case label:
2174                             var prevResolveHelper = rs.basicLogResolveHelper;
2175                             try {
2176                                 rs.basicLogResolveHelper = rs.silentLogResolveHelper;
2177                                 attribExpr(expr, switchEnv, seltype);
2178                             } finally {
2179                                 rs.basicLogResolveHelper = prevResolveHelper;
2180                             }
2181                         } else {
2182                             Type pattype = attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
2183                             if (!pattype.hasTag(ERROR)) {
2184                                 if (pattype.constValue() == null) {
2185                                     Symbol s = TreeInfo.symbol(expr);
2186                                     if (s != null && s.kind == TYP) {
2187                                         log.error(expr.pos(),
2188                                                   Errors.PatternExpected);
2189                                     } else if (s == null || !s.isEnum()) {
2190                                         log.error(expr.pos(),
2191                                                   (stringSwitch ? Errors.StringConstReq
2192                                                                 : intSwitch ? Errors.ConstExprReq
2193                                                                             : Errors.PatternOrEnumReq));
2194                                     } else if (!constants.add(s)) {
2195                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
2196                                     }
2197                                 }
2198                                 else {
2199                                     boolean isLongFloatDoubleOrBooleanConstant =
2200                                             pattype.getTag().isInSuperClassesOf(LONG) || pattype.getTag().equals(BOOLEAN);
2201                                     if (isLongFloatDoubleOrBooleanConstant) {
2202                                         preview.checkSourceLevel(label.pos(), Feature.PRIMITIVE_PATTERNS);
2203                                     }
2204                                     if (!stringSwitch && !intSwitch && !(isLongFloatDoubleOrBooleanConstant && types.isSameType(seltypeUnboxed, pattype))) {
2205                                         log.error(label.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype));
2206                                     } else if (!constants.add(pattype.constValue())) {
2207                                         log.error(c.pos(), Errors.DuplicateCaseLabel);
2208                                     }
2209                                 }
2210                             }
2211                         }
2212                     } else if (label instanceof JCDefaultCaseLabel def) {
2213                         if (hasDefault) {
2214                             log.error(label.pos(), Errors.DuplicateDefaultLabel);
2215                         } else if (hasUnconditionalPattern) {
2216                             log.error(label.pos(), Errors.UnconditionalPatternAndDefault);
2217                         }  else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
2218                             log.error(label.pos(), Errors.DefaultAndBothBooleanValues);
2219                         }
2220                         hasDefault = true;
2221                         matchBindings = MatchBindingsComputer.EMPTY;
2222                     } else if (label instanceof JCPatternCaseLabel patternlabel) {
2223                         //pattern
2224                         JCPattern pat = patternlabel.pat;
2225                         attribExpr(pat, switchEnv, seltype);
2226                         Type primaryType = TreeInfo.primaryPatternType(pat);
2227 
2228                         if (primaryType.isPrimitive()) {
2229                             preview.checkSourceLevel(pat.pos(), Feature.PRIMITIVE_PATTERNS);
2230                         } else if (!primaryType.hasTag(TYPEVAR)) {
2231                             primaryType = chk.checkClassOrArrayType(pat.pos(), primaryType);
2232                         }
2233                         checkCastablePattern(pat.pos(), seltype, primaryType);
2234                         Type patternType = types.erasure(primaryType);
2235                         JCExpression guard = c.guard;
2236                         if (guardBindings == null && guard != null) {
2237                             MatchBindings afterPattern = matchBindings;
2238                             Env<AttrContext> bodyEnv = bindingEnv(switchEnv, matchBindings.bindingsWhenTrue);
2239                             try {
2240                                 attribExpr(guard, bodyEnv, syms.booleanType);
2241                             } finally {
2242                                 bodyEnv.info.scope.leave();
2243                             }
2244 
2245                             guardBindings = matchBindings;
2246                             matchBindings = afterPattern;
2247 
2248                             if (TreeInfo.isBooleanWithValue(guard, 0)) {
2249                                 log.error(guard.pos(), Errors.GuardHasConstantExpressionFalse);
2250                             }
2251                         }
2252                         boolean unguarded = TreeInfo.unguardedCase(c) && !pat.hasTag(RECORDPATTERN);
2253                         boolean unconditional =
2254                                 unguarded &&
2255                                 !patternType.isErroneous() &&
2256                                 types.isUnconditionallyExactTypeBased(seltype, patternType);
2257                         if (unconditional) {
2258                             if (hasUnconditionalPattern) {
2259                                 log.error(pat.pos(), Errors.DuplicateUnconditionalPattern);
2260                             } else if (hasDefault) {
2261                                 log.error(pat.pos(), Errors.UnconditionalPatternAndDefault);
2262                             } else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
2263                                 log.error(pat.pos(), Errors.UnconditionalPatternAndBothBooleanValues);
2264                             }
2265                             hasUnconditionalPattern = true;
2266                             unconditionalCaseLabel = label;
2267                         }
2268                         lastPatternErroneous = patternType.isErroneous();
2269                     } else {
2270                         Assert.error();
2271                     }
2272                     currentBindings = matchBindingsComputer.switchCase(label, currentBindings, matchBindings);
2273                 }
2274 
2275                 if (guardBindings != null) {
2276                     currentBindings = matchBindingsComputer.caseGuard(c, currentBindings, guardBindings);
2277                 }
2278 
2279                 Env<AttrContext> caseEnv =
2280                         bindingEnv(switchEnv, c, currentBindings.bindingsWhenTrue);
2281                 try {
2282                     attribCase.accept(c, caseEnv);
2283                 } finally {
2284                     caseEnv.info.scope.leave();
2285                 }
2286                 addVars(c.stats, switchEnv.info.scope);
2287 
2288                 preFlow(c);
2289                 c.completesNormally = flow.aliveAfter(caseEnv, c, make);
2290             }
2291             if (patternSwitch) {
2292                 chk.checkSwitchCaseStructure(cases);
2293                 chk.checkSwitchCaseLabelDominated(unconditionalCaseLabel, cases);
2294             }
2295             if (switchTree.hasTag(SWITCH)) {
2296                 ((JCSwitch) switchTree).hasUnconditionalPattern =
2297                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
2298                 ((JCSwitch) switchTree).patternSwitch = patternSwitch;
2299             } else if (switchTree.hasTag(SWITCH_EXPRESSION)) {
2300                 ((JCSwitchExpression) switchTree).hasUnconditionalPattern =
2301                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
2302                 ((JCSwitchExpression) switchTree).patternSwitch = patternSwitch;
2303             } else {
2304                 Assert.error(switchTree.getTag().name());
2305             }
2306         } finally {
2307             switchEnv.info.scope.leave();
2308         }
2309     }
2310     // where
2311         private ResultInfo caseLabelResultInfo(Type seltype) {
2312             return new ResultInfo(KindSelector.VAL_TYP,
2313                                   !seltype.hasTag(ERROR) ? seltype
2314                                                          : Type.noType);
2315         }
2316         /** Add any variables defined in stats to the switch scope. */
2317         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
2318             for (;stats.nonEmpty(); stats = stats.tail) {
2319                 JCTree stat = stats.head;
2320                 if (stat.hasTag(VARDEF))
2321                     switchScope.enter(((JCVariableDecl) stat).sym);
2322             }
2323         }
2324     // where
2325     /** Return the selected enumeration constant symbol, or null. */
2326     private Symbol enumConstant(JCTree tree, Type enumType) {
2327         if (tree.hasTag(IDENT)) {
2328             JCIdent ident = (JCIdent)tree;
2329             Name name = ident.name;
2330             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
2331                 if (sym.kind == VAR) {
2332                     Symbol s = ident.sym = sym;
2333                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
2334                     ident.type = s.type;
2335                     return ((s.flags_field & Flags.ENUM) == 0)
2336                         ? null : s;
2337                 }
2338             }
2339         }
2340         return null;
2341     }
2342 
2343     public void visitSynchronized(JCSynchronized tree) {
2344         boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
2345         if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
2346             log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
2347         }
2348         attribStat(tree.body, env);
2349         result = null;
2350     }
2351 
2352     public void visitTry(JCTry tree) {
2353         // Create a new local environment with a local
2354         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
2355         try {
2356             boolean isTryWithResource = tree.resources.nonEmpty();
2357             // Create a nested environment for attributing the try block if needed
2358             Env<AttrContext> tryEnv = isTryWithResource ?
2359                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
2360                 localEnv;
2361             try {
2362                 // Attribute resource declarations
2363                 for (JCTree resource : tree.resources) {
2364                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
2365                         @Override
2366                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
2367                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
2368                         }
2369                     };
2370                     ResultInfo twrResult =
2371                         new ResultInfo(KindSelector.VAR,
2372                                        syms.autoCloseableType,
2373                                        twrContext);
2374                     if (resource.hasTag(VARDEF)) {
2375                         attribStat(resource, tryEnv);
2376                         twrResult.check(resource, resource.type);
2377 
2378                         //check that resource type cannot throw InterruptedException
2379                         checkAutoCloseable(localEnv, resource, true);
2380 
2381                         VarSymbol var = ((JCVariableDecl) resource).sym;
2382 
2383                         var.flags_field |= Flags.FINAL;
2384                         var.setData(ElementKind.RESOURCE_VARIABLE);
2385                     } else {
2386                         attribTree(resource, tryEnv, twrResult);
2387                     }
2388                 }
2389                 // Attribute body
2390                 attribStat(tree.body, tryEnv);
2391             } finally {
2392                 if (isTryWithResource)
2393                     tryEnv.info.scope.leave();
2394             }
2395 
2396             // Attribute catch clauses
2397             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
2398                 JCCatch c = l.head;
2399                 Env<AttrContext> catchEnv =
2400                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
2401                 try {
2402                     Type ctype = attribStat(c.param, catchEnv);
2403                     if (TreeInfo.isMultiCatch(c)) {
2404                         //multi-catch parameter is implicitly marked as final
2405                         c.param.sym.flags_field |= FINAL | UNION;
2406                     }
2407                     if (c.param.sym.kind == VAR) {
2408                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
2409                     }
2410                     chk.checkType(c.param.vartype.pos(),
2411                                   chk.checkClassType(c.param.vartype.pos(), ctype),
2412                                   syms.throwableType);
2413                     attribStat(c.body, catchEnv);
2414                 } finally {
2415                     catchEnv.info.scope.leave();
2416                 }
2417             }
2418 
2419             // Attribute finalizer
2420             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
2421             result = null;
2422         }
2423         finally {
2424             localEnv.info.scope.leave();
2425         }
2426     }
2427 
2428     void checkAutoCloseable(Env<AttrContext> env, JCTree tree, boolean useSite) {
2429         DiagnosticPosition pos = tree.pos();
2430         Type resource = tree.type;
2431         if (!resource.isErroneous() &&
2432             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
2433             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2434             Symbol close = syms.noSymbol;
2435             Log.DiagnosticHandler discardHandler = log.new DiscardDiagnosticHandler();
2436             try {
2437                 close = rs.resolveQualifiedMethod(pos,
2438                         env,
2439                         types.skipTypeVars(resource, false),
2440                         names.close,
2441                         List.nil(),
2442                         List.nil());
2443             }
2444             finally {
2445                 log.popDiagnosticHandler(discardHandler);
2446             }
2447             if (close.kind == MTH &&
2448                     (useSite || close.owner != syms.autoCloseableType.tsym) &&
2449                     ((MethodSymbol)close).binaryOverrides(syms.autoCloseableClose, resource.tsym, types) &&
2450                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes())) {
2451                 if (!useSite && close.owner == resource.tsym) {
2452                     log.warning(TreeInfo.diagnosticPositionFor(close, tree),
2453                         LintWarnings.TryResourceCanThrowInterruptedExc(resource));
2454                 } else {
2455                     log.warning(pos, LintWarnings.TryResourceThrowsInterruptedExc(resource));
2456                 }
2457             }
2458         }
2459     }
2460 
2461     public void visitConditional(JCConditional tree) {
2462         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
2463         MatchBindings condBindings = matchBindings;
2464 
2465         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
2466                 isBooleanOrNumeric(env, tree)) ?
2467                 PolyKind.STANDALONE : PolyKind.POLY;
2468 
2469         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2470             //this means we are returning a poly conditional from void-compatible lambda expression
2471             resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
2472             result = tree.type = types.createErrorType(resultInfo.pt);
2473             return;
2474         }
2475 
2476         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2477                 unknownExprInfo :
2478                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
2479 
2480 
2481         // x ? y : z
2482         // include x's bindings when true in y
2483         // include x's bindings when false in z
2484 
2485         Type truetype;
2486         Env<AttrContext> trueEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2487         try {
2488             truetype = attribTree(tree.truepart, trueEnv, condInfo);
2489         } finally {
2490             trueEnv.info.scope.leave();
2491         }
2492 
2493         MatchBindings trueBindings = matchBindings;
2494 
2495         Type falsetype;
2496         Env<AttrContext> falseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2497         try {
2498             falsetype = attribTree(tree.falsepart, falseEnv, condInfo);
2499         } finally {
2500             falseEnv.info.scope.leave();
2501         }
2502 
2503         MatchBindings falseBindings = matchBindings;
2504 
2505         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
2506                 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
2507                          List.of(truetype, falsetype)) : pt();
2508         if (condtype.constValue() != null &&
2509                 truetype.constValue() != null &&
2510                 falsetype.constValue() != null &&
2511                 !owntype.hasTag(NONE)) {
2512             //constant folding
2513             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
2514         }
2515         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2516         matchBindings = matchBindingsComputer.conditional(tree, condBindings, trueBindings, falseBindings);
2517     }
2518     //where
2519         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
2520             switch (tree.getTag()) {
2521                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
2522                               ((JCLiteral)tree).typetag == BOOLEAN ||
2523                               ((JCLiteral)tree).typetag == BOT;
2524                 case LAMBDA: case REFERENCE: return false;
2525                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
2526                 case CONDEXPR:
2527                     JCConditional condTree = (JCConditional)tree;
2528                     return isBooleanOrNumeric(env, condTree.truepart) &&
2529                             isBooleanOrNumeric(env, condTree.falsepart);
2530                 case APPLY:
2531                     JCMethodInvocation speculativeMethodTree =
2532                             (JCMethodInvocation)deferredAttr.attribSpeculative(
2533                                     tree, env, unknownExprInfo,
2534                                     argumentAttr.withLocalCacheContext());
2535                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
2536                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
2537                             env.enclClass.type :
2538                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
2539                     Type owntype = types.memberType(receiverType, msym).getReturnType();
2540                     return primitiveOrBoxed(owntype);
2541                 case NEWCLASS:
2542                     JCExpression className =
2543                             removeClassParams.translate(((JCNewClass)tree).clazz);
2544                     JCExpression speculativeNewClassTree =
2545                             (JCExpression)deferredAttr.attribSpeculative(
2546                                     className, env, unknownTypeInfo,
2547                                     argumentAttr.withLocalCacheContext());
2548                     return primitiveOrBoxed(speculativeNewClassTree.type);
2549                 default:
2550                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
2551                             argumentAttr.withLocalCacheContext()).type;
2552                     return primitiveOrBoxed(speculativeType);
2553             }
2554         }
2555         //where
2556             boolean primitiveOrBoxed(Type t) {
2557                 return (!t.hasTag(TYPEVAR) && !t.isErroneous() && types.unboxedTypeOrType(t).isPrimitive());
2558             }
2559 
2560             TreeTranslator removeClassParams = new TreeTranslator() {
2561                 @Override
2562                 public void visitTypeApply(JCTypeApply tree) {
2563                     result = translate(tree.clazz);
2564                 }
2565             };
2566 
2567         CheckContext conditionalContext(CheckContext checkContext) {
2568             return new Check.NestedCheckContext(checkContext) {
2569                 //this will use enclosing check context to check compatibility of
2570                 //subexpression against target type; if we are in a method check context,
2571                 //depending on whether boxing is allowed, we could have incompatibilities
2572                 @Override
2573                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2574                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
2575                 }
2576             };
2577         }
2578 
2579         /** Compute the type of a conditional expression, after
2580          *  checking that it exists.  See JLS 15.25. Does not take into
2581          *  account the special case where condition and both arms
2582          *  are constants.
2583          *
2584          *  @param pos      The source position to be used for error
2585          *                  diagnostics.
2586          *  @param thentype The type of the expression's then-part.
2587          *  @param elsetype The type of the expression's else-part.
2588          */
2589         Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
2590             if (condTypes.isEmpty()) {
2591                 return syms.objectType; //TODO: how to handle?
2592             }
2593             Type first = condTypes.head;
2594             // If same type, that is the result
2595             if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
2596                 return first.baseType();
2597 
2598             List<Type> unboxedTypes = condTypes.stream()
2599                                                .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
2600                                                .collect(List.collector());
2601 
2602             // Otherwise, if both arms can be converted to a numeric
2603             // type, return the least numeric type that fits both arms
2604             // (i.e. return larger of the two, or return int if one
2605             // arm is short, the other is char).
2606             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2607                 // If one arm has an integer subrange type (i.e., byte,
2608                 // short, or char), and the other is an integer constant
2609                 // that fits into the subrange, return the subrange type.
2610                 for (Type type : unboxedTypes) {
2611                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2612                         continue;
2613                     }
2614                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2615                         return type.baseType();
2616                 }
2617 
2618                 for (TypeTag tag : primitiveTags) {
2619                     Type candidate = syms.typeOfTag[tag.ordinal()];
2620                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2621                         return candidate;
2622                     }
2623                 }
2624             }
2625 
2626             // Those were all the cases that could result in a primitive
2627             condTypes = condTypes.stream()
2628                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
2629                                  .collect(List.collector());
2630 
2631             for (Type type : condTypes) {
2632                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2633                     return type.baseType();
2634             }
2635 
2636             Iterator<DiagnosticPosition> posIt = positions.iterator();
2637 
2638             condTypes = condTypes.stream()
2639                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
2640                                  .collect(List.collector());
2641 
2642             // both are known to be reference types.  The result is
2643             // lub(thentype,elsetype). This cannot fail, as it will
2644             // always be possible to infer "Object" if nothing better.
2645             return types.lub(condTypes.stream()
2646                         .map(t -> t.baseType())
2647                         .filter(t -> !t.hasTag(BOT))
2648                         .collect(List.collector()));
2649         }
2650 
2651     static final TypeTag[] primitiveTags = new TypeTag[]{
2652         BYTE,
2653         CHAR,
2654         SHORT,
2655         INT,
2656         LONG,
2657         FLOAT,
2658         DOUBLE,
2659         BOOLEAN,
2660     };
2661 
2662     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2663         return bindingEnv(env, env.tree, bindings);
2664     }
2665 
2666     Env<AttrContext> bindingEnv(Env<AttrContext> env, JCTree newTree, List<BindingSymbol> bindings) {
2667         Env<AttrContext> env1 = env.dup(newTree, env.info.dup(env.info.scope.dup()));
2668         bindings.forEach(env1.info.scope::enter);
2669         return env1;
2670     }
2671 
2672     public void visitIf(JCIf tree) {
2673         attribExpr(tree.cond, env, syms.booleanType);
2674 
2675         // if (x) { y } [ else z ]
2676         // include x's bindings when true in y
2677         // include x's bindings when false in z
2678 
2679         MatchBindings condBindings = matchBindings;
2680         Env<AttrContext> thenEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2681 
2682         try {
2683             attribStat(tree.thenpart, thenEnv);
2684         } finally {
2685             thenEnv.info.scope.leave();
2686         }
2687 
2688         preFlow(tree.thenpart);
2689         boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make);
2690         boolean aliveAfterElse;
2691 
2692         if (tree.elsepart != null) {
2693             Env<AttrContext> elseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2694             try {
2695                 attribStat(tree.elsepart, elseEnv);
2696             } finally {
2697                 elseEnv.info.scope.leave();
2698             }
2699             preFlow(tree.elsepart);
2700             aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make);
2701         } else {
2702             aliveAfterElse = true;
2703         }
2704 
2705         chk.checkEmptyIf(tree);
2706 
2707         List<BindingSymbol> afterIfBindings = List.nil();
2708 
2709         if (aliveAfterThen && !aliveAfterElse) {
2710             afterIfBindings = condBindings.bindingsWhenTrue;
2711         } else if (aliveAfterElse && !aliveAfterThen) {
2712             afterIfBindings = condBindings.bindingsWhenFalse;
2713         }
2714 
2715         addBindings2Scope(tree, afterIfBindings);
2716 
2717         result = null;
2718     }
2719 
2720         void preFlow(JCTree tree) {
2721             attrRecover.doRecovery();
2722             new PostAttrAnalyzer() {
2723                 @Override
2724                 public void scan(JCTree tree) {
2725                     if (tree == null ||
2726                             (tree.type != null &&
2727                             tree.type == Type.stuckType)) {
2728                         //don't touch stuck expressions!
2729                         return;
2730                     }
2731                     super.scan(tree);
2732                 }
2733 
2734                 @Override
2735                 public void visitClassDef(JCClassDecl that) {
2736                     if (that.sym != null) {
2737                         // Method preFlow shouldn't visit class definitions
2738                         // that have not been entered and attributed.
2739                         // See JDK-8254557 and JDK-8203277 for more details.
2740                         super.visitClassDef(that);
2741                     }
2742                 }
2743 
2744                 @Override
2745                 public void visitLambda(JCLambda that) {
2746                     if (that.type != null) {
2747                         // Method preFlow shouldn't visit lambda expressions
2748                         // that have not been entered and attributed.
2749                         // See JDK-8254557 and JDK-8203277 for more details.
2750                         super.visitLambda(that);
2751                     }
2752                 }
2753             }.scan(tree);
2754         }
2755 
2756     public void visitExec(JCExpressionStatement tree) {
2757         //a fresh environment is required for 292 inference to work properly ---
2758         //see Infer.instantiatePolymorphicSignatureInstance()
2759         Env<AttrContext> localEnv = env.dup(tree);
2760         attribExpr(tree.expr, localEnv);
2761         result = null;
2762     }
2763 
2764     public void visitBreak(JCBreak tree) {
2765         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2766         result = null;
2767     }
2768 
2769     public void visitYield(JCYield tree) {
2770         if (env.info.yieldResult != null) {
2771             attribTree(tree.value, env, env.info.yieldResult);
2772             tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
2773         } else {
2774             log.error(tree.pos(), tree.value.hasTag(PARENS)
2775                     ? Errors.NoSwitchExpressionQualify
2776                     : Errors.NoSwitchExpression);
2777             attribTree(tree.value, env, unknownExprInfo);
2778         }
2779         result = null;
2780     }
2781 
2782     public void visitContinue(JCContinue tree) {
2783         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2784         result = null;
2785     }
2786     //where
2787         /** Return the target of a break, continue or yield statement,
2788          *  if it exists, report an error if not.
2789          *  Note: The target of a labelled break or continue is the
2790          *  (non-labelled) statement tree referred to by the label,
2791          *  not the tree representing the labelled statement itself.
2792          *
2793          *  @param pos     The position to be used for error diagnostics
2794          *  @param tag     The tag of the jump statement. This is either
2795          *                 Tree.BREAK or Tree.CONTINUE.
2796          *  @param label   The label of the jump statement, or null if no
2797          *                 label is given.
2798          *  @param env     The environment current at the jump statement.
2799          */
2800         private JCTree findJumpTarget(DiagnosticPosition pos,
2801                                                    JCTree.Tag tag,
2802                                                    Name label,
2803                                                    Env<AttrContext> env) {
2804             Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
2805 
2806             if (jumpTarget.snd != null) {
2807                 log.error(pos, jumpTarget.snd);
2808             }
2809 
2810             return jumpTarget.fst;
2811         }
2812         /** Return the target of a break or continue statement, if it exists,
2813          *  report an error if not.
2814          *  Note: The target of a labelled break or continue is the
2815          *  (non-labelled) statement tree referred to by the label,
2816          *  not the tree representing the labelled statement itself.
2817          *
2818          *  @param tag     The tag of the jump statement. This is either
2819          *                 Tree.BREAK or Tree.CONTINUE.
2820          *  @param label   The label of the jump statement, or null if no
2821          *                 label is given.
2822          *  @param env     The environment current at the jump statement.
2823          */
2824         private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
2825                                                                        Name label,
2826                                                                        Env<AttrContext> env) {
2827             // Search environments outwards from the point of jump.
2828             Env<AttrContext> env1 = env;
2829             JCDiagnostic.Error pendingError = null;
2830             LOOP:
2831             while (env1 != null) {
2832                 switch (env1.tree.getTag()) {
2833                     case LABELLED:
2834                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
2835                         if (label == labelled.label) {
2836                             // If jump is a continue, check that target is a loop.
2837                             if (tag == CONTINUE) {
2838                                 if (!labelled.body.hasTag(DOLOOP) &&
2839                                         !labelled.body.hasTag(WHILELOOP) &&
2840                                         !labelled.body.hasTag(FORLOOP) &&
2841                                         !labelled.body.hasTag(FOREACHLOOP)) {
2842                                     pendingError = Errors.NotLoopLabel(label);
2843                                 }
2844                                 // Found labelled statement target, now go inwards
2845                                 // to next non-labelled tree.
2846                                 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
2847                             } else {
2848                                 return Pair.of(labelled, pendingError);
2849                             }
2850                         }
2851                         break;
2852                     case DOLOOP:
2853                     case WHILELOOP:
2854                     case FORLOOP:
2855                     case FOREACHLOOP:
2856                         if (label == null) return Pair.of(env1.tree, pendingError);
2857                         break;
2858                     case SWITCH:
2859                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
2860                         break;
2861                     case SWITCH_EXPRESSION:
2862                         if (tag == YIELD) {
2863                             return Pair.of(env1.tree, null);
2864                         } else if (tag == BREAK) {
2865                             pendingError = Errors.BreakOutsideSwitchExpression;
2866                         } else {
2867                             pendingError = Errors.ContinueOutsideSwitchExpression;
2868                         }
2869                         break;
2870                     case LAMBDA:
2871                     case METHODDEF:
2872                     case CLASSDEF:
2873                         break LOOP;
2874                     default:
2875                 }
2876                 env1 = env1.next;
2877             }
2878             if (label != null)
2879                 return Pair.of(null, Errors.UndefLabel(label));
2880             else if (pendingError != null)
2881                 return Pair.of(null, pendingError);
2882             else if (tag == CONTINUE)
2883                 return Pair.of(null, Errors.ContOutsideLoop);
2884             else
2885                 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
2886         }
2887 
2888     public void visitReturn(JCReturn tree) {
2889         // Check that there is an enclosing method which is
2890         // nested within than the enclosing class.
2891         if (env.info.returnResult == null) {
2892             log.error(tree.pos(), Errors.RetOutsideMeth);
2893         } else if (env.info.yieldResult != null) {
2894             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
2895             if (tree.expr != null) {
2896                 attribExpr(tree.expr, env, env.info.yieldResult.pt);
2897             }
2898         } else if (!env.info.isLambda &&
2899                 env.enclMethod != null &&
2900                 TreeInfo.isCompactConstructor(env.enclMethod)) {
2901             log.error(env.enclMethod,
2902                     Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement));
2903         } else {
2904             // Attribute return expression, if it exists, and check that
2905             // it conforms to result type of enclosing method.
2906             if (tree.expr != null) {
2907                 if (env.info.returnResult.pt.hasTag(VOID)) {
2908                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2909                               diags.fragment(Fragments.UnexpectedRetVal));
2910                 }
2911                 attribTree(tree.expr, env, env.info.returnResult);
2912             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2913                     !env.info.returnResult.pt.hasTag(NONE)) {
2914                 env.info.returnResult.checkContext.report(tree.pos(),
2915                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2916             }
2917         }
2918         result = null;
2919     }
2920 
2921     public void visitThrow(JCThrow tree) {
2922         Type owntype = attribExpr(tree.expr, env, Type.noType);
2923         chk.checkType(tree, owntype, syms.throwableType);
2924         result = null;
2925     }
2926 
2927     public void visitAssert(JCAssert tree) {
2928         attribExpr(tree.cond, env, syms.booleanType);
2929         if (tree.detail != null) {
2930             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2931         }
2932         result = null;
2933     }
2934 
2935      /** Visitor method for method invocations.
2936      *  NOTE: The method part of an application will have in its type field
2937      *        the return type of the method, not the method's type itself!
2938      */
2939     public void visitApply(JCMethodInvocation tree) {
2940         // The local environment of a method application is
2941         // a new environment nested in the current one.
2942         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2943 
2944         // The types of the actual method arguments.
2945         List<Type> argtypes;
2946 
2947         // The types of the actual method type arguments.
2948         List<Type> typeargtypes = null;
2949 
2950         Name methName = TreeInfo.name(tree.meth);
2951 
2952         boolean isConstructorCall =
2953             methName == names._this || methName == names._super;
2954 
2955         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2956         if (isConstructorCall) {
2957 
2958             // Attribute arguments, yielding list of argument types.
2959             KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2960             argtypes = argtypesBuf.toList();
2961             typeargtypes = attribTypes(tree.typeargs, localEnv);
2962 
2963             // Done with this()/super() parameters. End of constructor prologue.
2964             env.info.ctorPrologue = false;
2965 
2966             // Variable `site' points to the class in which the called
2967             // constructor is defined.
2968             Type site = env.enclClass.sym.type;
2969             if (methName == names._super) {
2970                 if (site == syms.objectType) {
2971                     log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2972                     site = types.createErrorType(syms.objectType);
2973                 } else {
2974                     site = types.supertype(site);
2975                 }
2976             }
2977 
2978             if (site.hasTag(CLASS)) {
2979                 Type encl = site.getEnclosingType();
2980                 while (encl != null && encl.hasTag(TYPEVAR))
2981                     encl = encl.getUpperBound();
2982                 if (encl.hasTag(CLASS)) {
2983                     // we are calling a nested class
2984 
2985                     if (tree.meth.hasTag(SELECT)) {
2986                         JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2987 
2988                         // We are seeing a prefixed call, of the form
2989                         //     <expr>.super(...).
2990                         // Check that the prefix expression conforms
2991                         // to the outer instance type of the class.
2992                         chk.checkRefType(qualifier.pos(),
2993                                          attribExpr(qualifier, localEnv,
2994                                                     encl));
2995                     }
2996                 } else if (tree.meth.hasTag(SELECT)) {
2997                     log.error(tree.meth.pos(),
2998                               Errors.IllegalQualNotIcls(site.tsym));
2999                     attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
3000                 }
3001 
3002                 if (tree.meth.hasTag(IDENT)) {
3003                     // non-qualified super(...) call; check whether explicit constructor
3004                     // invocation is well-formed. If the super class is an inner class,
3005                     // make sure that an appropriate implicit qualifier exists. If the super
3006                     // class is a local class, make sure that the current class is defined
3007                     // in the same context as the local class.
3008                     checkNewInnerClass(tree.meth.pos(), localEnv, site, true);
3009                 }
3010 
3011                 // if we're calling a java.lang.Enum constructor,
3012                 // prefix the implicit String and int parameters
3013                 if (site.tsym == syms.enumSym)
3014                     argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
3015 
3016                 // Resolve the called constructor under the assumption
3017                 // that we are referring to a superclass instance of the
3018                 // current instance (JLS ???).
3019                 boolean selectSuperPrev = localEnv.info.selectSuper;
3020                 localEnv.info.selectSuper = true;
3021                 localEnv.info.pendingResolutionPhase = null;
3022                 Symbol sym = rs.resolveConstructor(
3023                     tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
3024                 localEnv.info.selectSuper = selectSuperPrev;
3025 
3026                 // Set method symbol to resolved constructor...
3027                 TreeInfo.setSymbol(tree.meth, sym);
3028 
3029                 // ...and check that it is legal in the current context.
3030                 // (this will also set the tree's type)
3031                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
3032                 checkId(tree.meth, site, sym, localEnv,
3033                         new ResultInfo(kind, mpt));
3034             } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) {
3035                 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
3036             }
3037             // Otherwise, `site' is an error type and we do nothing
3038             result = tree.type = syms.voidType;
3039         } else {
3040             // Otherwise, we are seeing a regular method call.
3041             // Attribute the arguments, yielding list of argument types, ...
3042             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
3043             argtypes = argtypesBuf.toList();
3044             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
3045 
3046             // ... and attribute the method using as a prototype a methodtype
3047             // whose formal argument types is exactly the list of actual
3048             // arguments (this will also set the method symbol).
3049             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
3050             localEnv.info.pendingResolutionPhase = null;
3051             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
3052 
3053             // Compute the result type.
3054             Type restype = mtype.getReturnType();
3055             if (restype.hasTag(WILDCARD))
3056                 throw new AssertionError(mtype);
3057 
3058             Type qualifier = (tree.meth.hasTag(SELECT))
3059                     ? ((JCFieldAccess) tree.meth).selected.type
3060                     : env.enclClass.sym.type;
3061             Symbol msym = TreeInfo.symbol(tree.meth);
3062             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
3063 
3064             chk.checkRefTypes(tree.typeargs, typeargtypes);
3065 
3066             // Check that value of resulting type is admissible in the
3067             // current context.  Also, capture the return type
3068             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
3069             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
3070         }
3071         chk.checkRequiresIdentity(tree, env.info.lint);
3072         chk.validate(tree.typeargs, localEnv);
3073     }
3074     //where
3075         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
3076             if (msym != null &&
3077                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
3078                     methodName == names.getClass &&
3079                     argtypes.isEmpty()) {
3080                 // as a special case, x.getClass() has type Class<? extends |X|>
3081                 return new ClassType(restype.getEnclosingType(),
3082                         List.of(new WildcardType(types.erasure(qualifierType.baseType()),
3083                                 BoundKind.EXTENDS,
3084                                 syms.boundClass)),
3085                         restype.tsym,
3086                         restype.getMetadata());
3087             } else if (msym != null &&
3088                     msym.owner == syms.arrayClass &&
3089                     methodName == names.clone &&
3090                     types.isArray(qualifierType)) {
3091                 // as a special case, array.clone() has a result that is
3092                 // the same as static type of the array being cloned
3093                 return qualifierType;
3094             } else {
3095                 return restype;
3096             }
3097         }
3098 
3099         /** Obtain a method type with given argument types.
3100          */
3101         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
3102             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
3103             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
3104         }
3105 
3106     public void visitNewClass(final JCNewClass tree) {
3107         Type owntype = types.createErrorType(tree.type);
3108 
3109         // The local environment of a class creation is
3110         // a new environment nested in the current one.
3111         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
3112 
3113         // The anonymous inner class definition of the new expression,
3114         // if one is defined by it.
3115         JCClassDecl cdef = tree.def;
3116 
3117         // If enclosing class is given, attribute it, and
3118         // complete class name to be fully qualified
3119         JCExpression clazz = tree.clazz; // Class field following new
3120         JCExpression clazzid;            // Identifier in class field
3121         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
3122         annoclazzid = null;
3123 
3124         if (clazz.hasTag(TYPEAPPLY)) {
3125             clazzid = ((JCTypeApply) clazz).clazz;
3126             if (clazzid.hasTag(ANNOTATED_TYPE)) {
3127                 annoclazzid = (JCAnnotatedType) clazzid;
3128                 clazzid = annoclazzid.underlyingType;
3129             }
3130         } else {
3131             if (clazz.hasTag(ANNOTATED_TYPE)) {
3132                 annoclazzid = (JCAnnotatedType) clazz;
3133                 clazzid = annoclazzid.underlyingType;
3134             } else {
3135                 clazzid = clazz;
3136             }
3137         }
3138 
3139         JCExpression clazzid1 = clazzid; // The same in fully qualified form
3140 
3141         if (tree.encl != null) {
3142             // We are seeing a qualified new, of the form
3143             //    <expr>.new C <...> (...) ...
3144             // In this case, we let clazz stand for the name of the
3145             // allocated class C prefixed with the type of the qualifier
3146             // expression, so that we can
3147             // resolve it with standard techniques later. I.e., if
3148             // <expr> has type T, then <expr>.new C <...> (...)
3149             // yields a clazz T.C.
3150             Type encltype = chk.checkRefType(tree.encl.pos(),
3151                                              attribExpr(tree.encl, env));
3152             // TODO 308: in <expr>.new C, do we also want to add the type annotations
3153             // from expr to the combined type, or not? Yes, do this.
3154             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
3155                                                  ((JCIdent) clazzid).name);
3156 
3157             clazzid1.endpos = clazzid.getEndPosition();
3158             if (clazz.hasTag(ANNOTATED_TYPE)) {
3159                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
3160                 List<JCAnnotation> annos = annoType.annotations;
3161 
3162                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
3163                     clazzid1 = make.at(tree.pos).
3164                         TypeApply(clazzid1,
3165                                   ((JCTypeApply) clazz).arguments);
3166                 }
3167 
3168                 clazzid1 = make.at(tree.pos).
3169                     AnnotatedType(annos, clazzid1);
3170             } else if (clazz.hasTag(TYPEAPPLY)) {
3171                 clazzid1 = make.at(tree.pos).
3172                     TypeApply(clazzid1,
3173                               ((JCTypeApply) clazz).arguments);
3174             }
3175 
3176             clazz = clazzid1;
3177         }
3178 
3179         // Attribute clazz expression and store
3180         // symbol + type back into the attributed tree.
3181         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
3182             attribIdentAsEnumType(env, (JCIdent)clazz) :
3183             attribType(clazz, env);
3184 
3185         clazztype = chk.checkDiamond(tree, clazztype);
3186         chk.validate(clazz, localEnv);
3187         if (tree.encl != null) {
3188             // We have to work in this case to store
3189             // symbol + type back into the attributed tree.
3190             tree.clazz.type = clazztype;
3191             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
3192             clazzid.type = ((JCIdent) clazzid).sym.type;
3193             if (annoclazzid != null) {
3194                 annoclazzid.type = clazzid.type;
3195             }
3196             if (!clazztype.isErroneous()) {
3197                 if (cdef != null && clazztype.tsym.isInterface()) {
3198                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
3199                 } else if (clazztype.tsym.isStatic()) {
3200                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
3201                 }
3202             }
3203         } else {
3204             // Check for the existence of an apropos outer instance
3205             checkNewInnerClass(tree.pos(), env, clazztype, false);
3206         }
3207 
3208         // Attribute constructor arguments.
3209         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
3210         final KindSelector pkind =
3211             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
3212         List<Type> argtypes = argtypesBuf.toList();
3213         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
3214 
3215         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
3216             // Enums may not be instantiated except implicitly
3217             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
3218                 (!env.tree.hasTag(VARDEF) ||
3219                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
3220                  ((JCVariableDecl) env.tree).init != tree))
3221                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
3222 
3223             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
3224                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3225             boolean skipNonDiamondPath = false;
3226             // Check that class is not abstract
3227             if (cdef == null && !tree.classDeclRemoved() && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
3228                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
3229                 log.error(tree.pos(),
3230                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
3231                 skipNonDiamondPath = true;
3232             } else if (cdef != null && clazztype.tsym.isInterface()) {
3233                 // Check that no constructor arguments are given to
3234                 // anonymous classes implementing an interface
3235                 if (!argtypes.isEmpty())
3236                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
3237 
3238                 if (!typeargtypes.isEmpty())
3239                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
3240 
3241                 // Error recovery: pretend no arguments were supplied.
3242                 argtypes = List.nil();
3243                 typeargtypes = List.nil();
3244                 skipNonDiamondPath = true;
3245             }
3246             if (TreeInfo.isDiamond(tree)) {
3247                 ClassType site = new ClassType(clazztype.getEnclosingType(),
3248                             clazztype.tsym.type.getTypeArguments(),
3249                                                clazztype.tsym,
3250                                                clazztype.getMetadata());
3251 
3252                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
3253                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
3254                 diamondEnv.info.pendingResolutionPhase = null;
3255 
3256                 //if the type of the instance creation expression is a class type
3257                 //apply method resolution inference (JLS 15.12.2.7). The return type
3258                 //of the resolved constructor will be a partially instantiated type
3259                 Symbol constructor = rs.resolveDiamond(tree.pos(),
3260                             diamondEnv,
3261                             site,
3262                             argtypes,
3263                             typeargtypes);
3264                 tree.constructor = constructor.baseSymbol();
3265 
3266                 final TypeSymbol csym = clazztype.tsym;
3267                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
3268                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3269                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
3270                 constructorType = checkId(tree, site,
3271                         constructor,
3272                         diamondEnv,
3273                         diamondResult);
3274 
3275                 tree.clazz.type = types.createErrorType(clazztype);
3276                 if (!constructorType.isErroneous()) {
3277                     tree.clazz.type = clazz.type = constructorType.getReturnType();
3278                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
3279                 }
3280                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
3281             }
3282 
3283             // Resolve the called constructor under the assumption
3284             // that we are referring to a superclass instance of the
3285             // current instance (JLS ???).
3286             else if (!skipNonDiamondPath) {
3287                 //the following code alters some of the fields in the current
3288                 //AttrContext - hence, the current context must be dup'ed in
3289                 //order to avoid downstream failures
3290                 Env<AttrContext> rsEnv = localEnv.dup(tree);
3291                 rsEnv.info.selectSuper = cdef != null;
3292                 rsEnv.info.pendingResolutionPhase = null;
3293                 tree.constructor = rs.resolveConstructor(
3294                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
3295                 if (cdef == null) { //do not check twice!
3296                     tree.constructorType = checkId(tree,
3297                             clazztype,
3298                             tree.constructor,
3299                             rsEnv,
3300                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3301                     if (rsEnv.info.lastResolveVarargs())
3302                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
3303                 }
3304             }
3305 
3306             chk.checkRequiresIdentity(tree, env.info.lint);
3307 
3308             if (cdef != null) {
3309                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
3310                 return;
3311             }
3312 
3313             if (tree.constructor != null && tree.constructor.kind == MTH)
3314                 owntype = clazztype;
3315         }
3316         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3317         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
3318         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
3319             //we need to wait for inference to finish and then replace inference vars in the constructor type
3320             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
3321                     instantiatedContext -> {
3322                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
3323                     });
3324         }
3325         chk.validate(tree.typeargs, localEnv);
3326     }
3327 
3328         // where
3329         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
3330                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
3331                                                    List<Type> argtypes, List<Type> typeargtypes,
3332                                                    KindSelector pkind) {
3333             // We are seeing an anonymous class instance creation.
3334             // In this case, the class instance creation
3335             // expression
3336             //
3337             //    E.new <typeargs1>C<typargs2>(args) { ... }
3338             //
3339             // is represented internally as
3340             //
3341             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
3342             //
3343             // This expression is then *transformed* as follows:
3344             //
3345             // (1) add an extends or implements clause
3346             // (2) add a constructor.
3347             //
3348             // For instance, if C is a class, and ET is the type of E,
3349             // the expression
3350             //
3351             //    E.new <typeargs1>C<typargs2>(args) { ... }
3352             //
3353             // is translated to (where X is a fresh name and typarams is the
3354             // parameter list of the super constructor):
3355             //
3356             //   new <typeargs1>X(<*nullchk*>E, args) where
3357             //     X extends C<typargs2> {
3358             //       <typarams> X(ET e, args) {
3359             //         e.<typeargs1>super(args)
3360             //       }
3361             //       ...
3362             //     }
3363             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
3364             Type enclType = clazztype.getEnclosingType();
3365             if (enclType != null &&
3366                     enclType.hasTag(CLASS) &&
3367                     !chk.checkDenotable((ClassType)enclType)) {
3368                 log.error(tree.encl, Errors.EnclosingClassTypeNonDenotable(enclType));
3369             }
3370             final boolean isDiamond = TreeInfo.isDiamond(tree);
3371             if (isDiamond
3372                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
3373                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
3374                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
3375                 Env<AttrContext> dupLocalEnv = copyEnv(localEnv);
3376                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
3377                         instantiatedContext -> {
3378                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
3379                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
3380                             ResultInfo prevResult = this.resultInfo;
3381                             try {
3382                                 this.resultInfo = resultInfoForClassDefinition;
3383                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
3384                                         dupLocalEnv, argtypes, typeargtypes, pkind);
3385                             } finally {
3386                                 this.resultInfo = prevResult;
3387                             }
3388                         });
3389             } else {
3390                 if (isDiamond && clazztype.hasTag(CLASS)) {
3391                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3392                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3393                         // One or more types inferred in the previous steps is non-denotable.
3394                         Fragment fragment = Diamond(clazztype.tsym);
3395                         log.error(tree.clazz.pos(),
3396                                 Errors.CantApplyDiamond1(
3397                                         fragment,
3398                                         invalidDiamondArgs.size() > 1 ?
3399                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3400                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3401                     }
3402                     // For <>(){}, inferred types must also be accessible.
3403                     for (Type t : clazztype.getTypeArguments()) {
3404                         rs.checkAccessibleType(env, t);
3405                     }
3406                 }
3407 
3408                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3409                 // false for isInterface call even when the original type is an interface.
3410                 boolean implementing = clazztype.tsym.isInterface() ||
3411                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3412                         clazztype.getOriginalType().tsym.isInterface();
3413 
3414                 if (implementing) {
3415                     cdef.implementing = List.of(clazz);
3416                 } else {
3417                     cdef.extending = clazz;
3418                 }
3419 
3420                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3421                     rs.isSerializable(clazztype)) {
3422                     localEnv.info.isSerializable = true;
3423                 }
3424 
3425                 attribStat(cdef, localEnv);
3426 
3427                 List<Type> finalargtypes;
3428                 // If an outer instance is given,
3429                 // prefix it to the constructor arguments
3430                 // and delete it from the new expression
3431                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
3432                     finalargtypes = argtypes.prepend(tree.encl.type);
3433                 } else {
3434                     finalargtypes = argtypes;
3435                 }
3436 
3437                 // Reassign clazztype and recompute constructor. As this necessarily involves
3438                 // another attribution pass for deferred types in the case of <>, replicate
3439                 // them. Original arguments have right decorations already.
3440                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
3441                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
3442                 }
3443 
3444                 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
3445                                                     : cdef.sym.type;
3446                 Symbol sym = tree.constructor = rs.resolveConstructor(
3447                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
3448                 Assert.check(!sym.kind.isResolutionError());
3449                 tree.constructor = sym;
3450                 tree.constructorType = checkId(tree,
3451                         clazztype,
3452                         tree.constructor,
3453                         localEnv,
3454                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3455             }
3456             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
3457                                 clazztype : types.createErrorType(tree.type);
3458             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3459             chk.validate(tree.typeargs, localEnv);
3460         }
3461 
3462         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3463             return new Check.NestedCheckContext(checkContext) {
3464                 @Override
3465                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3466                     enclosingContext.report(clazz.clazz,
3467                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3468                 }
3469             };
3470         }
3471 
3472         void checkNewInnerClass(DiagnosticPosition pos, Env<AttrContext> env, Type type, boolean isSuper) {
3473             boolean isLocal = type.tsym.owner.kind == VAR || type.tsym.owner.kind == MTH;
3474             if ((type.tsym.flags() & (INTERFACE | ENUM | RECORD)) != 0 ||
3475                     (!isLocal && !type.tsym.isInner()) ||
3476                     (isSuper && env.enclClass.sym.isAnonymous())) {
3477                 // nothing to check
3478                 return;
3479             }
3480             Symbol res = isLocal ?
3481                     rs.findLocalClassOwner(env, type.tsym) :
3482                     rs.findSelfContaining(pos, env, type.getEnclosingType().tsym, isSuper);
3483             if (res.exists()) {
3484                 rs.accessBase(res, pos, env.enclClass.sym.type, names._this, true);
3485             } else {
3486                 log.error(pos, Errors.EnclClassRequired(type.tsym));
3487             }
3488         }
3489 
3490     /** Make an attributed null check tree.
3491      */
3492     public JCExpression makeNullCheck(JCExpression arg) {
3493         // optimization: new Outer() can never be null; skip null check
3494         if (arg.getTag() == NEWCLASS)
3495             return arg;
3496         // optimization: X.this is never null; skip null check
3497         Name name = TreeInfo.name(arg);
3498         if (name == names._this || name == names._super) return arg;
3499 
3500         JCTree.Tag optag = NULLCHK;
3501         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3502         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3503         tree.type = arg.type;
3504         return tree;
3505     }
3506 
3507     public void visitNewArray(JCNewArray tree) {
3508         Type owntype = types.createErrorType(tree.type);
3509         Env<AttrContext> localEnv = env.dup(tree);
3510         Type elemtype;
3511         if (tree.elemtype != null) {
3512             elemtype = attribType(tree.elemtype, localEnv);
3513             chk.validate(tree.elemtype, localEnv);
3514             owntype = elemtype;
3515             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3516                 attribExpr(l.head, localEnv, syms.intType);
3517                 owntype = new ArrayType(owntype, syms.arrayClass);
3518             }
3519         } else {
3520             // we are seeing an untyped aggregate { ... }
3521             // this is allowed only if the prototype is an array
3522             if (pt().hasTag(ARRAY)) {
3523                 elemtype = types.elemtype(pt());
3524             } else {
3525                 if (!pt().hasTag(ERROR) &&
3526                         (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3527                     log.error(tree.pos(),
3528                               Errors.IllegalInitializerForType(pt()));
3529                 }
3530                 elemtype = types.createErrorType(pt());
3531             }
3532         }
3533         if (tree.elems != null) {
3534             attribExprs(tree.elems, localEnv, elemtype);
3535             owntype = new ArrayType(elemtype, syms.arrayClass);
3536         }
3537         if (!types.isReifiable(elemtype))
3538             log.error(tree.pos(), Errors.GenericArrayCreation);
3539         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3540     }
3541 
3542     /*
3543      * A lambda expression can only be attributed when a target-type is available.
3544      * In addition, if the target-type is that of a functional interface whose
3545      * descriptor contains inference variables in argument position the lambda expression
3546      * is 'stuck' (see DeferredAttr).
3547      */
3548     @Override
3549     public void visitLambda(final JCLambda that) {
3550         boolean wrongContext = false;
3551         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3552             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3553                 //lambda only allowed in assignment or method invocation/cast context
3554                 log.error(that.pos(), Errors.UnexpectedLambda);
3555             }
3556             resultInfo = recoveryInfo;
3557             wrongContext = true;
3558         }
3559         //create an environment for attribution of the lambda expression
3560         final Env<AttrContext> localEnv = lambdaEnv(that, env);
3561         boolean needsRecovery =
3562                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
3563         try {
3564             if (needsRecovery && rs.isSerializable(pt())) {
3565                 localEnv.info.isSerializable = true;
3566                 localEnv.info.isSerializableLambda = true;
3567             }
3568             List<Type> explicitParamTypes = null;
3569             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
3570                 //attribute lambda parameters
3571                 attribStats(that.params, localEnv);
3572                 explicitParamTypes = TreeInfo.types(that.params);
3573             }
3574 
3575             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
3576             Type currentTarget = targetInfo.target;
3577             Type lambdaType = targetInfo.descriptor;
3578 
3579             if (currentTarget.isErroneous()) {
3580                 result = that.type = currentTarget;
3581                 return;
3582             }
3583 
3584             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
3585 
3586             if (lambdaType.hasTag(FORALL)) {
3587                 //lambda expression target desc cannot be a generic method
3588                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3589                                                                     kindName(currentTarget.tsym),
3590                                                                     currentTarget.tsym);
3591                 resultInfo.checkContext.report(that, diags.fragment(msg));
3592                 result = that.type = types.createErrorType(pt());
3593                 return;
3594             }
3595 
3596             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
3597                 //add param type info in the AST
3598                 List<Type> actuals = lambdaType.getParameterTypes();
3599                 List<JCVariableDecl> params = that.params;
3600 
3601                 boolean arityMismatch = false;
3602 
3603                 while (params.nonEmpty()) {
3604                     if (actuals.isEmpty()) {
3605                         //not enough actuals to perform lambda parameter inference
3606                         arityMismatch = true;
3607                     }
3608                     //reset previously set info
3609                     Type argType = arityMismatch ?
3610                             syms.errType :
3611                             actuals.head;
3612                     if (params.head.isImplicitlyTyped()) {
3613                         setSyntheticVariableType(params.head, argType);
3614                     }
3615                     params.head.sym = null;
3616                     actuals = actuals.isEmpty() ?
3617                             actuals :
3618                             actuals.tail;
3619                     params = params.tail;
3620                 }
3621 
3622                 //attribute lambda parameters
3623                 attribStats(that.params, localEnv);
3624 
3625                 if (arityMismatch) {
3626                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3627                         result = that.type = types.createErrorType(currentTarget);
3628                         return;
3629                 }
3630             }
3631 
3632             //from this point on, no recovery is needed; if we are in assignment context
3633             //we will be able to attribute the whole lambda body, regardless of errors;
3634             //if we are in a 'check' method context, and the lambda is not compatible
3635             //with the target-type, it will be recovered anyway in Attr.checkId
3636             needsRecovery = false;
3637 
3638             ResultInfo bodyResultInfo = localEnv.info.returnResult =
3639                     lambdaBodyResult(that, lambdaType, resultInfo);
3640 
3641             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
3642                 attribTree(that.getBody(), localEnv, bodyResultInfo);
3643             } else {
3644                 JCBlock body = (JCBlock)that.body;
3645                 if (body == breakTree &&
3646                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3647                     breakTreeFound(copyEnv(localEnv));
3648                 }
3649                 attribStats(body.stats, localEnv);
3650             }
3651 
3652             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3653 
3654             boolean isSpeculativeRound =
3655                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3656 
3657             preFlow(that);
3658             flow.analyzeLambda(env, that, make, isSpeculativeRound);
3659 
3660             that.type = currentTarget; //avoids recovery at this stage
3661             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
3662 
3663             if (!isSpeculativeRound) {
3664                 //add thrown types as bounds to the thrown types free variables if needed:
3665                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
3666                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
3667                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
3668                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
3669                     }
3670                 }
3671 
3672                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
3673             }
3674             result = wrongContext ? that.type = types.createErrorType(pt())
3675                                   : check(that, currentTarget, KindSelector.VAL, resultInfo);
3676         } catch (Types.FunctionDescriptorLookupError ex) {
3677             JCDiagnostic cause = ex.getDiagnostic();
3678             resultInfo.checkContext.report(that, cause);
3679             result = that.type = types.createErrorType(pt());
3680             return;
3681         } catch (CompletionFailure cf) {
3682             chk.completionError(that.pos(), cf);
3683         } catch (Throwable t) {
3684             //when an unexpected exception happens, avoid attempts to attribute the same tree again
3685             //as that would likely cause the same exception again.
3686             needsRecovery = false;
3687             throw t;
3688         } finally {
3689             localEnv.info.scope.leave();
3690             if (needsRecovery) {
3691                 Type prevResult = result;
3692                 try {
3693                     attribTree(that, env, recoveryInfo);
3694                 } finally {
3695                     if (result == Type.recoveryType) {
3696                         result = prevResult;
3697                     }
3698                 }
3699             }
3700         }
3701     }
3702     //where
3703         class TargetInfo {
3704             Type target;
3705             Type descriptor;
3706 
3707             public TargetInfo(Type target, Type descriptor) {
3708                 this.target = target;
3709                 this.descriptor = descriptor;
3710             }
3711         }
3712 
3713         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
3714             Type lambdaType;
3715             Type currentTarget = resultInfo.pt;
3716             if (resultInfo.pt != Type.recoveryType) {
3717                 /* We need to adjust the target. If the target is an
3718                  * intersection type, for example: SAM & I1 & I2 ...
3719                  * the target will be updated to SAM
3720                  */
3721                 currentTarget = targetChecker.visit(currentTarget, that);
3722                 if (!currentTarget.isIntersection()) {
3723                     if (explicitParamTypes != null) {
3724                         currentTarget = infer.instantiateFunctionalInterface(that,
3725                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
3726                     }
3727                     currentTarget = types.removeWildcards(currentTarget);
3728                     lambdaType = types.findDescriptorType(currentTarget);
3729                 } else {
3730                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
3731                     ListBuffer<Type> components = new ListBuffer<>();
3732                     for (Type bound : ict.getExplicitComponents()) {
3733                         if (explicitParamTypes != null) {
3734                             try {
3735                                 bound = infer.instantiateFunctionalInterface(that,
3736                                         bound, explicitParamTypes, resultInfo.checkContext);
3737                             } catch (FunctionDescriptorLookupError t) {
3738                                 // do nothing
3739                             }
3740                         }
3741                         if (bound.tsym != syms.objectType.tsym && (!bound.isInterface() || (bound.tsym.flags() & ANNOTATION) != 0)) {
3742                             // bound must be j.l.Object or an interface, but not an annotation
3743                             reportIntersectionError(that, "not.an.intf.component", bound);
3744                         }
3745                         bound = types.removeWildcards(bound);
3746                         components.add(bound);
3747                     }
3748                     currentTarget = types.makeIntersectionType(components.toList());
3749                     currentTarget.tsym.flags_field |= INTERFACE;
3750                     lambdaType = types.findDescriptorType(currentTarget);
3751                 }
3752 
3753             } else {
3754                 currentTarget = Type.recoveryType;
3755                 lambdaType = fallbackDescriptorType(that);
3756             }
3757             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
3758                 //lambda expression target desc cannot be a generic method
3759                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3760                                                                     kindName(currentTarget.tsym),
3761                                                                     currentTarget.tsym);
3762                 resultInfo.checkContext.report(that, diags.fragment(msg));
3763                 currentTarget = types.createErrorType(pt());
3764             }
3765             return new TargetInfo(currentTarget, lambdaType);
3766         }
3767 
3768         private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
3769              resultInfo.checkContext.report(pos,
3770                  diags.fragment(Fragments.BadIntersectionTargetForFunctionalExpr(diags.fragment(key, args))));
3771         }
3772 
3773         void preFlow(JCLambda tree) {
3774             attrRecover.doRecovery();
3775             new PostAttrAnalyzer() {
3776                 @Override
3777                 public void scan(JCTree tree) {
3778                     if (tree == null ||
3779                             (tree.type != null &&
3780                             tree.type == Type.stuckType)) {
3781                         //don't touch stuck expressions!
3782                         return;
3783                     }
3784                     super.scan(tree);
3785                 }
3786 
3787                 @Override
3788                 public void visitClassDef(JCClassDecl that) {
3789                     // or class declaration trees!
3790                 }
3791 
3792                 public void visitLambda(JCLambda that) {
3793                     // or lambda expressions!
3794                 }
3795             }.scan(tree.body);
3796         }
3797 
3798         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
3799 
3800             @Override
3801             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
3802                 return t.isIntersection() ?
3803                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
3804             }
3805 
3806             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
3807                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
3808                 return ict;
3809             }
3810 
3811             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
3812                 ListBuffer<Type> targs = new ListBuffer<>();
3813                 ListBuffer<Type> supertypes = new ListBuffer<>();
3814                 for (Type i : ict.interfaces_field) {
3815                     if (i.isParameterized()) {
3816                         targs.appendList(i.tsym.type.allparams());
3817                     }
3818                     supertypes.append(i.tsym.type);
3819                 }
3820                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
3821                 notionalIntf.allparams_field = targs.toList();
3822                 notionalIntf.tsym.flags_field |= INTERFACE;
3823                 return notionalIntf.tsym;
3824             }
3825         };
3826 
3827         private Type fallbackDescriptorType(JCExpression tree) {
3828             switch (tree.getTag()) {
3829                 case LAMBDA:
3830                     JCLambda lambda = (JCLambda)tree;
3831                     List<Type> argtypes = List.nil();
3832                     for (JCVariableDecl param : lambda.params) {
3833                         argtypes = param.vartype != null && param.vartype.type != null ?
3834                                 argtypes.append(param.vartype.type) :
3835                                 argtypes.append(syms.errType);
3836                     }
3837                     return new MethodType(argtypes, Type.recoveryType,
3838                             List.of(syms.throwableType), syms.methodClass);
3839                 case REFERENCE:
3840                     return new MethodType(List.nil(), Type.recoveryType,
3841                             List.of(syms.throwableType), syms.methodClass);
3842                 default:
3843                     Assert.error("Cannot get here!");
3844             }
3845             return null;
3846         }
3847 
3848         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3849                 final InferenceContext inferenceContext, final Type... ts) {
3850             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
3851         }
3852 
3853         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3854                 final InferenceContext inferenceContext, final List<Type> ts) {
3855             if (inferenceContext.free(ts)) {
3856                 inferenceContext.addFreeTypeListener(ts,
3857                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
3858             } else {
3859                 for (Type t : ts) {
3860                     rs.checkAccessibleType(env, t);
3861                 }
3862             }
3863         }
3864 
3865         /**
3866          * Lambda/method reference have a special check context that ensures
3867          * that i.e. a lambda return type is compatible with the expected
3868          * type according to both the inherited context and the assignment
3869          * context.
3870          */
3871         class FunctionalReturnContext extends Check.NestedCheckContext {
3872 
3873             FunctionalReturnContext(CheckContext enclosingContext) {
3874                 super(enclosingContext);
3875             }
3876 
3877             @Override
3878             public boolean compatible(Type found, Type req, Warner warn) {
3879                 //return type must be compatible in both current context and assignment context
3880                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
3881             }
3882 
3883             @Override
3884             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3885                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
3886             }
3887         }
3888 
3889         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
3890 
3891             JCExpression expr;
3892             boolean expStmtExpected;
3893 
3894             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
3895                 super(enclosingContext);
3896                 this.expr = expr;
3897             }
3898 
3899             @Override
3900             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3901                 if (expStmtExpected) {
3902                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
3903                 } else {
3904                     super.report(pos, details);
3905                 }
3906             }
3907 
3908             @Override
3909             public boolean compatible(Type found, Type req, Warner warn) {
3910                 //a void return is compatible with an expression statement lambda
3911                 if (req.hasTag(VOID)) {
3912                     expStmtExpected = true;
3913                     return TreeInfo.isExpressionStatement(expr);
3914                 } else {
3915                     return super.compatible(found, req, warn);
3916                 }
3917             }
3918         }
3919 
3920         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
3921             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
3922                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
3923                     new FunctionalReturnContext(resultInfo.checkContext);
3924 
3925             return descriptor.getReturnType() == Type.recoveryType ?
3926                     recoveryInfo :
3927                     new ResultInfo(KindSelector.VAL,
3928                             descriptor.getReturnType(), funcContext);
3929         }
3930 
3931         /**
3932         * Lambda compatibility. Check that given return types, thrown types, parameter types
3933         * are compatible with the expected functional interface descriptor. This means that:
3934         * (i) parameter types must be identical to those of the target descriptor; (ii) return
3935         * types must be compatible with the return type of the expected descriptor.
3936         */
3937         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3938             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3939 
3940             //return values have already been checked - but if lambda has no return
3941             //values, we must ensure that void/value compatibility is correct;
3942             //this amounts at checking that, if a lambda body can complete normally,
3943             //the descriptor's return type must be void
3944             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3945                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3946                 Fragment msg =
3947                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3948                 checkContext.report(tree,
3949                                     diags.fragment(msg));
3950             }
3951 
3952             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3953             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3954                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3955             }
3956         }
3957 
3958         /* This method returns an environment to be used to attribute a lambda
3959          * expression.
3960          *
3961          * The owner of this environment is a method symbol. If the current owner
3962          * is not a method (e.g. if the lambda occurs in a field initializer), then
3963          * a synthetic method symbol owner is created.
3964          */
3965         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3966             Env<AttrContext> lambdaEnv;
3967             Symbol owner = env.info.scope.owner;
3968             if (owner.kind == VAR && owner.owner.kind == TYP) {
3969                 // If the lambda is nested in a field initializer, we need to create a fake init method.
3970                 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3971                 // init symbol's owner).
3972                 ClassSymbol enclClass = owner.enclClass();
3973                 Name initName = owner.isStatic() ? names.clinit : names.init;
3974                 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3975                         initName, initBlockType, enclClass);
3976                 initSym.params = List.nil();
3977                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3978             } else {
3979                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3980             }
3981             lambdaEnv.info.yieldResult = null;
3982             lambdaEnv.info.isLambda = true;
3983             return lambdaEnv;
3984         }
3985 
3986     @Override
3987     public void visitReference(final JCMemberReference that) {
3988         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3989             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3990                 //method reference only allowed in assignment or method invocation/cast context
3991                 log.error(that.pos(), Errors.UnexpectedMref);
3992             }
3993             result = that.type = types.createErrorType(pt());
3994             return;
3995         }
3996         final Env<AttrContext> localEnv = env.dup(that);
3997         try {
3998             //attribute member reference qualifier - if this is a constructor
3999             //reference, the expected kind must be a type
4000             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
4001 
4002             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
4003                 exprType = chk.checkConstructorRefType(that.expr, exprType);
4004                 if (!exprType.isErroneous() &&
4005                     exprType.isRaw() &&
4006                     that.typeargs != null) {
4007                     log.error(that.expr.pos(),
4008                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
4009                                                  Fragments.MrefInferAndExplicitParams));
4010                     exprType = types.createErrorType(exprType);
4011                 }
4012             }
4013 
4014             if (exprType.isErroneous()) {
4015                 //if the qualifier expression contains problems,
4016                 //give up attribution of method reference
4017                 result = that.type = exprType;
4018                 return;
4019             }
4020 
4021             if (TreeInfo.isStaticSelector(that.expr, names)) {
4022                 //if the qualifier is a type, validate it; raw warning check is
4023                 //omitted as we don't know at this stage as to whether this is a
4024                 //raw selector (because of inference)
4025                 chk.validate(that.expr, env, false);
4026             } else {
4027                 Symbol lhsSym = TreeInfo.symbol(that.expr);
4028                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
4029             }
4030             //attrib type-arguments
4031             List<Type> typeargtypes = List.nil();
4032             if (that.typeargs != null) {
4033                 typeargtypes = attribTypes(that.typeargs, localEnv);
4034             }
4035 
4036             boolean isTargetSerializable =
4037                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
4038                     rs.isSerializable(pt());
4039             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
4040             Type currentTarget = targetInfo.target;
4041             Type desc = targetInfo.descriptor;
4042 
4043             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
4044             List<Type> argtypes = desc.getParameterTypes();
4045             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
4046 
4047             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
4048                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
4049             }
4050 
4051             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
4052             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
4053             try {
4054                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
4055                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
4056                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
4057             } finally {
4058                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
4059             }
4060 
4061             Symbol refSym = refResult.fst;
4062             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
4063 
4064             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
4065              *  JDK-8075541
4066              */
4067             if (refSym.kind != MTH) {
4068                 boolean targetError;
4069                 switch (refSym.kind) {
4070                     case ABSENT_MTH:
4071                         targetError = false;
4072                         break;
4073                     case WRONG_MTH:
4074                     case WRONG_MTHS:
4075                     case AMBIGUOUS:
4076                     case HIDDEN:
4077                     case STATICERR:
4078                         targetError = true;
4079                         break;
4080                     default:
4081                         Assert.error("unexpected result kind " + refSym.kind);
4082                         targetError = false;
4083                 }
4084 
4085                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
4086                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
4087                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
4088 
4089                 JCDiagnostic diag = diags.create(log.currentSource(), that,
4090                         targetError ?
4091                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
4092                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
4093 
4094                 if (targetError && currentTarget == Type.recoveryType) {
4095                     //a target error doesn't make sense during recovery stage
4096                     //as we don't know what actual parameter types are
4097                     result = that.type = currentTarget;
4098                     return;
4099                 } else {
4100                     if (targetError) {
4101                         resultInfo.checkContext.report(that, diag);
4102                     } else {
4103                         log.report(diag);
4104                     }
4105                     result = that.type = types.createErrorType(currentTarget);
4106                     return;
4107                 }
4108             }
4109 
4110             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
4111             that.kind = lookupHelper.referenceKind(that.sym);
4112             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
4113 
4114             if (desc.getReturnType() == Type.recoveryType) {
4115                 // stop here
4116                 result = that.type = currentTarget;
4117                 return;
4118             }
4119 
4120             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
4121                 checkNewInnerClass(that.pos(), env, exprType, false);
4122             }
4123 
4124             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
4125 
4126                 if (that.getMode() == ReferenceMode.INVOKE &&
4127                         TreeInfo.isStaticSelector(that.expr, names) &&
4128                         that.kind.isUnbound() &&
4129                         lookupHelper.site.isRaw()) {
4130                     chk.checkRaw(that.expr, localEnv);
4131                 }
4132 
4133                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
4134                         exprType.getTypeArguments().nonEmpty()) {
4135                     //static ref with class type-args
4136                     log.error(that.expr.pos(),
4137                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
4138                                                  Fragments.StaticMrefWithTargs));
4139                     result = that.type = types.createErrorType(currentTarget);
4140                     return;
4141                 }
4142 
4143                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
4144                     // Check that super-qualified symbols are not abstract (JLS)
4145                     rs.checkNonAbstract(that.pos(), that.sym);
4146                 }
4147 
4148                 if (isTargetSerializable) {
4149                     chk.checkAccessFromSerializableElement(that, true);
4150                 }
4151             }
4152 
4153             ResultInfo checkInfo =
4154                     resultInfo.dup(newMethodTemplate(
4155                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
4156                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
4157                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
4158 
4159             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
4160 
4161             if (that.kind.isUnbound() &&
4162                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
4163                 //re-generate inference constraints for unbound receiver
4164                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
4165                     //cannot happen as this has already been checked - we just need
4166                     //to regenerate the inference constraints, as that has been lost
4167                     //as a result of the call to inferenceContext.save()
4168                     Assert.error("Can't get here");
4169                 }
4170             }
4171 
4172             if (!refType.isErroneous()) {
4173                 refType = types.createMethodTypeWithReturn(refType,
4174                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
4175             }
4176 
4177             //go ahead with standard method reference compatibility check - note that param check
4178             //is a no-op (as this has been taken care during method applicability)
4179             boolean isSpeculativeRound =
4180                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
4181 
4182             that.type = currentTarget; //avoids recovery at this stage
4183             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
4184             if (!isSpeculativeRound) {
4185                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
4186             }
4187             chk.checkRequiresIdentity(that, localEnv.info.lint);
4188             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
4189         } catch (Types.FunctionDescriptorLookupError ex) {
4190             JCDiagnostic cause = ex.getDiagnostic();
4191             resultInfo.checkContext.report(that, cause);
4192             result = that.type = types.createErrorType(pt());
4193             return;
4194         }
4195     }
4196     //where
4197         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
4198             //if this is a constructor reference, the expected kind must be a type
4199             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
4200                                   KindSelector.VAL_TYP : KindSelector.TYP,
4201                                   Type.noType);
4202         }
4203 
4204 
4205     @SuppressWarnings("fallthrough")
4206     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
4207         InferenceContext inferenceContext = checkContext.inferenceContext();
4208         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
4209 
4210         Type resType;
4211         switch (tree.getMode()) {
4212             case NEW:
4213                 if (!tree.expr.type.isRaw()) {
4214                     resType = tree.expr.type;
4215                     break;
4216                 }
4217             default:
4218                 resType = refType.getReturnType();
4219         }
4220 
4221         Type incompatibleReturnType = resType;
4222 
4223         if (returnType.hasTag(VOID)) {
4224             incompatibleReturnType = null;
4225         }
4226 
4227         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
4228             Type capturedResType = captureMRefReturnType ? types.capture(resType) : resType;
4229             if (resType.isErroneous() ||
4230                     new FunctionalReturnContext(checkContext).compatible(capturedResType, returnType,
4231                             checkContext.checkWarner(tree, capturedResType, returnType))) {
4232                 incompatibleReturnType = null;
4233             }
4234         }
4235 
4236         if (incompatibleReturnType != null) {
4237             Fragment msg =
4238                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
4239             checkContext.report(tree, diags.fragment(msg));
4240         } else {
4241             if (inferenceContext.free(refType)) {
4242                 // we need to wait for inference to finish and then replace inference vars in the referent type
4243                 inferenceContext.addFreeTypeListener(List.of(refType),
4244                         instantiatedContext -> {
4245                             tree.referentType = instantiatedContext.asInstType(refType);
4246                         });
4247             } else {
4248                 tree.referentType = refType;
4249             }
4250         }
4251 
4252         if (!speculativeAttr) {
4253             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
4254                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
4255             }
4256         }
4257     }
4258 
4259     boolean checkExConstraints(
4260             List<Type> thrownByFuncExpr,
4261             List<Type> thrownAtFuncType,
4262             InferenceContext inferenceContext) {
4263         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
4264          *  are not proper types
4265          */
4266         List<Type> nonProperList = thrownAtFuncType.stream()
4267                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
4268         List<Type> properList = thrownAtFuncType.diff(nonProperList);
4269 
4270         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
4271          *  in the throws clause of the invocation type of the method reference's compile-time
4272          *  declaration
4273          */
4274         List<Type> checkedList = thrownByFuncExpr.stream()
4275                 .filter(e -> chk.isChecked(e)).collect(List.collector());
4276 
4277         /** If n = 0 (the function type's throws clause consists only of proper types), then
4278          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
4279          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
4280          *  reduces to true
4281          */
4282         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
4283         for (Type checked : checkedList) {
4284             boolean isSubtype = false;
4285             for (Type proper : properList) {
4286                 if (types.isSubtype(checked, proper)) {
4287                     isSubtype = true;
4288                     break;
4289                 }
4290             }
4291             if (!isSubtype) {
4292                 uncaughtByProperTypes.add(checked);
4293             }
4294         }
4295 
4296         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
4297             return false;
4298         }
4299 
4300         /** If n > 0, the constraint reduces to a set of subtyping constraints:
4301          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
4302          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
4303          */
4304         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
4305         uncaughtByProperTypes.forEach(checkedEx -> {
4306             nonProperAsUndet.forEach(nonProper -> {
4307                 types.isSubtype(checkedEx, nonProper);
4308             });
4309         });
4310 
4311         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
4312          */
4313         nonProperAsUndet.stream()
4314                 .filter(t -> t.hasTag(UNDETVAR))
4315                 .forEach(t -> ((UndetVar)t).setThrow());
4316         return true;
4317     }
4318 
4319     /**
4320      * Set functional type info on the underlying AST. Note: as the target descriptor
4321      * might contain inference variables, we might need to register an hook in the
4322      * current inference context.
4323      */
4324     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
4325             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
4326         if (checkContext.inferenceContext().free(descriptorType)) {
4327             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
4328                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
4329                     inferenceContext.asInstType(primaryTarget), checkContext));
4330         } else {
4331             fExpr.owner = env.info.scope.owner;
4332             if (pt.hasTag(CLASS)) {
4333                 fExpr.target = primaryTarget;
4334             }
4335             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
4336                     pt != Type.recoveryType) {
4337                 //check that functional interface class is well-formed
4338                 try {
4339                     /* Types.makeFunctionalInterfaceClass() may throw an exception
4340                      * when it's executed post-inference. See the listener code
4341                      * above.
4342                      */
4343                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
4344                             names.empty, fExpr.target, ABSTRACT);
4345                     if (csym != null) {
4346                         chk.checkImplementations(env.tree, csym, csym);
4347                         try {
4348                             //perform an additional functional interface check on the synthetic class,
4349                             //as there may be spurious errors for raw targets - because of existing issues
4350                             //with membership and inheritance (see JDK-8074570).
4351                             csym.flags_field |= INTERFACE;
4352                             types.findDescriptorType(csym.type);
4353                         } catch (FunctionDescriptorLookupError err) {
4354                             resultInfo.checkContext.report(fExpr,
4355                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
4356                         }
4357                     }
4358                 } catch (Types.FunctionDescriptorLookupError ex) {
4359                     JCDiagnostic cause = ex.getDiagnostic();
4360                     resultInfo.checkContext.report(env.tree, cause);
4361                 }
4362             }
4363         }
4364     }
4365 
4366     public void visitParens(JCParens tree) {
4367         Type owntype = attribTree(tree.expr, env, resultInfo);
4368         result = check(tree, owntype, pkind(), resultInfo);
4369         Symbol sym = TreeInfo.symbol(tree);
4370         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
4371             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
4372     }
4373 
4374     public void visitAssign(JCAssign tree) {
4375         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
4376         Type capturedType = capture(owntype);
4377         attribExpr(tree.rhs, env, owntype);
4378         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
4379     }
4380 
4381     public void visitAssignop(JCAssignOp tree) {
4382         // Attribute arguments.
4383         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
4384         Type operand = attribExpr(tree.rhs, env);
4385         // Find operator.
4386         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
4387         if (operator != operators.noOpSymbol &&
4388                 !owntype.isErroneous() &&
4389                 !operand.isErroneous()) {
4390             chk.checkDivZero(tree.rhs.pos(), operator, operand);
4391             chk.checkCastable(tree.rhs.pos(),
4392                               operator.type.getReturnType(),
4393                               owntype);
4394             switch (tree.getTag()) {
4395             case SL_ASG, SR_ASG, USR_ASG -> { }     // we only use (at most) the lower 6 bits, so any integral type is OK
4396             default -> chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4397             }
4398             chk.checkOutOfRangeShift(tree.rhs.pos(), operator, operand);
4399         }
4400         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4401     }
4402 
4403     public void visitUnary(JCUnary tree) {
4404         // Attribute arguments.
4405         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4406             ? attribTree(tree.arg, env, varAssignmentInfo)
4407             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4408 
4409         // Find operator.
4410         OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4411         Type owntype = types.createErrorType(tree.type);
4412         if (operator != operators.noOpSymbol &&
4413                 !argtype.isErroneous()) {
4414             owntype = (tree.getTag().isIncOrDecUnaryOp())
4415                 ? tree.arg.type
4416                 : operator.type.getReturnType();
4417             int opc = operator.opcode;
4418 
4419             // If the argument is constant, fold it.
4420             if (argtype.constValue() != null) {
4421                 Type ctype = cfolder.fold1(opc, argtype);
4422                 if (ctype != null) {
4423                     owntype = cfolder.coerce(ctype, owntype);
4424                 }
4425             }
4426         }
4427         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4428         matchBindings = matchBindingsComputer.unary(tree, matchBindings);
4429     }
4430 
4431     public void visitBinary(JCBinary tree) {
4432         // Attribute arguments.
4433         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
4434         // x && y
4435         // include x's bindings when true in y
4436 
4437         // x || y
4438         // include x's bindings when false in y
4439 
4440         MatchBindings lhsBindings = matchBindings;
4441         List<BindingSymbol> propagatedBindings;
4442         switch (tree.getTag()) {
4443             case AND:
4444                 propagatedBindings = lhsBindings.bindingsWhenTrue;
4445                 break;
4446             case OR:
4447                 propagatedBindings = lhsBindings.bindingsWhenFalse;
4448                 break;
4449             default:
4450                 propagatedBindings = List.nil();
4451                 break;
4452         }
4453         Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings);
4454         Type right;
4455         try {
4456             right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
4457         } finally {
4458             rhsEnv.info.scope.leave();
4459         }
4460 
4461         matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings);
4462 
4463         // Find operator.
4464         OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
4465         Type owntype = types.createErrorType(tree.type);
4466         if (operator != operators.noOpSymbol &&
4467                 !left.isErroneous() &&
4468                 !right.isErroneous()) {
4469             owntype = operator.type.getReturnType();
4470             int opc = operator.opcode;
4471             // If both arguments are constants, fold them.
4472             if (left.constValue() != null && right.constValue() != null) {
4473                 Type ctype = cfolder.fold2(opc, left, right);
4474                 if (ctype != null) {
4475                     owntype = cfolder.coerce(ctype, owntype);
4476                 }
4477             }
4478 
4479             // Check that argument types of a reference ==, != are
4480             // castable to each other, (JLS 15.21).  Note: unboxing
4481             // comparisons will not have an acmp* opc at this point.
4482             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4483                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4484                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4485                 }
4486             }
4487 
4488             chk.checkDivZero(tree.rhs.pos(), operator, right);
4489             chk.checkOutOfRangeShift(tree.rhs.pos(), operator, right);
4490         }
4491         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4492     }
4493 
4494     public void visitTypeCast(final JCTypeCast tree) {
4495         Type clazztype = attribType(tree.clazz, env);
4496         chk.validate(tree.clazz, env, false);
4497         chk.checkRequiresIdentity(tree, env.info.lint);
4498         //a fresh environment is required for 292 inference to work properly ---
4499         //see Infer.instantiatePolymorphicSignatureInstance()
4500         Env<AttrContext> localEnv = env.dup(tree);
4501         //should we propagate the target type?
4502         final ResultInfo castInfo;
4503         JCExpression expr = TreeInfo.skipParens(tree.expr);
4504         boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4505         if (isPoly) {
4506             //expression is a poly - we need to propagate target type info
4507             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
4508                                       new Check.NestedCheckContext(resultInfo.checkContext) {
4509                 @Override
4510                 public boolean compatible(Type found, Type req, Warner warn) {
4511                     return types.isCastable(found, req, warn);
4512                 }
4513             });
4514         } else {
4515             //standalone cast - target-type info is not propagated
4516             castInfo = unknownExprInfo;
4517         }
4518         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
4519         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4520         if (exprtype.constValue() != null)
4521             owntype = cfolder.coerce(exprtype, owntype);
4522         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
4523         if (!isPoly)
4524             chk.checkRedundantCast(localEnv, tree);
4525     }
4526 
4527     public void visitTypeTest(JCInstanceOf tree) {
4528         Type exprtype = attribExpr(tree.expr, env);
4529         if (exprtype.isPrimitive()) {
4530             preview.checkSourceLevel(tree.expr.pos(), Feature.PRIMITIVE_PATTERNS);
4531         } else {
4532             exprtype = chk.checkNullOrRefType(
4533                     tree.expr.pos(), exprtype);
4534         }
4535         Type clazztype;
4536         JCTree typeTree;
4537         if (tree.pattern.getTag() == BINDINGPATTERN ||
4538             tree.pattern.getTag() == RECORDPATTERN) {
4539             attribExpr(tree.pattern, env, exprtype);
4540             clazztype = tree.pattern.type;
4541             if (types.isSubtype(exprtype, clazztype) &&
4542                 !exprtype.isErroneous() && !clazztype.isErroneous() &&
4543                 tree.pattern.getTag() != RECORDPATTERN) {
4544                 if (!allowUnconditionalPatternsInstanceOf) {
4545                     log.error(tree.pos(), Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName));
4546                 }
4547             }
4548             typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern);
4549         } else {
4550             clazztype = attribType(tree.pattern, env);
4551             typeTree = tree.pattern;
4552             chk.validate(typeTree, env, false);
4553         }
4554         if (clazztype.isPrimitive()) {
4555             preview.checkSourceLevel(tree.pattern.pos(), Feature.PRIMITIVE_PATTERNS);
4556         } else {
4557             if (!clazztype.hasTag(TYPEVAR)) {
4558                 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype);
4559             }
4560             if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
4561                 boolean valid = false;
4562                 if (allowReifiableTypesInInstanceof) {
4563                     valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype);
4564                 } else {
4565                     log.error(tree.pos(), Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName));
4566                     allowReifiableTypesInInstanceof = true;
4567                 }
4568                 if (!valid) {
4569                     clazztype = types.createErrorType(clazztype);
4570                 }
4571             }
4572         }
4573         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4574         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
4575     }
4576 
4577     private boolean checkCastablePattern(DiagnosticPosition pos,
4578                                          Type exprType,
4579                                          Type pattType) {
4580         Warner warner = new Warner();
4581         // if any type is erroneous, the problem is reported elsewhere
4582         if (exprType.isErroneous() || pattType.isErroneous()) {
4583             return false;
4584         }
4585         if (!types.isCastable(exprType, pattType, warner)) {
4586             chk.basicHandler.report(pos,
4587                     diags.fragment(Fragments.InconvertibleTypes(exprType, pattType)));
4588             return false;
4589         } else if ((exprType.isPrimitive() || pattType.isPrimitive()) &&
4590                 (!exprType.isPrimitive() || !pattType.isPrimitive() || !types.isSameType(exprType, pattType))) {
4591             preview.checkSourceLevel(pos, Feature.PRIMITIVE_PATTERNS);
4592             return true;
4593         } else if (warner.hasLint(LintCategory.UNCHECKED)) {
4594             log.error(pos,
4595                     Errors.InstanceofReifiableNotSafe(exprType, pattType));
4596             return false;
4597         } else {
4598             return true;
4599         }
4600     }
4601 
4602     @Override
4603     public void visitAnyPattern(JCAnyPattern tree) {
4604         result = tree.type = resultInfo.pt;
4605     }
4606 
4607     public void visitBindingPattern(JCBindingPattern tree) {
4608         Type type;
4609         if (tree.var.vartype != null) {
4610             type = attribType(tree.var.vartype, env);
4611         } else {
4612             type = resultInfo.pt;
4613         }
4614         tree.type = tree.var.type = type;
4615         BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, type, env.info.scope.owner);
4616         v.pos = tree.pos;
4617         tree.var.sym = v;
4618         if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
4619             chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
4620         }
4621         chk.validate(tree.var.vartype, env, true);
4622         if (tree.var.isImplicitlyTyped()) {
4623             setSyntheticVariableType(tree.var, type == Type.noType ? syms.errType
4624                                                                    : type);
4625         }
4626         annotate.annotateLater(tree.var.mods.annotations, env, v);
4627         if (!tree.var.isImplicitlyTyped()) {
4628             annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v);
4629         }
4630         annotate.flush();
4631         result = tree.type;
4632         if (v.isUnnamedVariable()) {
4633             matchBindings = MatchBindingsComputer.EMPTY;
4634         } else {
4635             matchBindings = new MatchBindings(List.of(v), List.nil());
4636         }
4637         chk.checkRequiresIdentity(tree, env.info.lint);
4638     }
4639 
4640     @Override
4641     public void visitRecordPattern(JCRecordPattern tree) {
4642         Type site;
4643 
4644         if (tree.deconstructor == null) {
4645             log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed);
4646             tree.record = syms.errSymbol;
4647             site = tree.type = types.createErrorType(tree.record.type);
4648         } else {
4649             Type type = attribType(tree.deconstructor, env);
4650             if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) {
4651                 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym);
4652                 if (inferred == null) {
4653                     log.error(tree.pos(), Errors.PatternTypeCannotInfer);
4654                 } else {
4655                     type = inferred;
4656                 }
4657             }
4658             tree.type = tree.deconstructor.type = type;
4659             site = types.capture(tree.type);
4660         }
4661 
4662         List<Type> expectedRecordTypes;
4663         if (site.tsym instanceof ClassSymbol clazz && clazz.isRecord()) {
4664             ClassSymbol record = (ClassSymbol) site.tsym;
4665             expectedRecordTypes = record.getRecordComponents()
4666                                         .stream()
4667                                         .map(rc -> types.memberType(site, rc))
4668                                         .map(t -> types.upward(t, types.captures(t)).baseType())
4669                                         .collect(List.collector());
4670             tree.record = record;
4671         } else {
4672             log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym));
4673             expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type))
4674                                 .limit(tree.nested.size())
4675                                 .collect(List.collector());
4676             tree.record = syms.errSymbol;
4677         }
4678         ListBuffer<BindingSymbol> outBindings = new ListBuffer<>();
4679         List<Type> recordTypes = expectedRecordTypes;
4680         List<JCPattern> nestedPatterns = tree.nested;
4681         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
4682         try {
4683             while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) {
4684                 attribExpr(nestedPatterns.head, localEnv, recordTypes.head);
4685                 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type);
4686                 outBindings.addAll(matchBindings.bindingsWhenTrue);
4687                 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter);
4688                 nestedPatterns = nestedPatterns.tail;
4689                 recordTypes = recordTypes.tail;
4690             }
4691             if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) {
4692                 while (nestedPatterns.nonEmpty()) {
4693                     attribExpr(nestedPatterns.head, localEnv, Type.noType);
4694                     nestedPatterns = nestedPatterns.tail;
4695                 }
4696                 List<Type> nestedTypes =
4697                         tree.nested.stream().map(p -> p.type).collect(List.collector());
4698                 log.error(tree.pos(),
4699                           Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes,
4700                                                                  nestedTypes));
4701             }
4702         } finally {
4703             localEnv.info.scope.leave();
4704         }
4705         chk.validate(tree.deconstructor, env, true);
4706         result = tree.type;
4707         matchBindings = new MatchBindings(outBindings.toList(), List.nil());
4708     }
4709 
4710     public void visitIndexed(JCArrayAccess tree) {
4711         Type owntype = types.createErrorType(tree.type);
4712         Type atype = attribExpr(tree.indexed, env);
4713         attribExpr(tree.index, env, syms.intType);
4714         if (types.isArray(atype))
4715             owntype = types.elemtype(atype);
4716         else if (!atype.hasTag(ERROR))
4717             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
4718         if (!pkind().contains(KindSelector.VAL))
4719             owntype = capture(owntype);
4720         result = check(tree, owntype, KindSelector.VAR, resultInfo);
4721     }
4722 
4723     public void visitIdent(JCIdent tree) {
4724         Symbol sym;
4725 
4726         // Find symbol
4727         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
4728             // If we are looking for a method, the prototype `pt' will be a
4729             // method type with the type of the call's arguments as parameters.
4730             env.info.pendingResolutionPhase = null;
4731             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
4732         } else if (tree.sym != null && tree.sym.kind != VAR) {
4733             sym = tree.sym;
4734         } else {
4735             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
4736         }
4737         tree.sym = sym;
4738 
4739         // Also find the environment current for the class where
4740         // sym is defined (`symEnv').
4741         Env<AttrContext> symEnv = env;
4742         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
4743             sym.kind.matches(KindSelector.VAL_MTH) &&
4744             sym.owner.kind == TYP &&
4745             tree.name != names._this && tree.name != names._super) {
4746 
4747             // Find environment in which identifier is defined.
4748             while (symEnv.outer != null &&
4749                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
4750                 symEnv = symEnv.outer;
4751             }
4752         }
4753 
4754         // If symbol is a variable, ...
4755         if (sym.kind == VAR) {
4756             VarSymbol v = (VarSymbol)sym;
4757 
4758             // ..., evaluate its initializer, if it has one, and check for
4759             // illegal forward reference.
4760             checkInit(tree, env, v, false);
4761 
4762             // If we are expecting a variable (as opposed to a value), check
4763             // that the variable is assignable in the current environment.
4764             if (KindSelector.ASG.subset(pkind()))
4765                 checkAssignable(tree.pos(), v, null, env);
4766         }
4767 
4768         Env<AttrContext> env1 = env;
4769         if (sym.kind != ERR && sym.kind != TYP &&
4770             sym.owner != null && sym.owner != env1.enclClass.sym) {
4771             // If the found symbol is inaccessible, then it is
4772             // accessed through an enclosing instance.  Locate this
4773             // enclosing instance:
4774             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4775                 env1 = env1.outer;
4776         }
4777 
4778         if (env.info.isSerializable) {
4779             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4780         }
4781 
4782         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4783     }
4784 
4785     public void visitSelect(JCFieldAccess tree) {
4786         // Determine the expected kind of the qualifier expression.
4787         KindSelector skind = KindSelector.NIL;
4788         if (tree.name == names._this || tree.name == names._super ||
4789                 tree.name == names._class)
4790         {
4791             skind = KindSelector.TYP;
4792         } else {
4793             if (pkind().contains(KindSelector.PCK))
4794                 skind = KindSelector.of(skind, KindSelector.PCK);
4795             if (pkind().contains(KindSelector.TYP))
4796                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4797             if (pkind().contains(KindSelector.VAL_MTH))
4798                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4799         }
4800 
4801         // Attribute the qualifier expression, and determine its symbol (if any).
4802         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4803         Assert.check(site == tree.selected.type);
4804         if (!pkind().contains(KindSelector.TYP_PCK))
4805             site = capture(site); // Capture field access
4806 
4807         // don't allow T.class T[].class, etc
4808         if (skind == KindSelector.TYP) {
4809             Type elt = site;
4810             while (elt.hasTag(ARRAY))
4811                 elt = ((ArrayType)elt).elemtype;
4812             if (elt.hasTag(TYPEVAR)) {
4813                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4814                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4815                 tree.sym = tree.type.tsym;
4816                 return ;
4817             }
4818         }
4819 
4820         // If qualifier symbol is a type or `super', assert `selectSuper'
4821         // for the selection. This is relevant for determining whether
4822         // protected symbols are accessible.
4823         Symbol sitesym = TreeInfo.symbol(tree.selected);
4824         boolean selectSuperPrev = env.info.selectSuper;
4825         env.info.selectSuper =
4826             sitesym != null &&
4827             sitesym.name == names._super;
4828 
4829         // Determine the symbol represented by the selection.
4830         env.info.pendingResolutionPhase = null;
4831         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4832         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4833             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4834             sym = syms.errSymbol;
4835         }
4836         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4837             site = capture(site);
4838             sym = selectSym(tree, sitesym, site, env, resultInfo);
4839         }
4840         boolean varArgs = env.info.lastResolveVarargs();
4841         tree.sym = sym;
4842 
4843         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4844             site = types.skipTypeVars(site, true);
4845         }
4846 
4847         // If that symbol is a variable, ...
4848         if (sym.kind == VAR) {
4849             VarSymbol v = (VarSymbol)sym;
4850 
4851             // ..., evaluate its initializer, if it has one, and check for
4852             // illegal forward reference.
4853             checkInit(tree, env, v, true);
4854 
4855             // If we are expecting a variable (as opposed to a value), check
4856             // that the variable is assignable in the current environment.
4857             if (KindSelector.ASG.subset(pkind()))
4858                 checkAssignable(tree.pos(), v, tree.selected, env);
4859         }
4860 
4861         if (sitesym != null &&
4862                 sitesym.kind == VAR &&
4863                 ((VarSymbol)sitesym).isResourceVariable() &&
4864                 sym.kind == MTH &&
4865                 sym.name.equals(names.close) &&
4866                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
4867             log.warning(tree, LintWarnings.TryExplicitCloseCall);
4868         }
4869 
4870         // Disallow selecting a type from an expression
4871         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4872             tree.type = check(tree.selected, pt(),
4873                               sitesym == null ?
4874                                       KindSelector.VAL : sitesym.kind.toSelector(),
4875                               new ResultInfo(KindSelector.TYP_PCK, pt()));
4876         }
4877 
4878         if (isType(sitesym)) {
4879             if (sym.name != names._this && sym.name != names._super) {
4880                 // Check if type-qualified fields or methods are static (JLS)
4881                 if ((sym.flags() & STATIC) == 0 &&
4882                     sym.name != names._super &&
4883                     (sym.kind == VAR || sym.kind == MTH)) {
4884                     rs.accessBase(rs.new StaticError(sym),
4885                               tree.pos(), site, sym.name, true);
4886                 }
4887             }
4888         } else if (sym.kind != ERR &&
4889                    (sym.flags() & STATIC) != 0 &&
4890                    sym.name != names._class) {
4891             // If the qualified item is not a type and the selected item is static, report
4892             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4893             if (!sym.owner.isAnonymous()) {
4894                 log.warning(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4895             } else {
4896                 log.warning(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4897             }
4898         }
4899 
4900         // If we are selecting an instance member via a `super', ...
4901         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4902 
4903             // Check that super-qualified symbols are not abstract (JLS)
4904             rs.checkNonAbstract(tree.pos(), sym);
4905 
4906             if (site.isRaw()) {
4907                 // Determine argument types for site.
4908                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4909                 if (site1 != null) site = site1;
4910             }
4911         }
4912 
4913         if (env.info.isSerializable) {
4914             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4915         }
4916 
4917         env.info.selectSuper = selectSuperPrev;
4918         result = checkId(tree, site, sym, env, resultInfo);
4919     }
4920     //where
4921         /** Determine symbol referenced by a Select expression,
4922          *
4923          *  @param tree   The select tree.
4924          *  @param site   The type of the selected expression,
4925          *  @param env    The current environment.
4926          *  @param resultInfo The current result.
4927          */
4928         private Symbol selectSym(JCFieldAccess tree,
4929                                  Symbol location,
4930                                  Type site,
4931                                  Env<AttrContext> env,
4932                                  ResultInfo resultInfo) {
4933             DiagnosticPosition pos = tree.pos();
4934             Name name = tree.name;
4935             switch (site.getTag()) {
4936             case PACKAGE:
4937                 return rs.accessBase(
4938                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4939                     pos, location, site, name, true);
4940             case ARRAY:
4941             case CLASS:
4942                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4943                     return rs.resolveQualifiedMethod(
4944                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4945                 } else if (name == names._this || name == names._super) {
4946                     return rs.resolveSelf(pos, env, site.tsym, tree);
4947                 } else if (name == names._class) {
4948                     // In this case, we have already made sure in
4949                     // visitSelect that qualifier expression is a type.
4950                     return syms.getClassField(site, types);
4951                 } else {
4952                     // We are seeing a plain identifier as selector.
4953                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4954                         sym = rs.accessBase(sym, pos, location, site, name, true);
4955                     return sym;
4956                 }
4957             case WILDCARD:
4958                 throw new AssertionError(tree);
4959             case TYPEVAR:
4960                 // Normally, site.getUpperBound() shouldn't be null.
4961                 // It should only happen during memberEnter/attribBase
4962                 // when determining the supertype which *must* be
4963                 // done before attributing the type variables.  In
4964                 // other words, we are seeing this illegal program:
4965                 // class B<T> extends A<T.foo> {}
4966                 Symbol sym = (site.getUpperBound() != null)
4967                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4968                     : null;
4969                 if (sym == null) {
4970                     log.error(pos, Errors.TypeVarCantBeDeref);
4971                     return syms.errSymbol;
4972                 } else {
4973                     // JLS 4.9 specifies the members are derived by inheritance.
4974                     // We skip inducing a whole class by filtering members that
4975                     // can never be inherited:
4976                     Symbol sym2;
4977                     if (sym.isPrivate()) {
4978                         // Private members
4979                         sym2 = rs.new AccessError(env, site, sym);
4980                     } else if (sym.owner.isInterface() && sym.kind == MTH && (sym.flags() & STATIC) != 0) {
4981                         // Interface static methods
4982                         sym2 = rs.new SymbolNotFoundError(ABSENT_MTH);
4983                     } else {
4984                         sym2 = sym;
4985                     }
4986                     rs.accessBase(sym2, pos, location, site, name, true);
4987                     return sym;
4988                 }
4989             case ERROR:
4990                 // preserve identifier names through errors
4991                 return types.createErrorType(name, site.tsym, site).tsym;
4992             default:
4993                 // The qualifier expression is of a primitive type -- only
4994                 // .class is allowed for these.
4995                 if (name == names._class) {
4996                     // In this case, we have already made sure in Select that
4997                     // qualifier expression is a type.
4998                     return syms.getClassField(site, types);
4999                 } else {
5000                     log.error(pos, Errors.CantDeref(site));
5001                     return syms.errSymbol;
5002                 }
5003             }
5004         }
5005 
5006         /** Determine type of identifier or select expression and check that
5007          *  (1) the referenced symbol is not deprecated
5008          *  (2) the symbol's type is safe (@see checkSafe)
5009          *  (3) if symbol is a variable, check that its type and kind are
5010          *      compatible with the prototype and protokind.
5011          *  (4) if symbol is an instance field of a raw type,
5012          *      which is being assigned to, issue an unchecked warning if its
5013          *      type changes under erasure.
5014          *  (5) if symbol is an instance method of a raw type, issue an
5015          *      unchecked warning if its argument types change under erasure.
5016          *  If checks succeed:
5017          *    If symbol is a constant, return its constant type
5018          *    else if symbol is a method, return its result type
5019          *    otherwise return its type.
5020          *  Otherwise return errType.
5021          *
5022          *  @param tree       The syntax tree representing the identifier
5023          *  @param site       If this is a select, the type of the selected
5024          *                    expression, otherwise the type of the current class.
5025          *  @param sym        The symbol representing the identifier.
5026          *  @param env        The current environment.
5027          *  @param resultInfo    The expected result
5028          */
5029         Type checkId(JCTree tree,
5030                      Type site,
5031                      Symbol sym,
5032                      Env<AttrContext> env,
5033                      ResultInfo resultInfo) {
5034             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
5035                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
5036                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
5037         }
5038 
5039         Type checkMethodIdInternal(JCTree tree,
5040                      Type site,
5041                      Symbol sym,
5042                      Env<AttrContext> env,
5043                      ResultInfo resultInfo) {
5044             if (resultInfo.pkind.contains(KindSelector.POLY)) {
5045                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
5046             } else {
5047                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
5048             }
5049         }
5050 
5051         Type checkIdInternal(JCTree tree,
5052                      Type site,
5053                      Symbol sym,
5054                      Type pt,
5055                      Env<AttrContext> env,
5056                      ResultInfo resultInfo) {
5057             Type owntype; // The computed type of this identifier occurrence.
5058             switch (sym.kind) {
5059             case TYP:
5060                 // For types, the computed type equals the symbol's type,
5061                 // except for two situations:
5062                 owntype = sym.type;
5063                 if (owntype.hasTag(CLASS)) {
5064                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
5065                     Type ownOuter = owntype.getEnclosingType();
5066 
5067                     // (a) If the symbol's type is parameterized, erase it
5068                     // because no type parameters were given.
5069                     // We recover generic outer type later in visitTypeApply.
5070                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
5071                         owntype = types.erasure(owntype);
5072                     }
5073 
5074                     // (b) If the symbol's type is an inner class, then
5075                     // we have to interpret its outer type as a superclass
5076                     // of the site type. Example:
5077                     //
5078                     // class Tree<A> { class Visitor { ... } }
5079                     // class PointTree extends Tree<Point> { ... }
5080                     // ...PointTree.Visitor...
5081                     //
5082                     // Then the type of the last expression above is
5083                     // Tree<Point>.Visitor.
5084                     else if ((ownOuter.hasTag(CLASS) || ownOuter.hasTag(TYPEVAR)) && site != ownOuter) {
5085                         Type normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
5086                         if (normOuter == null) // perhaps from an import
5087                             normOuter = types.erasure(ownOuter);
5088                         if (normOuter != ownOuter)
5089                             owntype = new ClassType(
5090                                 normOuter, List.nil(), owntype.tsym,
5091                                 owntype.getMetadata());
5092                     }
5093                 }
5094                 break;
5095             case VAR:
5096                 VarSymbol v = (VarSymbol)sym;
5097 
5098                 if (env.info.enclVar != null
5099                         && v.type.hasTag(NONE)) {
5100                     //self reference to implicitly typed variable declaration
5101                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
5102                     return tree.type = v.type = types.createErrorType(v.type);
5103                 }
5104 
5105                 // Test (4): if symbol is an instance field of a raw type,
5106                 // which is being assigned to, issue an unchecked warning if
5107                 // its type changes under erasure.
5108                 if (KindSelector.ASG.subset(pkind()) &&
5109                     v.owner.kind == TYP &&
5110                     (v.flags() & STATIC) == 0 &&
5111                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
5112                     Type s = types.asOuterSuper(site, v.owner);
5113                     if (s != null &&
5114                         s.isRaw() &&
5115                         !types.isSameType(v.type, v.erasure(types))) {
5116                         chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
5117                     }
5118                 }
5119                 // The computed type of a variable is the type of the
5120                 // variable symbol, taken as a member of the site type.
5121                 owntype = (sym.owner.kind == TYP &&
5122                            sym.name != names._this && sym.name != names._super)
5123                     ? types.memberType(site, sym)
5124                     : sym.type;
5125 
5126                 // If the variable is a constant, record constant value in
5127                 // computed type.
5128                 if (v.getConstValue() != null && isStaticReference(tree))
5129                     owntype = owntype.constType(v.getConstValue());
5130 
5131                 if (resultInfo.pkind == KindSelector.VAL) {
5132                     owntype = capture(owntype); // capture "names as expressions"
5133                 }
5134                 break;
5135             case MTH: {
5136                 owntype = checkMethod(site, sym,
5137                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
5138                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
5139                         resultInfo.pt.getTypeArguments());
5140                 chk.checkRestricted(tree.pos(), sym);
5141                 break;
5142             }
5143             case PCK: case ERR:
5144                 owntype = sym.type;
5145                 break;
5146             default:
5147                 throw new AssertionError("unexpected kind: " + sym.kind +
5148                                          " in tree " + tree);
5149             }
5150 
5151             // Emit a `deprecation' warning if symbol is deprecated.
5152             // (for constructors (but not for constructor references), the error
5153             // was given when the constructor was resolved)
5154 
5155             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
5156                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
5157                 chk.checkSunAPI(tree.pos(), sym);
5158                 chk.checkProfile(tree.pos(), sym);
5159                 chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym);
5160             }
5161 
5162             if (pt.isErroneous()) {
5163                 owntype = types.createErrorType(owntype);
5164             }
5165 
5166             // If symbol is a variable, check that its type and
5167             // kind are compatible with the prototype and protokind.
5168             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
5169         }
5170 
5171         /** Check that variable is initialized and evaluate the variable's
5172          *  initializer, if not yet done. Also check that variable is not
5173          *  referenced before it is defined.
5174          *  @param tree    The tree making up the variable reference.
5175          *  @param env     The current environment.
5176          *  @param v       The variable's symbol.
5177          */
5178         private void checkInit(JCTree tree,
5179                                Env<AttrContext> env,
5180                                VarSymbol v,
5181                                boolean onlyWarning) {
5182             // A forward reference is diagnosed if the declaration position
5183             // of the variable is greater than the current tree position
5184             // and the tree and variable definition occur in the same class
5185             // definition.  Note that writes don't count as references.
5186             // This check applies only to class and instance
5187             // variables.  Local variables follow different scope rules,
5188             // and are subject to definite assignment checking.
5189             Env<AttrContext> initEnv = enclosingInitEnv(env);
5190             if (initEnv != null &&
5191                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
5192                 v.owner.kind == TYP &&
5193                 v.owner == env.info.scope.owner.enclClass() &&
5194                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
5195                 (!env.tree.hasTag(ASSIGN) ||
5196                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
5197                 if (!onlyWarning || isStaticEnumField(v)) {
5198                     Error errkey = (initEnv.info.enclVar == v) ?
5199                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
5200                     log.error(tree.pos(), errkey);
5201                 } else if (useBeforeDeclarationWarning) {
5202                     Warning warnkey = (initEnv.info.enclVar == v) ?
5203                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
5204                     log.warning(tree.pos(), warnkey);
5205                 }
5206             }
5207 
5208             v.getConstValue(); // ensure initializer is evaluated
5209 
5210             checkEnumInitializer(tree, env, v);
5211         }
5212 
5213         /**
5214          * Returns the enclosing init environment associated with this env (if any). An init env
5215          * can be either a field declaration env or a static/instance initializer env.
5216          */
5217         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
5218             while (true) {
5219                 switch (env.tree.getTag()) {
5220                     case VARDEF:
5221                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
5222                         if (vdecl.sym.owner.kind == TYP) {
5223                             //field
5224                             return env;
5225                         }
5226                         break;
5227                     case BLOCK:
5228                         if (env.next.tree.hasTag(CLASSDEF)) {
5229                             //instance/static initializer
5230                             return env;
5231                         }
5232                         break;
5233                     case METHODDEF:
5234                     case CLASSDEF:
5235                     case TOPLEVEL:
5236                         return null;
5237                 }
5238                 Assert.checkNonNull(env.next);
5239                 env = env.next;
5240             }
5241         }
5242 
5243         /**
5244          * Check for illegal references to static members of enum.  In
5245          * an enum type, constructors and initializers may not
5246          * reference its static members unless they are constant.
5247          *
5248          * @param tree    The tree making up the variable reference.
5249          * @param env     The current environment.
5250          * @param v       The variable's symbol.
5251          * @jls 8.9 Enum Types
5252          */
5253         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
5254             // JLS:
5255             //
5256             // "It is a compile-time error to reference a static field
5257             // of an enum type that is not a compile-time constant
5258             // (15.28) from constructors, instance initializer blocks,
5259             // or instance variable initializer expressions of that
5260             // type. It is a compile-time error for the constructors,
5261             // instance initializer blocks, or instance variable
5262             // initializer expressions of an enum constant e to refer
5263             // to itself or to an enum constant of the same type that
5264             // is declared to the right of e."
5265             if (isStaticEnumField(v)) {
5266                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
5267 
5268                 if (enclClass == null || enclClass.owner == null)
5269                     return;
5270 
5271                 // See if the enclosing class is the enum (or a
5272                 // subclass thereof) declaring v.  If not, this
5273                 // reference is OK.
5274                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
5275                     return;
5276 
5277                 // If the reference isn't from an initializer, then
5278                 // the reference is OK.
5279                 if (!Resolve.isInitializer(env))
5280                     return;
5281 
5282                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
5283             }
5284         }
5285 
5286         /** Is the given symbol a static, non-constant field of an Enum?
5287          *  Note: enum literals should not be regarded as such
5288          */
5289         private boolean isStaticEnumField(VarSymbol v) {
5290             return Flags.isEnum(v.owner) &&
5291                    Flags.isStatic(v) &&
5292                    !Flags.isConstant(v) &&
5293                    v.name != names._class;
5294         }
5295 
5296     /**
5297      * Check that method arguments conform to its instantiation.
5298      **/
5299     public Type checkMethod(Type site,
5300                             final Symbol sym,
5301                             ResultInfo resultInfo,
5302                             Env<AttrContext> env,
5303                             final List<JCExpression> argtrees,
5304                             List<Type> argtypes,
5305                             List<Type> typeargtypes) {
5306         // Test (5): if symbol is an instance method of a raw type, issue
5307         // an unchecked warning if its argument types change under erasure.
5308         if ((sym.flags() & STATIC) == 0 &&
5309             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
5310             Type s = types.asOuterSuper(site, sym.owner);
5311             if (s != null && s.isRaw() &&
5312                 !types.isSameTypes(sym.type.getParameterTypes(),
5313                                    sym.erasure(types).getParameterTypes())) {
5314                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
5315             }
5316         }
5317 
5318         if (env.info.defaultSuperCallSite != null) {
5319             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
5320                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
5321                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
5322                 List<MethodSymbol> icand_sup =
5323                         types.interfaceCandidates(sup, (MethodSymbol)sym);
5324                 if (icand_sup.nonEmpty() &&
5325                         icand_sup.head != sym &&
5326                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
5327                     log.error(env.tree.pos(),
5328                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
5329                     break;
5330                 }
5331             }
5332             env.info.defaultSuperCallSite = null;
5333         }
5334 
5335         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
5336             JCMethodInvocation app = (JCMethodInvocation)env.tree;
5337             if (app.meth.hasTag(SELECT) &&
5338                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
5339                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
5340             }
5341         }
5342 
5343         // Compute the identifier's instantiated type.
5344         // For methods, we need to compute the instance type by
5345         // Resolve.instantiate from the symbol's type as well as
5346         // any type arguments and value arguments.
5347         Warner noteWarner = new Warner();
5348         try {
5349             Type owntype = rs.checkMethod(
5350                     env,
5351                     site,
5352                     sym,
5353                     resultInfo,
5354                     argtypes,
5355                     typeargtypes,
5356                     noteWarner);
5357 
5358             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
5359                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
5360 
5361             argtypes = argtypes.map(checkDeferredMap);
5362 
5363             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
5364                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
5365                         sym.name,
5366                         rs.methodArguments(sym.type.getParameterTypes()),
5367                         rs.methodArguments(argtypes.map(checkDeferredMap)),
5368                         kindName(sym.location()),
5369                         sym.location()));
5370                 if (resultInfo.pt != Infer.anyPoly ||
5371                         !owntype.hasTag(METHOD) ||
5372                         !owntype.isPartial()) {
5373                     //if this is not a partially inferred method type, erase return type. Otherwise,
5374                     //erasure is carried out in PartiallyInferredMethodType.check().
5375                     owntype = new MethodType(owntype.getParameterTypes(),
5376                             types.erasure(owntype.getReturnType()),
5377                             types.erasure(owntype.getThrownTypes()),
5378                             syms.methodClass);
5379                 }
5380             }
5381 
5382             PolyKind pkind = (sym.type.hasTag(FORALL) &&
5383                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
5384                  PolyKind.POLY : PolyKind.STANDALONE;
5385             TreeInfo.setPolyKind(env.tree, pkind);
5386 
5387             return (resultInfo.pt == Infer.anyPoly) ?
5388                     owntype :
5389                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
5390                             resultInfo.checkContext.inferenceContext());
5391         } catch (Infer.InferenceException ex) {
5392             //invalid target type - propagate exception outwards or report error
5393             //depending on the current check context
5394             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5395             return types.createErrorType(site);
5396         } catch (Resolve.InapplicableMethodException ex) {
5397             final JCDiagnostic diag = ex.getDiagnostic();
5398             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5399                 @Override
5400                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5401                     return new Pair<>(sym, diag);
5402                 }
5403             };
5404             List<Type> argtypes2 = argtypes.map(
5405                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5406             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5407                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5408             log.report(errDiag);
5409             return types.createErrorType(site);
5410         }
5411     }
5412 
5413     public void visitLiteral(JCLiteral tree) {
5414         result = check(tree, litType(tree.typetag).constType(tree.value),
5415                 KindSelector.VAL, resultInfo);
5416     }
5417     //where
5418     /** Return the type of a literal with given type tag.
5419      */
5420     Type litType(TypeTag tag) {
5421         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5422     }
5423 
5424     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5425         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5426     }
5427 
5428     public void visitTypeArray(JCArrayTypeTree tree) {
5429         Type etype = attribType(tree.elemtype, env);
5430         Type type = new ArrayType(etype, syms.arrayClass);
5431         result = check(tree, type, KindSelector.TYP, resultInfo);
5432     }
5433 
5434     /** Visitor method for parameterized types.
5435      *  Bound checking is left until later, since types are attributed
5436      *  before supertype structure is completely known
5437      */
5438     public void visitTypeApply(JCTypeApply tree) {
5439         Type owntype = types.createErrorType(tree.type);
5440 
5441         // Attribute functor part of application and make sure it's a class.
5442         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5443 
5444         // Attribute type parameters
5445         List<Type> actuals = attribTypes(tree.arguments, env);
5446 
5447         if (clazztype.hasTag(CLASS)) {
5448             List<Type> formals = clazztype.tsym.type.getTypeArguments();
5449             if (actuals.isEmpty()) //diamond
5450                 actuals = formals;
5451 
5452             if (actuals.length() == formals.length()) {
5453                 List<Type> a = actuals;
5454                 List<Type> f = formals;
5455                 while (a.nonEmpty()) {
5456                     a.head = a.head.withTypeVar(f.head);
5457                     a = a.tail;
5458                     f = f.tail;
5459                 }
5460                 // Compute the proper generic outer
5461                 Type clazzOuter = clazztype.getEnclosingType();
5462                 if (clazzOuter.hasTag(CLASS)) {
5463                     Type site;
5464                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5465                     if (clazz.hasTag(IDENT)) {
5466                         site = env.enclClass.sym.type;
5467                     } else if (clazz.hasTag(SELECT)) {
5468                         site = ((JCFieldAccess) clazz).selected.type;
5469                     } else throw new AssertionError(""+tree);
5470                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5471                         if (site.hasTag(CLASS) || site.hasTag(TYPEVAR))
5472                             site = types.asEnclosingSuper(site, clazzOuter.tsym);
5473                         if (site == null)
5474                             site = types.erasure(clazzOuter);
5475                         clazzOuter = site;
5476                     }
5477                 }
5478                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5479                                         clazztype.getMetadata());
5480             } else {
5481                 if (formals.length() != 0) {
5482                     log.error(tree.pos(),
5483                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5484                 } else {
5485                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5486                 }
5487                 owntype = types.createErrorType(tree.type);
5488             }
5489         } else if (clazztype.hasTag(ERROR)) {
5490             ErrorType parameterizedErroneous =
5491                     new ErrorType(clazztype.getOriginalType(),
5492                                   clazztype.tsym,
5493                                   clazztype.getMetadata());
5494 
5495             parameterizedErroneous.typarams_field = actuals;
5496             owntype = parameterizedErroneous;
5497         }
5498         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5499     }
5500 
5501     public void visitTypeUnion(JCTypeUnion tree) {
5502         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5503         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5504         for (JCExpression typeTree : tree.alternatives) {
5505             Type ctype = attribType(typeTree, env);
5506             ctype = chk.checkType(typeTree.pos(),
5507                           chk.checkClassType(typeTree.pos(), ctype),
5508                           syms.throwableType);
5509             if (!ctype.isErroneous()) {
5510                 //check that alternatives of a union type are pairwise
5511                 //unrelated w.r.t. subtyping
5512                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
5513                     for (Type t : multicatchTypes) {
5514                         boolean sub = types.isSubtype(ctype, t);
5515                         boolean sup = types.isSubtype(t, ctype);
5516                         if (sub || sup) {
5517                             //assume 'a' <: 'b'
5518                             Type a = sub ? ctype : t;
5519                             Type b = sub ? t : ctype;
5520                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5521                         }
5522                     }
5523                 }
5524                 multicatchTypes.append(ctype);
5525                 if (all_multicatchTypes != null)
5526                     all_multicatchTypes.append(ctype);
5527             } else {
5528                 if (all_multicatchTypes == null) {
5529                     all_multicatchTypes = new ListBuffer<>();
5530                     all_multicatchTypes.appendList(multicatchTypes);
5531                 }
5532                 all_multicatchTypes.append(ctype);
5533             }
5534         }
5535         Type t = check(tree, types.lub(multicatchTypes.toList()),
5536                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5537         if (t.hasTag(CLASS)) {
5538             List<Type> alternatives =
5539                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5540             t = new UnionClassType((ClassType) t, alternatives);
5541         }
5542         tree.type = result = t;
5543     }
5544 
5545     public void visitTypeIntersection(JCTypeIntersection tree) {
5546         attribTypes(tree.bounds, env);
5547         tree.type = result = checkIntersection(tree, tree.bounds);
5548     }
5549 
5550     public void visitTypeParameter(JCTypeParameter tree) {
5551         TypeVar typeVar = (TypeVar) tree.type;
5552 
5553         if (tree.annotations != null && tree.annotations.nonEmpty()) {
5554             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5555         }
5556 
5557         if (!typeVar.getUpperBound().isErroneous()) {
5558             //fixup type-parameter bound computed in 'attribTypeVariables'
5559             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5560         }
5561     }
5562 
5563     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5564         Set<Symbol> boundSet = new HashSet<>();
5565         if (bounds.nonEmpty()) {
5566             // accept class or interface or typevar as first bound.
5567             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5568             boundSet.add(types.erasure(bounds.head.type).tsym);
5569             if (bounds.head.type.isErroneous()) {
5570                 return bounds.head.type;
5571             }
5572             else if (bounds.head.type.hasTag(TYPEVAR)) {
5573                 // if first bound was a typevar, do not accept further bounds.
5574                 if (bounds.tail.nonEmpty()) {
5575                     log.error(bounds.tail.head.pos(),
5576                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
5577                     return bounds.head.type;
5578                 }
5579             } else {
5580                 // if first bound was a class or interface, accept only interfaces
5581                 // as further bounds.
5582                 for (JCExpression bound : bounds.tail) {
5583                     bound.type = checkBase(bound.type, bound, env, false, true, false);
5584                     if (bound.type.isErroneous()) {
5585                         bounds = List.of(bound);
5586                     }
5587                     else if (bound.type.hasTag(CLASS)) {
5588                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5589                     }
5590                 }
5591             }
5592         }
5593 
5594         if (bounds.length() == 0) {
5595             return syms.objectType;
5596         } else if (bounds.length() == 1) {
5597             return bounds.head.type;
5598         } else {
5599             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5600             // ... the variable's bound is a class type flagged COMPOUND
5601             // (see comment for TypeVar.bound).
5602             // In this case, generate a class tree that represents the
5603             // bound class, ...
5604             JCExpression extending;
5605             List<JCExpression> implementing;
5606             if (!bounds.head.type.isInterface()) {
5607                 extending = bounds.head;
5608                 implementing = bounds.tail;
5609             } else {
5610                 extending = null;
5611                 implementing = bounds;
5612             }
5613             JCClassDecl cd = make.at(tree).ClassDef(
5614                 make.Modifiers(PUBLIC | ABSTRACT),
5615                 names.empty, List.nil(),
5616                 extending, implementing, List.nil());
5617 
5618             ClassSymbol c = (ClassSymbol)owntype.tsym;
5619             Assert.check((c.flags() & COMPOUND) != 0);
5620             cd.sym = c;
5621             c.sourcefile = env.toplevel.sourcefile;
5622 
5623             // ... and attribute the bound class
5624             c.flags_field |= UNATTRIBUTED;
5625             Env<AttrContext> cenv = enter.classEnv(cd, env);
5626             typeEnvs.put(c, cenv);
5627             attribClass(c);
5628             return owntype;
5629         }
5630     }
5631 
5632     public void visitWildcard(JCWildcard tree) {
5633         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5634         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5635             ? syms.objectType
5636             : attribType(tree.inner, env);
5637         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5638                                               tree.kind.kind,
5639                                               syms.boundClass),
5640                 KindSelector.TYP, resultInfo);
5641     }
5642 
5643     public void visitAnnotation(JCAnnotation tree) {
5644         Assert.error("should be handled in annotate");
5645     }
5646 
5647     @Override
5648     public void visitModifiers(JCModifiers tree) {
5649         //error recovery only:
5650         Assert.check(resultInfo.pkind == KindSelector.ERR);
5651 
5652         attribAnnotationTypes(tree.annotations, env);
5653     }
5654 
5655     public void visitAnnotatedType(JCAnnotatedType tree) {
5656         attribAnnotationTypes(tree.annotations, env);
5657         Type underlyingType = attribType(tree.underlyingType, env);
5658         Type annotatedType = underlyingType.preannotatedType();
5659 
5660         annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5661         result = tree.type = annotatedType;
5662     }
5663 
5664     public void visitErroneous(JCErroneous tree) {
5665         if (tree.errs != null) {
5666             WriteableScope newScope = env.info.scope;
5667 
5668             if (env.tree instanceof JCClassDecl) {
5669                 Symbol fakeOwner =
5670                     new MethodSymbol(BLOCK, names.empty, null,
5671                         env.info.scope.owner);
5672                 newScope = newScope.dupUnshared(fakeOwner);
5673             }
5674 
5675             Env<AttrContext> errEnv =
5676                     env.dup(env.tree,
5677                             env.info.dup(newScope));
5678             errEnv.info.returnResult = unknownExprInfo;
5679             for (JCTree err : tree.errs)
5680                 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5681         }
5682         result = tree.type = syms.errType;
5683     }
5684 
5685     /** Default visitor method for all other trees.
5686      */
5687     public void visitTree(JCTree tree) {
5688         throw new AssertionError();
5689     }
5690 
5691     /**
5692      * Attribute an env for either a top level tree or class or module declaration.
5693      */
5694     public void attrib(Env<AttrContext> env) {
5695         switch (env.tree.getTag()) {
5696             case MODULEDEF:
5697                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5698                 break;
5699             case PACKAGEDEF:
5700                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5701                 break;
5702             default:
5703                 attribClass(env.tree.pos(), env.enclClass.sym);
5704         }
5705 
5706         annotate.flush();
5707 
5708         // Now that this tree is attributed, we can calculate the Lint configuration everywhere within it
5709         lintMapper.calculateLints(env.toplevel.sourcefile, env.tree);
5710     }
5711 
5712     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5713         try {
5714             annotate.flush();
5715             attribPackage(p);
5716         } catch (CompletionFailure ex) {
5717             chk.completionError(pos, ex);
5718         }
5719     }
5720 
5721     void attribPackage(PackageSymbol p) {
5722         attribWithLint(p,
5723                        env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5724     }
5725 
5726     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5727         try {
5728             annotate.flush();
5729             attribModule(m);
5730         } catch (CompletionFailure ex) {
5731             chk.completionError(pos, ex);
5732         }
5733     }
5734 
5735     void attribModule(ModuleSymbol m) {
5736         attribWithLint(m, env -> attribStat(env.tree, env));
5737     }
5738 
5739     private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5740         Env<AttrContext> env = typeEnvs.get(sym);
5741 
5742         Env<AttrContext> lintEnv = env;
5743         while (lintEnv.info.lint == null)
5744             lintEnv = lintEnv.next;
5745 
5746         Lint lint = lintEnv.info.lint.augment(sym);
5747 
5748         Lint prevLint = chk.setLint(lint);
5749         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5750 
5751         try {
5752             attrib.accept(env);
5753         } finally {
5754             log.useSource(prev);
5755             chk.setLint(prevLint);
5756         }
5757     }
5758 
5759     /** Main method: attribute class definition associated with given class symbol.
5760      *  reporting completion failures at the given position.
5761      *  @param pos The source position at which completion errors are to be
5762      *             reported.
5763      *  @param c   The class symbol whose definition will be attributed.
5764      */
5765     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5766         try {
5767             annotate.flush();
5768             attribClass(c);
5769         } catch (CompletionFailure ex) {
5770             chk.completionError(pos, ex);
5771         }
5772     }
5773 
5774     /** Attribute class definition associated with given class symbol.
5775      *  @param c   The class symbol whose definition will be attributed.
5776      */
5777     void attribClass(ClassSymbol c) throws CompletionFailure {
5778         if (c.type.hasTag(ERROR)) return;
5779 
5780         // Check for cycles in the inheritance graph, which can arise from
5781         // ill-formed class files.
5782         chk.checkNonCyclic(null, c.type);
5783 
5784         Type st = types.supertype(c.type);
5785         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5786             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5787             // First, attribute superclass.
5788             if (st.hasTag(CLASS))
5789                 attribClass((ClassSymbol)st.tsym);
5790 
5791             // Next attribute owner, if it is a class.
5792             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5793                 attribClass((ClassSymbol)c.owner);
5794 
5795             c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5796         }
5797 
5798         // The previous operations might have attributed the current class
5799         // if there was a cycle. So we test first whether the class is still
5800         // UNATTRIBUTED.
5801         if ((c.flags_field & UNATTRIBUTED) != 0) {
5802             c.flags_field &= ~UNATTRIBUTED;
5803 
5804             // Get environment current at the point of class definition.
5805             Env<AttrContext> env = typeEnvs.get(c);
5806 
5807             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5808             // because the annotations were not available at the time the env was created. Therefore,
5809             // we look up the environment chain for the first enclosing environment for which the
5810             // lint value is set. Typically, this is the parent env, but might be further if there
5811             // are any envs created as a result of TypeParameter nodes.
5812             Env<AttrContext> lintEnv = env;
5813             while (lintEnv.info.lint == null)
5814                 lintEnv = lintEnv.next;
5815 
5816             // Having found the enclosing lint value, we can initialize the lint value for this class
5817             env.info.lint = lintEnv.info.lint.augment(c);
5818 
5819             Lint prevLint = chk.setLint(env.info.lint);
5820             JavaFileObject prev = log.useSource(c.sourcefile);
5821             ResultInfo prevReturnRes = env.info.returnResult;
5822 
5823             try {
5824                 if (c.isSealed() &&
5825                         !c.isEnum() &&
5826                         !c.isPermittedExplicit &&
5827                         c.getPermittedSubclasses().isEmpty()) {
5828                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5829                 }
5830 
5831                 if (c.isSealed()) {
5832                     Set<Symbol> permittedTypes = new HashSet<>();
5833                     boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5834                     for (Type subType : c.getPermittedSubclasses()) {
5835                         if (subType.isErroneous()) {
5836                             // the type already caused errors, don't produce more potentially misleading errors
5837                             continue;
5838                         }
5839                         boolean isTypeVar = false;
5840                         if (subType.getTag() == TYPEVAR) {
5841                             isTypeVar = true; //error recovery
5842                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5843                                     Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5844                         }
5845                         if (subType.tsym.isAnonymous() && !c.isEnum()) {
5846                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),  Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5847                         }
5848                         if (permittedTypes.contains(subType.tsym)) {
5849                             DiagnosticPosition pos =
5850                                     env.enclClass.permitting.stream()
5851                                             .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5852                                             .limit(2).collect(List.collector()).get(1);
5853                             log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5854                         } else {
5855                             permittedTypes.add(subType.tsym);
5856                         }
5857                         if (sealedInUnnamed) {
5858                             if (subType.tsym.packge() != c.packge()) {
5859                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5860                                         Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5861                                 );
5862                             }
5863                         } else if (subType.tsym.packge().modle != c.packge().modle) {
5864                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5865                                     Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5866                             );
5867                         }
5868                         if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5869                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5870                                     Errors.InvalidPermitsClause(
5871                                             subType.tsym == c.type.tsym ?
5872                                                     Fragments.MustNotBeSameClass :
5873                                                     Fragments.MustNotBeSupertype(subType)
5874                                     )
5875                             );
5876                         } else if (!isTypeVar) {
5877                             boolean thisIsASuper = types.directSupertypes(subType)
5878                                                         .stream()
5879                                                         .anyMatch(d -> d.tsym == c);
5880                             if (!thisIsASuper) {
5881                                 if(c.isInterface()) {
5882                                     log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5883                                             Errors.InvalidPermitsClause(Fragments.DoesntImplementSealed(kindName(subType.tsym), subType)));
5884                                 } else {
5885                                     log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5886                                             Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5887                                 }
5888                             }
5889                         }
5890                     }
5891                 }
5892 
5893                 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5894                                                       .stream()
5895                                                       .filter(s -> s.tsym.isSealed())
5896                                                       .map(s -> (ClassSymbol) s.tsym)
5897                                                       .collect(List.collector());
5898 
5899                 if (sealedSupers.isEmpty()) {
5900                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5901                         boolean hasErrorSuper = false;
5902 
5903                         hasErrorSuper |= types.directSupertypes(c.type)
5904                                               .stream()
5905                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5906 
5907                         ClassType ct = (ClassType) c.type;
5908 
5909                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5910 
5911                         if (!hasErrorSuper) {
5912                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5913                         }
5914                     }
5915                 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5916                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5917                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5918                     }
5919 
5920                     if (!c.type.isCompound()) {
5921                         for (ClassSymbol supertypeSym : sealedSupers) {
5922                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5923                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5924                             }
5925                         }
5926                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5927                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5928                                     c.isInterface() ?
5929                                             Errors.NonSealedOrSealedExpected :
5930                                             Errors.NonSealedSealedOrFinalExpected);
5931                         }
5932                     }
5933                 }
5934 
5935                 env.info.returnResult = null;
5936                 // java.lang.Enum may not be subclassed by a non-enum
5937                 if (st.tsym == syms.enumSym &&
5938                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5939                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5940 
5941                 // Enums may not be extended by source-level classes
5942                 if (st.tsym != null &&
5943                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5944                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5945                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5946                 }
5947 
5948                 if (rs.isSerializable(c.type)) {
5949                     env.info.isSerializable = true;
5950                 }
5951 
5952                 if (c.isValueClass()) {
5953                     Assert.check(env.tree.hasTag(CLASSDEF));
5954                     chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5955                 }
5956 
5957                 attribClassBody(env, c);
5958 
5959                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5960                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5961                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5962                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5963 
5964                 if (c.isImplicit()) {
5965                     chk.checkHasMain(env.tree.pos(), c);
5966                 }
5967             } finally {
5968                 env.info.returnResult = prevReturnRes;
5969                 log.useSource(prev);
5970                 chk.setLint(prevLint);
5971             }
5972 
5973         }
5974     }
5975 
5976     public void visitImport(JCImport tree) {
5977         // nothing to do
5978     }
5979 
5980     public void visitModuleDef(JCModuleDecl tree) {
5981         tree.sym.completeUsesProvides();
5982         ModuleSymbol msym = tree.sym;
5983         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5984         Lint prevLint = chk.setLint(lint);
5985         try {
5986             chk.checkModuleName(tree);
5987             chk.checkDeprecatedAnnotation(tree, msym);
5988         } finally {
5989             chk.setLint(prevLint);
5990         }
5991     }
5992 
5993     /** Finish the attribution of a class. */
5994     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5995         JCClassDecl tree = (JCClassDecl)env.tree;
5996         Assert.check(c == tree.sym);
5997 
5998         // Validate type parameters, supertype and interfaces.
5999         attribStats(tree.typarams, env);
6000         if (!c.isAnonymous()) {
6001             //already checked if anonymous
6002             chk.validate(tree.typarams, env);
6003             chk.validate(tree.extending, env);
6004             chk.validate(tree.implementing, env);
6005         }
6006 
6007         chk.checkRequiresIdentity(tree, env.info.lint);
6008 
6009         c.markAbstractIfNeeded(types);
6010 
6011         // If this is a non-abstract class, check that it has no abstract
6012         // methods or unimplemented methods of an implemented interface.
6013         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
6014             chk.checkAllDefined(tree.pos(), c);
6015         }
6016 
6017         if ((c.flags() & ANNOTATION) != 0) {
6018             if (tree.implementing.nonEmpty())
6019                 log.error(tree.implementing.head.pos(),
6020                           Errors.CantExtendIntfAnnotation);
6021             if (tree.typarams.nonEmpty()) {
6022                 log.error(tree.typarams.head.pos(),
6023                           Errors.IntfAnnotationCantHaveTypeParams(c));
6024             }
6025 
6026             // If this annotation type has a @Repeatable, validate
6027             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
6028             // If this annotation type has a @Repeatable, validate
6029             if (repeatable != null) {
6030                 // get diagnostic position for error reporting
6031                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
6032                 Assert.checkNonNull(cbPos);
6033 
6034                 chk.validateRepeatable(c, repeatable, cbPos);
6035             }
6036         } else {
6037             try {
6038                 // Check that all extended classes and interfaces
6039                 // are compatible (i.e. no two define methods with same arguments
6040                 // yet different return types).  (JLS 8.4.8.3)
6041                 chk.checkCompatibleSupertypes(tree.pos(), c.type);
6042                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
6043                 chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
6044             } catch (CompletionFailure cf) {
6045                 chk.completionError(tree.pos(), cf);
6046             }
6047         }
6048 
6049         // Check that class does not import the same parameterized interface
6050         // with two different argument lists.
6051         chk.checkClassBounds(tree.pos(), c.type);
6052 
6053         tree.type = c.type;
6054 
6055         for (List<JCTypeParameter> l = tree.typarams;
6056              l.nonEmpty(); l = l.tail) {
6057              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
6058         }
6059 
6060         // Check that a generic class doesn't extend Throwable
6061         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
6062             log.error(tree.extending.pos(), Errors.GenericThrowable);
6063 
6064         // Check that all methods which implement some
6065         // method conform to the method they implement.
6066         chk.checkImplementations(tree);
6067 
6068         //check that a resource implementing AutoCloseable cannot throw InterruptedException
6069         checkAutoCloseable(env, tree, false);
6070 
6071         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
6072             // Attribute declaration
6073             attribStat(l.head, env);
6074             // Check that declarations in inner classes are not static (JLS 8.1.2)
6075             // Make an exception for static constants.
6076             if (!allowRecords &&
6077                     c.owner.kind != PCK &&
6078                     ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
6079                     (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
6080                 VarSymbol sym = null;
6081                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
6082                 if (sym == null ||
6083                         sym.kind != VAR ||
6084                         sym.getConstValue() == null)
6085                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
6086             }
6087         }
6088 
6089         // Check for proper placement of super()/this() calls.
6090         chk.checkSuperInitCalls(tree);
6091 
6092         // Check for cycles among non-initial constructors.
6093         chk.checkCyclicConstructors(tree);
6094 
6095         // Check for cycles among annotation elements.
6096         chk.checkNonCyclicElements(tree);
6097 
6098         // Check for proper use of serialVersionUID and other
6099         // serialization-related fields and methods
6100         if (env.info.lint.isEnabled(LintCategory.SERIAL)
6101                 && rs.isSerializable(c.type)
6102                 && !c.isAnonymous()) {
6103             chk.checkSerialStructure(env, tree, c);
6104         }
6105         // Correctly organize the positions of the type annotations
6106         typeAnnotations.organizeTypeAnnotationsBodies(tree);
6107 
6108         // Check type annotations applicability rules
6109         validateTypeAnnotations(tree, false);
6110     }
6111         // where
6112         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
6113         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
6114             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
6115                 if (types.isSameType(al.head.annotationType.type, t))
6116                     return al.head.pos();
6117             }
6118 
6119             return null;
6120         }
6121 
6122     private Type capture(Type type) {
6123         return types.capture(type);
6124     }
6125 
6126     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
6127         if (type.isErroneous()) {
6128             tree.vartype = make.at(tree.pos()).Erroneous();
6129         } else if (tree.declaredUsingVar()) {
6130             Assert.check(tree.typePos != Position.NOPOS);
6131             tree.vartype = make.at(tree.typePos).Type(type);
6132         } else {
6133             tree.vartype = make.at(tree.pos()).Type(type);
6134         }
6135     }
6136 
6137     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
6138         tree.accept(new TypeAnnotationsValidator(sigOnly));
6139     }
6140     //where
6141     private final class TypeAnnotationsValidator extends TreeScanner {
6142 
6143         private final boolean sigOnly;
6144         public TypeAnnotationsValidator(boolean sigOnly) {
6145             this.sigOnly = sigOnly;
6146         }
6147 
6148         public void visitAnnotation(JCAnnotation tree) {
6149             chk.validateTypeAnnotation(tree, null, false);
6150             super.visitAnnotation(tree);
6151         }
6152         public void visitAnnotatedType(JCAnnotatedType tree) {
6153             if (!tree.underlyingType.type.isErroneous()) {
6154                 super.visitAnnotatedType(tree);
6155             }
6156         }
6157         public void visitTypeParameter(JCTypeParameter tree) {
6158             chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
6159             scan(tree.bounds);
6160             // Don't call super.
6161             // This is needed because above we call validateTypeAnnotation with
6162             // false, which would forbid annotations on type parameters.
6163             // super.visitTypeParameter(tree);
6164         }
6165         public void visitMethodDef(JCMethodDecl tree) {
6166             if (tree.recvparam != null &&
6167                     !tree.recvparam.vartype.type.isErroneous()) {
6168                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
6169             }
6170             if (tree.restype != null && tree.restype.type != null) {
6171                 validateAnnotatedType(tree.restype, tree.restype.type);
6172             }
6173             if (sigOnly) {
6174                 scan(tree.mods);
6175                 scan(tree.restype);
6176                 scan(tree.typarams);
6177                 scan(tree.recvparam);
6178                 scan(tree.params);
6179                 scan(tree.thrown);
6180             } else {
6181                 scan(tree.defaultValue);
6182                 scan(tree.body);
6183             }
6184         }
6185         public void visitVarDef(final JCVariableDecl tree) {
6186             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
6187             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
6188                 validateAnnotatedType(tree.vartype, tree.sym.type);
6189             scan(tree.mods);
6190             scan(tree.vartype);
6191             if (!sigOnly) {
6192                 scan(tree.init);
6193             }
6194         }
6195         public void visitTypeCast(JCTypeCast tree) {
6196             if (tree.clazz != null && tree.clazz.type != null)
6197                 validateAnnotatedType(tree.clazz, tree.clazz.type);
6198             super.visitTypeCast(tree);
6199         }
6200         public void visitTypeTest(JCInstanceOf tree) {
6201             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
6202                 validateAnnotatedType(tree.pattern, tree.pattern.type);
6203             super.visitTypeTest(tree);
6204         }
6205         public void visitNewClass(JCNewClass tree) {
6206             if (tree.clazz != null && tree.clazz.type != null) {
6207                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
6208                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
6209                             tree.clazz.type.tsym);
6210                 }
6211                 if (tree.def != null) {
6212                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
6213                 }
6214 
6215                 validateAnnotatedType(tree.clazz, tree.clazz.type);
6216             }
6217             super.visitNewClass(tree);
6218         }
6219         public void visitNewArray(JCNewArray tree) {
6220             if (tree.elemtype != null && tree.elemtype.type != null) {
6221                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
6222                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
6223                             tree.elemtype.type.tsym);
6224                 }
6225                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
6226             }
6227             super.visitNewArray(tree);
6228         }
6229         public void visitClassDef(JCClassDecl tree) {
6230             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
6231             if (sigOnly) {
6232                 scan(tree.mods);
6233                 scan(tree.typarams);
6234                 scan(tree.extending);
6235                 scan(tree.implementing);
6236             }
6237             for (JCTree member : tree.defs) {
6238                 if (member.hasTag(Tag.CLASSDEF)) {
6239                     continue;
6240                 }
6241                 scan(member);
6242             }
6243         }
6244         public void visitBlock(JCBlock tree) {
6245             if (!sigOnly) {
6246                 scan(tree.stats);
6247             }
6248         }
6249 
6250         /* I would want to model this after
6251          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
6252          * and override visitSelect and visitTypeApply.
6253          * However, we only set the annotated type in the top-level type
6254          * of the symbol.
6255          * Therefore, we need to override each individual location where a type
6256          * can occur.
6257          */
6258         private void validateAnnotatedType(final JCTree errtree, final Type type) {
6259             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
6260 
6261             if (type.isPrimitiveOrVoid()) {
6262                 return;
6263             }
6264 
6265             JCTree enclTr = errtree;
6266             Type enclTy = type;
6267 
6268             boolean repeat = true;
6269             while (repeat) {
6270                 if (enclTr.hasTag(TYPEAPPLY)) {
6271                     List<Type> tyargs = enclTy.getTypeArguments();
6272                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
6273                     if (trargs.length() > 0) {
6274                         // Nothing to do for diamonds
6275                         if (tyargs.length() == trargs.length()) {
6276                             for (int i = 0; i < tyargs.length(); ++i) {
6277                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
6278                             }
6279                         }
6280                         // If the lengths don't match, it's either a diamond
6281                         // or some nested type that redundantly provides
6282                         // type arguments in the tree.
6283                     }
6284 
6285                     // Look at the clazz part of a generic type
6286                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
6287                 }
6288 
6289                 if (enclTr.hasTag(SELECT)) {
6290                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
6291                     if (enclTy != null &&
6292                             !enclTy.hasTag(NONE)) {
6293                         enclTy = enclTy.getEnclosingType();
6294                     }
6295                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
6296                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
6297                     if (enclTy == null || enclTy.hasTag(NONE)) {
6298                         ListBuffer<Attribute.TypeCompound> onlyTypeAnnotationsBuf = new ListBuffer<>();
6299                         for (JCAnnotation an : at.getAnnotations()) {
6300                             if (chk.isTypeAnnotation(an, false)) {
6301                                 onlyTypeAnnotationsBuf.add((Attribute.TypeCompound) an.attribute);
6302                             }
6303                         }
6304                         List<Attribute.TypeCompound> onlyTypeAnnotations = onlyTypeAnnotationsBuf.toList();
6305                         if (!onlyTypeAnnotations.isEmpty()) {
6306                             Fragment annotationFragment = onlyTypeAnnotations.size() == 1 ?
6307                                     Fragments.TypeAnnotation1(onlyTypeAnnotations.head) :
6308                                     Fragments.TypeAnnotation(onlyTypeAnnotations);
6309                             JCDiagnostic.AnnotatedType annotatedType = new JCDiagnostic.AnnotatedType(
6310                                     type.stripMetadata().annotatedType(onlyTypeAnnotations));
6311                             log.error(at.underlyingType.pos(), Errors.TypeAnnotationInadmissible(annotationFragment,
6312                                     type.tsym.owner, annotatedType));
6313                         }
6314                         repeat = false;
6315                     }
6316                     enclTr = at.underlyingType;
6317                     // enclTy doesn't need to be changed
6318                 } else if (enclTr.hasTag(IDENT)) {
6319                     repeat = false;
6320                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
6321                     JCWildcard wc = (JCWildcard) enclTr;
6322                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
6323                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
6324                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
6325                     } else {
6326                         // Nothing to do for UNBOUND
6327                     }
6328                     repeat = false;
6329                 } else if (enclTr.hasTag(TYPEARRAY)) {
6330                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
6331                     validateAnnotatedType(art.getType(), art.elemtype.type);
6332                     repeat = false;
6333                 } else if (enclTr.hasTag(TYPEUNION)) {
6334                     JCTypeUnion ut = (JCTypeUnion) enclTr;
6335                     for (JCTree t : ut.getTypeAlternatives()) {
6336                         validateAnnotatedType(t, t.type);
6337                     }
6338                     repeat = false;
6339                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
6340                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
6341                     for (JCTree t : it.getBounds()) {
6342                         validateAnnotatedType(t, t.type);
6343                     }
6344                     repeat = false;
6345                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
6346                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
6347                     repeat = false;
6348                 } else {
6349                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
6350                             " within: "+ errtree + " with kind: " + errtree.getKind());
6351                 }
6352             }
6353         }
6354 
6355         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
6356                 Symbol sym) {
6357             // Ensure that no declaration annotations are present.
6358             // Note that a tree type might be an AnnotatedType with
6359             // empty annotations, if only declaration annotations were given.
6360             // This method will raise an error for such a type.
6361             for (JCAnnotation ai : annotations) {
6362                 if (!ai.type.isErroneous() &&
6363                         typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
6364                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
6365                 }
6366             }
6367         }
6368     }
6369 
6370     // <editor-fold desc="post-attribution visitor">
6371 
6372     /**
6373      * Handle missing types/symbols in an AST. This routine is useful when
6374      * the compiler has encountered some errors (which might have ended up
6375      * terminating attribution abruptly); if the compiler is used in fail-over
6376      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
6377      * prevents NPE to be propagated during subsequent compilation steps.
6378      */
6379     public void postAttr(JCTree tree) {
6380         new PostAttrAnalyzer().scan(tree);
6381     }
6382 
6383     class PostAttrAnalyzer extends TreeScanner {
6384 
6385         private void initTypeIfNeeded(JCTree that) {
6386             if (that.type == null) {
6387                 if (that.hasTag(METHODDEF)) {
6388                     that.type = dummyMethodType((JCMethodDecl)that);
6389                 } else {
6390                     that.type = syms.unknownType;
6391                 }
6392             }
6393         }
6394 
6395         /* Construct a dummy method type. If we have a method declaration,
6396          * and the declared return type is void, then use that return type
6397          * instead of UNKNOWN to avoid spurious error messages in lambda
6398          * bodies (see:JDK-8041704).
6399          */
6400         private Type dummyMethodType(JCMethodDecl md) {
6401             Type restype = syms.unknownType;
6402             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
6403                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
6404                 if (prim.typetag == VOID)
6405                     restype = syms.voidType;
6406             }
6407             return new MethodType(List.nil(), restype,
6408                                   List.nil(), syms.methodClass);
6409         }
6410         private Type dummyMethodType() {
6411             return dummyMethodType(null);
6412         }
6413 
6414         @Override
6415         public void scan(JCTree tree) {
6416             if (tree == null) return;
6417             if (tree instanceof JCExpression) {
6418                 initTypeIfNeeded(tree);
6419             }
6420             super.scan(tree);
6421         }
6422 
6423         @Override
6424         public void visitIdent(JCIdent that) {
6425             if (that.sym == null) {
6426                 that.sym = syms.unknownSymbol;
6427             }
6428         }
6429 
6430         @Override
6431         public void visitSelect(JCFieldAccess that) {
6432             if (that.sym == null) {
6433                 that.sym = syms.unknownSymbol;
6434             }
6435             super.visitSelect(that);
6436         }
6437 
6438         @Override
6439         public void visitClassDef(JCClassDecl that) {
6440             initTypeIfNeeded(that);
6441             if (that.sym == null) {
6442                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6443             }
6444             super.visitClassDef(that);
6445         }
6446 
6447         @Override
6448         public void visitMethodDef(JCMethodDecl that) {
6449             initTypeIfNeeded(that);
6450             if (that.sym == null) {
6451                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6452             }
6453             super.visitMethodDef(that);
6454         }
6455 
6456         @Override
6457         public void visitVarDef(JCVariableDecl that) {
6458             initTypeIfNeeded(that);
6459             if (that.sym == null) {
6460                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6461                 that.sym.adr = 0;
6462             }
6463             if (that.vartype == null) {
6464                 that.vartype = make.at(Position.NOPOS).Erroneous();
6465             }
6466             super.visitVarDef(that);
6467         }
6468 
6469         @Override
6470         public void visitBindingPattern(JCBindingPattern that) {
6471             initTypeIfNeeded(that);
6472             initTypeIfNeeded(that.var);
6473             if (that.var.sym == null) {
6474                 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6475                 that.var.sym.adr = 0;
6476             }
6477             super.visitBindingPattern(that);
6478         }
6479 
6480         @Override
6481         public void visitRecordPattern(JCRecordPattern that) {
6482             initTypeIfNeeded(that);
6483             if (that.record == null) {
6484                 that.record = new ClassSymbol(0, TreeInfo.name(that.deconstructor),
6485                                               that.type, syms.noSymbol);
6486             }
6487             if (that.fullComponentTypes == null) {
6488                 that.fullComponentTypes = List.nil();
6489             }
6490             super.visitRecordPattern(that);
6491         }
6492 
6493         @Override
6494         public void visitNewClass(JCNewClass that) {
6495             if (that.constructor == null) {
6496                 that.constructor = new MethodSymbol(0, names.init,
6497                         dummyMethodType(), syms.noSymbol);
6498             }
6499             if (that.constructorType == null) {
6500                 that.constructorType = syms.unknownType;
6501             }
6502             super.visitNewClass(that);
6503         }
6504 
6505         @Override
6506         public void visitAssignop(JCAssignOp that) {
6507             if (that.operator == null) {
6508                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6509                         -1, syms.noSymbol);
6510             }
6511             super.visitAssignop(that);
6512         }
6513 
6514         @Override
6515         public void visitBinary(JCBinary that) {
6516             if (that.operator == null) {
6517                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6518                         -1, syms.noSymbol);
6519             }
6520             super.visitBinary(that);
6521         }
6522 
6523         @Override
6524         public void visitUnary(JCUnary that) {
6525             if (that.operator == null) {
6526                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6527                         -1, syms.noSymbol);
6528             }
6529             super.visitUnary(that);
6530         }
6531 
6532         @Override
6533         public void visitReference(JCMemberReference that) {
6534             super.visitReference(that);
6535             if (that.sym == null) {
6536                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6537                         syms.noSymbol);
6538             }
6539         }
6540     }
6541     // </editor-fold>
6542 
6543     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6544         new TreeScanner() {
6545             Symbol packge = pkg;
6546             @Override
6547             public void visitIdent(JCIdent that) {
6548                 that.sym = packge;
6549             }
6550 
6551             @Override
6552             public void visitSelect(JCFieldAccess that) {
6553                 that.sym = packge;
6554                 packge = packge.owner;
6555                 super.visitSelect(that);
6556             }
6557         }.scan(pid);
6558     }
6559 
6560 }
--- EOF ---