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 = log.new DiscardDiagnosticHandler();
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.enclMethod != null &&
2516                 TreeInfo.isCompactConstructor(env.enclMethod)) {
2517             log.error(env.enclMethod,
2518                     Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement));
2519         } else {
2520             // Attribute return expression, if it exists, and check that
2521             // it conforms to result type of enclosing method.
2522             if (tree.expr != null) {
2523                 if (env.info.returnResult.pt.hasTag(VOID)) {
2524                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2525                               diags.fragment(Fragments.UnexpectedRetVal));
2526                 }
2527                 attribTree(tree.expr, env, env.info.returnResult);
2528             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2529                     !env.info.returnResult.pt.hasTag(NONE)) {
2530                 env.info.returnResult.checkContext.report(tree.pos(),
2531                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2532             }
2533         }
2534         result = null;
2535     }
2536 
2537     public void visitThrow(JCThrow tree) {
2538         Type owntype = attribExpr(tree.expr, env, Type.noType);
2539         chk.checkType(tree, owntype, syms.throwableType);
2540         result = null;
2541     }
2542 
2543     public void visitAssert(JCAssert tree) {
2544         attribExpr(tree.cond, env, syms.booleanType);
2545         if (tree.detail != null) {
2546             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2547         }
2548         result = null;
2549     }
2550 
2551      /** Visitor method for method invocations.
2552      *  NOTE: The method part of an application will have in its type field
2553      *        the return type of the method, not the method's type itself!
2554      */
2555     public void visitApply(JCMethodInvocation tree) {
2556         // The local environment of a method application is
2557         // a new environment nested in the current one.
2558         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2559 
2560         // The types of the actual method arguments.
2561         List<Type> argtypes;
2562 
2563         // The types of the actual method type arguments.
2564         List<Type> typeargtypes = null;
2565 
2566         Name methName = TreeInfo.name(tree.meth);
2567 
2568         boolean isConstructorCall =
2569             methName == names._this || methName == names._super;
2570 
2571         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2572         if (isConstructorCall) {
2573 
2574             // Attribute arguments, yielding list of argument types.
2575             KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2576             argtypes = argtypesBuf.toList();
2577             typeargtypes = attribTypes(tree.typeargs, localEnv);
2578 
2579             // Done with this()/super() parameters. End of constructor prologue.
2580             env.info.ctorPrologue = false;
2581 
2582             // Variable `site' points to the class in which the called
2583             // constructor is defined.
2584             Type site = env.enclClass.sym.type;
2585             if (methName == names._super) {
2586                 if (site == syms.objectType) {
2587                     log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2588                     site = types.createErrorType(syms.objectType);
2589                 } else {
2590                     site = types.supertype(site);
2591                 }
2592             }
2593 
2594             if (site.hasTag(CLASS)) {
2595                 Type encl = site.getEnclosingType();
2596                 while (encl != null && encl.hasTag(TYPEVAR))
2597                     encl = encl.getUpperBound();
2598                 if (encl.hasTag(CLASS)) {
2599                     // we are calling a nested class
2600 
2601                     if (tree.meth.hasTag(SELECT)) {
2602                         JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2603 
2604                         // We are seeing a prefixed call, of the form
2605                         //     <expr>.super(...).
2606                         // Check that the prefix expression conforms
2607                         // to the outer instance type of the class.
2608                         chk.checkRefType(qualifier.pos(),
2609                                          attribExpr(qualifier, localEnv,
2610                                                     encl));
2611                     }
2612                 } else if (tree.meth.hasTag(SELECT)) {
2613                     log.error(tree.meth.pos(),
2614                               Errors.IllegalQualNotIcls(site.tsym));
2615                     attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2616                 }
2617 
2618                 if (tree.meth.hasTag(IDENT)) {
2619                     // non-qualified super(...) call; check whether explicit constructor
2620                     // invocation is well-formed. If the super class is an inner class,
2621                     // make sure that an appropriate implicit qualifier exists. If the super
2622                     // class is a local class, make sure that the current class is defined
2623                     // in the same context as the local class.
2624                     checkNewInnerClass(tree.meth.pos(), localEnv, site, true);
2625                 }
2626 
2627                 // if we're calling a java.lang.Enum constructor,
2628                 // prefix the implicit String and int parameters
2629                 if (site.tsym == syms.enumSym)
2630                     argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
2631 
2632                 // Resolve the called constructor under the assumption
2633                 // that we are referring to a superclass instance of the
2634                 // current instance (JLS ???).
2635                 boolean selectSuperPrev = localEnv.info.selectSuper;
2636                 localEnv.info.selectSuper = true;
2637                 localEnv.info.pendingResolutionPhase = null;
2638                 Symbol sym = rs.resolveConstructor(
2639                     tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
2640                 localEnv.info.selectSuper = selectSuperPrev;
2641 
2642                 // Set method symbol to resolved constructor...
2643                 TreeInfo.setSymbol(tree.meth, sym);
2644 
2645                 // ...and check that it is legal in the current context.
2646                 // (this will also set the tree's type)
2647                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2648                 checkId(tree.meth, site, sym, localEnv,
2649                         new ResultInfo(kind, mpt));
2650             } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) {
2651                 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2652             }
2653             // Otherwise, `site' is an error type and we do nothing
2654             result = tree.type = syms.voidType;
2655         } else {
2656             // Otherwise, we are seeing a regular method call.
2657             // Attribute the arguments, yielding list of argument types, ...
2658             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2659             argtypes = argtypesBuf.toList();
2660             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
2661 
2662             // ... and attribute the method using as a prototype a methodtype
2663             // whose formal argument types is exactly the list of actual
2664             // arguments (this will also set the method symbol).
2665             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2666             localEnv.info.pendingResolutionPhase = null;
2667             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2668 
2669             // Compute the result type.
2670             Type restype = mtype.getReturnType();
2671             if (restype.hasTag(WILDCARD))
2672                 throw new AssertionError(mtype);
2673 
2674             Type qualifier = (tree.meth.hasTag(SELECT))
2675                     ? ((JCFieldAccess) tree.meth).selected.type
2676                     : env.enclClass.sym.type;
2677             Symbol msym = TreeInfo.symbol(tree.meth);
2678             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2679 
2680             chk.checkRefTypes(tree.typeargs, typeargtypes);
2681 
2682             // Check that value of resulting type is admissible in the
2683             // current context.  Also, capture the return type
2684             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2685             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2686         }
2687         chk.validate(tree.typeargs, localEnv);
2688     }
2689     //where
2690         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2691             if (msym != null &&
2692                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2693                     methodName == names.getClass &&
2694                     argtypes.isEmpty()) {
2695                 // as a special case, x.getClass() has type Class<? extends |X|>
2696                 return new ClassType(restype.getEnclosingType(),
2697                         List.of(new WildcardType(types.erasure(qualifierType.baseType()),
2698                                 BoundKind.EXTENDS,
2699                                 syms.boundClass)),
2700                         restype.tsym,
2701                         restype.getMetadata());
2702             } else if (msym != null &&
2703                     msym.owner == syms.arrayClass &&
2704                     methodName == names.clone &&
2705                     types.isArray(qualifierType)) {
2706                 // as a special case, array.clone() has a result that is
2707                 // the same as static type of the array being cloned
2708                 return qualifierType;
2709             } else {
2710                 return restype;
2711             }
2712         }
2713 
2714         /** Obtain a method type with given argument types.
2715          */
2716         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2717             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2718             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2719         }
2720 
2721     public void visitNewClass(final JCNewClass tree) {
2722         Type owntype = types.createErrorType(tree.type);
2723 
2724         // The local environment of a class creation is
2725         // a new environment nested in the current one.
2726         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2727 
2728         // The anonymous inner class definition of the new expression,
2729         // if one is defined by it.
2730         JCClassDecl cdef = tree.def;
2731 
2732         // If enclosing class is given, attribute it, and
2733         // complete class name to be fully qualified
2734         JCExpression clazz = tree.clazz; // Class field following new
2735         JCExpression clazzid;            // Identifier in class field
2736         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
2737         annoclazzid = null;
2738 
2739         if (clazz.hasTag(TYPEAPPLY)) {
2740             clazzid = ((JCTypeApply) clazz).clazz;
2741             if (clazzid.hasTag(ANNOTATED_TYPE)) {
2742                 annoclazzid = (JCAnnotatedType) clazzid;
2743                 clazzid = annoclazzid.underlyingType;
2744             }
2745         } else {
2746             if (clazz.hasTag(ANNOTATED_TYPE)) {
2747                 annoclazzid = (JCAnnotatedType) clazz;
2748                 clazzid = annoclazzid.underlyingType;
2749             } else {
2750                 clazzid = clazz;
2751             }
2752         }
2753 
2754         JCExpression clazzid1 = clazzid; // The same in fully qualified form
2755 
2756         if (tree.encl != null) {
2757             // We are seeing a qualified new, of the form
2758             //    <expr>.new C <...> (...) ...
2759             // In this case, we let clazz stand for the name of the
2760             // allocated class C prefixed with the type of the qualifier
2761             // expression, so that we can
2762             // resolve it with standard techniques later. I.e., if
2763             // <expr> has type T, then <expr>.new C <...> (...)
2764             // yields a clazz T.C.
2765             Type encltype = chk.checkRefType(tree.encl.pos(),
2766                                              attribExpr(tree.encl, env));
2767             // TODO 308: in <expr>.new C, do we also want to add the type annotations
2768             // from expr to the combined type, or not? Yes, do this.
2769             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
2770                                                  ((JCIdent) clazzid).name);
2771 
2772             EndPosTable endPosTable = this.env.toplevel.endPositions;
2773             endPosTable.storeEnd(clazzid1, clazzid.getEndPosition(endPosTable));
2774             if (clazz.hasTag(ANNOTATED_TYPE)) {
2775                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
2776                 List<JCAnnotation> annos = annoType.annotations;
2777 
2778                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
2779                     clazzid1 = make.at(tree.pos).
2780                         TypeApply(clazzid1,
2781                                   ((JCTypeApply) clazz).arguments);
2782                 }
2783 
2784                 clazzid1 = make.at(tree.pos).
2785                     AnnotatedType(annos, clazzid1);
2786             } else if (clazz.hasTag(TYPEAPPLY)) {
2787                 clazzid1 = make.at(tree.pos).
2788                     TypeApply(clazzid1,
2789                               ((JCTypeApply) clazz).arguments);
2790             }
2791 
2792             clazz = clazzid1;
2793         }
2794 
2795         // Attribute clazz expression and store
2796         // symbol + type back into the attributed tree.
2797         Type clazztype;
2798 
2799         try {
2800             env.info.isAnonymousNewClass = tree.def != null;
2801             clazztype = TreeInfo.isEnumInit(env.tree) ?
2802                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2803                 attribType(clazz, env);
2804         } finally {
2805             env.info.isAnonymousNewClass = false;
2806         }
2807 
2808         clazztype = chk.checkDiamond(tree, clazztype);
2809         chk.validate(clazz, localEnv);
2810         if (tree.encl != null) {
2811             // We have to work in this case to store
2812             // symbol + type back into the attributed tree.
2813             tree.clazz.type = clazztype;
2814             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2815             clazzid.type = ((JCIdent) clazzid).sym.type;
2816             if (annoclazzid != null) {
2817                 annoclazzid.type = clazzid.type;
2818             }
2819             if (!clazztype.isErroneous()) {
2820                 if (cdef != null && clazztype.tsym.isInterface()) {
2821                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2822                 } else if (clazztype.tsym.isStatic()) {
2823                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
2824                 }
2825             }
2826         } else {
2827             // Check for the existence of an apropos outer instance
2828             checkNewInnerClass(tree.pos(), env, clazztype, false);
2829         }
2830 
2831         // Attribute constructor arguments.
2832         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2833         final KindSelector pkind =
2834             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2835         List<Type> argtypes = argtypesBuf.toList();
2836         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2837 
2838         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2839             // Enums may not be instantiated except implicitly
2840             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2841                 (!env.tree.hasTag(VARDEF) ||
2842                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2843                  ((JCVariableDecl) env.tree).init != tree))
2844                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2845 
2846             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2847                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2848             boolean skipNonDiamondPath = false;
2849             // Check that class is not abstract
2850             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2851                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2852                 log.error(tree.pos(),
2853                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2854                 skipNonDiamondPath = true;
2855             } else if (cdef != null && clazztype.tsym.isInterface()) {
2856                 // Check that no constructor arguments are given to
2857                 // anonymous classes implementing an interface
2858                 if (!argtypes.isEmpty())
2859                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2860 
2861                 if (!typeargtypes.isEmpty())
2862                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2863 
2864                 // Error recovery: pretend no arguments were supplied.
2865                 argtypes = List.nil();
2866                 typeargtypes = List.nil();
2867                 skipNonDiamondPath = true;
2868             }
2869             if (TreeInfo.isDiamond(tree)) {
2870                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2871                             clazztype.tsym.type.getTypeArguments(),
2872                                                clazztype.tsym,
2873                                                clazztype.getMetadata());
2874 
2875                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2876                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2877                 diamondEnv.info.pendingResolutionPhase = null;
2878 
2879                 //if the type of the instance creation expression is a class type
2880                 //apply method resolution inference (JLS 15.12.2.7). The return type
2881                 //of the resolved constructor will be a partially instantiated type
2882                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2883                             diamondEnv,
2884                             site,
2885                             argtypes,
2886                             typeargtypes);
2887                 tree.constructor = constructor.baseSymbol();
2888 
2889                 final TypeSymbol csym = clazztype.tsym;
2890                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2891                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2892                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2893                 constructorType = checkId(tree, site,
2894                         constructor,
2895                         diamondEnv,
2896                         diamondResult);
2897 
2898                 tree.clazz.type = types.createErrorType(clazztype);
2899                 if (!constructorType.isErroneous()) {
2900                     tree.clazz.type = clazz.type = constructorType.getReturnType();
2901                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2902                 }
2903                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2904             }
2905 
2906             // Resolve the called constructor under the assumption
2907             // that we are referring to a superclass instance of the
2908             // current instance (JLS ???).
2909             else if (!skipNonDiamondPath) {
2910                 //the following code alters some of the fields in the current
2911                 //AttrContext - hence, the current context must be dup'ed in
2912                 //order to avoid downstream failures
2913                 Env<AttrContext> rsEnv = localEnv.dup(tree);
2914                 rsEnv.info.selectSuper = cdef != null;
2915                 rsEnv.info.pendingResolutionPhase = null;
2916                 tree.constructor = rs.resolveConstructor(
2917                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2918                 if (cdef == null) { //do not check twice!
2919                     tree.constructorType = checkId(tree,
2920                             clazztype,
2921                             tree.constructor,
2922                             rsEnv,
2923                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2924                     if (rsEnv.info.lastResolveVarargs())
2925                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2926                 }
2927             }
2928 
2929             if (cdef != null) {
2930                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2931                 return;
2932             }
2933 
2934             if (tree.constructor != null && tree.constructor.kind == MTH)
2935                 owntype = clazztype;
2936         }
2937         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2938         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2939         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2940             //we need to wait for inference to finish and then replace inference vars in the constructor type
2941             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2942                     instantiatedContext -> {
2943                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2944                     });
2945         }
2946         chk.validate(tree.typeargs, localEnv);
2947     }
2948 
2949         // where
2950         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2951                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
2952                                                    List<Type> argtypes, List<Type> typeargtypes,
2953                                                    KindSelector pkind) {
2954             // We are seeing an anonymous class instance creation.
2955             // In this case, the class instance creation
2956             // expression
2957             //
2958             //    E.new <typeargs1>C<typargs2>(args) { ... }
2959             //
2960             // is represented internally as
2961             //
2962             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2963             //
2964             // This expression is then *transformed* as follows:
2965             //
2966             // (1) add an extends or implements clause
2967             // (2) add a constructor.
2968             //
2969             // For instance, if C is a class, and ET is the type of E,
2970             // the expression
2971             //
2972             //    E.new <typeargs1>C<typargs2>(args) { ... }
2973             //
2974             // is translated to (where X is a fresh name and typarams is the
2975             // parameter list of the super constructor):
2976             //
2977             //   new <typeargs1>X(<*nullchk*>E, args) where
2978             //     X extends C<typargs2> {
2979             //       <typarams> X(ET e, args) {
2980             //         e.<typeargs1>super(args)
2981             //       }
2982             //       ...
2983             //     }
2984             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2985             Type enclType = clazztype.getEnclosingType();
2986             if (enclType != null &&
2987                     enclType.hasTag(CLASS) &&
2988                     !chk.checkDenotable((ClassType)enclType)) {
2989                 log.error(tree.encl, Errors.EnclosingClassTypeNonDenotable(enclType));
2990             }
2991             final boolean isDiamond = TreeInfo.isDiamond(tree);
2992             if (isDiamond
2993                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2994                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2995                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2996                 Env<AttrContext> dupLocalEnv = copyEnv(localEnv);
2997                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2998                         instantiatedContext -> {
2999                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
3000                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
3001                             ResultInfo prevResult = this.resultInfo;
3002                             try {
3003                                 this.resultInfo = resultInfoForClassDefinition;
3004                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
3005                                         dupLocalEnv, argtypes, typeargtypes, pkind);
3006                             } finally {
3007                                 this.resultInfo = prevResult;
3008                             }
3009                         });
3010             } else {
3011                 if (isDiamond && clazztype.hasTag(CLASS)) {
3012                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3013                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3014                         // One or more types inferred in the previous steps is non-denotable.
3015                         Fragment fragment = Diamond(clazztype.tsym);
3016                         log.error(tree.clazz.pos(),
3017                                 Errors.CantApplyDiamond1(
3018                                         fragment,
3019                                         invalidDiamondArgs.size() > 1 ?
3020                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3021                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3022                     }
3023                     // For <>(){}, inferred types must also be accessible.
3024                     for (Type t : clazztype.getTypeArguments()) {
3025                         rs.checkAccessibleType(env, t);
3026                     }
3027                 }
3028 
3029                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3030                 // false for isInterface call even when the original type is an interface.
3031                 boolean implementing = clazztype.tsym.isInterface() ||
3032                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3033                         clazztype.getOriginalType().tsym.isInterface();
3034 
3035                 if (implementing) {
3036                     cdef.implementing = List.of(clazz);
3037                 } else {
3038                     cdef.extending = clazz;
3039                 }
3040 
3041                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3042                     rs.isSerializable(clazztype)) {
3043                     localEnv.info.isSerializable = true;
3044                 }
3045 
3046                 attribStat(cdef, localEnv);
3047 
3048                 List<Type> finalargtypes;
3049                 // If an outer instance is given,
3050                 // prefix it to the constructor arguments
3051                 // and delete it from the new expression
3052                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
3053                     finalargtypes = argtypes.prepend(tree.encl.type);
3054                 } else {
3055                     finalargtypes = argtypes;
3056                 }
3057 
3058                 // Reassign clazztype and recompute constructor. As this necessarily involves
3059                 // another attribution pass for deferred types in the case of <>, replicate
3060                 // them. Original arguments have right decorations already.
3061                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
3062                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
3063                 }
3064 
3065                 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
3066                                                     : cdef.sym.type;
3067                 Symbol sym = tree.constructor = rs.resolveConstructor(
3068                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
3069                 Assert.check(!sym.kind.isResolutionError());
3070                 tree.constructor = sym;
3071                 tree.constructorType = checkId(tree,
3072                         clazztype,
3073                         tree.constructor,
3074                         localEnv,
3075                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3076             }
3077             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
3078                                 clazztype : types.createErrorType(tree.type);
3079             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3080             chk.validate(tree.typeargs, localEnv);
3081         }
3082 
3083         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3084             return new Check.NestedCheckContext(checkContext) {
3085                 @Override
3086                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3087                     enclosingContext.report(clazz.clazz,
3088                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3089                 }
3090             };
3091         }
3092 
3093         void checkNewInnerClass(DiagnosticPosition pos, Env<AttrContext> env, Type type, boolean isSuper) {
3094             boolean isLocal = type.tsym.owner.kind == VAR || type.tsym.owner.kind == MTH;
3095             if ((type.tsym.flags() & (INTERFACE | ENUM | RECORD)) != 0 ||
3096                     (!isLocal && !type.tsym.isInner()) ||
3097                     (isSuper && env.enclClass.sym.isAnonymous())) {
3098                 // nothing to check
3099                 return;
3100             }
3101             Symbol res = isLocal ?
3102                     rs.findLocalClassOwner(env, type.tsym) :
3103                     rs.findSelfContaining(pos, env, type.getEnclosingType().tsym, isSuper);
3104             if (res.exists()) {
3105                 rs.accessBase(res, pos, env.enclClass.sym.type, names._this, true);
3106             } else {
3107                 log.error(pos, Errors.EnclClassRequired(type.tsym));
3108             }
3109         }
3110 
3111     /** Make an attributed null check tree.
3112      */
3113     public JCExpression makeNullCheck(JCExpression arg) {
3114         // optimization: new Outer() can never be null; skip null check
3115         if (arg.getTag() == NEWCLASS)
3116             return arg;
3117         // optimization: X.this is never null; skip null check
3118         Name name = TreeInfo.name(arg);
3119         if (name == names._this || name == names._super) return arg;
3120 
3121         JCTree.Tag optag = NULLCHK;
3122         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3123         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3124         tree.type = arg.type;
3125         return tree;
3126     }
3127 
3128     public void visitNewArray(JCNewArray tree) {
3129         Type owntype = types.createErrorType(tree.type);
3130         Env<AttrContext> localEnv = env.dup(tree);
3131         Type elemtype;
3132         if (tree.elemtype != null) {
3133             elemtype = attribType(tree.elemtype, localEnv);
3134             chk.validate(tree.elemtype, localEnv);
3135             owntype = elemtype;
3136             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3137                 attribExpr(l.head, localEnv, syms.intType);
3138                 owntype = new ArrayType(owntype, syms.arrayClass);
3139             }
3140         } else {
3141             // we are seeing an untyped aggregate { ... }
3142             // this is allowed only if the prototype is an array
3143             if (pt().hasTag(ARRAY)) {
3144                 elemtype = types.elemtype(pt());
3145             } else {
3146                 if (!pt().hasTag(ERROR) &&
3147                         (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3148                     log.error(tree.pos(),
3149                               Errors.IllegalInitializerForType(pt()));
3150                 }
3151                 elemtype = types.createErrorType(pt());
3152             }
3153         }
3154         if (tree.elems != null) {
3155             attribExprs(tree.elems, localEnv, elemtype);
3156             owntype = new ArrayType(elemtype, syms.arrayClass);
3157         }
3158         if (!types.isReifiable(elemtype))
3159             log.error(tree.pos(), Errors.GenericArrayCreation);
3160         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3161     }
3162 
3163     /*
3164      * A lambda expression can only be attributed when a target-type is available.
3165      * In addition, if the target-type is that of a functional interface whose
3166      * descriptor contains inference variables in argument position the lambda expression
3167      * is 'stuck' (see DeferredAttr).
3168      */
3169     @Override
3170     public void visitLambda(final JCLambda that) {
3171         boolean wrongContext = false;
3172         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3173             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3174                 //lambda only allowed in assignment or method invocation/cast context
3175                 log.error(that.pos(), Errors.UnexpectedLambda);
3176             }
3177             resultInfo = recoveryInfo;
3178             wrongContext = true;
3179         }
3180         //create an environment for attribution of the lambda expression
3181         final Env<AttrContext> localEnv = lambdaEnv(that, env);
3182         boolean needsRecovery =
3183                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
3184         try {
3185             if (needsRecovery && rs.isSerializable(pt())) {
3186                 localEnv.info.isSerializable = true;
3187                 localEnv.info.isSerializableLambda = true;
3188             }
3189             List<Type> explicitParamTypes = null;
3190             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
3191                 //attribute lambda parameters
3192                 attribStats(that.params, localEnv);
3193                 explicitParamTypes = TreeInfo.types(that.params);
3194             }
3195 
3196             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
3197             Type currentTarget = targetInfo.target;
3198             Type lambdaType = targetInfo.descriptor;
3199 
3200             if (currentTarget.isErroneous()) {
3201                 result = that.type = currentTarget;
3202                 return;
3203             }
3204 
3205             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
3206 
3207             if (lambdaType.hasTag(FORALL)) {
3208                 //lambda expression target desc cannot be a generic method
3209                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3210                                                                     kindName(currentTarget.tsym),
3211                                                                     currentTarget.tsym);
3212                 resultInfo.checkContext.report(that, diags.fragment(msg));
3213                 result = that.type = types.createErrorType(pt());
3214                 return;
3215             }
3216 
3217             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
3218                 //add param type info in the AST
3219                 List<Type> actuals = lambdaType.getParameterTypes();
3220                 List<JCVariableDecl> params = that.params;
3221 
3222                 boolean arityMismatch = false;
3223 
3224                 while (params.nonEmpty()) {
3225                     if (actuals.isEmpty()) {
3226                         //not enough actuals to perform lambda parameter inference
3227                         arityMismatch = true;
3228                     }
3229                     //reset previously set info
3230                     Type argType = arityMismatch ?
3231                             syms.errType :
3232                             actuals.head;
3233                     if (params.head.isImplicitlyTyped()) {
3234                         setSyntheticVariableType(params.head, argType);
3235                     }
3236                     params.head.sym = null;
3237                     actuals = actuals.isEmpty() ?
3238                             actuals :
3239                             actuals.tail;
3240                     params = params.tail;
3241                 }
3242 
3243                 //attribute lambda parameters
3244                 attribStats(that.params, localEnv);
3245 
3246                 if (arityMismatch) {
3247                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3248                         result = that.type = types.createErrorType(currentTarget);
3249                         return;
3250                 }
3251             }
3252 
3253             //from this point on, no recovery is needed; if we are in assignment context
3254             //we will be able to attribute the whole lambda body, regardless of errors;
3255             //if we are in a 'check' method context, and the lambda is not compatible
3256             //with the target-type, it will be recovered anyway in Attr.checkId
3257             needsRecovery = false;
3258 
3259             ResultInfo bodyResultInfo = localEnv.info.returnResult =
3260                     lambdaBodyResult(that, lambdaType, resultInfo);
3261 
3262             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
3263                 attribTree(that.getBody(), localEnv, bodyResultInfo);
3264             } else {
3265                 JCBlock body = (JCBlock)that.body;
3266                 if (body == breakTree &&
3267                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3268                     breakTreeFound(copyEnv(localEnv));
3269                 }
3270                 attribStats(body.stats, localEnv);
3271             }
3272 
3273             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3274 
3275             boolean isSpeculativeRound =
3276                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3277 
3278             preFlow(that);
3279             flow.analyzeLambda(env, that, make, isSpeculativeRound);
3280 
3281             that.type = currentTarget; //avoids recovery at this stage
3282             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
3283 
3284             if (!isSpeculativeRound) {
3285                 //add thrown types as bounds to the thrown types free variables if needed:
3286                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
3287                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
3288                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
3289                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
3290                     }
3291                 }
3292 
3293                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
3294             }
3295             result = wrongContext ? that.type = types.createErrorType(pt())
3296                                   : check(that, currentTarget, KindSelector.VAL, resultInfo);
3297         } catch (Types.FunctionDescriptorLookupError ex) {
3298             JCDiagnostic cause = ex.getDiagnostic();
3299             resultInfo.checkContext.report(that, cause);
3300             result = that.type = types.createErrorType(pt());
3301             return;
3302         } catch (CompletionFailure cf) {
3303             chk.completionError(that.pos(), cf);
3304         } catch (Throwable t) {
3305             //when an unexpected exception happens, avoid attempts to attribute the same tree again
3306             //as that would likely cause the same exception again.
3307             needsRecovery = false;
3308             throw t;
3309         } finally {
3310             localEnv.info.scope.leave();
3311             if (needsRecovery) {
3312                 Type prevResult = result;
3313                 try {
3314                     attribTree(that, env, recoveryInfo);
3315                 } finally {
3316                     if (result == Type.recoveryType) {
3317                         result = prevResult;
3318                     }
3319                 }
3320             }
3321         }
3322     }
3323     //where
3324         class TargetInfo {
3325             Type target;
3326             Type descriptor;
3327 
3328             public TargetInfo(Type target, Type descriptor) {
3329                 this.target = target;
3330                 this.descriptor = descriptor;
3331             }
3332         }
3333 
3334         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
3335             Type lambdaType;
3336             Type currentTarget = resultInfo.pt;
3337             if (resultInfo.pt != Type.recoveryType) {
3338                 /* We need to adjust the target. If the target is an
3339                  * intersection type, for example: SAM & I1 & I2 ...
3340                  * the target will be updated to SAM
3341                  */
3342                 currentTarget = targetChecker.visit(currentTarget, that);
3343                 if (!currentTarget.isIntersection()) {
3344                     if (explicitParamTypes != null) {
3345                         currentTarget = infer.instantiateFunctionalInterface(that,
3346                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
3347                     }
3348                     currentTarget = types.removeWildcards(currentTarget);
3349                     lambdaType = types.findDescriptorType(currentTarget);
3350                 } else {
3351                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
3352                     ListBuffer<Type> components = new ListBuffer<>();
3353                     for (Type bound : ict.getExplicitComponents()) {
3354                         if (explicitParamTypes != null) {
3355                             try {
3356                                 bound = infer.instantiateFunctionalInterface(that,
3357                                         bound, explicitParamTypes, resultInfo.checkContext);
3358                             } catch (FunctionDescriptorLookupError t) {
3359                                 // do nothing
3360                             }
3361                         }
3362                         bound = types.removeWildcards(bound);
3363                         components.add(bound);
3364                     }
3365                     currentTarget = types.makeIntersectionType(components.toList());
3366                     currentTarget.tsym.flags_field |= INTERFACE;
3367                     lambdaType = types.findDescriptorType(currentTarget);
3368                 }
3369 
3370             } else {
3371                 currentTarget = Type.recoveryType;
3372                 lambdaType = fallbackDescriptorType(that);
3373             }
3374             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
3375                 //lambda expression target desc cannot be a generic method
3376                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3377                                                                     kindName(currentTarget.tsym),
3378                                                                     currentTarget.tsym);
3379                 resultInfo.checkContext.report(that, diags.fragment(msg));
3380                 currentTarget = types.createErrorType(pt());
3381             }
3382             return new TargetInfo(currentTarget, lambdaType);
3383         }
3384 
3385         void preFlow(JCLambda tree) {
3386             attrRecover.doRecovery();
3387             new PostAttrAnalyzer() {
3388                 @Override
3389                 public void scan(JCTree tree) {
3390                     if (tree == null ||
3391                             (tree.type != null &&
3392                             tree.type == Type.stuckType)) {
3393                         //don't touch stuck expressions!
3394                         return;
3395                     }
3396                     super.scan(tree);
3397                 }
3398 
3399                 @Override
3400                 public void visitClassDef(JCClassDecl that) {
3401                     // or class declaration trees!
3402                 }
3403 
3404                 public void visitLambda(JCLambda that) {
3405                     // or lambda expressions!
3406                 }
3407             }.scan(tree.body);
3408         }
3409 
3410         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
3411 
3412             @Override
3413             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
3414                 return t.isIntersection() ?
3415                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
3416             }
3417 
3418             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
3419                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
3420                 return ict;
3421             }
3422 
3423             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
3424                 ListBuffer<Type> targs = new ListBuffer<>();
3425                 ListBuffer<Type> supertypes = new ListBuffer<>();
3426                 for (Type i : ict.interfaces_field) {
3427                     if (i.isParameterized()) {
3428                         targs.appendList(i.tsym.type.allparams());
3429                     }
3430                     supertypes.append(i.tsym.type);
3431                 }
3432                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
3433                 notionalIntf.allparams_field = targs.toList();
3434                 notionalIntf.tsym.flags_field |= INTERFACE;
3435                 return notionalIntf.tsym;
3436             }
3437         };
3438 
3439         private Type fallbackDescriptorType(JCExpression tree) {
3440             switch (tree.getTag()) {
3441                 case LAMBDA:
3442                     JCLambda lambda = (JCLambda)tree;
3443                     List<Type> argtypes = List.nil();
3444                     for (JCVariableDecl param : lambda.params) {
3445                         argtypes = param.vartype != null && param.vartype.type != null ?
3446                                 argtypes.append(param.vartype.type) :
3447                                 argtypes.append(syms.errType);
3448                     }
3449                     return new MethodType(argtypes, Type.recoveryType,
3450                             List.of(syms.throwableType), syms.methodClass);
3451                 case REFERENCE:
3452                     return new MethodType(List.nil(), Type.recoveryType,
3453                             List.of(syms.throwableType), syms.methodClass);
3454                 default:
3455                     Assert.error("Cannot get here!");
3456             }
3457             return null;
3458         }
3459 
3460         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3461                 final InferenceContext inferenceContext, final Type... ts) {
3462             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
3463         }
3464 
3465         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3466                 final InferenceContext inferenceContext, final List<Type> ts) {
3467             if (inferenceContext.free(ts)) {
3468                 inferenceContext.addFreeTypeListener(ts,
3469                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
3470             } else {
3471                 for (Type t : ts) {
3472                     rs.checkAccessibleType(env, t);
3473                 }
3474             }
3475         }
3476 
3477         /**
3478          * Lambda/method reference have a special check context that ensures
3479          * that i.e. a lambda return type is compatible with the expected
3480          * type according to both the inherited context and the assignment
3481          * context.
3482          */
3483         class FunctionalReturnContext extends Check.NestedCheckContext {
3484 
3485             FunctionalReturnContext(CheckContext enclosingContext) {
3486                 super(enclosingContext);
3487             }
3488 
3489             @Override
3490             public boolean compatible(Type found, Type req, Warner warn) {
3491                 //return type must be compatible in both current context and assignment context
3492                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
3493             }
3494 
3495             @Override
3496             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3497                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
3498             }
3499         }
3500 
3501         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
3502 
3503             JCExpression expr;
3504             boolean expStmtExpected;
3505 
3506             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
3507                 super(enclosingContext);
3508                 this.expr = expr;
3509             }
3510 
3511             @Override
3512             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3513                 if (expStmtExpected) {
3514                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
3515                 } else {
3516                     super.report(pos, details);
3517                 }
3518             }
3519 
3520             @Override
3521             public boolean compatible(Type found, Type req, Warner warn) {
3522                 //a void return is compatible with an expression statement lambda
3523                 if (req.hasTag(VOID)) {
3524                     expStmtExpected = true;
3525                     return TreeInfo.isExpressionStatement(expr);
3526                 } else {
3527                     return super.compatible(found, req, warn);
3528                 }
3529             }
3530         }
3531 
3532         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
3533             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
3534                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
3535                     new FunctionalReturnContext(resultInfo.checkContext);
3536 
3537             return descriptor.getReturnType() == Type.recoveryType ?
3538                     recoveryInfo :
3539                     new ResultInfo(KindSelector.VAL,
3540                             descriptor.getReturnType(), funcContext);
3541         }
3542 
3543         /**
3544         * Lambda compatibility. Check that given return types, thrown types, parameter types
3545         * are compatible with the expected functional interface descriptor. This means that:
3546         * (i) parameter types must be identical to those of the target descriptor; (ii) return
3547         * types must be compatible with the return type of the expected descriptor.
3548         */
3549         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3550             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3551 
3552             //return values have already been checked - but if lambda has no return
3553             //values, we must ensure that void/value compatibility is correct;
3554             //this amounts at checking that, if a lambda body can complete normally,
3555             //the descriptor's return type must be void
3556             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3557                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3558                 Fragment msg =
3559                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3560                 checkContext.report(tree,
3561                                     diags.fragment(msg));
3562             }
3563 
3564             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3565             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3566                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3567             }
3568         }
3569 
3570         /* This method returns an environment to be used to attribute a lambda
3571          * expression.
3572          *
3573          * The owner of this environment is a method symbol. If the current owner
3574          * is not a method (e.g. if the lambda occurs in a field initializer), then
3575          * a synthetic method symbol owner is created.
3576          */
3577         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3578             Env<AttrContext> lambdaEnv;
3579             Symbol owner = env.info.scope.owner;
3580             if (owner.kind == VAR && owner.owner.kind == TYP) {
3581                 // If the lambda is nested in a field initializer, we need to create a fake init method.
3582                 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3583                 // init symbol's owner).
3584                 ClassSymbol enclClass = owner.enclClass();
3585                 Name initName = owner.isStatic() ? names.clinit : names.init;
3586                 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3587                         initName, initBlockType, enclClass);
3588                 initSym.params = List.nil();
3589                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3590             } else {
3591                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3592             }
3593             lambdaEnv.info.yieldResult = null;
3594             lambdaEnv.info.isLambda = true;
3595             return lambdaEnv;
3596         }
3597 
3598     @Override
3599     public void visitReference(final JCMemberReference that) {
3600         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3601             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3602                 //method reference only allowed in assignment or method invocation/cast context
3603                 log.error(that.pos(), Errors.UnexpectedMref);
3604             }
3605             result = that.type = types.createErrorType(pt());
3606             return;
3607         }
3608         final Env<AttrContext> localEnv = env.dup(that);
3609         try {
3610             //attribute member reference qualifier - if this is a constructor
3611             //reference, the expected kind must be a type
3612             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3613 
3614             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3615                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3616                 if (!exprType.isErroneous() &&
3617                     exprType.isRaw() &&
3618                     that.typeargs != null) {
3619                     log.error(that.expr.pos(),
3620                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3621                                                  Fragments.MrefInferAndExplicitParams));
3622                     exprType = types.createErrorType(exprType);
3623                 }
3624             }
3625 
3626             if (exprType.isErroneous()) {
3627                 //if the qualifier expression contains problems,
3628                 //give up attribution of method reference
3629                 result = that.type = exprType;
3630                 return;
3631             }
3632 
3633             if (TreeInfo.isStaticSelector(that.expr, names)) {
3634                 //if the qualifier is a type, validate it; raw warning check is
3635                 //omitted as we don't know at this stage as to whether this is a
3636                 //raw selector (because of inference)
3637                 chk.validate(that.expr, env, false);
3638             } else {
3639                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3640                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3641             }
3642             //attrib type-arguments
3643             List<Type> typeargtypes = List.nil();
3644             if (that.typeargs != null) {
3645                 typeargtypes = attribTypes(that.typeargs, localEnv);
3646             }
3647 
3648             boolean isTargetSerializable =
3649                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3650                     rs.isSerializable(pt());
3651             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3652             Type currentTarget = targetInfo.target;
3653             Type desc = targetInfo.descriptor;
3654 
3655             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3656             List<Type> argtypes = desc.getParameterTypes();
3657             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3658 
3659             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3660                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3661             }
3662 
3663             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3664             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3665             try {
3666                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3667                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3668                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3669             } finally {
3670                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3671             }
3672 
3673             Symbol refSym = refResult.fst;
3674             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3675 
3676             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3677              *  JDK-8075541
3678              */
3679             if (refSym.kind != MTH) {
3680                 boolean targetError;
3681                 switch (refSym.kind) {
3682                     case ABSENT_MTH:
3683                         targetError = false;
3684                         break;
3685                     case WRONG_MTH:
3686                     case WRONG_MTHS:
3687                     case AMBIGUOUS:
3688                     case HIDDEN:
3689                     case STATICERR:
3690                         targetError = true;
3691                         break;
3692                     default:
3693                         Assert.error("unexpected result kind " + refSym.kind);
3694                         targetError = false;
3695                 }
3696 
3697                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3698                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3699                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3700 
3701                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3702                         targetError ?
3703                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3704                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3705 
3706                 if (targetError && currentTarget == Type.recoveryType) {
3707                     //a target error doesn't make sense during recovery stage
3708                     //as we don't know what actual parameter types are
3709                     result = that.type = currentTarget;
3710                     return;
3711                 } else {
3712                     if (targetError) {
3713                         resultInfo.checkContext.report(that, diag);
3714                     } else {
3715                         log.report(diag);
3716                     }
3717                     result = that.type = types.createErrorType(currentTarget);
3718                     return;
3719                 }
3720             }
3721 
3722             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3723             that.kind = lookupHelper.referenceKind(that.sym);
3724             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3725 
3726             if (desc.getReturnType() == Type.recoveryType) {
3727                 // stop here
3728                 result = that.type = currentTarget;
3729                 return;
3730             }
3731 
3732             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3733                 checkNewInnerClass(that.pos(), env, exprType, false);
3734             }
3735 
3736             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3737 
3738                 if (that.getMode() == ReferenceMode.INVOKE &&
3739                         TreeInfo.isStaticSelector(that.expr, names) &&
3740                         that.kind.isUnbound() &&
3741                         lookupHelper.site.isRaw()) {
3742                     chk.checkRaw(that.expr, localEnv);
3743                 }
3744 
3745                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3746                         exprType.getTypeArguments().nonEmpty()) {
3747                     //static ref with class type-args
3748                     log.error(that.expr.pos(),
3749                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3750                                                  Fragments.StaticMrefWithTargs));
3751                     result = that.type = types.createErrorType(currentTarget);
3752                     return;
3753                 }
3754 
3755                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3756                     // Check that super-qualified symbols are not abstract (JLS)
3757                     rs.checkNonAbstract(that.pos(), that.sym);
3758                 }
3759 
3760                 if (isTargetSerializable) {
3761                     chk.checkAccessFromSerializableElement(that, true);
3762                 }
3763             }
3764 
3765             ResultInfo checkInfo =
3766                     resultInfo.dup(newMethodTemplate(
3767                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3768                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3769                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3770 
3771             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3772 
3773             if (that.kind.isUnbound() &&
3774                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3775                 //re-generate inference constraints for unbound receiver
3776                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3777                     //cannot happen as this has already been checked - we just need
3778                     //to regenerate the inference constraints, as that has been lost
3779                     //as a result of the call to inferenceContext.save()
3780                     Assert.error("Can't get here");
3781                 }
3782             }
3783 
3784             if (!refType.isErroneous()) {
3785                 refType = types.createMethodTypeWithReturn(refType,
3786                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3787             }
3788 
3789             //go ahead with standard method reference compatibility check - note that param check
3790             //is a no-op (as this has been taken care during method applicability)
3791             boolean isSpeculativeRound =
3792                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3793 
3794             that.type = currentTarget; //avoids recovery at this stage
3795             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3796             if (!isSpeculativeRound) {
3797                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3798             }
3799             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3800         } catch (Types.FunctionDescriptorLookupError ex) {
3801             JCDiagnostic cause = ex.getDiagnostic();
3802             resultInfo.checkContext.report(that, cause);
3803             result = that.type = types.createErrorType(pt());
3804             return;
3805         }
3806     }
3807     //where
3808         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3809             //if this is a constructor reference, the expected kind must be a type
3810             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3811                                   KindSelector.VAL_TYP : KindSelector.TYP,
3812                                   Type.noType);
3813         }
3814 
3815 
3816     @SuppressWarnings("fallthrough")
3817     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3818         InferenceContext inferenceContext = checkContext.inferenceContext();
3819         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3820 
3821         Type resType;
3822         switch (tree.getMode()) {
3823             case NEW:
3824                 if (!tree.expr.type.isRaw()) {
3825                     resType = tree.expr.type;
3826                     break;
3827                 }
3828             default:
3829                 resType = refType.getReturnType();
3830         }
3831 
3832         Type incompatibleReturnType = resType;
3833 
3834         if (returnType.hasTag(VOID)) {
3835             incompatibleReturnType = null;
3836         }
3837 
3838         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3839             if (resType.isErroneous() ||
3840                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3841                             checkContext.checkWarner(tree, resType, returnType))) {
3842                 incompatibleReturnType = null;
3843             }
3844         }
3845 
3846         if (incompatibleReturnType != null) {
3847             Fragment msg =
3848                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3849             checkContext.report(tree, diags.fragment(msg));
3850         } else {
3851             if (inferenceContext.free(refType)) {
3852                 // we need to wait for inference to finish and then replace inference vars in the referent type
3853                 inferenceContext.addFreeTypeListener(List.of(refType),
3854                         instantiatedContext -> {
3855                             tree.referentType = instantiatedContext.asInstType(refType);
3856                         });
3857             } else {
3858                 tree.referentType = refType;
3859             }
3860         }
3861 
3862         if (!speculativeAttr) {
3863             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3864                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3865             }
3866         }
3867     }
3868 
3869     boolean checkExConstraints(
3870             List<Type> thrownByFuncExpr,
3871             List<Type> thrownAtFuncType,
3872             InferenceContext inferenceContext) {
3873         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3874          *  are not proper types
3875          */
3876         List<Type> nonProperList = thrownAtFuncType.stream()
3877                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3878         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3879 
3880         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3881          *  in the throws clause of the invocation type of the method reference's compile-time
3882          *  declaration
3883          */
3884         List<Type> checkedList = thrownByFuncExpr.stream()
3885                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3886 
3887         /** If n = 0 (the function type's throws clause consists only of proper types), then
3888          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3889          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3890          *  reduces to true
3891          */
3892         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3893         for (Type checked : checkedList) {
3894             boolean isSubtype = false;
3895             for (Type proper : properList) {
3896                 if (types.isSubtype(checked, proper)) {
3897                     isSubtype = true;
3898                     break;
3899                 }
3900             }
3901             if (!isSubtype) {
3902                 uncaughtByProperTypes.add(checked);
3903             }
3904         }
3905 
3906         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3907             return false;
3908         }
3909 
3910         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3911          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3912          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3913          */
3914         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3915         uncaughtByProperTypes.forEach(checkedEx -> {
3916             nonProperAsUndet.forEach(nonProper -> {
3917                 types.isSubtype(checkedEx, nonProper);
3918             });
3919         });
3920 
3921         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3922          */
3923         nonProperAsUndet.stream()
3924                 .filter(t -> t.hasTag(UNDETVAR))
3925                 .forEach(t -> ((UndetVar)t).setThrow());
3926         return true;
3927     }
3928 
3929     /**
3930      * Set functional type info on the underlying AST. Note: as the target descriptor
3931      * might contain inference variables, we might need to register an hook in the
3932      * current inference context.
3933      */
3934     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3935             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3936         if (checkContext.inferenceContext().free(descriptorType)) {
3937             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3938                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3939                     inferenceContext.asInstType(primaryTarget), checkContext));
3940         } else {
3941             fExpr.owner = env.info.scope.owner;
3942             if (pt.hasTag(CLASS)) {
3943                 fExpr.target = primaryTarget;
3944             }
3945             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3946                     pt != Type.recoveryType) {
3947                 //check that functional interface class is well-formed
3948                 try {
3949                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3950                      * when it's executed post-inference. See the listener code
3951                      * above.
3952                      */
3953                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3954                             names.empty, fExpr.target, ABSTRACT);
3955                     if (csym != null) {
3956                         chk.checkImplementations(env.tree, csym, csym);
3957                         try {
3958                             //perform an additional functional interface check on the synthetic class,
3959                             //as there may be spurious errors for raw targets - because of existing issues
3960                             //with membership and inheritance (see JDK-8074570).
3961                             csym.flags_field |= INTERFACE;
3962                             types.findDescriptorType(csym.type);
3963                         } catch (FunctionDescriptorLookupError err) {
3964                             resultInfo.checkContext.report(fExpr,
3965                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3966                         }
3967                     }
3968                 } catch (Types.FunctionDescriptorLookupError ex) {
3969                     JCDiagnostic cause = ex.getDiagnostic();
3970                     resultInfo.checkContext.report(env.tree, cause);
3971                 }
3972             }
3973         }
3974     }
3975 
3976     public void visitParens(JCParens tree) {
3977         Type owntype = attribTree(tree.expr, env, resultInfo);
3978         result = check(tree, owntype, pkind(), resultInfo);
3979         Symbol sym = TreeInfo.symbol(tree);
3980         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
3981             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3982     }
3983 
3984     public void visitAssign(JCAssign tree) {
3985         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3986         Type capturedType = capture(owntype);
3987         attribExpr(tree.rhs, env, owntype);
3988         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3989     }
3990 
3991     public void visitAssignop(JCAssignOp tree) {
3992         // Attribute arguments.
3993         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3994         Type operand = attribExpr(tree.rhs, env);
3995         // Find operator.
3996         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3997         if (operator != operators.noOpSymbol &&
3998                 !owntype.isErroneous() &&
3999                 !operand.isErroneous()) {
4000             chk.checkDivZero(tree.rhs.pos(), operator, operand);
4001             chk.checkCastable(tree.rhs.pos(),
4002                               operator.type.getReturnType(),
4003                               owntype);
4004             chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4005         }
4006         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4007     }
4008 
4009     public void visitUnary(JCUnary tree) {
4010         // Attribute arguments.
4011         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4012             ? attribTree(tree.arg, env, varAssignmentInfo)
4013             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4014 
4015         // Find operator.
4016         OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4017         Type owntype = types.createErrorType(tree.type);
4018         if (operator != operators.noOpSymbol &&
4019                 !argtype.isErroneous()) {
4020             owntype = (tree.getTag().isIncOrDecUnaryOp())
4021                 ? tree.arg.type
4022                 : operator.type.getReturnType();
4023             int opc = operator.opcode;
4024 
4025             // If the argument is constant, fold it.
4026             if (argtype.constValue() != null) {
4027                 Type ctype = cfolder.fold1(opc, argtype);
4028                 if (ctype != null) {
4029                     owntype = cfolder.coerce(ctype, owntype);
4030                 }
4031             }
4032         }
4033         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4034         matchBindings = matchBindingsComputer.unary(tree, matchBindings);
4035     }
4036 
4037     public void visitBinary(JCBinary tree) {
4038         // Attribute arguments.
4039         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
4040         // x && y
4041         // include x's bindings when true in y
4042 
4043         // x || y
4044         // include x's bindings when false in y
4045 
4046         MatchBindings lhsBindings = matchBindings;
4047         List<BindingSymbol> propagatedBindings;
4048         switch (tree.getTag()) {
4049             case AND:
4050                 propagatedBindings = lhsBindings.bindingsWhenTrue;
4051                 break;
4052             case OR:
4053                 propagatedBindings = lhsBindings.bindingsWhenFalse;
4054                 break;
4055             default:
4056                 propagatedBindings = List.nil();
4057                 break;
4058         }
4059         Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings);
4060         Type right;
4061         try {
4062             right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
4063         } finally {
4064             rhsEnv.info.scope.leave();
4065         }
4066 
4067         matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings);
4068 
4069         // Find operator.
4070         OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
4071         Type owntype = types.createErrorType(tree.type);
4072         if (operator != operators.noOpSymbol &&
4073                 !left.isErroneous() &&
4074                 !right.isErroneous()) {
4075             owntype = operator.type.getReturnType();
4076             int opc = operator.opcode;
4077             // If both arguments are constants, fold them.
4078             if (left.constValue() != null && right.constValue() != null) {
4079                 Type ctype = cfolder.fold2(opc, left, right);
4080                 if (ctype != null) {
4081                     owntype = cfolder.coerce(ctype, owntype);
4082                 }
4083             }
4084 
4085             // Check that argument types of a reference ==, != are
4086             // castable to each other, (JLS 15.21).  Note: unboxing
4087             // comparisons will not have an acmp* opc at this point.
4088             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4089                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4090                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4091                 }
4092             }
4093 
4094             chk.checkDivZero(tree.rhs.pos(), operator, right);
4095         }
4096         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4097     }
4098 
4099     public void visitTypeCast(final JCTypeCast tree) {
4100         Type clazztype = attribType(tree.clazz, env);
4101         chk.validate(tree.clazz, env, false);
4102         //a fresh environment is required for 292 inference to work properly ---
4103         //see Infer.instantiatePolymorphicSignatureInstance()
4104         Env<AttrContext> localEnv = env.dup(tree);
4105         //should we propagate the target type?
4106         final ResultInfo castInfo;
4107         JCExpression expr = TreeInfo.skipParens(tree.expr);
4108         boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4109         if (isPoly) {
4110             //expression is a poly - we need to propagate target type info
4111             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
4112                                       new Check.NestedCheckContext(resultInfo.checkContext) {
4113                 @Override
4114                 public boolean compatible(Type found, Type req, Warner warn) {
4115                     return types.isCastable(found, req, warn);
4116                 }
4117             });
4118         } else {
4119             //standalone cast - target-type info is not propagated
4120             castInfo = unknownExprInfo;
4121         }
4122         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
4123         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4124         if (exprtype.constValue() != null)
4125             owntype = cfolder.coerce(exprtype, owntype);
4126         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
4127         if (!isPoly)
4128             chk.checkRedundantCast(localEnv, tree);
4129     }
4130 
4131     public void visitTypeTest(JCInstanceOf tree) {
4132         Type exprtype = attribExpr(tree.expr, env);
4133         if (exprtype.isPrimitive()) {
4134             preview.checkSourceLevel(tree.expr.pos(), Feature.PRIMITIVE_PATTERNS);
4135         } else {
4136             exprtype = chk.checkNullOrRefType(
4137                     tree.expr.pos(), exprtype);
4138         }
4139         Type clazztype;
4140         JCTree typeTree;
4141         if (tree.pattern.getTag() == BINDINGPATTERN ||
4142             tree.pattern.getTag() == RECORDPATTERN) {
4143             attribExpr(tree.pattern, env, exprtype);
4144             clazztype = tree.pattern.type;
4145             if (types.isSubtype(exprtype, clazztype) &&
4146                 !exprtype.isErroneous() && !clazztype.isErroneous() &&
4147                 tree.pattern.getTag() != RECORDPATTERN) {
4148                 if (!allowUnconditionalPatternsInstanceOf) {
4149                     log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
4150                               Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName));
4151                 }
4152             }
4153             typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern);
4154         } else {
4155             clazztype = attribType(tree.pattern, env);
4156             typeTree = tree.pattern;
4157             chk.validate(typeTree, env, false);
4158         }
4159         if (clazztype.isPrimitive()) {
4160             preview.checkSourceLevel(tree.pattern.pos(), Feature.PRIMITIVE_PATTERNS);
4161         } else {
4162             if (!clazztype.hasTag(TYPEVAR)) {
4163                 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype);
4164             }
4165             if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
4166                 boolean valid = false;
4167                 if (allowReifiableTypesInInstanceof) {
4168                     valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype);
4169                 } else {
4170                     log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
4171                             Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName));
4172                     allowReifiableTypesInInstanceof = true;
4173                 }
4174                 if (!valid) {
4175                     clazztype = types.createErrorType(clazztype);
4176                 }
4177             }
4178         }
4179         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4180         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
4181     }
4182 
4183     private boolean checkCastablePattern(DiagnosticPosition pos,
4184                                          Type exprType,
4185                                          Type pattType) {
4186         Warner warner = new Warner();
4187         // if any type is erroneous, the problem is reported elsewhere
4188         if (exprType.isErroneous() || pattType.isErroneous()) {
4189             return false;
4190         }
4191         if (!types.isCastable(exprType, pattType, warner)) {
4192             chk.basicHandler.report(pos,
4193                     diags.fragment(Fragments.InconvertibleTypes(exprType, pattType)));
4194             return false;
4195         } else if ((exprType.isPrimitive() || pattType.isPrimitive()) &&
4196                 (!exprType.isPrimitive() || !pattType.isPrimitive() || !types.isSameType(exprType, pattType))) {
4197             preview.checkSourceLevel(pos, Feature.PRIMITIVE_PATTERNS);
4198             return true;
4199         } else if (warner.hasLint(LintCategory.UNCHECKED)) {
4200             log.error(pos,
4201                     Errors.InstanceofReifiableNotSafe(exprType, pattType));
4202             return false;
4203         } else {
4204             return true;
4205         }
4206     }
4207 
4208     @Override
4209     public void visitAnyPattern(JCAnyPattern tree) {
4210         result = tree.type = resultInfo.pt;
4211     }
4212 
4213     public void visitBindingPattern(JCBindingPattern tree) {
4214         Type type;
4215         if (tree.var.vartype != null) {
4216             type = attribType(tree.var.vartype, env);
4217         } else {
4218             type = resultInfo.pt;
4219         }
4220         tree.type = tree.var.type = type;
4221         BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, type, env.info.scope.owner);
4222         v.pos = tree.pos;
4223         tree.var.sym = v;
4224         if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
4225             chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
4226         }
4227         chk.validate(tree.var.vartype, env, true);
4228         if (tree.var.isImplicitlyTyped()) {
4229             setSyntheticVariableType(tree.var, type == Type.noType ? syms.errType
4230                                                                    : type);
4231         }
4232         annotate.annotateLater(tree.var.mods.annotations, env, v, tree.var);
4233         if (!tree.var.isImplicitlyTyped()) {
4234             annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v, tree.var);
4235         }
4236         annotate.flush();
4237         result = tree.type;
4238         if (v.isUnnamedVariable()) {
4239             matchBindings = MatchBindingsComputer.EMPTY;
4240         } else {
4241             matchBindings = new MatchBindings(List.of(v), List.nil());
4242         }
4243     }
4244 
4245     @Override
4246     public void visitRecordPattern(JCRecordPattern tree) {
4247         Type site;
4248 
4249         if (tree.deconstructor == null) {
4250             log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed);
4251             tree.record = syms.errSymbol;
4252             site = tree.type = types.createErrorType(tree.record.type);
4253         } else {
4254             Type type = attribType(tree.deconstructor, env);
4255             if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) {
4256                 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym);
4257                 if (inferred == null) {
4258                     log.error(tree.pos(), Errors.PatternTypeCannotInfer);
4259                 } else {
4260                     type = inferred;
4261                 }
4262             }
4263             tree.type = tree.deconstructor.type = type;
4264             site = types.capture(tree.type);
4265         }
4266 
4267         List<Type> expectedRecordTypes;
4268         if (site.tsym.kind == Kind.TYP && ((ClassSymbol) site.tsym).isRecord()) {
4269             ClassSymbol record = (ClassSymbol) site.tsym;
4270             expectedRecordTypes = record.getRecordComponents()
4271                                         .stream()
4272                                         .map(rc -> types.memberType(site, rc))
4273                                         .map(t -> types.upward(t, types.captures(t)).baseType())
4274                                         .collect(List.collector());
4275             tree.record = record;
4276         } else {
4277             log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym));
4278             expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type))
4279                                 .limit(tree.nested.size())
4280                                 .collect(List.collector());
4281             tree.record = syms.errSymbol;
4282         }
4283         ListBuffer<BindingSymbol> outBindings = new ListBuffer<>();
4284         List<Type> recordTypes = expectedRecordTypes;
4285         List<JCPattern> nestedPatterns = tree.nested;
4286         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
4287         try {
4288             while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) {
4289                 attribExpr(nestedPatterns.head, localEnv, recordTypes.head);
4290                 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type);
4291                 outBindings.addAll(matchBindings.bindingsWhenTrue);
4292                 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter);
4293                 nestedPatterns = nestedPatterns.tail;
4294                 recordTypes = recordTypes.tail;
4295             }
4296             if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) {
4297                 while (nestedPatterns.nonEmpty()) {
4298                     attribExpr(nestedPatterns.head, localEnv, Type.noType);
4299                     nestedPatterns = nestedPatterns.tail;
4300                 }
4301                 List<Type> nestedTypes =
4302                         tree.nested.stream().map(p -> p.type).collect(List.collector());
4303                 log.error(tree.pos(),
4304                           Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes,
4305                                                                  nestedTypes));
4306             }
4307         } finally {
4308             localEnv.info.scope.leave();
4309         }
4310         chk.validate(tree.deconstructor, env, true);
4311         result = tree.type;
4312         matchBindings = new MatchBindings(outBindings.toList(), List.nil());
4313     }
4314 
4315     public void visitIndexed(JCArrayAccess tree) {
4316         Type owntype = types.createErrorType(tree.type);
4317         Type atype = attribExpr(tree.indexed, env);
4318         attribExpr(tree.index, env, syms.intType);
4319         if (types.isArray(atype))
4320             owntype = types.elemtype(atype);
4321         else if (!atype.hasTag(ERROR))
4322             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
4323         if (!pkind().contains(KindSelector.VAL))
4324             owntype = capture(owntype);
4325         result = check(tree, owntype, KindSelector.VAR, resultInfo);
4326     }
4327 
4328     public void visitIdent(JCIdent tree) {
4329         Symbol sym;
4330 
4331         // Find symbol
4332         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
4333             // If we are looking for a method, the prototype `pt' will be a
4334             // method type with the type of the call's arguments as parameters.
4335             env.info.pendingResolutionPhase = null;
4336             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
4337         } else if (tree.sym != null && tree.sym.kind != VAR) {
4338             sym = tree.sym;
4339         } else {
4340             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
4341         }
4342         tree.sym = sym;
4343 
4344         // Also find the environment current for the class where
4345         // sym is defined (`symEnv').
4346         Env<AttrContext> symEnv = env;
4347         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
4348             sym.kind.matches(KindSelector.VAL_MTH) &&
4349             sym.owner.kind == TYP &&
4350             tree.name != names._this && tree.name != names._super) {
4351 
4352             // Find environment in which identifier is defined.
4353             while (symEnv.outer != null &&
4354                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
4355                 symEnv = symEnv.outer;
4356             }
4357         }
4358 
4359         // If symbol is a variable, ...
4360         if (sym.kind == VAR) {
4361             VarSymbol v = (VarSymbol)sym;
4362 
4363             // ..., evaluate its initializer, if it has one, and check for
4364             // illegal forward reference.
4365             checkInit(tree, env, v, false);
4366 
4367             // If we are expecting a variable (as opposed to a value), check
4368             // that the variable is assignable in the current environment.
4369             if (KindSelector.ASG.subset(pkind()))
4370                 checkAssignable(tree.pos(), v, null, env);
4371         }
4372 
4373         Env<AttrContext> env1 = env;
4374         if (sym.kind != ERR && sym.kind != TYP &&
4375             sym.owner != null && sym.owner != env1.enclClass.sym) {
4376             // If the found symbol is inaccessible, then it is
4377             // accessed through an enclosing instance.  Locate this
4378             // enclosing instance:
4379             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4380                 env1 = env1.outer;
4381         }
4382 
4383         if (env.info.isSerializable) {
4384             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4385         }
4386 
4387         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4388     }
4389 
4390     public void visitSelect(JCFieldAccess tree) {
4391         // Determine the expected kind of the qualifier expression.
4392         KindSelector skind = KindSelector.NIL;
4393         if (tree.name == names._this || tree.name == names._super ||
4394                 tree.name == names._class)
4395         {
4396             skind = KindSelector.TYP;
4397         } else {
4398             if (pkind().contains(KindSelector.PCK))
4399                 skind = KindSelector.of(skind, KindSelector.PCK);
4400             if (pkind().contains(KindSelector.TYP))
4401                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4402             if (pkind().contains(KindSelector.VAL_MTH))
4403                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4404         }
4405 
4406         // Attribute the qualifier expression, and determine its symbol (if any).
4407         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4408         Assert.check(site == tree.selected.type);
4409         if (!pkind().contains(KindSelector.TYP_PCK))
4410             site = capture(site); // Capture field access
4411 
4412         // don't allow T.class T[].class, etc
4413         if (skind == KindSelector.TYP) {
4414             Type elt = site;
4415             while (elt.hasTag(ARRAY))
4416                 elt = ((ArrayType)elt).elemtype;
4417             if (elt.hasTag(TYPEVAR)) {
4418                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4419                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4420                 tree.sym = tree.type.tsym;
4421                 return ;
4422             }
4423         }
4424 
4425         // If qualifier symbol is a type or `super', assert `selectSuper'
4426         // for the selection. This is relevant for determining whether
4427         // protected symbols are accessible.
4428         Symbol sitesym = TreeInfo.symbol(tree.selected);
4429         boolean selectSuperPrev = env.info.selectSuper;
4430         env.info.selectSuper =
4431             sitesym != null &&
4432             sitesym.name == names._super;
4433 
4434         // Determine the symbol represented by the selection.
4435         env.info.pendingResolutionPhase = null;
4436         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4437         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4438             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4439             sym = syms.errSymbol;
4440         }
4441         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4442             site = capture(site);
4443             sym = selectSym(tree, sitesym, site, env, resultInfo);
4444         }
4445         boolean varArgs = env.info.lastResolveVarargs();
4446         tree.sym = sym;
4447 
4448         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4449             site = types.skipTypeVars(site, true);
4450         }
4451 
4452         // If that symbol is a variable, ...
4453         if (sym.kind == VAR) {
4454             VarSymbol v = (VarSymbol)sym;
4455 
4456             // ..., evaluate its initializer, if it has one, and check for
4457             // illegal forward reference.
4458             checkInit(tree, env, v, true);
4459 
4460             // If we are expecting a variable (as opposed to a value), check
4461             // that the variable is assignable in the current environment.
4462             if (KindSelector.ASG.subset(pkind()))
4463                 checkAssignable(tree.pos(), v, tree.selected, env);
4464         }
4465 
4466         if (sitesym != null &&
4467                 sitesym.kind == VAR &&
4468                 ((VarSymbol)sitesym).isResourceVariable() &&
4469                 sym.kind == MTH &&
4470                 sym.name.equals(names.close) &&
4471                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
4472             env.info.lint.logIfEnabled(tree, LintWarnings.TryExplicitCloseCall);
4473         }
4474 
4475         // Disallow selecting a type from an expression
4476         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4477             tree.type = check(tree.selected, pt(),
4478                               sitesym == null ?
4479                                       KindSelector.VAL : sitesym.kind.toSelector(),
4480                               new ResultInfo(KindSelector.TYP_PCK, pt()));
4481         }
4482 
4483         if (isType(sitesym)) {
4484             if (sym.name != names._this && sym.name != names._super) {
4485                 // Check if type-qualified fields or methods are static (JLS)
4486                 if ((sym.flags() & STATIC) == 0 &&
4487                     sym.name != names._super &&
4488                     (sym.kind == VAR || sym.kind == MTH)) {
4489                     rs.accessBase(rs.new StaticError(sym),
4490                               tree.pos(), site, sym.name, true);
4491                 }
4492             }
4493         } else if (sym.kind != ERR &&
4494                    (sym.flags() & STATIC) != 0 &&
4495                    sym.name != names._class) {
4496             // If the qualified item is not a type and the selected item is static, report
4497             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4498             if (!sym.owner.isAnonymous()) {
4499                 chk.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4500             } else {
4501                 chk.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4502             }
4503         }
4504 
4505         // If we are selecting an instance member via a `super', ...
4506         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4507 
4508             // Check that super-qualified symbols are not abstract (JLS)
4509             rs.checkNonAbstract(tree.pos(), sym);
4510 
4511             if (site.isRaw()) {
4512                 // Determine argument types for site.
4513                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4514                 if (site1 != null) site = site1;
4515             }
4516         }
4517 
4518         if (env.info.isSerializable) {
4519             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4520         }
4521 
4522         env.info.selectSuper = selectSuperPrev;
4523         result = checkId(tree, site, sym, env, resultInfo);
4524     }
4525     //where
4526         /** Determine symbol referenced by a Select expression,
4527          *
4528          *  @param tree   The select tree.
4529          *  @param site   The type of the selected expression,
4530          *  @param env    The current environment.
4531          *  @param resultInfo The current result.
4532          */
4533         private Symbol selectSym(JCFieldAccess tree,
4534                                  Symbol location,
4535                                  Type site,
4536                                  Env<AttrContext> env,
4537                                  ResultInfo resultInfo) {
4538             DiagnosticPosition pos = tree.pos();
4539             Name name = tree.name;
4540             switch (site.getTag()) {
4541             case PACKAGE:
4542                 return rs.accessBase(
4543                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4544                     pos, location, site, name, true);
4545             case ARRAY:
4546             case CLASS:
4547                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4548                     return rs.resolveQualifiedMethod(
4549                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4550                 } else if (name == names._this || name == names._super) {
4551                     return rs.resolveSelf(pos, env, site.tsym, name);
4552                 } else if (name == names._class) {
4553                     // In this case, we have already made sure in
4554                     // visitSelect that qualifier expression is a type.
4555                     return syms.getClassField(site, types);
4556                 } else {
4557                     // We are seeing a plain identifier as selector.
4558                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4559                         sym = rs.accessBase(sym, pos, location, site, name, true);
4560                     return sym;
4561                 }
4562             case WILDCARD:
4563                 throw new AssertionError(tree);
4564             case TYPEVAR:
4565                 // Normally, site.getUpperBound() shouldn't be null.
4566                 // It should only happen during memberEnter/attribBase
4567                 // when determining the supertype which *must* be
4568                 // done before attributing the type variables.  In
4569                 // other words, we are seeing this illegal program:
4570                 // class B<T> extends A<T.foo> {}
4571                 Symbol sym = (site.getUpperBound() != null)
4572                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4573                     : null;
4574                 if (sym == null) {
4575                     log.error(pos, Errors.TypeVarCantBeDeref);
4576                     return syms.errSymbol;
4577                 } else {
4578                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
4579                         rs.new AccessError(env, site, sym) :
4580                                 sym;
4581                     rs.accessBase(sym2, pos, location, site, name, true);
4582                     return sym;
4583                 }
4584             case ERROR:
4585                 // preserve identifier names through errors
4586                 return types.createErrorType(name, site.tsym, site).tsym;
4587             default:
4588                 // The qualifier expression is of a primitive type -- only
4589                 // .class is allowed for these.
4590                 if (name == names._class) {
4591                     // In this case, we have already made sure in Select that
4592                     // qualifier expression is a type.
4593                     return syms.getClassField(site, types);
4594                 } else {
4595                     log.error(pos, Errors.CantDeref(site));
4596                     return syms.errSymbol;
4597                 }
4598             }
4599         }
4600 
4601         /** Determine type of identifier or select expression and check that
4602          *  (1) the referenced symbol is not deprecated
4603          *  (2) the symbol's type is safe (@see checkSafe)
4604          *  (3) if symbol is a variable, check that its type and kind are
4605          *      compatible with the prototype and protokind.
4606          *  (4) if symbol is an instance field of a raw type,
4607          *      which is being assigned to, issue an unchecked warning if its
4608          *      type changes under erasure.
4609          *  (5) if symbol is an instance method of a raw type, issue an
4610          *      unchecked warning if its argument types change under erasure.
4611          *  If checks succeed:
4612          *    If symbol is a constant, return its constant type
4613          *    else if symbol is a method, return its result type
4614          *    otherwise return its type.
4615          *  Otherwise return errType.
4616          *
4617          *  @param tree       The syntax tree representing the identifier
4618          *  @param site       If this is a select, the type of the selected
4619          *                    expression, otherwise the type of the current class.
4620          *  @param sym        The symbol representing the identifier.
4621          *  @param env        The current environment.
4622          *  @param resultInfo    The expected result
4623          */
4624         Type checkId(JCTree tree,
4625                      Type site,
4626                      Symbol sym,
4627                      Env<AttrContext> env,
4628                      ResultInfo resultInfo) {
4629             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
4630                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
4631                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4632         }
4633 
4634         Type checkMethodIdInternal(JCTree tree,
4635                      Type site,
4636                      Symbol sym,
4637                      Env<AttrContext> env,
4638                      ResultInfo resultInfo) {
4639             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4640                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4641             } else {
4642                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4643             }
4644         }
4645 
4646         Type checkIdInternal(JCTree tree,
4647                      Type site,
4648                      Symbol sym,
4649                      Type pt,
4650                      Env<AttrContext> env,
4651                      ResultInfo resultInfo) {
4652             Type owntype; // The computed type of this identifier occurrence.
4653             switch (sym.kind) {
4654             case TYP:
4655                 // For types, the computed type equals the symbol's type,
4656                 // except for two situations:
4657                 owntype = sym.type;
4658                 if (owntype.hasTag(CLASS)) {
4659                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4660                     Type ownOuter = owntype.getEnclosingType();
4661 
4662                     // (a) If the symbol's type is parameterized, erase it
4663                     // because no type parameters were given.
4664                     // We recover generic outer type later in visitTypeApply.
4665                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4666                         owntype = types.erasure(owntype);
4667                     }
4668 
4669                     // (b) If the symbol's type is an inner class, then
4670                     // we have to interpret its outer type as a superclass
4671                     // of the site type. Example:
4672                     //
4673                     // class Tree<A> { class Visitor { ... } }
4674                     // class PointTree extends Tree<Point> { ... }
4675                     // ...PointTree.Visitor...
4676                     //
4677                     // Then the type of the last expression above is
4678                     // Tree<Point>.Visitor.
4679                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4680                         Type normOuter = site;
4681                         if (normOuter.hasTag(CLASS)) {
4682                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4683                         }
4684                         if (normOuter == null) // perhaps from an import
4685                             normOuter = types.erasure(ownOuter);
4686                         if (normOuter != ownOuter)
4687                             owntype = new ClassType(
4688                                 normOuter, List.nil(), owntype.tsym,
4689                                 owntype.getMetadata());
4690                     }
4691                 }
4692                 break;
4693             case VAR:
4694                 VarSymbol v = (VarSymbol)sym;
4695 
4696                 if (env.info.enclVar != null
4697                         && v.type.hasTag(NONE)) {
4698                     //self reference to implicitly typed variable declaration
4699                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4700                     return tree.type = v.type = types.createErrorType(v.type);
4701                 }
4702 
4703                 // Test (4): if symbol is an instance field of a raw type,
4704                 // which is being assigned to, issue an unchecked warning if
4705                 // its type changes under erasure.
4706                 if (KindSelector.ASG.subset(pkind()) &&
4707                     v.owner.kind == TYP &&
4708                     (v.flags() & STATIC) == 0 &&
4709                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4710                     Type s = types.asOuterSuper(site, v.owner);
4711                     if (s != null &&
4712                         s.isRaw() &&
4713                         !types.isSameType(v.type, v.erasure(types))) {
4714                         chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
4715                     }
4716                 }
4717                 // The computed type of a variable is the type of the
4718                 // variable symbol, taken as a member of the site type.
4719                 owntype = (sym.owner.kind == TYP &&
4720                            sym.name != names._this && sym.name != names._super)
4721                     ? types.memberType(site, sym)
4722                     : sym.type;
4723 
4724                 // If the variable is a constant, record constant value in
4725                 // computed type.
4726                 if (v.getConstValue() != null && isStaticReference(tree))
4727                     owntype = owntype.constType(v.getConstValue());
4728 
4729                 if (resultInfo.pkind == KindSelector.VAL) {
4730                     owntype = capture(owntype); // capture "names as expressions"
4731                 }
4732                 break;
4733             case MTH: {
4734                 owntype = checkMethod(site, sym,
4735                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4736                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4737                         resultInfo.pt.getTypeArguments());
4738                 chk.checkRestricted(tree.pos(), sym);
4739                 break;
4740             }
4741             case PCK: case ERR:
4742                 owntype = sym.type;
4743                 break;
4744             default:
4745                 throw new AssertionError("unexpected kind: " + sym.kind +
4746                                          " in tree " + tree);
4747             }
4748 
4749             // Emit a `deprecation' warning if symbol is deprecated.
4750             // (for constructors (but not for constructor references), the error
4751             // was given when the constructor was resolved)
4752 
4753             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4754                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4755                 chk.checkSunAPI(tree.pos(), sym);
4756                 chk.checkProfile(tree.pos(), sym);
4757                 chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym);
4758             }
4759 
4760             if (pt.isErroneous()) {
4761                 owntype = types.createErrorType(owntype);
4762             }
4763 
4764             // If symbol is a variable, check that its type and
4765             // kind are compatible with the prototype and protokind.
4766             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4767         }
4768 
4769         /** Check that variable is initialized and evaluate the variable's
4770          *  initializer, if not yet done. Also check that variable is not
4771          *  referenced before it is defined.
4772          *  @param tree    The tree making up the variable reference.
4773          *  @param env     The current environment.
4774          *  @param v       The variable's symbol.
4775          */
4776         private void checkInit(JCTree tree,
4777                                Env<AttrContext> env,
4778                                VarSymbol v,
4779                                boolean onlyWarning) {
4780             // A forward reference is diagnosed if the declaration position
4781             // of the variable is greater than the current tree position
4782             // and the tree and variable definition occur in the same class
4783             // definition.  Note that writes don't count as references.
4784             // This check applies only to class and instance
4785             // variables.  Local variables follow different scope rules,
4786             // and are subject to definite assignment checking.
4787             Env<AttrContext> initEnv = enclosingInitEnv(env);
4788             if (initEnv != null &&
4789                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4790                 v.owner.kind == TYP &&
4791                 v.owner == env.info.scope.owner.enclClass() &&
4792                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4793                 (!env.tree.hasTag(ASSIGN) ||
4794                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4795                 if (!onlyWarning || isStaticEnumField(v)) {
4796                     Error errkey = (initEnv.info.enclVar == v) ?
4797                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4798                     log.error(tree.pos(), errkey);
4799                 } else if (useBeforeDeclarationWarning) {
4800                     Warning warnkey = (initEnv.info.enclVar == v) ?
4801                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4802                     log.warning(tree.pos(), warnkey);
4803                 }
4804             }
4805 
4806             v.getConstValue(); // ensure initializer is evaluated
4807 
4808             checkEnumInitializer(tree, env, v);
4809         }
4810 
4811         /**
4812          * Returns the enclosing init environment associated with this env (if any). An init env
4813          * can be either a field declaration env or a static/instance initializer env.
4814          */
4815         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4816             while (true) {
4817                 switch (env.tree.getTag()) {
4818                     case VARDEF:
4819                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4820                         if (vdecl.sym.owner.kind == TYP) {
4821                             //field
4822                             return env;
4823                         }
4824                         break;
4825                     case BLOCK:
4826                         if (env.next.tree.hasTag(CLASSDEF)) {
4827                             //instance/static initializer
4828                             return env;
4829                         }
4830                         break;
4831                     case METHODDEF:
4832                     case CLASSDEF:
4833                     case TOPLEVEL:
4834                         return null;
4835                 }
4836                 Assert.checkNonNull(env.next);
4837                 env = env.next;
4838             }
4839         }
4840 
4841         /**
4842          * Check for illegal references to static members of enum.  In
4843          * an enum type, constructors and initializers may not
4844          * reference its static members unless they are constant.
4845          *
4846          * @param tree    The tree making up the variable reference.
4847          * @param env     The current environment.
4848          * @param v       The variable's symbol.
4849          * @jls 8.9 Enum Types
4850          */
4851         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4852             // JLS:
4853             //
4854             // "It is a compile-time error to reference a static field
4855             // of an enum type that is not a compile-time constant
4856             // (15.28) from constructors, instance initializer blocks,
4857             // or instance variable initializer expressions of that
4858             // type. It is a compile-time error for the constructors,
4859             // instance initializer blocks, or instance variable
4860             // initializer expressions of an enum constant e to refer
4861             // to itself or to an enum constant of the same type that
4862             // is declared to the right of e."
4863             if (isStaticEnumField(v)) {
4864                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4865 
4866                 if (enclClass == null || enclClass.owner == null)
4867                     return;
4868 
4869                 // See if the enclosing class is the enum (or a
4870                 // subclass thereof) declaring v.  If not, this
4871                 // reference is OK.
4872                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4873                     return;
4874 
4875                 // If the reference isn't from an initializer, then
4876                 // the reference is OK.
4877                 if (!Resolve.isInitializer(env))
4878                     return;
4879 
4880                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4881             }
4882         }
4883 
4884         /** Is the given symbol a static, non-constant field of an Enum?
4885          *  Note: enum literals should not be regarded as such
4886          */
4887         private boolean isStaticEnumField(VarSymbol v) {
4888             return Flags.isEnum(v.owner) &&
4889                    Flags.isStatic(v) &&
4890                    !Flags.isConstant(v) &&
4891                    v.name != names._class;
4892         }
4893 
4894     /**
4895      * Check that method arguments conform to its instantiation.
4896      **/
4897     public Type checkMethod(Type site,
4898                             final Symbol sym,
4899                             ResultInfo resultInfo,
4900                             Env<AttrContext> env,
4901                             final List<JCExpression> argtrees,
4902                             List<Type> argtypes,
4903                             List<Type> typeargtypes) {
4904         // Test (5): if symbol is an instance method of a raw type, issue
4905         // an unchecked warning if its argument types change under erasure.
4906         if ((sym.flags() & STATIC) == 0 &&
4907             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4908             Type s = types.asOuterSuper(site, sym.owner);
4909             if (s != null && s.isRaw() &&
4910                 !types.isSameTypes(sym.type.getParameterTypes(),
4911                                    sym.erasure(types).getParameterTypes())) {
4912                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
4913             }
4914         }
4915 
4916         if (env.info.defaultSuperCallSite != null) {
4917             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4918                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4919                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4920                 List<MethodSymbol> icand_sup =
4921                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4922                 if (icand_sup.nonEmpty() &&
4923                         icand_sup.head != sym &&
4924                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4925                     log.error(env.tree.pos(),
4926                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4927                     break;
4928                 }
4929             }
4930             env.info.defaultSuperCallSite = null;
4931         }
4932 
4933         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4934             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4935             if (app.meth.hasTag(SELECT) &&
4936                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4937                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4938             }
4939         }
4940 
4941         // Compute the identifier's instantiated type.
4942         // For methods, we need to compute the instance type by
4943         // Resolve.instantiate from the symbol's type as well as
4944         // any type arguments and value arguments.
4945         Warner noteWarner = new Warner();
4946         try {
4947             Type owntype = rs.checkMethod(
4948                     env,
4949                     site,
4950                     sym,
4951                     resultInfo,
4952                     argtypes,
4953                     typeargtypes,
4954                     noteWarner);
4955 
4956             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4957                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4958 
4959             argtypes = argtypes.map(checkDeferredMap);
4960 
4961             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4962                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
4963                         sym.name,
4964                         rs.methodArguments(sym.type.getParameterTypes()),
4965                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4966                         kindName(sym.location()),
4967                         sym.location()));
4968                 if (resultInfo.pt != Infer.anyPoly ||
4969                         !owntype.hasTag(METHOD) ||
4970                         !owntype.isPartial()) {
4971                     //if this is not a partially inferred method type, erase return type. Otherwise,
4972                     //erasure is carried out in PartiallyInferredMethodType.check().
4973                     owntype = new MethodType(owntype.getParameterTypes(),
4974                             types.erasure(owntype.getReturnType()),
4975                             types.erasure(owntype.getThrownTypes()),
4976                             syms.methodClass);
4977                 }
4978             }
4979 
4980             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4981                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4982                  PolyKind.POLY : PolyKind.STANDALONE;
4983             TreeInfo.setPolyKind(env.tree, pkind);
4984 
4985             return (resultInfo.pt == Infer.anyPoly) ?
4986                     owntype :
4987                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4988                             resultInfo.checkContext.inferenceContext());
4989         } catch (Infer.InferenceException ex) {
4990             //invalid target type - propagate exception outwards or report error
4991             //depending on the current check context
4992             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4993             return types.createErrorType(site);
4994         } catch (Resolve.InapplicableMethodException ex) {
4995             final JCDiagnostic diag = ex.getDiagnostic();
4996             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4997                 @Override
4998                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4999                     return new Pair<>(sym, diag);
5000                 }
5001             };
5002             List<Type> argtypes2 = argtypes.map(
5003                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5004             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5005                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5006             log.report(errDiag);
5007             return types.createErrorType(site);
5008         }
5009     }
5010 
5011     public void visitLiteral(JCLiteral tree) {
5012         result = check(tree, litType(tree.typetag).constType(tree.value),
5013                 KindSelector.VAL, resultInfo);
5014     }
5015     //where
5016     /** Return the type of a literal with given type tag.
5017      */
5018     Type litType(TypeTag tag) {
5019         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5020     }
5021 
5022     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5023         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5024     }
5025 
5026     public void visitTypeArray(JCArrayTypeTree tree) {
5027         Type etype = attribType(tree.elemtype, env);
5028         Type type = new ArrayType(etype, syms.arrayClass);
5029         result = check(tree, type, KindSelector.TYP, resultInfo);
5030     }
5031 
5032     /** Visitor method for parameterized types.
5033      *  Bound checking is left until later, since types are attributed
5034      *  before supertype structure is completely known
5035      */
5036     public void visitTypeApply(JCTypeApply tree) {
5037         Type owntype = types.createErrorType(tree.type);
5038 
5039         // Attribute functor part of application and make sure it's a class.
5040         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5041 
5042         // Attribute type parameters
5043         List<Type> actuals = attribTypes(tree.arguments, env);
5044 
5045         if (clazztype.hasTag(CLASS)) {
5046             List<Type> formals = clazztype.tsym.type.getTypeArguments();
5047             if (actuals.isEmpty()) //diamond
5048                 actuals = formals;
5049 
5050             if (actuals.length() == formals.length()) {
5051                 List<Type> a = actuals;
5052                 List<Type> f = formals;
5053                 while (a.nonEmpty()) {
5054                     a.head = a.head.withTypeVar(f.head);
5055                     a = a.tail;
5056                     f = f.tail;
5057                 }
5058                 // Compute the proper generic outer
5059                 Type clazzOuter = clazztype.getEnclosingType();
5060                 if (clazzOuter.hasTag(CLASS)) {
5061                     Type site;
5062                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5063                     if (clazz.hasTag(IDENT)) {
5064                         site = env.enclClass.sym.type;
5065                     } else if (clazz.hasTag(SELECT)) {
5066                         site = ((JCFieldAccess) clazz).selected.type;
5067                     } else throw new AssertionError(""+tree);
5068                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5069                         if (site.hasTag(CLASS))
5070                             site = types.asOuterSuper(site, clazzOuter.tsym);
5071                         if (site == null)
5072                             site = types.erasure(clazzOuter);
5073                         clazzOuter = site;
5074                     }
5075                 }
5076                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5077                                         clazztype.getMetadata());
5078             } else {
5079                 if (formals.length() != 0) {
5080                     log.error(tree.pos(),
5081                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5082                 } else {
5083                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5084                 }
5085                 owntype = types.createErrorType(tree.type);
5086             }
5087         } else if (clazztype.hasTag(ERROR)) {
5088             ErrorType parameterizedErroneous =
5089                     new ErrorType(clazztype.getOriginalType(),
5090                                   clazztype.tsym,
5091                                   clazztype.getMetadata());
5092 
5093             parameterizedErroneous.typarams_field = actuals;
5094             owntype = parameterizedErroneous;
5095         }
5096         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5097     }
5098 
5099     public void visitTypeUnion(JCTypeUnion tree) {
5100         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5101         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5102         for (JCExpression typeTree : tree.alternatives) {
5103             Type ctype = attribType(typeTree, env);
5104             ctype = chk.checkType(typeTree.pos(),
5105                           chk.checkClassType(typeTree.pos(), ctype),
5106                           syms.throwableType);
5107             if (!ctype.isErroneous()) {
5108                 //check that alternatives of a union type are pairwise
5109                 //unrelated w.r.t. subtyping
5110                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
5111                     for (Type t : multicatchTypes) {
5112                         boolean sub = types.isSubtype(ctype, t);
5113                         boolean sup = types.isSubtype(t, ctype);
5114                         if (sub || sup) {
5115                             //assume 'a' <: 'b'
5116                             Type a = sub ? ctype : t;
5117                             Type b = sub ? t : ctype;
5118                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5119                         }
5120                     }
5121                 }
5122                 multicatchTypes.append(ctype);
5123                 if (all_multicatchTypes != null)
5124                     all_multicatchTypes.append(ctype);
5125             } else {
5126                 if (all_multicatchTypes == null) {
5127                     all_multicatchTypes = new ListBuffer<>();
5128                     all_multicatchTypes.appendList(multicatchTypes);
5129                 }
5130                 all_multicatchTypes.append(ctype);
5131             }
5132         }
5133         Type t = check(tree, types.lub(multicatchTypes.toList()),
5134                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5135         if (t.hasTag(CLASS)) {
5136             List<Type> alternatives =
5137                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5138             t = new UnionClassType((ClassType) t, alternatives);
5139         }
5140         tree.type = result = t;
5141     }
5142 
5143     public void visitTypeIntersection(JCTypeIntersection tree) {
5144         attribTypes(tree.bounds, env);
5145         tree.type = result = checkIntersection(tree, tree.bounds);
5146     }
5147 
5148     public void visitTypeParameter(JCTypeParameter tree) {
5149         TypeVar typeVar = (TypeVar) tree.type;
5150 
5151         if (tree.annotations != null && tree.annotations.nonEmpty()) {
5152             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5153         }
5154 
5155         if (!typeVar.getUpperBound().isErroneous()) {
5156             //fixup type-parameter bound computed in 'attribTypeVariables'
5157             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5158         }
5159     }
5160 
5161     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5162         Set<Symbol> boundSet = new HashSet<>();
5163         if (bounds.nonEmpty()) {
5164             // accept class or interface or typevar as first bound.
5165             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5166             boundSet.add(types.erasure(bounds.head.type).tsym);
5167             if (bounds.head.type.isErroneous()) {
5168                 return bounds.head.type;
5169             }
5170             else if (bounds.head.type.hasTag(TYPEVAR)) {
5171                 // if first bound was a typevar, do not accept further bounds.
5172                 if (bounds.tail.nonEmpty()) {
5173                     log.error(bounds.tail.head.pos(),
5174                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
5175                     return bounds.head.type;
5176                 }
5177             } else {
5178                 // if first bound was a class or interface, accept only interfaces
5179                 // as further bounds.
5180                 for (JCExpression bound : bounds.tail) {
5181                     bound.type = checkBase(bound.type, bound, env, false, true, false);
5182                     if (bound.type.isErroneous()) {
5183                         bounds = List.of(bound);
5184                     }
5185                     else if (bound.type.hasTag(CLASS)) {
5186                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5187                     }
5188                 }
5189             }
5190         }
5191 
5192         if (bounds.length() == 0) {
5193             return syms.objectType;
5194         } else if (bounds.length() == 1) {
5195             return bounds.head.type;
5196         } else {
5197             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5198             // ... the variable's bound is a class type flagged COMPOUND
5199             // (see comment for TypeVar.bound).
5200             // In this case, generate a class tree that represents the
5201             // bound class, ...
5202             JCExpression extending;
5203             List<JCExpression> implementing;
5204             if (!bounds.head.type.isInterface()) {
5205                 extending = bounds.head;
5206                 implementing = bounds.tail;
5207             } else {
5208                 extending = null;
5209                 implementing = bounds;
5210             }
5211             JCClassDecl cd = make.at(tree).ClassDef(
5212                 make.Modifiers(PUBLIC | ABSTRACT),
5213                 names.empty, List.nil(),
5214                 extending, implementing, List.nil());
5215 
5216             ClassSymbol c = (ClassSymbol)owntype.tsym;
5217             Assert.check((c.flags() & COMPOUND) != 0);
5218             cd.sym = c;
5219             c.sourcefile = env.toplevel.sourcefile;
5220 
5221             // ... and attribute the bound class
5222             c.flags_field |= UNATTRIBUTED;
5223             Env<AttrContext> cenv = enter.classEnv(cd, env);
5224             typeEnvs.put(c, cenv);
5225             attribClass(c);
5226             return owntype;
5227         }
5228     }
5229 
5230     public void visitWildcard(JCWildcard tree) {
5231         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5232         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5233             ? syms.objectType
5234             : attribType(tree.inner, env);
5235         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5236                                               tree.kind.kind,
5237                                               syms.boundClass),
5238                 KindSelector.TYP, resultInfo);
5239     }
5240 
5241     public void visitAnnotation(JCAnnotation tree) {
5242         Assert.error("should be handled in annotate");
5243     }
5244 
5245     @Override
5246     public void visitModifiers(JCModifiers tree) {
5247         //error recovery only:
5248         Assert.check(resultInfo.pkind == KindSelector.ERR);
5249 
5250         attribAnnotationTypes(tree.annotations, env);
5251     }
5252 
5253     public void visitAnnotatedType(JCAnnotatedType tree) {
5254         attribAnnotationTypes(tree.annotations, env);
5255         Type underlyingType = attribType(tree.underlyingType, env);
5256         Type annotatedType = underlyingType.preannotatedType();
5257 
5258         if (!env.info.isAnonymousNewClass)
5259             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5260         result = tree.type = annotatedType;
5261     }
5262 
5263     public void visitErroneous(JCErroneous tree) {
5264         if (tree.errs != null) {
5265             WriteableScope newScope = env.info.scope;
5266 
5267             if (env.tree instanceof JCClassDecl) {
5268                 Symbol fakeOwner =
5269                     new MethodSymbol(BLOCK, names.empty, null,
5270                         env.info.scope.owner);
5271                 newScope = newScope.dupUnshared(fakeOwner);
5272             }
5273 
5274             Env<AttrContext> errEnv =
5275                     env.dup(env.tree,
5276                             env.info.dup(newScope));
5277             errEnv.info.returnResult = unknownExprInfo;
5278             for (JCTree err : tree.errs)
5279                 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5280         }
5281         result = tree.type = syms.errType;
5282     }
5283 
5284     /** Default visitor method for all other trees.
5285      */
5286     public void visitTree(JCTree tree) {
5287         throw new AssertionError();
5288     }
5289 
5290     /**
5291      * Attribute an env for either a top level tree or class or module declaration.
5292      */
5293     public void attrib(Env<AttrContext> env) {
5294         switch (env.tree.getTag()) {
5295             case MODULEDEF:
5296                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5297                 break;
5298             case PACKAGEDEF:
5299                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5300                 break;
5301             default:
5302                 attribClass(env.tree.pos(), env.enclClass.sym);
5303         }
5304 
5305         annotate.flush();
5306     }
5307 
5308     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5309         try {
5310             annotate.flush();
5311             attribPackage(p);
5312         } catch (CompletionFailure ex) {
5313             chk.completionError(pos, ex);
5314         }
5315     }
5316 
5317     void attribPackage(PackageSymbol p) {
5318         attribWithLint(p,
5319                        env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5320     }
5321 
5322     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5323         try {
5324             annotate.flush();
5325             attribModule(m);
5326         } catch (CompletionFailure ex) {
5327             chk.completionError(pos, ex);
5328         }
5329     }
5330 
5331     void attribModule(ModuleSymbol m) {
5332         attribWithLint(m, env -> attribStat(env.tree, env));
5333     }
5334 
5335     private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5336         Env<AttrContext> env = typeEnvs.get(sym);
5337 
5338         Env<AttrContext> lintEnv = env;
5339         while (lintEnv.info.lint == null)
5340             lintEnv = lintEnv.next;
5341 
5342         Lint lint = lintEnv.info.lint.augment(sym);
5343 
5344         Lint prevLint = chk.setLint(lint);
5345         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5346 
5347         try {
5348             deferredLintHandler.flush(env.tree, lint);
5349             attrib.accept(env);
5350         } finally {
5351             log.useSource(prev);
5352             chk.setLint(prevLint);
5353         }
5354     }
5355 
5356     /** Main method: attribute class definition associated with given class symbol.
5357      *  reporting completion failures at the given position.
5358      *  @param pos The source position at which completion errors are to be
5359      *             reported.
5360      *  @param c   The class symbol whose definition will be attributed.
5361      */
5362     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5363         try {
5364             annotate.flush();
5365             attribClass(c);
5366         } catch (CompletionFailure ex) {
5367             chk.completionError(pos, ex);
5368         }
5369     }
5370 
5371     /** Attribute class definition associated with given class symbol.
5372      *  @param c   The class symbol whose definition will be attributed.
5373      */
5374     void attribClass(ClassSymbol c) throws CompletionFailure {
5375         if (c.type.hasTag(ERROR)) return;
5376 
5377         // Check for cycles in the inheritance graph, which can arise from
5378         // ill-formed class files.
5379         chk.checkNonCyclic(null, c.type);
5380 
5381         Type st = types.supertype(c.type);
5382         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5383             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5384             // First, attribute superclass.
5385             if (st.hasTag(CLASS))
5386                 attribClass((ClassSymbol)st.tsym);
5387 
5388             // Next attribute owner, if it is a class.
5389             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5390                 attribClass((ClassSymbol)c.owner);
5391 
5392             c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5393         }
5394 
5395         // The previous operations might have attributed the current class
5396         // if there was a cycle. So we test first whether the class is still
5397         // UNATTRIBUTED.
5398         if ((c.flags_field & UNATTRIBUTED) != 0) {
5399             c.flags_field &= ~UNATTRIBUTED;
5400 
5401             // Get environment current at the point of class definition.
5402             Env<AttrContext> env = typeEnvs.get(c);
5403 
5404             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5405             // because the annotations were not available at the time the env was created. Therefore,
5406             // we look up the environment chain for the first enclosing environment for which the
5407             // lint value is set. Typically, this is the parent env, but might be further if there
5408             // are any envs created as a result of TypeParameter nodes.
5409             Env<AttrContext> lintEnv = env;
5410             while (lintEnv.info.lint == null)
5411                 lintEnv = lintEnv.next;
5412 
5413             // Having found the enclosing lint value, we can initialize the lint value for this class
5414             env.info.lint = lintEnv.info.lint.augment(c);
5415 
5416             Lint prevLint = chk.setLint(env.info.lint);
5417             JavaFileObject prev = log.useSource(c.sourcefile);
5418             ResultInfo prevReturnRes = env.info.returnResult;
5419 
5420             try {
5421                 if (c.isSealed() &&
5422                         !c.isEnum() &&
5423                         !c.isPermittedExplicit &&
5424                         c.getPermittedSubclasses().isEmpty()) {
5425                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5426                 }
5427 
5428                 if (c.isSealed()) {
5429                     Set<Symbol> permittedTypes = new HashSet<>();
5430                     boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5431                     for (Type subType : c.getPermittedSubclasses()) {
5432                         if (subType.isErroneous()) {
5433                             // the type already caused errors, don't produce more potentially misleading errors
5434                             continue;
5435                         }
5436                         boolean isTypeVar = false;
5437                         if (subType.getTag() == TYPEVAR) {
5438                             isTypeVar = true; //error recovery
5439                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5440                                     Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5441                         }
5442                         if (subType.tsym.isAnonymous() && !c.isEnum()) {
5443                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),  Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5444                         }
5445                         if (permittedTypes.contains(subType.tsym)) {
5446                             DiagnosticPosition pos =
5447                                     env.enclClass.permitting.stream()
5448                                             .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5449                                             .limit(2).collect(List.collector()).get(1);
5450                             log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5451                         } else {
5452                             permittedTypes.add(subType.tsym);
5453                         }
5454                         if (sealedInUnnamed) {
5455                             if (subType.tsym.packge() != c.packge()) {
5456                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5457                                         Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5458                                 );
5459                             }
5460                         } else if (subType.tsym.packge().modle != c.packge().modle) {
5461                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5462                                     Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5463                             );
5464                         }
5465                         if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5466                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5467                                     Errors.InvalidPermitsClause(
5468                                             subType.tsym == c.type.tsym ?
5469                                                     Fragments.MustNotBeSameClass :
5470                                                     Fragments.MustNotBeSupertype(subType)
5471                                     )
5472                             );
5473                         } else if (!isTypeVar) {
5474                             boolean thisIsASuper = types.directSupertypes(subType)
5475                                                         .stream()
5476                                                         .anyMatch(d -> d.tsym == c);
5477                             if (!thisIsASuper) {
5478                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5479                                         Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5480                             }
5481                         }
5482                     }
5483                 }
5484 
5485                 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5486                                                       .stream()
5487                                                       .filter(s -> s.tsym.isSealed())
5488                                                       .map(s -> (ClassSymbol) s.tsym)
5489                                                       .collect(List.collector());
5490 
5491                 if (sealedSupers.isEmpty()) {
5492                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5493                         boolean hasErrorSuper = false;
5494 
5495                         hasErrorSuper |= types.directSupertypes(c.type)
5496                                               .stream()
5497                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5498 
5499                         ClassType ct = (ClassType) c.type;
5500 
5501                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5502 
5503                         if (!hasErrorSuper) {
5504                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5505                         }
5506                     }
5507                 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5508                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5509                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5510                     }
5511 
5512                     if (!c.type.isCompound()) {
5513                         for (ClassSymbol supertypeSym : sealedSupers) {
5514                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5515                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5516                             }
5517                         }
5518                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5519                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5520                                     c.isInterface() ?
5521                                             Errors.NonSealedOrSealedExpected :
5522                                             Errors.NonSealedSealedOrFinalExpected);
5523                         }
5524                     }
5525                 }
5526 
5527                 deferredLintHandler.flush(env.tree, env.info.lint);
5528                 env.info.returnResult = null;
5529                 // java.lang.Enum may not be subclassed by a non-enum
5530                 if (st.tsym == syms.enumSym &&
5531                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5532                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5533 
5534                 // Enums may not be extended by source-level classes
5535                 if (st.tsym != null &&
5536                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5537                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5538                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5539                 }
5540 
5541                 if (rs.isSerializable(c.type)) {
5542                     env.info.isSerializable = true;
5543                 }
5544 
5545                 if (c.isValueClass()) {
5546                     Assert.check(env.tree.hasTag(CLASSDEF));
5547                     chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5548                 }
5549 
5550                 attribClassBody(env, c);
5551 
5552                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5553                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5554                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5555                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5556 
5557                 if (c.isImplicit()) {
5558                     chk.checkHasMain(env.tree.pos(), c);
5559                 }
5560             } finally {
5561                 env.info.returnResult = prevReturnRes;
5562                 log.useSource(prev);
5563                 chk.setLint(prevLint);
5564             }
5565 
5566         }
5567     }
5568 
5569     public void visitImport(JCImport tree) {
5570         // nothing to do
5571     }
5572 
5573     public void visitModuleDef(JCModuleDecl tree) {
5574         tree.sym.completeUsesProvides();
5575         ModuleSymbol msym = tree.sym;
5576         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5577         Lint prevLint = chk.setLint(lint);
5578         chk.checkModuleName(tree);
5579         chk.checkDeprecatedAnnotation(tree, msym);
5580 
5581         try {
5582             deferredLintHandler.flush(tree, lint);
5583         } finally {
5584             chk.setLint(prevLint);
5585         }
5586     }
5587 
5588     /** Finish the attribution of a class. */
5589     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5590         JCClassDecl tree = (JCClassDecl)env.tree;
5591         Assert.check(c == tree.sym);
5592 
5593         // Validate type parameters, supertype and interfaces.
5594         attribStats(tree.typarams, env);
5595         if (!c.isAnonymous()) {
5596             //already checked if anonymous
5597             chk.validate(tree.typarams, env);
5598             chk.validate(tree.extending, env);
5599             chk.validate(tree.implementing, env);
5600         }
5601 
5602         c.markAbstractIfNeeded(types);
5603 
5604         // If this is a non-abstract class, check that it has no abstract
5605         // methods or unimplemented methods of an implemented interface.
5606         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
5607             chk.checkAllDefined(tree.pos(), c);
5608         }
5609 
5610         if ((c.flags() & ANNOTATION) != 0) {
5611             if (tree.implementing.nonEmpty())
5612                 log.error(tree.implementing.head.pos(),
5613                           Errors.CantExtendIntfAnnotation);
5614             if (tree.typarams.nonEmpty()) {
5615                 log.error(tree.typarams.head.pos(),
5616                           Errors.IntfAnnotationCantHaveTypeParams(c));
5617             }
5618 
5619             // If this annotation type has a @Repeatable, validate
5620             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
5621             // If this annotation type has a @Repeatable, validate
5622             if (repeatable != null) {
5623                 // get diagnostic position for error reporting
5624                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
5625                 Assert.checkNonNull(cbPos);
5626 
5627                 chk.validateRepeatable(c, repeatable, cbPos);
5628             }
5629         } else {
5630             // Check that all extended classes and interfaces
5631             // are compatible (i.e. no two define methods with same arguments
5632             // yet different return types).  (JLS 8.4.8.3)
5633             chk.checkCompatibleSupertypes(tree.pos(), c.type);
5634             chk.checkDefaultMethodClashes(tree.pos(), c.type);
5635             chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
5636         }
5637 
5638         // Check that class does not import the same parameterized interface
5639         // with two different argument lists.
5640         chk.checkClassBounds(tree.pos(), c.type);
5641 
5642         tree.type = c.type;
5643 
5644         for (List<JCTypeParameter> l = tree.typarams;
5645              l.nonEmpty(); l = l.tail) {
5646              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
5647         }
5648 
5649         // Check that a generic class doesn't extend Throwable
5650         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
5651             log.error(tree.extending.pos(), Errors.GenericThrowable);
5652 
5653         // Check that all methods which implement some
5654         // method conform to the method they implement.
5655         chk.checkImplementations(tree);
5656 
5657         //check that a resource implementing AutoCloseable cannot throw InterruptedException
5658         checkAutoCloseable(tree.pos(), env, c.type);
5659 
5660         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
5661             // Attribute declaration
5662             attribStat(l.head, env);
5663             // Check that declarations in inner classes are not static (JLS 8.1.2)
5664             // Make an exception for static constants.
5665             if (!allowRecords &&
5666                     c.owner.kind != PCK &&
5667                     ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
5668                     (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
5669                 VarSymbol sym = null;
5670                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
5671                 if (sym == null ||
5672                         sym.kind != VAR ||
5673                         sym.getConstValue() == null)
5674                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5675             }
5676         }
5677 
5678         // Check for proper placement of super()/this() calls.
5679         chk.checkSuperInitCalls(tree);
5680 
5681         // Check for cycles among non-initial constructors.
5682         chk.checkCyclicConstructors(tree);
5683 
5684         // Check for cycles among annotation elements.
5685         chk.checkNonCyclicElements(tree);
5686 
5687         // Check for proper use of serialVersionUID and other
5688         // serialization-related fields and methods
5689         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5690                 && rs.isSerializable(c.type)
5691                 && !c.isAnonymous()) {
5692             chk.checkSerialStructure(env, tree, c);
5693         }
5694         // Correctly organize the positions of the type annotations
5695         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5696 
5697         // Check type annotations applicability rules
5698         validateTypeAnnotations(tree, false);
5699     }
5700         // where
5701         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5702         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5703             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5704                 if (types.isSameType(al.head.annotationType.type, t))
5705                     return al.head.pos();
5706             }
5707 
5708             return null;
5709         }
5710 
5711     private Type capture(Type type) {
5712         return types.capture(type);
5713     }
5714 
5715     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
5716         if (type.isErroneous()) {
5717             tree.vartype = make.at(Position.NOPOS).Erroneous();
5718         } else {
5719             tree.vartype = make.at(Position.NOPOS).Type(type);
5720         }
5721     }
5722 
5723     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
5724         tree.accept(new TypeAnnotationsValidator(sigOnly));
5725     }
5726     //where
5727     private final class TypeAnnotationsValidator extends TreeScanner {
5728 
5729         private final boolean sigOnly;
5730         public TypeAnnotationsValidator(boolean sigOnly) {
5731             this.sigOnly = sigOnly;
5732         }
5733 
5734         public void visitAnnotation(JCAnnotation tree) {
5735             chk.validateTypeAnnotation(tree, null, false);
5736             super.visitAnnotation(tree);
5737         }
5738         public void visitAnnotatedType(JCAnnotatedType tree) {
5739             if (!tree.underlyingType.type.isErroneous()) {
5740                 super.visitAnnotatedType(tree);
5741             }
5742         }
5743         public void visitTypeParameter(JCTypeParameter tree) {
5744             chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
5745             scan(tree.bounds);
5746             // Don't call super.
5747             // This is needed because above we call validateTypeAnnotation with
5748             // false, which would forbid annotations on type parameters.
5749             // super.visitTypeParameter(tree);
5750         }
5751         public void visitMethodDef(JCMethodDecl tree) {
5752             if (tree.recvparam != null &&
5753                     !tree.recvparam.vartype.type.isErroneous()) {
5754                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
5755             }
5756             if (tree.restype != null && tree.restype.type != null) {
5757                 validateAnnotatedType(tree.restype, tree.restype.type);
5758             }
5759             if (sigOnly) {
5760                 scan(tree.mods);
5761                 scan(tree.restype);
5762                 scan(tree.typarams);
5763                 scan(tree.recvparam);
5764                 scan(tree.params);
5765                 scan(tree.thrown);
5766             } else {
5767                 scan(tree.defaultValue);
5768                 scan(tree.body);
5769             }
5770         }
5771         public void visitVarDef(final JCVariableDecl tree) {
5772             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
5773             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
5774                 validateAnnotatedType(tree.vartype, tree.sym.type);
5775             scan(tree.mods);
5776             scan(tree.vartype);
5777             if (!sigOnly) {
5778                 scan(tree.init);
5779             }
5780         }
5781         public void visitTypeCast(JCTypeCast tree) {
5782             if (tree.clazz != null && tree.clazz.type != null)
5783                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5784             super.visitTypeCast(tree);
5785         }
5786         public void visitTypeTest(JCInstanceOf tree) {
5787             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
5788                 validateAnnotatedType(tree.pattern, tree.pattern.type);
5789             super.visitTypeTest(tree);
5790         }
5791         public void visitNewClass(JCNewClass tree) {
5792             if (tree.clazz != null && tree.clazz.type != null) {
5793                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5794                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5795                             tree.clazz.type.tsym);
5796                 }
5797                 if (tree.def != null) {
5798                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5799                 }
5800 
5801                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5802             }
5803             super.visitNewClass(tree);
5804         }
5805         public void visitNewArray(JCNewArray tree) {
5806             if (tree.elemtype != null && tree.elemtype.type != null) {
5807                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5808                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5809                             tree.elemtype.type.tsym);
5810                 }
5811                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5812             }
5813             super.visitNewArray(tree);
5814         }
5815         public void visitClassDef(JCClassDecl tree) {
5816             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5817             if (sigOnly) {
5818                 scan(tree.mods);
5819                 scan(tree.typarams);
5820                 scan(tree.extending);
5821                 scan(tree.implementing);
5822             }
5823             for (JCTree member : tree.defs) {
5824                 if (member.hasTag(Tag.CLASSDEF)) {
5825                     continue;
5826                 }
5827                 scan(member);
5828             }
5829         }
5830         public void visitBlock(JCBlock tree) {
5831             if (!sigOnly) {
5832                 scan(tree.stats);
5833             }
5834         }
5835 
5836         /* I would want to model this after
5837          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5838          * and override visitSelect and visitTypeApply.
5839          * However, we only set the annotated type in the top-level type
5840          * of the symbol.
5841          * Therefore, we need to override each individual location where a type
5842          * can occur.
5843          */
5844         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5845             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5846 
5847             if (type.isPrimitiveOrVoid()) {
5848                 return;
5849             }
5850 
5851             JCTree enclTr = errtree;
5852             Type enclTy = type;
5853 
5854             boolean repeat = true;
5855             while (repeat) {
5856                 if (enclTr.hasTag(TYPEAPPLY)) {
5857                     List<Type> tyargs = enclTy.getTypeArguments();
5858                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5859                     if (trargs.length() > 0) {
5860                         // Nothing to do for diamonds
5861                         if (tyargs.length() == trargs.length()) {
5862                             for (int i = 0; i < tyargs.length(); ++i) {
5863                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5864                             }
5865                         }
5866                         // If the lengths don't match, it's either a diamond
5867                         // or some nested type that redundantly provides
5868                         // type arguments in the tree.
5869                     }
5870 
5871                     // Look at the clazz part of a generic type
5872                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5873                 }
5874 
5875                 if (enclTr.hasTag(SELECT)) {
5876                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5877                     if (enclTy != null &&
5878                             !enclTy.hasTag(NONE)) {
5879                         enclTy = enclTy.getEnclosingType();
5880                     }
5881                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5882                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5883                     if (enclTy == null || enclTy.hasTag(NONE)) {
5884                         ListBuffer<Attribute.TypeCompound> onlyTypeAnnotationsBuf = new ListBuffer<>();
5885                         for (JCAnnotation an : at.getAnnotations()) {
5886                             if (chk.isTypeAnnotation(an, false)) {
5887                                 onlyTypeAnnotationsBuf.add((Attribute.TypeCompound) an.attribute);
5888                             }
5889                         }
5890                         List<Attribute.TypeCompound> onlyTypeAnnotations = onlyTypeAnnotationsBuf.toList();
5891                         if (!onlyTypeAnnotations.isEmpty()) {
5892                             Fragment annotationFragment = onlyTypeAnnotations.size() == 1 ?
5893                                     Fragments.TypeAnnotation1(onlyTypeAnnotations.head) :
5894                                     Fragments.TypeAnnotation(onlyTypeAnnotations);
5895                             JCDiagnostic.AnnotatedType annotatedType = new JCDiagnostic.AnnotatedType(
5896                                     type.stripMetadata().annotatedType(onlyTypeAnnotations));
5897                             log.error(at.underlyingType.pos(), Errors.TypeAnnotationInadmissible(annotationFragment,
5898                                     type.tsym.owner, annotatedType));
5899                         }
5900                         repeat = false;
5901                     }
5902                     enclTr = at.underlyingType;
5903                     // enclTy doesn't need to be changed
5904                 } else if (enclTr.hasTag(IDENT)) {
5905                     repeat = false;
5906                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5907                     JCWildcard wc = (JCWildcard) enclTr;
5908                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5909                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5910                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5911                     } else {
5912                         // Nothing to do for UNBOUND
5913                     }
5914                     repeat = false;
5915                 } else if (enclTr.hasTag(TYPEARRAY)) {
5916                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5917                     validateAnnotatedType(art.getType(), art.elemtype.type);
5918                     repeat = false;
5919                 } else if (enclTr.hasTag(TYPEUNION)) {
5920                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5921                     for (JCTree t : ut.getTypeAlternatives()) {
5922                         validateAnnotatedType(t, t.type);
5923                     }
5924                     repeat = false;
5925                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5926                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5927                     for (JCTree t : it.getBounds()) {
5928                         validateAnnotatedType(t, t.type);
5929                     }
5930                     repeat = false;
5931                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5932                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5933                     repeat = false;
5934                 } else {
5935                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5936                             " within: "+ errtree + " with kind: " + errtree.getKind());
5937                 }
5938             }
5939         }
5940 
5941         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5942                 Symbol sym) {
5943             // Ensure that no declaration annotations are present.
5944             // Note that a tree type might be an AnnotatedType with
5945             // empty annotations, if only declaration annotations were given.
5946             // This method will raise an error for such a type.
5947             for (JCAnnotation ai : annotations) {
5948                 if (!ai.type.isErroneous() &&
5949                         typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5950                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5951                 }
5952             }
5953         }
5954     }
5955 
5956     // <editor-fold desc="post-attribution visitor">
5957 
5958     /**
5959      * Handle missing types/symbols in an AST. This routine is useful when
5960      * the compiler has encountered some errors (which might have ended up
5961      * terminating attribution abruptly); if the compiler is used in fail-over
5962      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5963      * prevents NPE to be propagated during subsequent compilation steps.
5964      */
5965     public void postAttr(JCTree tree) {
5966         new PostAttrAnalyzer().scan(tree);
5967     }
5968 
5969     class PostAttrAnalyzer extends TreeScanner {
5970 
5971         private void initTypeIfNeeded(JCTree that) {
5972             if (that.type == null) {
5973                 if (that.hasTag(METHODDEF)) {
5974                     that.type = dummyMethodType((JCMethodDecl)that);
5975                 } else {
5976                     that.type = syms.unknownType;
5977                 }
5978             }
5979         }
5980 
5981         /* Construct a dummy method type. If we have a method declaration,
5982          * and the declared return type is void, then use that return type
5983          * instead of UNKNOWN to avoid spurious error messages in lambda
5984          * bodies (see:JDK-8041704).
5985          */
5986         private Type dummyMethodType(JCMethodDecl md) {
5987             Type restype = syms.unknownType;
5988             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5989                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5990                 if (prim.typetag == VOID)
5991                     restype = syms.voidType;
5992             }
5993             return new MethodType(List.nil(), restype,
5994                                   List.nil(), syms.methodClass);
5995         }
5996         private Type dummyMethodType() {
5997             return dummyMethodType(null);
5998         }
5999 
6000         @Override
6001         public void scan(JCTree tree) {
6002             if (tree == null) return;
6003             if (tree instanceof JCExpression) {
6004                 initTypeIfNeeded(tree);
6005             }
6006             super.scan(tree);
6007         }
6008 
6009         @Override
6010         public void visitIdent(JCIdent that) {
6011             if (that.sym == null) {
6012                 that.sym = syms.unknownSymbol;
6013             }
6014         }
6015 
6016         @Override
6017         public void visitSelect(JCFieldAccess that) {
6018             if (that.sym == null) {
6019                 that.sym = syms.unknownSymbol;
6020             }
6021             super.visitSelect(that);
6022         }
6023 
6024         @Override
6025         public void visitClassDef(JCClassDecl that) {
6026             initTypeIfNeeded(that);
6027             if (that.sym == null) {
6028                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6029             }
6030             super.visitClassDef(that);
6031         }
6032 
6033         @Override
6034         public void visitMethodDef(JCMethodDecl that) {
6035             initTypeIfNeeded(that);
6036             if (that.sym == null) {
6037                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6038             }
6039             super.visitMethodDef(that);
6040         }
6041 
6042         @Override
6043         public void visitVarDef(JCVariableDecl that) {
6044             initTypeIfNeeded(that);
6045             if (that.sym == null) {
6046                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6047                 that.sym.adr = 0;
6048             }
6049             if (that.vartype == null) {
6050                 that.vartype = make.at(Position.NOPOS).Erroneous();
6051             }
6052             super.visitVarDef(that);
6053         }
6054 
6055         @Override
6056         public void visitBindingPattern(JCBindingPattern that) {
6057             initTypeIfNeeded(that);
6058             initTypeIfNeeded(that.var);
6059             if (that.var.sym == null) {
6060                 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6061                 that.var.sym.adr = 0;
6062             }
6063             super.visitBindingPattern(that);
6064         }
6065 
6066         @Override
6067         public void visitRecordPattern(JCRecordPattern that) {
6068             initTypeIfNeeded(that);
6069             if (that.record == null) {
6070                 that.record = new ClassSymbol(0, TreeInfo.name(that.deconstructor),
6071                                               that.type, syms.noSymbol);
6072             }
6073             if (that.fullComponentTypes == null) {
6074                 that.fullComponentTypes = List.nil();
6075             }
6076             super.visitRecordPattern(that);
6077         }
6078 
6079         @Override
6080         public void visitNewClass(JCNewClass that) {
6081             if (that.constructor == null) {
6082                 that.constructor = new MethodSymbol(0, names.init,
6083                         dummyMethodType(), syms.noSymbol);
6084             }
6085             if (that.constructorType == null) {
6086                 that.constructorType = syms.unknownType;
6087             }
6088             super.visitNewClass(that);
6089         }
6090 
6091         @Override
6092         public void visitAssignop(JCAssignOp that) {
6093             if (that.operator == null) {
6094                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6095                         -1, syms.noSymbol);
6096             }
6097             super.visitAssignop(that);
6098         }
6099 
6100         @Override
6101         public void visitBinary(JCBinary that) {
6102             if (that.operator == null) {
6103                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6104                         -1, syms.noSymbol);
6105             }
6106             super.visitBinary(that);
6107         }
6108 
6109         @Override
6110         public void visitUnary(JCUnary that) {
6111             if (that.operator == null) {
6112                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6113                         -1, syms.noSymbol);
6114             }
6115             super.visitUnary(that);
6116         }
6117 
6118         @Override
6119         public void visitReference(JCMemberReference that) {
6120             super.visitReference(that);
6121             if (that.sym == null) {
6122                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6123                         syms.noSymbol);
6124             }
6125         }
6126     }
6127     // </editor-fold>
6128 
6129     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6130         new TreeScanner() {
6131             Symbol packge = pkg;
6132             @Override
6133             public void visitIdent(JCIdent that) {
6134                 that.sym = packge;
6135             }
6136 
6137             @Override
6138             public void visitSelect(JCFieldAccess that) {
6139                 that.sym = packge;
6140                 packge = packge.owner;
6141                 super.visitSelect(that);
6142             }
6143         }.scan(pid);
6144     }
6145 
6146 }