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