1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.Consumer;
  31 import java.util.stream.Stream;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.tools.JavaFileObject;
  35 
  36 import com.sun.source.tree.CaseTree;
  37 import com.sun.source.tree.IdentifierTree;
  38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  39 import com.sun.source.tree.MemberSelectTree;
  40 import com.sun.source.tree.TreeVisitor;
  41 import com.sun.source.util.SimpleTreeVisitor;
  42 import com.sun.tools.javac.code.*;
  43 import com.sun.tools.javac.code.Lint.LintCategory;
  44 import com.sun.tools.javac.code.LintMapper;
  45 import com.sun.tools.javac.code.Scope.WriteableScope;
  46 import com.sun.tools.javac.code.Source.Feature;
  47 import com.sun.tools.javac.code.Symbol.*;
  48 import com.sun.tools.javac.code.Type.*;
  49 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  50 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  51 import com.sun.tools.javac.comp.Check.CheckContext;
  52 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  53 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  54 import com.sun.tools.javac.jvm.*;
  55 
  56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  59 
  60 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  62 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
  63 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  64 import com.sun.tools.javac.tree.*;
  65 import com.sun.tools.javac.tree.JCTree.*;
  66 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  67 import com.sun.tools.javac.util.*;
  68 import com.sun.tools.javac.util.DefinedBy.Api;
  69 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  70 import com.sun.tools.javac.util.JCDiagnostic.Error;
  71 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  72 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  73 import com.sun.tools.javac.util.List;
  74 
  75 import static com.sun.tools.javac.code.Flags.*;
  76 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  77 import static com.sun.tools.javac.code.Flags.BLOCK;
  78 import static com.sun.tools.javac.code.Kinds.*;
  79 import static com.sun.tools.javac.code.Kinds.Kind.*;
  80 import static com.sun.tools.javac.code.TypeTag.*;
  81 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  82 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  83 
  84 /** This is the main context-dependent analysis phase in GJC. It
  85  *  encompasses name resolution, type checking and constant folding as
  86  *  subtasks. Some subtasks involve auxiliary classes.
  87  *  @see Check
  88  *  @see Resolve
  89  *  @see ConstFold
  90  *  @see Infer
  91  *
  92  *  <p><b>This is NOT part of any supported API.
  93  *  If you write code that depends on this, you do so at your own risk.
  94  *  This code and its internal interfaces are subject to change or
  95  *  deletion without notice.</b>
  96  */
  97 public class Attr extends JCTree.Visitor {
  98     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
  99 
 100     final Names names;
 101     final Log log;
 102     final LintMapper lintMapper;
 103     final Symtab syms;
 104     final Resolve rs;
 105     final Operators operators;
 106     final Infer infer;
 107     final Analyzer analyzer;
 108     final DeferredAttr deferredAttr;
 109     final Check chk;
 110     final Flow flow;
 111     final MemberEnter memberEnter;
 112     final TypeEnter typeEnter;
 113     final TreeMaker make;
 114     final ConstFold cfolder;
 115     final Enter enter;
 116     final Target target;
 117     final Types types;
 118     final Preview preview;
 119     final JCDiagnostic.Factory diags;
 120     final TypeAnnotations typeAnnotations;
 121     final TypeEnvs typeEnvs;
 122     final Dependencies dependencies;
 123     final Annotate annotate;
 124     final ArgumentAttr argumentAttr;
 125     final MatchBindingsComputer matchBindingsComputer;
 126     final AttrRecover attrRecover;
 127     final LocalProxyVarsGen localProxyVarsGen;
 128 
 129     public static Attr instance(Context context) {
 130         Attr instance = context.get(attrKey);
 131         if (instance == null)
 132             instance = new Attr(context);
 133         return instance;
 134     }
 135 
 136     @SuppressWarnings("this-escape")
 137     protected Attr(Context context) {
 138         context.put(attrKey, this);
 139 
 140         names = Names.instance(context);
 141         log = Log.instance(context);
 142         lintMapper = LintMapper.instance(context);
 143         syms = Symtab.instance(context);
 144         rs = Resolve.instance(context);
 145         operators = Operators.instance(context);
 146         chk = Check.instance(context);
 147         flow = Flow.instance(context);
 148         memberEnter = MemberEnter.instance(context);
 149         typeEnter = TypeEnter.instance(context);
 150         make = TreeMaker.instance(context);
 151         enter = Enter.instance(context);
 152         infer = Infer.instance(context);
 153         analyzer = Analyzer.instance(context);
 154         deferredAttr = DeferredAttr.instance(context);
 155         cfolder = ConstFold.instance(context);
 156         target = Target.instance(context);
 157         types = Types.instance(context);
 158         preview = Preview.instance(context);
 159         diags = JCDiagnostic.Factory.instance(context);
 160         annotate = Annotate.instance(context);
 161         typeAnnotations = TypeAnnotations.instance(context);
 162         typeEnvs = TypeEnvs.instance(context);
 163         dependencies = Dependencies.instance(context);
 164         argumentAttr = ArgumentAttr.instance(context);
 165         matchBindingsComputer = MatchBindingsComputer.instance(context);
 166         attrRecover = AttrRecover.instance(context);
 167         localProxyVarsGen = LocalProxyVarsGen.instance(context);
 168 
 169         Options options = Options.instance(context);
 170 
 171         Source source = Source.instance(context);
 172         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 173         allowRecords = Feature.RECORDS.allowedInSource(source);
 174         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 175                              Feature.PATTERN_SWITCH.allowedInSource(source);
 176         allowUnconditionalPatternsInstanceOf =
 177                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 178         sourceName = source.name;
 179         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 180 
 181         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 182         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 183         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 184         methodAttrInfo = new MethodAttrInfo();
 185         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 186         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 187         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 188         initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
 189         allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 190                 Feature.VALUE_CLASSES.allowedInSource(source);
 191     }
 192 
 193     /** Switch: reifiable types in instanceof enabled?
 194      */
 195     boolean allowReifiableTypesInInstanceof;
 196 
 197     /** Are records allowed
 198      */
 199     private final boolean allowRecords;
 200 
 201     /** Are patterns in switch allowed
 202      */
 203     private final boolean allowPatternSwitch;
 204 
 205     /** Are unconditional patterns in instanceof allowed
 206      */
 207     private final boolean allowUnconditionalPatternsInstanceOf;
 208 
 209     /** Are value classes allowed
 210      */
 211     private final boolean allowValueClasses;
 212 
 213     /**
 214      * Switch: warn about use of variable before declaration?
 215      * RFE: 6425594
 216      */
 217     boolean useBeforeDeclarationWarning;
 218 
 219     /**
 220      * Switch: name of source level; used for error reporting.
 221      */
 222     String sourceName;
 223 
 224     /** Check kind and type of given tree against protokind and prototype.
 225      *  If check succeeds, store type in tree and return it.
 226      *  If check fails, store errType in tree and return it.
 227      *  No checks are performed if the prototype is a method type.
 228      *  It is not necessary in this case since we know that kind and type
 229      *  are correct.
 230      *
 231      *  @param tree     The tree whose kind and type is checked
 232      *  @param found    The computed type of the tree
 233      *  @param ownkind  The computed kind of the tree
 234      *  @param resultInfo  The expected result of the tree
 235      */
 236     Type check(final JCTree tree,
 237                final Type found,
 238                final KindSelector ownkind,
 239                final ResultInfo resultInfo) {
 240         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 241         Type owntype;
 242         boolean shouldCheck = !found.hasTag(ERROR) &&
 243                 !resultInfo.pt.hasTag(METHOD) &&
 244                 !resultInfo.pt.hasTag(FORALL);
 245         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 246             log.error(tree.pos(),
 247                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 248                                             ownkind.kindNames()));
 249             owntype = types.createErrorType(found);
 250         } else if (inferenceContext.free(found)) {
 251             //delay the check if there are inference variables in the found type
 252             //this means we are dealing with a partially inferred poly expression
 253             owntype = shouldCheck ? resultInfo.pt : found;
 254             if (resultInfo.checkMode.installPostInferenceHook()) {
 255                 inferenceContext.addFreeTypeListener(List.of(found),
 256                         instantiatedContext -> {
 257                             ResultInfo pendingResult =
 258                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 259                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 260                         });
 261             }
 262         } else {
 263             owntype = shouldCheck ?
 264             resultInfo.check(tree, found) :
 265             found;
 266         }
 267         if (resultInfo.checkMode.updateTreeType()) {
 268             tree.type = owntype;
 269         }
 270         return owntype;
 271     }
 272 
 273     /** Is given blank final variable assignable, i.e. in a scope where it
 274      *  may be assigned to even though it is final?
 275      *  @param v      The blank final variable.
 276      *  @param env    The current environment.
 277      */
 278     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 279         Symbol owner = env.info.scope.owner;
 280            // owner refers to the innermost variable, method or
 281            // initializer block declaration at this point.
 282         boolean isAssignable =
 283             v.owner == owner
 284             ||
 285             ((owner.name == names.init ||    // i.e. we are in a constructor
 286               owner.kind == VAR ||           // i.e. we are in a variable initializer
 287               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 288              &&
 289              v.owner == owner.owner
 290              &&
 291              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 292         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 293         return isAssignable & !insideCompactConstructor;
 294     }
 295 
 296     /** Check that variable can be assigned to.
 297      *  @param pos    The current source code position.
 298      *  @param v      The assigned variable
 299      *  @param base   If the variable is referred to in a Select, the part
 300      *                to the left of the `.', null otherwise.
 301      *  @param env    The current environment.
 302      */
 303     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 304         if (v.name == names._this) {
 305             log.error(pos, Errors.CantAssignValToThis);
 306         } else if ((v.flags() & FINAL) != 0 &&


 307             ((v.flags() & HASINIT) != 0
 308              ||
 309              !((base == null ||
 310                TreeInfo.isThisQualifier(base)) &&
 311                isAssignableAsBlankFinal(v, env)))) {
 312             if (v.isResourceVariable()) { //TWR resource
 313                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 314             } else {
 315                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 316             }

















 317         }
 318     }
 319 
 320     /** Does tree represent a static reference to an identifier?
 321      *  It is assumed that tree is either a SELECT or an IDENT.
 322      *  We have to weed out selects from non-type names here.
 323      *  @param tree    The candidate tree.
 324      */
 325     boolean isStaticReference(JCTree tree) {
 326         if (tree.hasTag(SELECT)) {
 327             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 328             if (lsym == null || lsym.kind != TYP) {
 329                 return false;
 330             }
 331         }
 332         return true;
 333     }
 334 
 335     /** Is this symbol a type?
 336      */
 337     static boolean isType(Symbol sym) {
 338         return sym != null && sym.kind == TYP;
 339     }
 340 
 341     /** Attribute a parsed identifier.
 342      * @param tree Parsed identifier name
 343      * @param topLevel The toplevel to use
 344      */
 345     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 346         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 347         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 348                                            syms.errSymbol.name,
 349                                            null, null, null, null);
 350         localEnv.enclClass.sym = syms.errSymbol;
 351         return attribIdent(tree, localEnv);
 352     }
 353 
 354     /** Attribute a parsed identifier.
 355      * @param tree Parsed identifier name
 356      * @param env The env to use
 357      */
 358     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
 359         return tree.accept(identAttributer, env);
 360     }
 361     // where
 362         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 363         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 364             @Override @DefinedBy(Api.COMPILER_TREE)
 365             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 366                 Symbol site = visit(node.getExpression(), env);
 367                 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
 368                     return site;
 369                 Name name = (Name)node.getIdentifier();
 370                 if (site.kind == PCK) {
 371                     env.toplevel.packge = (PackageSymbol)site;
 372                     return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
 373                             KindSelector.TYP_PCK);
 374                 } else {
 375                     env.enclClass.sym = (ClassSymbol)site;
 376                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 377                 }
 378             }
 379 
 380             @Override @DefinedBy(Api.COMPILER_TREE)
 381             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 382                 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
 383             }
 384         }
 385 
 386     public Type coerce(Type etype, Type ttype) {
 387         return cfolder.coerce(etype, ttype);
 388     }
 389 
 390     public Type attribType(JCTree node, TypeSymbol sym) {
 391         Env<AttrContext> env = typeEnvs.get(sym);
 392         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 393         return attribTree(node, localEnv, unknownTypeInfo);
 394     }
 395 
 396     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
 397         // Attribute qualifying package or class.
 398         JCFieldAccess s = tree.qualid;
 399         return attribTree(s.selected, env,
 400                           new ResultInfo(tree.staticImport ?
 401                                          KindSelector.TYP : KindSelector.TYP_PCK,
 402                        Type.noType));
 403     }
 404 
 405     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 406         return attribToTree(expr, env, tree, unknownExprInfo);
 407     }
 408 
 409     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 410         return attribToTree(stmt, env, tree, statInfo);
 411     }
 412 
 413     private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) {
 414         breakTree = tree;
 415         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 416         try {
 417             deferredAttr.attribSpeculative(root, env, resultInfo,
 418                     null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE,
 419                     argumentAttr.withLocalCacheContext());
 420             attrRecover.doRecovery();
 421         } catch (BreakAttr b) {
 422             return b.env;
 423         } catch (AssertionError ae) {
 424             if (ae.getCause() instanceof BreakAttr breakAttr) {
 425                 return breakAttr.env;
 426             } else {
 427                 throw ae;
 428             }
 429         } finally {
 430             breakTree = null;
 431             log.useSource(prev);
 432         }
 433         return env;
 434     }
 435 
 436     private JCTree breakTree = null;
 437 
 438     private static class BreakAttr extends RuntimeException {
 439         static final long serialVersionUID = -6924771130405446405L;
 440         private transient Env<AttrContext> env;
 441         private BreakAttr(Env<AttrContext> env) {
 442             this.env = env;
 443         }
 444     }
 445 
 446     /**
 447      * Mode controlling behavior of Attr.Check
 448      */
 449     enum CheckMode {
 450 
 451         NORMAL,
 452 
 453         /**
 454          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
 455          * that the captured var cache in {@code InferenceContext} will be used in read-only
 456          * mode when performing inference checks.
 457          */
 458         NO_TREE_UPDATE {
 459             @Override
 460             public boolean updateTreeType() {
 461                 return false;
 462             }
 463         },
 464         /**
 465          * Mode signalling that caller will manage free types in tree decorations.
 466          */
 467         NO_INFERENCE_HOOK {
 468             @Override
 469             public boolean installPostInferenceHook() {
 470                 return false;
 471             }
 472         };
 473 
 474         public boolean updateTreeType() {
 475             return true;
 476         }
 477         public boolean installPostInferenceHook() {
 478             return true;
 479         }
 480     }
 481 
 482 
 483     class ResultInfo {
 484         final KindSelector pkind;
 485         final Type pt;
 486         final CheckContext checkContext;
 487         final CheckMode checkMode;
 488 
 489         ResultInfo(KindSelector pkind, Type pt) {
 490             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
 491         }
 492 
 493         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
 494             this(pkind, pt, chk.basicHandler, checkMode);
 495         }
 496 
 497         protected ResultInfo(KindSelector pkind,
 498                              Type pt, CheckContext checkContext) {
 499             this(pkind, pt, checkContext, CheckMode.NORMAL);
 500         }
 501 
 502         protected ResultInfo(KindSelector pkind,
 503                              Type pt, CheckContext checkContext, CheckMode checkMode) {
 504             this.pkind = pkind;
 505             this.pt = pt;
 506             this.checkContext = checkContext;
 507             this.checkMode = checkMode;
 508         }
 509 
 510         /**
 511          * Should {@link Attr#attribTree} use the {@code ArgumentAttr} visitor instead of this one?
 512          * @param tree The tree to be type-checked.
 513          * @return true if {@code ArgumentAttr} should be used.
 514          */
 515         protected boolean needsArgumentAttr(JCTree tree) { return false; }
 516 
 517         protected Type check(final DiagnosticPosition pos, final Type found) {
 518             return chk.checkType(pos, found, pt, checkContext);
 519         }
 520 
 521         protected ResultInfo dup(Type newPt) {
 522             return new ResultInfo(pkind, newPt, checkContext, checkMode);
 523         }
 524 
 525         protected ResultInfo dup(CheckContext newContext) {
 526             return new ResultInfo(pkind, pt, newContext, checkMode);
 527         }
 528 
 529         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 530             return new ResultInfo(pkind, newPt, newContext, checkMode);
 531         }
 532 
 533         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 534             return new ResultInfo(pkind, newPt, newContext, newMode);
 535         }
 536 
 537         protected ResultInfo dup(CheckMode newMode) {
 538             return new ResultInfo(pkind, pt, checkContext, newMode);
 539         }
 540 
 541         @Override
 542         public String toString() {
 543             if (pt != null) {
 544                 return pt.toString();
 545             } else {
 546                 return "";
 547             }
 548         }
 549     }
 550 
 551     class MethodAttrInfo extends ResultInfo {
 552         public MethodAttrInfo() {
 553             this(chk.basicHandler);
 554         }
 555 
 556         public MethodAttrInfo(CheckContext checkContext) {
 557             super(KindSelector.VAL, Infer.anyPoly, checkContext);
 558         }
 559 
 560         @Override
 561         protected boolean needsArgumentAttr(JCTree tree) {
 562             return true;
 563         }
 564 
 565         protected ResultInfo dup(Type newPt) {
 566             throw new IllegalStateException();
 567         }
 568 
 569         protected ResultInfo dup(CheckContext newContext) {
 570             return new MethodAttrInfo(newContext);
 571         }
 572 
 573         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 574             throw new IllegalStateException();
 575         }
 576 
 577         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 578             throw new IllegalStateException();
 579         }
 580 
 581         protected ResultInfo dup(CheckMode newMode) {
 582             throw new IllegalStateException();
 583         }
 584     }
 585 
 586     class RecoveryInfo extends ResultInfo {
 587 
 588         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
 589             this(deferredAttrContext, Type.recoveryType);
 590         }
 591 
 592         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
 593             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
 594                 @Override
 595                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
 596                     return deferredAttrContext;
 597                 }
 598                 @Override
 599                 public boolean compatible(Type found, Type req, Warner warn) {
 600                     return true;
 601                 }
 602                 @Override
 603                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 604                     boolean needsReport = pt == Type.recoveryType ||
 605                             (details.getDiagnosticPosition() != null &&
 606                             details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
 607                     if (needsReport) {
 608                         chk.basicHandler.report(pos, details);
 609                     }
 610                 }
 611             });
 612         }
 613     }
 614 
 615     final ResultInfo statInfo;
 616     final ResultInfo varAssignmentInfo;
 617     final ResultInfo methodAttrInfo;
 618     final ResultInfo unknownExprInfo;
 619     final ResultInfo unknownTypeInfo;
 620     final ResultInfo unknownTypeExprInfo;
 621     final ResultInfo recoveryInfo;
 622     final MethodType initBlockType;
 623 
 624     Type pt() {
 625         return resultInfo.pt;
 626     }
 627 
 628     KindSelector pkind() {
 629         return resultInfo.pkind;
 630     }
 631 
 632 /* ************************************************************************
 633  * Visitor methods
 634  *************************************************************************/
 635 
 636     /** Visitor argument: the current environment.
 637      */
 638     Env<AttrContext> env;
 639 
 640     /** Visitor argument: the currently expected attribution result.
 641      */
 642     ResultInfo resultInfo;
 643 
 644     /** Visitor result: the computed type.
 645      */
 646     Type result;
 647 
 648     MatchBindings matchBindings = MatchBindingsComputer.EMPTY;
 649 
 650     /** Visitor method: attribute a tree, catching any completion failure
 651      *  exceptions. Return the tree's type.
 652      *
 653      *  @param tree    The tree to be visited.
 654      *  @param env     The environment visitor argument.
 655      *  @param resultInfo   The result info visitor argument.
 656      */
 657     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
 658         Env<AttrContext> prevEnv = this.env;
 659         ResultInfo prevResult = this.resultInfo;
 660         try {
 661             this.env = env;
 662             this.resultInfo = resultInfo;
 663             if (resultInfo.needsArgumentAttr(tree)) {
 664                 result = argumentAttr.attribArg(tree, env);
 665             } else {
 666                 tree.accept(this);
 667             }
 668             matchBindings = matchBindingsComputer.finishBindings(tree,
 669                                                                  matchBindings);
 670             if (tree == breakTree &&
 671                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
 672                 breakTreeFound(copyEnv(env));
 673             }
 674             return result;
 675         } catch (CompletionFailure ex) {
 676             tree.type = syms.errType;
 677             return chk.completionError(tree.pos(), ex);
 678         } finally {
 679             this.env = prevEnv;
 680             this.resultInfo = prevResult;
 681         }
 682     }
 683 
 684     protected void breakTreeFound(Env<AttrContext> env) {
 685         throw new BreakAttr(env);
 686     }
 687 
 688     Env<AttrContext> copyEnv(Env<AttrContext> env) {
 689         Env<AttrContext> newEnv =
 690                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
 691         if (newEnv.outer != null) {
 692             newEnv.outer = copyEnv(newEnv.outer);
 693         }
 694         return newEnv;
 695     }
 696 
 697     WriteableScope copyScope(WriteableScope sc) {
 698         WriteableScope newScope = WriteableScope.create(sc.owner);
 699         List<Symbol> elemsList = List.nil();
 700         for (Symbol sym : sc.getSymbols()) {
 701             elemsList = elemsList.prepend(sym);
 702         }
 703         for (Symbol s : elemsList) {
 704             newScope.enter(s);
 705         }
 706         return newScope;
 707     }
 708 
 709     /** Derived visitor method: attribute an expression tree.
 710      */
 711     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 712         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
 713     }
 714 
 715     /** Derived visitor method: attribute an expression tree with
 716      *  no constraints on the computed type.
 717      */
 718     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
 719         return attribTree(tree, env, unknownExprInfo);
 720     }
 721 
 722     /** Derived visitor method: attribute a type tree.
 723      */
 724     public Type attribType(JCTree tree, Env<AttrContext> env) {
 725         Type result = attribType(tree, env, Type.noType);
 726         return result;
 727     }
 728 
 729     /** Derived visitor method: attribute a type tree.
 730      */
 731     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 732         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
 733         return result;
 734     }
 735 
 736     /** Derived visitor method: attribute a statement or definition tree.
 737      */
 738     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 739         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
 740         Type result = attribTree(tree, env, statInfo);
 741         analyzer.analyzeIfNeeded(tree, analyzeEnv);
 742         attrRecover.doRecovery();
 743         return result;
 744     }
 745 
 746     /** Attribute a list of expressions, returning a list of types.
 747      */
 748     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 749         ListBuffer<Type> ts = new ListBuffer<>();
 750         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 751             ts.append(attribExpr(l.head, env, pt));
 752         return ts.toList();
 753     }
 754 
 755     /** Attribute a list of statements, returning nothing.
 756      */
 757     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 758         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 759             attribStat(l.head, env);
 760     }
 761 
 762     /** Attribute the arguments in a method call, returning the method kind.
 763      */
 764     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
 765         KindSelector kind = initialKind;
 766         for (JCExpression arg : trees) {
 767             Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, methodAttrInfo));
 768             if (argtype.hasTag(DEFERRED)) {
 769                 kind = KindSelector.of(KindSelector.POLY, kind);
 770             }
 771             argtypes.append(argtype);
 772         }
 773         return kind;
 774     }
 775 
 776     /** Attribute a type argument list, returning a list of types.
 777      *  Caller is responsible for calling checkRefTypes.
 778      */
 779     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 780         ListBuffer<Type> argtypes = new ListBuffer<>();
 781         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 782             argtypes.append(attribType(l.head, env));
 783         return argtypes.toList();
 784     }
 785 
 786     /** Attribute a type argument list, returning a list of types.
 787      *  Check that all the types are references.
 788      */
 789     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 790         List<Type> types = attribAnyTypes(trees, env);
 791         return chk.checkRefTypes(trees, types);
 792     }
 793 
 794     /**
 795      * Attribute type variables (of generic classes or methods).
 796      * Compound types are attributed later in attribBounds.
 797      * @param typarams the type variables to enter
 798      * @param env      the current environment
 799      */
 800     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 801         for (JCTypeParameter tvar : typarams) {
 802             TypeVar a = (TypeVar)tvar.type;
 803             a.tsym.flags_field |= UNATTRIBUTED;
 804             a.setUpperBound(Type.noType);
 805             if (!tvar.bounds.isEmpty()) {
 806                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 807                 for (JCExpression bound : tvar.bounds.tail)
 808                     bounds = bounds.prepend(attribType(bound, env));
 809                 types.setBounds(a, bounds.reverse());
 810             } else {
 811                 // if no bounds are given, assume a single bound of
 812                 // java.lang.Object.
 813                 types.setBounds(a, List.of(syms.objectType));
 814             }
 815             a.tsym.flags_field &= ~UNATTRIBUTED;
 816         }
 817         if (checkCyclic) {
 818             for (JCTypeParameter tvar : typarams) {
 819                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 820             }
 821         }
 822     }
 823 
 824     /**
 825      * Attribute the type references in a list of annotations.
 826      */
 827     void attribAnnotationTypes(List<JCAnnotation> annotations,
 828                                Env<AttrContext> env) {
 829         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 830             JCAnnotation a = al.head;
 831             attribType(a.annotationType, env);
 832         }
 833     }
 834 
 835     /**
 836      * Attribute a "lazy constant value".
 837      *  @param env         The env for the const value
 838      *  @param variable    The initializer for the const value
 839      *  @param type        The expected type, or null
 840      *  @see VarSymbol#setLazyConstValue
 841      */
 842     public Object attribLazyConstantValue(Env<AttrContext> env,
 843                                       Env<AttrContext> enclosingEnv,
 844                                       JCVariableDecl variable,
 845                                       Type type) {
 846         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 847         try {
 848             doQueueScanTreeAndTypeAnnotateForVarInit(variable, enclosingEnv);
 849             Type itype = attribExpr(variable.init, env, type);
 850             if (variable.isImplicitlyTyped()) {
 851                 //fixup local variable type
 852                 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype, variable.name);
 853             }
 854             if (itype.constValue() != null) {
 855                 return coerce(itype, type).constValue();
 856             } else {
 857                 return null;
 858             }
 859         } finally {
 860             log.useSource(prevSource);
 861         }
 862     }
 863 
 864     /** Attribute type reference in an `extends', `implements', or 'permits' clause.
 865      *  Supertypes of anonymous inner classes are usually already attributed.
 866      *
 867      *  @param tree              The tree making up the type reference.
 868      *  @param env               The environment current at the reference.
 869      *  @param classExpected     true if only a class is expected here.
 870      *  @param interfaceExpected true if only an interface is expected here.
 871      */
 872     Type attribBase(JCTree tree,
 873                     Env<AttrContext> env,
 874                     boolean classExpected,
 875                     boolean interfaceExpected,
 876                     boolean checkExtensible) {
 877         Type t = tree.type != null ?
 878             tree.type :
 879             attribType(tree, env);
 880         try {
 881             return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 882         } catch (CompletionFailure ex) {
 883             chk.completionError(tree.pos(), ex);
 884             return t;
 885         }
 886     }
 887     Type checkBase(Type t,
 888                    JCTree tree,
 889                    Env<AttrContext> env,
 890                    boolean classExpected,
 891                    boolean interfaceExpected,
 892                    boolean checkExtensible) {
 893         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
 894                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
 895         if (t.tsym.isAnonymous()) {
 896             log.error(pos, Errors.CantInheritFromAnon);
 897             return types.createErrorType(t);
 898         }
 899         if (t.isErroneous())
 900             return t;
 901         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
 902             // check that type variable is already visible
 903             if (t.getUpperBound() == null) {
 904                 log.error(pos, Errors.IllegalForwardRef);
 905                 return types.createErrorType(t);
 906             }
 907         } else {
 908             t = chk.checkClassType(pos, t, checkExtensible);
 909         }
 910         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 911             log.error(pos, Errors.IntfExpectedHere);
 912             // return errType is necessary since otherwise there might
 913             // be undetected cycles which cause attribution to loop
 914             return types.createErrorType(t);
 915         } else if (checkExtensible &&
 916                    classExpected &&
 917                    (t.tsym.flags() & INTERFACE) != 0) {
 918             log.error(pos, Errors.NoIntfExpectedHere);
 919             return types.createErrorType(t);
 920         }
 921         if (checkExtensible &&
 922             ((t.tsym.flags() & FINAL) != 0)) {
 923             log.error(pos,
 924                       Errors.CantInheritFromFinal(t.tsym));
 925         }
 926         chk.checkNonCyclic(pos, t);
 927         return t;
 928     }
 929 
 930     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
 931         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
 932         id.type = env.info.scope.owner.enclClass().type;
 933         id.sym = env.info.scope.owner.enclClass();
 934         return id.type;
 935     }
 936 
 937     public void visitClassDef(JCClassDecl tree) {
 938         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
 939                 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
 940                         argumentAttr.withLocalCacheContext() : null);
 941         boolean ctorProloguePrev = env.info.ctorPrologue;
 942         try {
 943             // Local and anonymous classes have not been entered yet, so we need to
 944             // do it now.
 945             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
 946                 enter.classEnter(tree, env);
 947             } else {
 948                 // If this class declaration is part of a class level annotation,
 949                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
 950                 // order to simplify later steps and allow for sensible error
 951                 // messages.
 952                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
 953                     enter.classEnter(tree, env);
 954             }
 955 
 956             ClassSymbol c = tree.sym;
 957             if (c == null) {
 958                 // exit in case something drastic went wrong during enter.
 959                 result = null;
 960             } else {
 961                 // make sure class has been completed:
 962                 c.complete();
 963 
 964                 // If a class declaration appears in a constructor prologue,
 965                 // that means it's either a local class or an anonymous class.
 966                 // Either way, there is no immediately enclosing instance.
 967                 if (ctorProloguePrev) {
 968                     c.flags_field |= NOOUTERTHIS;
 969                 }
 970                 attribClass(tree.pos(), c);
 971                 result = tree.type = c.type;
 972             }
 973         } finally {
 974             localCacheContext.ifPresent(LocalCacheContext::leave);
 975             env.info.ctorPrologue = ctorProloguePrev;
 976         }
 977     }
 978 
 979     public void visitMethodDef(JCMethodDecl tree) {
 980         MethodSymbol m = tree.sym;
 981         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
 982 
 983         Lint lint = env.info.lint.augment(m);
 984         Lint prevLint = chk.setLint(lint);
 985         boolean ctorProloguePrev = env.info.ctorPrologue;
 986         Assert.check(!env.info.ctorPrologue);
 987         MethodSymbol prevMethod = chk.setMethod(m);
 988         try {
 989             chk.checkDeprecatedAnnotation(tree.pos(), m);
 990 
 991 
 992             // Create a new environment with local scope
 993             // for attributing the method.
 994             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
 995             localEnv.info.lint = lint;
 996 
 997             attribStats(tree.typarams, localEnv);
 998 
 999             // If we override any other methods, check that we do so properly.
1000             // JLS ???
1001             if (m.isStatic()) {
1002                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1003             } else {
1004                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1005             }
1006             chk.checkOverride(env, tree, m);
1007 
1008             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1009                 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1010             }
1011 
1012             // Enter all type parameters into the local method scope.
1013             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1014                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1015 
1016             ClassSymbol owner = env.enclClass.sym;
1017             if ((owner.flags() & ANNOTATION) != 0 &&
1018                     (tree.params.nonEmpty() ||
1019                     tree.recvparam != null))
1020                 log.error(tree.params.nonEmpty() ?
1021                         tree.params.head.pos() :
1022                         tree.recvparam.pos(),
1023                         Errors.IntfAnnotationMembersCantHaveParams);
1024 
1025             // Attribute all value parameters.
1026             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1027                 attribStat(l.head, localEnv);
1028             }
1029 
1030             chk.checkVarargsMethodDecl(localEnv, tree);
1031 
1032             // Check that type parameters are well-formed.
1033             chk.validate(tree.typarams, localEnv);
1034 
1035             // Check that result type is well-formed.
1036             if (tree.restype != null && !tree.restype.type.hasTag(VOID)) {
1037                 chk.validate(tree.restype, localEnv);
1038             }
1039             chk.checkRequiresIdentity(tree, env.info.lint);
1040 
1041             // Check that receiver type is well-formed.
1042             if (tree.recvparam != null) {
1043                 // Use a new environment to check the receiver parameter.
1044                 // Otherwise I get "might not have been initialized" errors.
1045                 // Is there a better way?
1046                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1047                 attribType(tree.recvparam, newEnv);
1048                 chk.validate(tree.recvparam, newEnv);
1049             }
1050 
1051             // Is this method a constructor?
1052             boolean isConstructor = TreeInfo.isConstructor(tree);
1053 
1054             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP) {
1055                 // lets find if this method is an accessor
1056                 Optional<? extends RecordComponent> recordComponent = env.enclClass.sym.getRecordComponents().stream()
1057                         .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
1058                 if (recordComponent.isPresent()) {
1059                     // the method is a user defined accessor lets check that everything is fine
1060                     if (!tree.sym.isPublic()) {
1061                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1062                     }
1063                     if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1064                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1065                                 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1066                     }
1067                     if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1068                         log.error(tree,
1069                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1070                     }
1071                     if (!tree.typarams.isEmpty()) {
1072                         log.error(tree,
1073                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1074                     }
1075                     if (tree.sym.isStatic()) {
1076                         log.error(tree,
1077                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1078                     }
1079                 }
1080 
1081                 if (isConstructor) {
1082                     // if this a constructor other than the canonical one
1083                     if ((tree.sym.flags_field & RECORD) == 0) {
1084                         if (!TreeInfo.hasConstructorCall(tree, names._this)) {
1085                             log.error(tree, Errors.NonCanonicalConstructorInvokeAnotherConstructor(env.enclClass.sym));
1086                         }
1087                     } else {
1088                         // but if it is the canonical:
1089 
1090                         /* if user generated, then it shouldn't:
1091                          *     - have an accessibility stricter than that of the record type
1092                          *     - explicitly invoke any other constructor
1093                          */
1094                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1095                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1096                                 log.error(tree,
1097                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1098                                             Errors.InvalidCanonicalConstructorInRecord(
1099                                                 Fragments.Canonical,
1100                                                 env.enclClass.sym.name,
1101                                                 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1102                                             ) :
1103                                             Errors.InvalidCanonicalConstructorInRecord(
1104                                                     Fragments.Canonical,
1105                                                     env.enclClass.sym.name,
1106                                                     Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1107                                             )
1108                                 );
1109                             }
1110 
1111                             if (!allowValueClasses && TreeInfo.hasAnyConstructorCall(tree)) {
1112                                 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1113                                         Fragments.Canonical, env.enclClass.sym.name,
1114                                         Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1115                             }
1116                         }
1117 
1118                         // also we want to check that no type variables have been defined
1119                         if (!tree.typarams.isEmpty()) {
1120                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1121                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1122                         }
1123 
1124                         /* and now we need to check that the constructor's arguments are exactly the same as those of the
1125                          * record components
1126                          */
1127                         List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1128                         List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1129                         for (JCVariableDecl param: tree.params) {
1130                             boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1131                             if (!types.isSameType(param.type, recordFieldTypes.head) ||
1132                                     (recordComponents.head.isVarargs() != paramIsVarArgs)) {
1133                                 log.error(param, Errors.InvalidCanonicalConstructorInRecord(
1134                                         Fragments.Canonical, env.enclClass.sym.name,
1135                                         Fragments.TypeMustBeIdenticalToCorrespondingRecordComponentType));
1136                             }
1137                             recordComponents = recordComponents.tail;
1138                             recordFieldTypes = recordFieldTypes.tail;
1139                         }
1140                     }
1141                 }
1142             }
1143 
1144             // annotation method checks
1145             if ((owner.flags() & ANNOTATION) != 0) {
1146                 // annotation method cannot have throws clause
1147                 if (tree.thrown.nonEmpty()) {
1148                     log.error(tree.thrown.head.pos(),
1149                               Errors.ThrowsNotAllowedInIntfAnnotation);
1150                 }
1151                 // annotation method cannot declare type-parameters
1152                 if (tree.typarams.nonEmpty()) {
1153                     log.error(tree.typarams.head.pos(),
1154                               Errors.IntfAnnotationMembersCantHaveTypeParams);
1155                 }
1156                 // validate annotation method's return type (could be an annotation type)
1157                 chk.validateAnnotationType(tree.restype);
1158                 // ensure that annotation method does not clash with members of Object/Annotation
1159                 chk.validateAnnotationMethod(tree.pos(), m);
1160             }
1161 
1162             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1163                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1164 
1165             if (tree.body == null) {
1166                 // Empty bodies are only allowed for
1167                 // abstract, native, or interface methods, or for methods
1168                 // in a retrofit signature class.
1169                 if (tree.defaultValue != null) {
1170                     if ((owner.flags() & ANNOTATION) == 0)
1171                         log.error(tree.pos(),
1172                                   Errors.DefaultAllowedInIntfAnnotationMember);
1173                 }
1174                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1175                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract(tree.sym, owner));
1176             } else {
1177                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1178                     if ((owner.flags() & INTERFACE) != 0) {
1179                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1180                     } else {
1181                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1182                     }
1183                 } else if ((tree.mods.flags & NATIVE) != 0) {
1184                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1185                 }
1186                 // Add an implicit super() call unless an explicit call to
1187                 // super(...) or this(...) is given
1188                 // or we are compiling class java.lang.Object.
1189                 boolean addedSuperInIdentityClass = false;
1190                 if (isConstructor && owner.type != syms.objectType) {
1191                     if (!TreeInfo.hasAnyConstructorCall(tree)) {
1192                         JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1193                                 make.Ident(names._super), make.Idents(List.nil())));
1194                         if (allowValueClasses && (owner.isValueClass() || owner.hasStrict() || ((owner.flags_field & RECORD) != 0))) {
1195                             tree.body.stats = tree.body.stats.append(supCall);
1196                         } else {
1197                             tree.body.stats = tree.body.stats.prepend(supCall);
1198                             addedSuperInIdentityClass = true;
1199                         }
1200                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1201                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1202                             TreeInfo.hasConstructorCall(tree, names._super)) {
1203                         // enum constructors are not allowed to call super
1204                         // directly, so make sure there aren't any super calls
1205                         // in enum constructors, except in the compiler
1206                         // generated one.
1207                         log.error(tree.body.stats.head.pos(),
1208                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1209                     }
1210                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1211                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1212                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1213                         if (!initParamNames.equals(recordComponentNames)) {
1214                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1215                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1216                         }
1217                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1218                             log.error(tree,
1219                                     Errors.InvalidCanonicalConstructorInRecord(
1220                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1221                                             env.enclClass.sym.name,
1222                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1223                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1224                         }
1225                     }
1226                 }
1227 
1228                 // Attribute all type annotations in the body
1229                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1230                 annotate.flush();
1231 
1232                 // Start of constructor prologue (if not in java.lang.Object constructor)
1233                 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1234 
1235                 // Attribute method body.
1236                 attribStat(tree.body, localEnv);
1237                 if (localEnv.info.ctorPrologue) {
1238                     boolean thisInvocation = false;
1239                     ListBuffer<JCTree> prologueCode = new ListBuffer<>();
1240                     for (JCTree stat : tree.body.stats) {
1241                         prologueCode.add(stat);
1242                         /* gather all the stats in the body until a `super` or `this` constructor invocation is found,
1243                          * including the constructor invocation, that way we don't need to worry in the visitor below if
1244                          * if we are dealing or not with prologue code
1245                          */
1246                         if (stat instanceof JCExpressionStatement expStmt &&
1247                                 expStmt.expr instanceof JCMethodInvocation mi &&
1248                                 TreeInfo.isConstructorCall(mi)) {
1249                             thisInvocation = TreeInfo.name(mi.meth) == names._this;
1250                             if (!addedSuperInIdentityClass || !allowValueClasses) {
1251                                 break;
1252                             }
1253                         }
1254                     }
1255                     if (!prologueCode.isEmpty()) {
1256                         CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(localEnv,
1257                                 addedSuperInIdentityClass && allowValueClasses ?
1258                                         PrologueVisitorMode.WARNINGS_ONLY :
1259                                         thisInvocation ?
1260                                                 PrologueVisitorMode.THIS_CONSTRUCTOR :
1261                                                 PrologueVisitorMode.SUPER_CONSTRUCTOR,
1262                                 false);
1263                         ctorPrologueVisitor.scan(prologueCode.toList());
1264                     }
1265                 }
1266             }
1267 
1268             localEnv.info.scope.leave();
1269             result = tree.type = m.type;
1270         } finally {
1271             chk.setLint(prevLint);
1272             chk.setMethod(prevMethod);
1273             env.info.ctorPrologue = ctorProloguePrev;
1274         }
1275     }
1276 
1277     enum PrologueVisitorMode {
1278         WARNINGS_ONLY,
1279         SUPER_CONSTRUCTOR,
1280         THIS_CONSTRUCTOR
1281     }
1282 
1283     class CtorPrologueVisitor extends TreeScanner {
1284         Env<AttrContext> localEnv;
1285         PrologueVisitorMode mode;
1286         boolean isInitializer;
1287 
1288         CtorPrologueVisitor(Env<AttrContext> localEnv, PrologueVisitorMode mode, boolean isInitializer) {
1289             this.localEnv = localEnv;
1290             currentClassSym = localEnv.enclClass.sym;
1291             this.mode = mode;
1292             this.isInitializer = isInitializer;
1293         }
1294 
1295         boolean insideLambdaOrClassDef = false;
1296 
1297         @Override
1298         public void visitLambda(JCLambda lambda) {
1299             boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1300             try {
1301                 insideLambdaOrClassDef = true;
1302                 super.visitLambda(lambda);
1303             } finally {
1304                 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1305             }
1306         }
1307 
1308         ClassSymbol currentClassSym;
1309 
1310         @Override
1311         public void visitClassDef(JCClassDecl classDecl) {
1312             boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1313             ClassSymbol previousClassSym = currentClassSym;
1314             try {
1315                 insideLambdaOrClassDef = true;
1316                 currentClassSym = classDecl.sym;
1317                 super.visitClassDef(classDecl);
1318             } finally {
1319                 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1320                 currentClassSym = previousClassSym;
1321             }
1322         }
1323 
1324         private void reportPrologueError(JCTree tree, Symbol sym) {
1325             reportPrologueError(tree, sym, false);
1326         }
1327 
1328         private void reportPrologueError(JCTree tree, Symbol sym, boolean hasInit) {
1329             preview.checkSourceLevel(tree, Feature.FLEXIBLE_CONSTRUCTORS);
1330             if (mode != PrologueVisitorMode.WARNINGS_ONLY) {
1331                 if (hasInit) {
1332                     log.error(tree, Errors.CantAssignInitializedBeforeCtorCalled(sym));
1333                 } else {
1334                     log.error(tree, Errors.CantRefBeforeCtorCalled(sym));
1335                 }
1336             } else if (allowValueClasses) {
1337                 // issue lint warning
1338                 log.warning(tree, LintWarnings.WouldNotBeAllowedInPrologue(sym));
1339             }
1340         }
1341 
1342         @Override
1343         public void visitApply(JCMethodInvocation tree) {
1344             super.visitApply(tree);
1345             Name name = TreeInfo.name(tree.meth);
1346             boolean isConstructorCall = name == names._this || name == names._super;
1347             Symbol msym = TreeInfo.symbolFor(tree.meth);
1348             // is this an instance method call or an illegal constructor invocation like: `this.super()`?
1349             if (msym != null && // for erroneous invocations msym can be null, ignore those
1350                 (!isConstructorCall ||
1351                 isConstructorCall && tree.meth.hasTag(SELECT))) {
1352                 if (isEarlyReference(localEnv, tree.meth, msym))
1353                     reportPrologueError(tree.meth, msym);
1354             }
1355         }
1356 
1357         @Override
1358         public void visitIdent(JCIdent tree) {
1359             analyzeSymbol(tree);
1360         }
1361 
1362         boolean isIndexed = false;
1363 
1364         @Override
1365         public void visitIndexed(JCArrayAccess tree) {
1366             boolean previousIsIndexed = isIndexed;
1367             try {
1368                 isIndexed = true;
1369                 scan(tree.indexed);
1370             } finally {
1371                 isIndexed = previousIsIndexed;
1372             }
1373             scan(tree.index);
1374             if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR && isInstanceField(tree.indexed)) {
1375                 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(tree.indexed));
1376             }
1377         }
1378 
1379         @Override
1380         public void visitSelect(JCFieldAccess tree) {
1381             SelectScanner ss = new SelectScanner();
1382             ss.scan(tree);
1383             if (ss.scanLater == null) {
1384                 analyzeSymbol(tree);
1385             } else {
1386                 boolean prevLhs = isInLHS;
1387                 try {
1388                     isInLHS = false;
1389                     scan(ss.scanLater);
1390                 } finally {
1391                     isInLHS = prevLhs;
1392                 }
1393             }
1394             if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1395                 for (JCTree subtree : ss.selectorTrees) {
1396                     if (isInstanceField(subtree)) {
1397                         // we need to add a proxy for this one
1398                         localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(subtree));
1399                     }
1400                 }
1401             }
1402         }
1403 
1404         boolean isInstanceField(JCTree tree) {
1405             Symbol sym = TreeInfo.symbolFor(tree);
1406             return (sym != null &&
1407                     !sym.isStatic() &&
1408                     sym.kind == VAR &&
1409                     sym.owner.kind == TYP &&
1410                     sym.name != names._this &&
1411                     sym.name != names._super &&
1412                     isEarlyReference(localEnv, tree, sym));
1413         }
1414 
1415         @Override
1416         public void visitNewClass(JCNewClass tree) {
1417             super.visitNewClass(tree);
1418             checkNewClassAndMethRefs(tree, tree.type);
1419         }
1420 
1421         @Override
1422         public void visitReference(JCMemberReference tree) {
1423             super.visitReference(tree);
1424             if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1425                 checkNewClassAndMethRefs(tree, tree.expr.type);
1426             }
1427         }
1428 
1429         void checkNewClassAndMethRefs(JCTree tree, Type t) {
1430             if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1431                     !t.tsym.isStatic() &&
1432                     !t.tsym.isDirectlyOrIndirectlyLocal()) {
1433                 reportPrologueError(tree, t.getEnclosingType().tsym);
1434             }
1435         }
1436 
1437         /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1438          * for a proxy local variable later on
1439          */
1440         boolean isInLHS = false;
1441 
1442         @Override
1443         public void visitAssign(JCAssign tree) {
1444             boolean previousIsInLHS = isInLHS;
1445             try {
1446                 isInLHS = true;
1447                 scan(tree.lhs);
1448             } finally {
1449                 isInLHS = previousIsInLHS;
1450             }
1451             scan(tree.rhs);
1452         }
1453 
1454         @Override
1455         public void visitMethodDef(JCMethodDecl tree) {
1456             // ignore any declarative part, mainly to avoid scanning receiver parameters
1457             scan(tree.body);
1458         }
1459 
1460         void analyzeSymbol(JCTree tree) {
1461             Symbol sym = TreeInfo.symbolFor(tree);
1462             // make sure that there is a symbol and it is not static
1463             if (sym == null || sym.isStatic()) {
1464                 return;
1465             }
1466             if (isInLHS && !insideLambdaOrClassDef) {
1467                 // Check instance field assignments that appear in constructor prologues
1468                 if (isEarlyReference(localEnv, tree, sym)) {
1469                     // Field may not be inherited from a superclass
1470                     if (sym.owner != localEnv.enclClass.sym) {
1471                         reportPrologueError(tree, sym);
1472                         return;
1473                     }
1474                     // Field may not have an initializer
1475                     if ((sym.flags() & HASINIT) != 0) {
1476                         if (!localEnv.enclClass.sym.isValueClass() || !sym.type.hasTag(ARRAY) || !isIndexed) {
1477                             reportPrologueError(tree, sym, true);
1478                         }
1479                         return;
1480                     }
1481                     // cant reference an instance field before a this constructor
1482                     if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1483                         reportPrologueError(tree, sym);
1484                         return;
1485                     }
1486                 }
1487                 return;
1488             }
1489             tree = TreeInfo.skipParens(tree);
1490             if (sym.kind == VAR && sym.owner.kind == TYP) {
1491                 if (sym.name == names._this || sym.name == names._super) {
1492                     // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1493                     if (TreeInfo.isExplicitThisReference(
1494                             types,
1495                             (ClassType)localEnv.enclClass.sym.type,
1496                             tree)) {
1497                         reportPrologueError(tree, sym);
1498                     }
1499                 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1500                     if (sym.owner != localEnv.enclClass.sym) {
1501                         if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1502                                 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1503                             /* if we are dealing with a field that doesn't belong to the current class, but the
1504                              * field is inherited, this is an error. Unless, the super class is also an outer
1505                              * class and the field's qualifier refers to the outer class
1506                              */
1507                             if (tree.hasTag(IDENT) ||
1508                                 TreeInfo.isExplicitThisReference(
1509                                         types,
1510                                         (ClassType)localEnv.enclClass.sym.type,
1511                                         ((JCFieldAccess)tree).selected)) {
1512                                 reportPrologueError(tree, sym);
1513                             }
1514                         }
1515                     } else if (isEarlyReference(localEnv, tree, sym)) {
1516                         /* now this is a `proper` instance field of the current class
1517                          * references to fields of identity classes which happen to have initializers are
1518                          * not allowed in the prologue.
1519                          * But it is OK for a field with initializer to refer to another field with initializer,
1520                          * so no warning or error if we are analyzing a field initializer.
1521                          */
1522                         if (insideLambdaOrClassDef ||
1523                             (!localEnv.enclClass.sym.isValueClass() &&
1524                              (sym.flags_field & HASINIT) != 0 &&
1525                              !isInitializer))
1526                             reportPrologueError(tree, sym);
1527                         // we will need to generate a proxy for this field later on
1528                         if (!isInLHS) {
1529                             if (!allowValueClasses) {
1530                                 reportPrologueError(tree, sym);
1531                             } else {
1532                                 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1533                                     reportPrologueError(tree, sym);
1534                                 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1535                                     localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1536                                 }
1537                                 /* we do nothing in warnings only mode, as in that mode we are simulating what
1538                                  * the compiler would do in case the constructor code would be in the prologue
1539                                  * phase
1540                                  */
1541                             }
1542                         }
1543                     }
1544                 }
1545             }
1546         }
1547 
1548         /**
1549          * Determine if the symbol appearance constitutes an early reference to the current class.
1550          *
1551          * <p>
1552          * This means the symbol is an instance field, or method, of the current class and it appears
1553          * in an early initialization context of it (i.e., one of its constructor prologues).
1554          *
1555          * @param env    The current environment
1556          * @param tree   the AST referencing the variable
1557          * @param sym    The symbol
1558          */
1559         private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1560             if ((sym.flags() & STATIC) == 0 &&
1561                     (sym.kind == VAR || sym.kind == MTH) &&
1562                     sym.isMemberOf(env.enclClass.sym, types)) {
1563                 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1564                 if (tree instanceof JCFieldAccess fa) {
1565                     return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1566                 } else if (currentClassSym != env.enclClass.sym) {
1567                     /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1568                      * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1569                      * otherwise it is not.
1570                      * It could be that the reference to CI's member happens inside CI's own prologue, but that
1571                      * will be checked separately, when CI's prologue is analyzed.
1572                      */
1573                     return !sym.isMemberOf(currentClassSym, types);
1574                 }
1575                 return true;
1576             }
1577             return false;
1578         }
1579 
1580         /* scanner for a select expression, anything that is not a select or identifier
1581          * will be stored for further analysis
1582          */
1583         class SelectScanner extends DeferredAttr.FilterScanner {
1584             JCTree scanLater;
1585             java.util.List<JCTree> selectorTrees = new ArrayList<>();
1586 
1587             SelectScanner() {
1588                 super(Set.of(IDENT, SELECT, PARENS));
1589             }
1590 
1591             @Override
1592             public void visitSelect(JCFieldAccess tree) {
1593                 super.visitSelect(tree);
1594                 selectorTrees.add(tree.selected);
1595             }
1596 
1597             @Override
1598             void skip(JCTree tree) {
1599                 scanLater = tree;
1600             }
1601         }
1602     }
1603 
1604     public void visitVarDef(JCVariableDecl tree) {
1605         // Local variables have not been entered yet, so we need to do it now:
1606         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1607             if (tree.sym != null) {
1608                 // parameters have already been entered
1609                 env.info.scope.enter(tree.sym);
1610             } else {
1611                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1612                     if (tree.init == null) {
1613                         //cannot use 'var' without initializer
1614                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1615                         tree.vartype = make.at(tree.pos()).Erroneous();
1616                     } else {
1617                         Fragment msg = canInferLocalVarType(tree);
1618                         if (msg != null) {
1619                             //cannot use 'var' with initializer which require an explicit target
1620                             //(e.g. lambda, method reference, array initializer).
1621                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1622                             tree.vartype = make.at(tree.pos()).Erroneous();
1623                         }
1624                     }
1625                 }
1626                 try {
1627                     annotate.blockAnnotations();
1628                     memberEnter.memberEnter(tree, env);
1629                 } finally {
1630                     annotate.unblockAnnotations();
1631                 }
1632             }
1633         } else {
1634             doQueueScanTreeAndTypeAnnotateForVarInit(tree, env);
1635         }
1636 
1637         VarSymbol v = tree.sym;
1638         Lint lint = env.info.lint.augment(v);
1639         Lint prevLint = chk.setLint(lint);
1640 
1641         // Check that the variable's declared type is well-formed.
1642         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1643                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1644                 (tree.sym.flags() & PARAMETER) != 0;
1645         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1646 
1647         try {
1648             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1649             chk.checkDeprecatedAnnotation(tree.pos(), v);
1650 
1651             if (tree.init != null) {
1652                 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1653                 if ((v.flags_field & FINAL) == 0 ||
1654                     !memberEnter.needsLazyConstValue(tree.init)) {
1655                     // Not a compile-time constant
1656                     // Attribute initializer in a new environment
1657                     // with the declared variable as owner.
1658                     // Check that initializer conforms to variable's declared type.

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