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