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