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