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