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