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

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