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