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