1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.Consumer;
  31 import java.util.stream.Stream;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.tools.JavaFileObject;
  35 
  36 import com.sun.source.tree.CaseTree;
  37 import com.sun.source.tree.IdentifierTree;
  38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  39 import com.sun.source.tree.MemberSelectTree;
  40 import com.sun.source.tree.TreeVisitor;
  41 import com.sun.source.util.SimpleTreeVisitor;
  42 import com.sun.tools.javac.code.*;
  43 import com.sun.tools.javac.code.Lint.LintCategory;
  44 import com.sun.tools.javac.code.Scope.WriteableScope;
  45 import com.sun.tools.javac.code.Source.Feature;
  46 import com.sun.tools.javac.code.Symbol.*;
  47 import com.sun.tools.javac.code.Type.*;
  48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  50 import com.sun.tools.javac.comp.Check.CheckContext;
  51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  52 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  53 import com.sun.tools.javac.jvm.*;
  54 
  55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  58 
  59 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  60 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  61 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
  62 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  63 import com.sun.tools.javac.tree.*;
  64 import com.sun.tools.javac.tree.JCTree.*;
  65 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  66 import com.sun.tools.javac.util.*;
  67 import com.sun.tools.javac.util.DefinedBy.Api;
  68 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  69 import com.sun.tools.javac.util.JCDiagnostic.Error;
  70 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  71 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  72 import com.sun.tools.javac.util.List;
  73 
  74 import static com.sun.tools.javac.code.Flags.*;
  75 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  76 import static com.sun.tools.javac.code.Flags.BLOCK;
  77 import static com.sun.tools.javac.code.Kinds.*;
  78 import static com.sun.tools.javac.code.Kinds.Kind.*;
  79 import static com.sun.tools.javac.code.TypeTag.*;
  80 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  82 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  83 
  84 /** This is the main context-dependent analysis phase in GJC. It
  85  *  encompasses name resolution, type checking and constant folding as
  86  *  subtasks. Some subtasks involve auxiliary classes.
  87  *  @see Check
  88  *  @see Resolve
  89  *  @see ConstFold
  90  *  @see Infer
  91  *
  92  *  <p><b>This is NOT part of any supported API.
  93  *  If you write code that depends on this, you do so at your own risk.
  94  *  This code and its internal interfaces are subject to change or
  95  *  deletion without notice.</b>
  96  */
  97 public class Attr extends JCTree.Visitor {
  98     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
  99 
 100     final Names names;
 101     final Log log;
 102     final Symtab syms;
 103     final Resolve rs;
 104     final Operators operators;
 105     final Infer infer;
 106     final Analyzer analyzer;
 107     final DeferredAttr deferredAttr;
 108     final Check chk;
 109     final Flow flow;
 110     final MemberEnter memberEnter;
 111     final TypeEnter typeEnter;
 112     final TreeMaker make;
 113     final ConstFold cfolder;
 114     final Enter enter;
 115     final Target target;
 116     final Types types;
 117     final Preview preview;
 118     final JCDiagnostic.Factory diags;
 119     final TypeAnnotations typeAnnotations;
 120     final DeferredLintHandler deferredLintHandler;
 121     final TypeEnvs typeEnvs;
 122     final Dependencies dependencies;
 123     final Annotate annotate;
 124     final ArgumentAttr argumentAttr;
 125     final MatchBindingsComputer matchBindingsComputer;
 126     final AttrRecover attrRecover;
 127     final LocalProxyVarsGen localProxyVarsGen;
 128 
 129     public static Attr instance(Context context) {
 130         Attr instance = context.get(attrKey);
 131         if (instance == null)
 132             instance = new Attr(context);
 133         return instance;
 134     }
 135 
 136     @SuppressWarnings("this-escape")
 137     protected Attr(Context context) {
 138         context.put(attrKey, this);
 139 
 140         names = Names.instance(context);
 141         log = Log.instance(context);
 142         syms = Symtab.instance(context);
 143         rs = Resolve.instance(context);
 144         operators = Operators.instance(context);
 145         chk = Check.instance(context);
 146         flow = Flow.instance(context);
 147         memberEnter = MemberEnter.instance(context);
 148         typeEnter = TypeEnter.instance(context);
 149         make = TreeMaker.instance(context);
 150         enter = Enter.instance(context);
 151         infer = Infer.instance(context);
 152         analyzer = Analyzer.instance(context);
 153         deferredAttr = DeferredAttr.instance(context);
 154         cfolder = ConstFold.instance(context);
 155         target = Target.instance(context);
 156         types = Types.instance(context);
 157         preview = Preview.instance(context);
 158         diags = JCDiagnostic.Factory.instance(context);
 159         annotate = Annotate.instance(context);
 160         typeAnnotations = TypeAnnotations.instance(context);
 161         deferredLintHandler = DeferredLintHandler.instance(context);
 162         typeEnvs = TypeEnvs.instance(context);
 163         dependencies = Dependencies.instance(context);
 164         argumentAttr = ArgumentAttr.instance(context);
 165         matchBindingsComputer = MatchBindingsComputer.instance(context);
 166         attrRecover = AttrRecover.instance(context);
 167         localProxyVarsGen = LocalProxyVarsGen.instance(context);
 168 
 169         Options options = Options.instance(context);
 170 
 171         Source source = Source.instance(context);
 172         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 173         allowRecords = Feature.RECORDS.allowedInSource(source);
 174         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 175                              Feature.PATTERN_SWITCH.allowedInSource(source);
 176         allowUnconditionalPatternsInstanceOf =
 177                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 178         sourceName = source.name;
 179         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 180 
 181         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 182         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 183         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 184         methodAttrInfo = new MethodAttrInfo();
 185         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 186         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 187         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 188         initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
 189         allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 190                 Feature.VALUE_CLASSES.allowedInSource(source);
 191     }
 192 
 193     /** Switch: reifiable types in instanceof enabled?
 194      */
 195     boolean allowReifiableTypesInInstanceof;
 196 
 197     /** Are records allowed
 198      */
 199     private final boolean allowRecords;
 200 
 201     /** Are patterns in switch allowed
 202      */
 203     private final boolean allowPatternSwitch;
 204 
 205     /** Are unconditional patterns in instanceof allowed
 206      */
 207     private final boolean allowUnconditionalPatternsInstanceOf;
 208 
 209     /** Are value classes allowed
 210      */
 211     private final boolean allowValueClasses;
 212 
 213     /**
 214      * Switch: warn about use of variable before declaration?
 215      * RFE: 6425594
 216      */
 217     boolean useBeforeDeclarationWarning;
 218 
 219     /**
 220      * Switch: name of source level; used for error reporting.
 221      */
 222     String sourceName;
 223 
 224     /** Check kind and type of given tree against protokind and prototype.
 225      *  If check succeeds, store type in tree and return it.
 226      *  If check fails, store errType in tree and return it.
 227      *  No checks are performed if the prototype is a method type.
 228      *  It is not necessary in this case since we know that kind and type
 229      *  are correct.
 230      *
 231      *  @param tree     The tree whose kind and type is checked
 232      *  @param found    The computed type of the tree
 233      *  @param ownkind  The computed kind of the tree
 234      *  @param resultInfo  The expected result of the tree
 235      */
 236     Type check(final JCTree tree,
 237                final Type found,
 238                final KindSelector ownkind,
 239                final ResultInfo resultInfo) {
 240         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 241         Type owntype;
 242         boolean shouldCheck = !found.hasTag(ERROR) &&
 243                 !resultInfo.pt.hasTag(METHOD) &&
 244                 !resultInfo.pt.hasTag(FORALL);
 245         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 246             log.error(tree.pos(),
 247                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 248                                             ownkind.kindNames()));
 249             owntype = types.createErrorType(found);
 250         } else if (inferenceContext.free(found)) {
 251             //delay the check if there are inference variables in the found type
 252             //this means we are dealing with a partially inferred poly expression
 253             owntype = shouldCheck ? resultInfo.pt : found;
 254             if (resultInfo.checkMode.installPostInferenceHook()) {
 255                 inferenceContext.addFreeTypeListener(List.of(found),
 256                         instantiatedContext -> {
 257                             ResultInfo pendingResult =
 258                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 259                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 260                         });
 261             }
 262         } else {
 263             owntype = shouldCheck ?
 264             resultInfo.check(tree, found) :
 265             found;
 266         }
 267         if (resultInfo.checkMode.updateTreeType()) {
 268             tree.type = owntype;
 269         }
 270         return owntype;
 271     }
 272 
 273     /** Is given blank final variable assignable, i.e. in a scope where it
 274      *  may be assigned to even though it is final?
 275      *  @param v      The blank final variable.
 276      *  @param env    The current environment.
 277      */
 278     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 279         Symbol owner = env.info.scope.owner;
 280            // owner refers to the innermost variable, method or
 281            // initializer block declaration at this point.
 282         boolean isAssignable =
 283             v.owner == owner
 284             ||
 285             ((owner.name == names.init ||    // i.e. we are in a constructor
 286               owner.kind == VAR ||           // i.e. we are in a variable initializer
 287               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 288              &&
 289              v.owner == owner.owner
 290              &&
 291              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 292         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 293         return isAssignable & !insideCompactConstructor;
 294     }
 295 
 296     /** Check that variable can be assigned to.
 297      *  @param pos    The current source code position.
 298      *  @param v      The assigned variable
 299      *  @param base   If the variable is referred to in a Select, the part
 300      *                to the left of the `.', null otherwise.
 301      *  @param env    The current environment.
 302      */
 303     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 304         if (v.name == names._this) {
 305             log.error(pos, Errors.CantAssignValToThis);
 306         } else if ((v.flags() & FINAL) != 0 &&


 307             ((v.flags() & HASINIT) != 0
 308              ||
 309              !((base == null ||
 310                TreeInfo.isThisQualifier(base)) &&
 311                isAssignableAsBlankFinal(v, env)))) {
 312             if (v.isResourceVariable()) { //TWR resource
 313                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 314             } else {
 315                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 316             }

















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