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