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