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.WrongNumberArgsInLambda(currentTarget.tsym)));
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, currentTarget.tsym, 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, TypeSymbol target, 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(argTypes.size() != tree.params.size()
3571                         ? Fragments.WrongNumberArgsInLambda(target)
3572                         : Fragments.IncompatibleArgTypesInLambda(argTypes, TreeInfo.types(tree.params))));
3573             }
3574         }
3575 
3576         /* This method returns an environment to be used to attribute a lambda
3577          * expression.
3578          *
3579          * The owner of this environment is a method symbol. If the current owner
3580          * is not a method (e.g. if the lambda occurs in a field initializer), then
3581          * a synthetic method symbol owner is created.
3582          */
3583         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3584             Env<AttrContext> lambdaEnv;
3585             Symbol owner = env.info.scope.owner;
3586             if (owner.kind == VAR && owner.owner.kind == TYP) {
3587                 // If the lambda is nested in a field initializer, we need to create a fake init method.
3588                 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3589                 // init symbol's owner).
3590                 ClassSymbol enclClass = owner.enclClass();
3591                 Name initName = owner.isStatic() ? names.clinit : names.init;
3592                 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3593                         initName, initBlockType, enclClass);
3594                 initSym.params = List.nil();
3595                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3596             } else {
3597                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3598             }
3599             lambdaEnv.info.yieldResult = null;
3600             lambdaEnv.info.isLambda = true;
3601             return lambdaEnv;
3602         }
3603 
3604     @Override
3605     public void visitReference(final JCMemberReference that) {
3606         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3607             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3608                 //method reference only allowed in assignment or method invocation/cast context
3609                 log.error(that.pos(), Errors.UnexpectedMref);
3610             }
3611             result = that.type = types.createErrorType(pt());
3612             return;
3613         }
3614         final Env<AttrContext> localEnv = env.dup(that);
3615         try {
3616             //attribute member reference qualifier - if this is a constructor
3617             //reference, the expected kind must be a type
3618             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3619 
3620             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3621                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3622                 if (!exprType.isErroneous() &&
3623                     exprType.isRaw() &&
3624                     that.typeargs != null) {
3625                     log.error(that.expr.pos(),
3626                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3627                                                  Fragments.MrefInferAndExplicitParams));
3628                     exprType = types.createErrorType(exprType);
3629                 }
3630             }
3631 
3632             if (exprType.isErroneous()) {
3633                 //if the qualifier expression contains problems,
3634                 //give up attribution of method reference
3635                 result = that.type = exprType;
3636                 return;
3637             }
3638 
3639             if (TreeInfo.isStaticSelector(that.expr, names)) {
3640                 //if the qualifier is a type, validate it; raw warning check is
3641                 //omitted as we don't know at this stage as to whether this is a
3642                 //raw selector (because of inference)
3643                 chk.validate(that.expr, env, false);
3644             } else {
3645                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3646                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3647             }
3648             //attrib type-arguments
3649             List<Type> typeargtypes = List.nil();
3650             if (that.typeargs != null) {
3651                 typeargtypes = attribTypes(that.typeargs, localEnv);
3652             }
3653 
3654             boolean isTargetSerializable =
3655                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3656                     rs.isSerializable(pt());
3657             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3658             Type currentTarget = targetInfo.target;
3659             Type desc = targetInfo.descriptor;
3660 
3661             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3662             List<Type> argtypes = desc.getParameterTypes();
3663             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3664 
3665             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3666                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3667             }
3668 
3669             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3670             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3671             try {
3672                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3673                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3674                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3675             } finally {
3676                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3677             }
3678 
3679             Symbol refSym = refResult.fst;
3680             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3681 
3682             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3683              *  JDK-8075541
3684              */
3685             if (refSym.kind != MTH) {
3686                 boolean targetError;
3687                 switch (refSym.kind) {
3688                     case ABSENT_MTH:
3689                         targetError = false;
3690                         break;
3691                     case WRONG_MTH:
3692                     case WRONG_MTHS:
3693                     case AMBIGUOUS:
3694                     case HIDDEN:
3695                     case STATICERR:
3696                         targetError = true;
3697                         break;
3698                     default:
3699                         Assert.error("unexpected result kind " + refSym.kind);
3700                         targetError = false;
3701                 }
3702 
3703                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3704                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3705                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3706 
3707                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3708                         targetError ?
3709                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3710                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3711 
3712                 if (targetError && currentTarget == Type.recoveryType) {
3713                     //a target error doesn't make sense during recovery stage
3714                     //as we don't know what actual parameter types are
3715                     result = that.type = currentTarget;
3716                     return;
3717                 } else {
3718                     if (targetError) {
3719                         resultInfo.checkContext.report(that, diag);
3720                     } else {
3721                         log.report(diag);
3722                     }
3723                     result = that.type = types.createErrorType(currentTarget);
3724                     return;
3725                 }
3726             }
3727 
3728             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3729             that.kind = lookupHelper.referenceKind(that.sym);
3730             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3731 
3732             if (desc.getReturnType() == Type.recoveryType) {
3733                 // stop here
3734                 result = that.type = currentTarget;
3735                 return;
3736             }
3737 
3738             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3739                 checkNewInnerClass(that.pos(), env, exprType, false);
3740             }
3741 
3742             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3743 
3744                 if (that.getMode() == ReferenceMode.INVOKE &&
3745                         TreeInfo.isStaticSelector(that.expr, names) &&
3746                         that.kind.isUnbound() &&
3747                         lookupHelper.site.isRaw()) {
3748                     chk.checkRaw(that.expr, localEnv);
3749                 }
3750 
3751                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3752                         exprType.getTypeArguments().nonEmpty()) {
3753                     //static ref with class type-args
3754                     log.error(that.expr.pos(),
3755                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3756                                                  Fragments.StaticMrefWithTargs));
3757                     result = that.type = types.createErrorType(currentTarget);
3758                     return;
3759                 }
3760 
3761                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3762                     // Check that super-qualified symbols are not abstract (JLS)
3763                     rs.checkNonAbstract(that.pos(), that.sym);
3764                 }
3765 
3766                 if (isTargetSerializable) {
3767                     chk.checkAccessFromSerializableElement(that, true);
3768                 }
3769             }
3770 
3771             ResultInfo checkInfo =
3772                     resultInfo.dup(newMethodTemplate(
3773                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3774                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3775                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3776 
3777             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3778 
3779             if (that.kind.isUnbound() &&
3780                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3781                 //re-generate inference constraints for unbound receiver
3782                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3783                     //cannot happen as this has already been checked - we just need
3784                     //to regenerate the inference constraints, as that has been lost
3785                     //as a result of the call to inferenceContext.save()
3786                     Assert.error("Can't get here");
3787                 }
3788             }
3789 
3790             if (!refType.isErroneous()) {
3791                 refType = types.createMethodTypeWithReturn(refType,
3792                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3793             }
3794 
3795             //go ahead with standard method reference compatibility check - note that param check
3796             //is a no-op (as this has been taken care during method applicability)
3797             boolean isSpeculativeRound =
3798                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3799 
3800             that.type = currentTarget; //avoids recovery at this stage
3801             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3802             if (!isSpeculativeRound) {
3803                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3804             }
3805             chk.checkRequiresIdentity(that, localEnv.info.lint);
3806             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3807         } catch (Types.FunctionDescriptorLookupError ex) {
3808             JCDiagnostic cause = ex.getDiagnostic();
3809             resultInfo.checkContext.report(that, cause);
3810             result = that.type = types.createErrorType(pt());
3811             return;
3812         }
3813     }
3814     //where
3815         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3816             //if this is a constructor reference, the expected kind must be a type
3817             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3818                                   KindSelector.VAL_TYP : KindSelector.TYP,
3819                                   Type.noType);
3820         }
3821 
3822 
3823     @SuppressWarnings("fallthrough")
3824     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3825         InferenceContext inferenceContext = checkContext.inferenceContext();
3826         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3827 
3828         Type resType;
3829         switch (tree.getMode()) {
3830             case NEW:
3831                 if (!tree.expr.type.isRaw()) {
3832                     resType = tree.expr.type;
3833                     break;
3834                 }
3835             default:
3836                 resType = refType.getReturnType();
3837         }
3838 
3839         Type incompatibleReturnType = resType;
3840 
3841         if (returnType.hasTag(VOID)) {
3842             incompatibleReturnType = null;
3843         }
3844 
3845         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3846             Type capturedResType = captureMRefReturnType ? types.capture(resType) : resType;
3847             if (resType.isErroneous() ||
3848                     new FunctionalReturnContext(checkContext).compatible(capturedResType, returnType,
3849                             checkContext.checkWarner(tree, capturedResType, returnType))) {
3850                 incompatibleReturnType = null;
3851             }
3852         }
3853 
3854         if (incompatibleReturnType != null) {
3855             Fragment msg =
3856                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3857             checkContext.report(tree, diags.fragment(msg));
3858         } else {
3859             if (inferenceContext.free(refType)) {
3860                 // we need to wait for inference to finish and then replace inference vars in the referent type
3861                 inferenceContext.addFreeTypeListener(List.of(refType),
3862                         instantiatedContext -> {
3863                             tree.referentType = instantiatedContext.asInstType(refType);
3864                         });
3865             } else {
3866                 tree.referentType = refType;
3867             }
3868         }
3869 
3870         if (!speculativeAttr) {
3871             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3872                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3873             }
3874         }
3875     }
3876 
3877     boolean checkExConstraints(
3878             List<Type> thrownByFuncExpr,
3879             List<Type> thrownAtFuncType,
3880             InferenceContext inferenceContext) {
3881         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3882          *  are not proper types
3883          */
3884         List<Type> nonProperList = thrownAtFuncType.stream()
3885                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3886         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3887 
3888         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3889          *  in the throws clause of the invocation type of the method reference's compile-time
3890          *  declaration
3891          */
3892         List<Type> checkedList = thrownByFuncExpr.stream()
3893                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3894 
3895         /** If n = 0 (the function type's throws clause consists only of proper types), then
3896          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3897          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3898          *  reduces to true
3899          */
3900         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3901         for (Type checked : checkedList) {
3902             boolean isSubtype = false;
3903             for (Type proper : properList) {
3904                 if (types.isSubtype(checked, proper)) {
3905                     isSubtype = true;
3906                     break;
3907                 }
3908             }
3909             if (!isSubtype) {
3910                 uncaughtByProperTypes.add(checked);
3911             }
3912         }
3913 
3914         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3915             return false;
3916         }
3917 
3918         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3919          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3920          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3921          */
3922         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3923         uncaughtByProperTypes.forEach(checkedEx -> {
3924             nonProperAsUndet.forEach(nonProper -> {
3925                 types.isSubtype(checkedEx, nonProper);
3926             });
3927         });
3928 
3929         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3930          */
3931         nonProperAsUndet.stream()
3932                 .filter(t -> t.hasTag(UNDETVAR))
3933                 .forEach(t -> ((UndetVar)t).setThrow());
3934         return true;
3935     }
3936 
3937     /**
3938      * Set functional type info on the underlying AST. Note: as the target descriptor
3939      * might contain inference variables, we might need to register an hook in the
3940      * current inference context.
3941      */
3942     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3943             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3944         if (checkContext.inferenceContext().free(descriptorType)) {
3945             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3946                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3947                     inferenceContext.asInstType(primaryTarget), checkContext));
3948         } else {
3949             fExpr.owner = env.info.scope.owner;
3950             if (pt.hasTag(CLASS)) {
3951                 fExpr.target = primaryTarget;
3952             }
3953             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3954                     pt != Type.recoveryType) {
3955                 //check that functional interface class is well-formed
3956                 try {
3957                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3958                      * when it's executed post-inference. See the listener code
3959                      * above.
3960                      */
3961                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3962                             names.empty, fExpr.target, ABSTRACT);
3963                     if (csym != null) {
3964                         chk.checkImplementations(env.tree, csym, csym);
3965                         try {
3966                             //perform an additional functional interface check on the synthetic class,
3967                             //as there may be spurious errors for raw targets - because of existing issues
3968                             //with membership and inheritance (see JDK-8074570).
3969                             csym.flags_field |= INTERFACE;
3970                             types.findDescriptorType(csym.type);
3971                         } catch (FunctionDescriptorLookupError err) {
3972                             resultInfo.checkContext.report(fExpr,
3973                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3974                         }
3975                     }
3976                 } catch (Types.FunctionDescriptorLookupError ex) {
3977                     JCDiagnostic cause = ex.getDiagnostic();
3978                     resultInfo.checkContext.report(env.tree, cause);
3979                 }
3980             }
3981         }
3982     }
3983 
3984     public void visitParens(JCParens tree) {
3985         Type owntype = attribTree(tree.expr, env, resultInfo);
3986         result = check(tree, owntype, pkind(), resultInfo);
3987         Symbol sym = TreeInfo.symbol(tree);
3988         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
3989             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3990     }
3991 
3992     public void visitAssign(JCAssign tree) {
3993         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3994         Type capturedType = capture(owntype);
3995         attribExpr(tree.rhs, env, owntype);
3996         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3997     }
3998 
3999     public void visitAssignop(JCAssignOp tree) {
4000         // Attribute arguments.
4001         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
4002         Type operand = attribExpr(tree.rhs, env);
4003         // Find operator.
4004         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
4005         if (operator != operators.noOpSymbol &&
4006                 !owntype.isErroneous() &&
4007                 !operand.isErroneous()) {
4008             chk.checkDivZero(tree.rhs.pos(), operator, operand);
4009             chk.checkCastable(tree.rhs.pos(),
4010                               operator.type.getReturnType(),
4011                               owntype);
4012             switch (tree.getTag()) {
4013             case SL_ASG, SR_ASG, USR_ASG -> { }     // we only use (at most) the lower 6 bits, so any integral type is OK
4014             default -> chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4015             }
4016             chk.checkOutOfRangeShift(tree.rhs.pos(), operator, operand);
4017         }
4018         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4019     }
4020 
4021     public void visitUnary(JCUnary tree) {
4022         // Attribute arguments.
4023         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4024             ? attribTree(tree.arg, env, varAssignmentInfo)
4025             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4026 
4027         // Find operator.
4028         OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4029         Type owntype = types.createErrorType(tree.type);
4030         if (operator != operators.noOpSymbol &&
4031                 !argtype.isErroneous()) {
4032             owntype = (tree.getTag().isIncOrDecUnaryOp())
4033                 ? tree.arg.type
4034                 : operator.type.getReturnType();
4035             int opc = operator.opcode;
4036 
4037             // If the argument is constant, fold it.
4038             if (argtype.constValue() != null) {
4039                 Type ctype = cfolder.fold1(opc, argtype);
4040                 if (ctype != null) {
4041                     owntype = cfolder.coerce(ctype, owntype);
4042                 }
4043             }
4044         }
4045         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4046         matchBindings = matchBindingsComputer.unary(tree, matchBindings);
4047     }
4048 
4049     public void visitBinary(JCBinary tree) {
4050         // Attribute arguments.
4051         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
4052         // x && y
4053         // include x's bindings when true in y
4054 
4055         // x || y
4056         // include x's bindings when false in y
4057 
4058         MatchBindings lhsBindings = matchBindings;
4059         List<BindingSymbol> propagatedBindings;
4060         switch (tree.getTag()) {
4061             case AND:
4062                 propagatedBindings = lhsBindings.bindingsWhenTrue;
4063                 break;
4064             case OR:
4065                 propagatedBindings = lhsBindings.bindingsWhenFalse;
4066                 break;
4067             default:
4068                 propagatedBindings = List.nil();
4069                 break;
4070         }
4071         Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings);
4072         Type right;
4073         try {
4074             right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
4075         } finally {
4076             rhsEnv.info.scope.leave();
4077         }
4078 
4079         matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings);
4080 
4081         // Find operator.
4082         OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
4083         Type owntype = types.createErrorType(tree.type);
4084         if (operator != operators.noOpSymbol &&
4085                 !left.isErroneous() &&
4086                 !right.isErroneous()) {
4087             owntype = operator.type.getReturnType();
4088             int opc = operator.opcode;
4089             // If both arguments are constants, fold them.
4090             if (left.constValue() != null && right.constValue() != null) {
4091                 Type ctype = cfolder.fold2(opc, left, right);
4092                 if (ctype != null) {
4093                     owntype = cfolder.coerce(ctype, owntype);
4094                 }
4095             }
4096 
4097             // Check that argument types of a reference ==, != are
4098             // castable to each other, (JLS 15.21).  Note: unboxing
4099             // comparisons will not have an acmp* opc at this point.
4100             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4101                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4102                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4103                 }
4104             }
4105 
4106             chk.checkDivZero(tree.rhs.pos(), operator, right);
4107             chk.checkOutOfRangeShift(tree.rhs.pos(), operator, right);
4108         }
4109         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4110     }
4111 
4112     public void visitTypeCast(final JCTypeCast tree) {
4113         Type clazztype = attribType(tree.clazz, env);
4114         chk.validate(tree.clazz, env, false);
4115         chk.checkRequiresIdentity(tree, env.info.lint);
4116         //a fresh environment is required for 292 inference to work properly ---
4117         //see Infer.instantiatePolymorphicSignatureInstance()
4118         Env<AttrContext> localEnv = env.dup(tree);
4119         //should we propagate the target type?
4120         final ResultInfo castInfo;
4121         JCExpression expr = TreeInfo.skipParens(tree.expr);
4122         boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4123         if (isPoly) {
4124             //expression is a poly - we need to propagate target type info
4125             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
4126                                       new Check.NestedCheckContext(resultInfo.checkContext) {
4127                 @Override
4128                 public boolean compatible(Type found, Type req, Warner warn) {
4129                     return types.isCastable(found, req, warn);
4130                 }
4131             });
4132         } else {
4133             //standalone cast - target-type info is not propagated
4134             castInfo = unknownExprInfo;
4135         }
4136         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
4137         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4138         if (exprtype.constValue() != null)
4139             owntype = cfolder.coerce(exprtype, owntype);
4140         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
4141         if (!isPoly)
4142             chk.checkRedundantCast(localEnv, tree);
4143     }
4144 
4145     public void visitTypeTest(JCInstanceOf tree) {
4146         Type exprtype = attribExpr(tree.expr, env);
4147         if (exprtype.isPrimitive()) {
4148             preview.checkSourceLevel(tree.expr.pos(), Feature.PRIMITIVE_PATTERNS);
4149         } else {
4150             exprtype = chk.checkNullOrRefType(
4151                     tree.expr.pos(), exprtype);
4152         }
4153         Type clazztype;
4154         JCTree typeTree;
4155         if (tree.pattern.getTag() == BINDINGPATTERN ||
4156             tree.pattern.getTag() == RECORDPATTERN) {
4157             attribExpr(tree.pattern, env, exprtype);
4158             clazztype = tree.pattern.type;
4159             if (types.isSubtype(exprtype, clazztype) &&
4160                 !exprtype.isErroneous() && !clazztype.isErroneous() &&
4161                 tree.pattern.getTag() != RECORDPATTERN) {
4162                 if (!allowUnconditionalPatternsInstanceOf) {
4163                     log.error(tree.pos(), Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName));
4164                 }
4165             }
4166             typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern);
4167         } else {
4168             clazztype = attribType(tree.pattern, env);
4169             typeTree = tree.pattern;
4170             chk.validate(typeTree, env, false);
4171         }
4172         if (clazztype.isPrimitive()) {
4173             preview.checkSourceLevel(tree.pattern.pos(), Feature.PRIMITIVE_PATTERNS);
4174         } else {
4175             if (!clazztype.hasTag(TYPEVAR)) {
4176                 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype);
4177             }
4178             if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
4179                 boolean valid = false;
4180                 if (allowReifiableTypesInInstanceof) {
4181                     valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype);
4182                 } else {
4183                     log.error(tree.pos(), Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName));
4184                     allowReifiableTypesInInstanceof = true;
4185                 }
4186                 if (!valid) {
4187                     clazztype = types.createErrorType(clazztype);
4188                 }
4189             }
4190         }
4191         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4192         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
4193     }
4194 
4195     private boolean checkCastablePattern(DiagnosticPosition pos,
4196                                          Type exprType,
4197                                          Type pattType) {
4198         Warner warner = new Warner();
4199         // if any type is erroneous, the problem is reported elsewhere
4200         if (exprType.isErroneous() || pattType.isErroneous()) {
4201             return false;
4202         }
4203         if (!types.isCastable(exprType, pattType, warner)) {
4204             chk.basicHandler.report(pos,
4205                     diags.fragment(Fragments.InconvertibleTypes(exprType, pattType)));
4206             return false;
4207         } else if ((exprType.isPrimitive() || pattType.isPrimitive()) &&
4208                 (!exprType.isPrimitive() || !pattType.isPrimitive() || !types.isSameType(exprType, pattType))) {
4209             preview.checkSourceLevel(pos, Feature.PRIMITIVE_PATTERNS);
4210             return true;
4211         } else if (warner.hasLint(LintCategory.UNCHECKED)) {
4212             log.error(pos,
4213                     Errors.InstanceofReifiableNotSafe(exprType, pattType));
4214             return false;
4215         } else {
4216             return true;
4217         }
4218     }
4219 
4220     @Override
4221     public void visitAnyPattern(JCAnyPattern tree) {
4222         result = tree.type = resultInfo.pt;
4223     }
4224 
4225     public void visitBindingPattern(JCBindingPattern tree) {
4226         Type type;
4227         if (!tree.var.isImplicitlyTyped()) {
4228             type = attribType(tree.var.vartype, env);
4229         } else {
4230             type = resultInfo.pt;
4231         }
4232         BindingSymbol v = new BindingSymbol(tree.var.mods.flags | tree.var.declKind.additionalSymbolFlags,
4233                                             tree.var.name, type, env.info.scope.owner);
4234         v.pos = tree.pos;
4235         tree.var.sym = v;
4236         if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
4237             chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
4238         }
4239         if (tree.var.isImplicitlyTyped()) {
4240             setupImplicitlyTypedVariable(tree.var, type == Type.noType ? syms.errType
4241                                                       : type);
4242         }
4243         chk.validate(tree.var.vartype, env, true);
4244         annotate.annotateLater(tree.var.mods.annotations, env, v);
4245         if (!tree.var.isImplicitlyTyped()) {
4246             annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v);
4247         }
4248         annotate.flush();
4249         typeAnnotations.organizeTypeAnnotationsSignaturesForLocalVarType(env, tree.var);
4250         result = tree.type = tree.var.type = v.type;
4251         if (v.isUnnamedVariable()) {
4252             matchBindings = MatchBindingsComputer.EMPTY;
4253         } else {
4254             matchBindings = new MatchBindings(List.of(v), List.nil());
4255         }
4256         chk.checkRequiresIdentity(tree, env.info.lint);
4257     }
4258 
4259     @Override
4260     public void visitRecordPattern(JCRecordPattern tree) {
4261         Type site;
4262 
4263         if (tree.deconstructor.hasTag(VARTYPE)) {
4264             log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed);
4265             tree.record = syms.errSymbol;
4266             site = tree.type = types.createErrorType(tree.record.type);
4267         } else {
4268             Type type = attribType(tree.deconstructor, env);
4269             if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) {
4270                 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym);
4271                 if (inferred == null) {
4272                     log.error(tree.pos(), Errors.PatternTypeCannotInfer);
4273                 } else {
4274                     type = inferred;
4275                 }
4276             }
4277             tree.type = tree.deconstructor.type = type;
4278             site = types.capture(tree.type);
4279             chk.validate(tree.deconstructor, env, true);
4280         }
4281 
4282         List<Type> expectedRecordTypes;
4283         if (site.tsym instanceof ClassSymbol clazz && clazz.isRecord()) {
4284             ClassSymbol record = (ClassSymbol) site.tsym;
4285             expectedRecordTypes = record.getRecordComponents()
4286                                         .stream()
4287                                         .map(rc -> types.memberType(site, rc))
4288                                         .map(t -> types.upward(t, types.captures(t)).baseType())
4289                                         .collect(List.collector());
4290             tree.record = record;
4291         } else {
4292             log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym));
4293             expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type))
4294                                 .limit(tree.nested.size())
4295                                 .collect(List.collector());
4296             tree.record = syms.errSymbol;
4297         }
4298         ListBuffer<BindingSymbol> outBindings = new ListBuffer<>();
4299         List<Type> recordTypes = expectedRecordTypes;
4300         List<JCPattern> nestedPatterns = tree.nested;
4301         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
4302         try {
4303             while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) {
4304                 attribExpr(nestedPatterns.head, localEnv, recordTypes.head);
4305                 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type);
4306                 outBindings.addAll(matchBindings.bindingsWhenTrue);
4307                 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter);
4308                 nestedPatterns = nestedPatterns.tail;
4309                 recordTypes = recordTypes.tail;
4310             }
4311             if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) {
4312                 while (nestedPatterns.nonEmpty()) {
4313                     attribExpr(nestedPatterns.head, localEnv, Type.noType);
4314                     nestedPatterns = nestedPatterns.tail;
4315                 }
4316                 List<Type> nestedTypes =
4317                         tree.nested.stream().map(p -> p.type).collect(List.collector());
4318                 log.error(tree.pos(),
4319                           Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes,
4320                                                                  nestedTypes));
4321             }
4322         } finally {
4323             localEnv.info.scope.leave();
4324         }
4325         result = tree.type;
4326         matchBindings = new MatchBindings(outBindings.toList(), List.nil());
4327     }
4328 
4329     public void visitIndexed(JCArrayAccess tree) {
4330         Type owntype = types.createErrorType(tree.type);
4331         Type atype = attribExpr(tree.indexed, env);
4332         attribExpr(tree.index, env, syms.intType);
4333         if (types.isArray(atype))
4334             owntype = types.elemtype(atype);
4335         else if (!atype.hasTag(ERROR))
4336             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
4337         if (!pkind().contains(KindSelector.VAL))
4338             owntype = capture(owntype);
4339         result = check(tree, owntype, KindSelector.VAR, resultInfo);
4340     }
4341 
4342     public void visitIdent(JCIdent tree) {
4343         Symbol sym;
4344 
4345         // Find symbol
4346         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
4347             // If we are looking for a method, the prototype `pt' will be a
4348             // method type with the type of the call's arguments as parameters.
4349             env.info.pendingResolutionPhase = null;
4350             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
4351         } else if (tree.sym != null && tree.sym.kind != VAR) {
4352             sym = tree.sym;
4353         } else {
4354             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
4355         }
4356         tree.sym = sym;
4357 
4358         // Also find the environment current for the class where
4359         // sym is defined (`symEnv').
4360         Env<AttrContext> symEnv = env;
4361         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
4362             sym.kind.matches(KindSelector.VAL_MTH) &&
4363             sym.owner.kind == TYP &&
4364             tree.name != names._this && tree.name != names._super) {
4365 
4366             // Find environment in which identifier is defined.
4367             while (symEnv.outer != null &&
4368                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
4369                 symEnv = symEnv.outer;
4370             }
4371         }
4372 
4373         // If symbol is a variable, ...
4374         if (sym.kind == VAR) {
4375             VarSymbol v = (VarSymbol)sym;
4376 
4377             // ..., evaluate its initializer, if it has one, and check for
4378             // illegal forward reference.
4379             checkInit(tree, env, v, false);
4380 
4381             // If we are expecting a variable (as opposed to a value), check
4382             // that the variable is assignable in the current environment.
4383             if (KindSelector.ASG.subset(pkind()))
4384                 checkAssignable(tree.pos(), v, null, env);
4385         }
4386 
4387         Env<AttrContext> env1 = env;
4388         if (sym.kind != ERR && sym.kind != TYP &&
4389             sym.owner != null && sym.owner != env1.enclClass.sym) {
4390             // If the found symbol is inaccessible, then it is
4391             // accessed through an enclosing instance.  Locate this
4392             // enclosing instance:
4393             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4394                 env1 = env1.outer;
4395         }
4396 
4397         if (env.info.isSerializable) {
4398             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4399         }
4400 
4401         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4402     }
4403 
4404     public void visitSelect(JCFieldAccess tree) {
4405         // Determine the expected kind of the qualifier expression.
4406         KindSelector skind = KindSelector.NIL;
4407         if (tree.name == names._this || tree.name == names._super ||
4408                 tree.name == names._class)
4409         {
4410             skind = KindSelector.TYP;
4411         } else {
4412             if (pkind().contains(KindSelector.PCK))
4413                 skind = KindSelector.of(skind, KindSelector.PCK);
4414             if (pkind().contains(KindSelector.TYP))
4415                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4416             if (pkind().contains(KindSelector.VAL_MTH))
4417                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4418         }
4419 
4420         // Attribute the qualifier expression, and determine its symbol (if any).
4421         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4422         if (!pkind().contains(KindSelector.TYP_PCK))
4423             site = capture(site); // Capture field access
4424 
4425         // don't allow T.class T[].class, etc
4426         if (skind == KindSelector.TYP) {
4427             Type elt = site;
4428             while (elt.hasTag(ARRAY))
4429                 elt = ((ArrayType)elt).elemtype;
4430             if (elt.hasTag(TYPEVAR)) {
4431                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4432                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4433                 tree.sym = tree.type.tsym;
4434                 return ;
4435             }
4436         }
4437 
4438         // If qualifier symbol is a type or `super', assert `selectSuper'
4439         // for the selection. This is relevant for determining whether
4440         // protected symbols are accessible.
4441         Symbol sitesym = TreeInfo.symbol(tree.selected);
4442         boolean selectSuperPrev = env.info.selectSuper;
4443         env.info.selectSuper =
4444             sitesym != null &&
4445             sitesym.name == names._super;
4446 
4447         // Determine the symbol represented by the selection.
4448         env.info.pendingResolutionPhase = null;
4449         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4450         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4451             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4452             sym = syms.errSymbol;
4453         }
4454         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4455             site = capture(site);
4456             sym = selectSym(tree, sitesym, site, env, resultInfo);
4457         }
4458         boolean varArgs = env.info.lastResolveVarargs();
4459         tree.sym = sym;
4460 
4461         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4462             site = types.skipTypeVars(site, true);
4463         }
4464 
4465         // If that symbol is a variable, ...
4466         if (sym.kind == VAR) {
4467             VarSymbol v = (VarSymbol)sym;
4468 
4469             // ..., evaluate its initializer, if it has one, and check for
4470             // illegal forward reference.
4471             checkInit(tree, env, v, true);
4472 
4473             // If we are expecting a variable (as opposed to a value), check
4474             // that the variable is assignable in the current environment.
4475             if (KindSelector.ASG.subset(pkind()))
4476                 checkAssignable(tree.pos(), v, tree.selected, env);
4477         }
4478 
4479         if (sitesym != null &&
4480                 sitesym.kind == VAR &&
4481                 ((VarSymbol)sitesym).isResourceVariable() &&
4482                 sym.kind == MTH &&
4483                 sym.name.equals(names.close) &&
4484                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
4485             log.warning(tree, LintWarnings.TryExplicitCloseCall);
4486         }
4487 
4488         // Disallow selecting a type from an expression
4489         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4490             tree.type = check(tree.selected, pt(),
4491                               sitesym == null ?
4492                                       KindSelector.VAL : sitesym.kind.toSelector(),
4493                               new ResultInfo(KindSelector.TYP_PCK, pt()));
4494         }
4495 
4496         if (isType(sitesym)) {
4497             if (sym.name != names._this && sym.name != names._super) {
4498                 // Check if type-qualified fields or methods are static (JLS)
4499                 if ((sym.flags() & STATIC) == 0 &&
4500                     sym.name != names._super &&
4501                     (sym.kind == VAR || sym.kind == MTH)) {
4502                     rs.accessBase(rs.new StaticError(sym),
4503                               tree.pos(), site, sym.name, true);
4504                 }
4505             }
4506         } else if (sym.kind != ERR &&
4507                    (sym.flags() & STATIC) != 0 &&
4508                    sym.name != names._class) {
4509             // If the qualified item is not a type and the selected item is static, report
4510             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4511             if (!sym.owner.isAnonymous()) {
4512                 log.warning(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4513             } else {
4514                 log.warning(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4515             }
4516         }
4517 
4518         // If we are selecting an instance member via a `super', ...
4519         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4520 
4521             // Check that super-qualified symbols are not abstract (JLS)
4522             rs.checkNonAbstract(tree.pos(), sym);
4523 
4524             if (site.isRaw()) {
4525                 // Determine argument types for site.
4526                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4527                 if (site1 != null) site = site1;
4528             }
4529         }
4530 
4531         if (env.info.isSerializable) {
4532             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4533         }
4534 
4535         env.info.selectSuper = selectSuperPrev;
4536         result = checkId(tree, site, sym, env, resultInfo);
4537     }
4538     //where
4539         /** Determine symbol referenced by a Select expression,
4540          *
4541          *  @param tree   The select tree.
4542          *  @param site   The type of the selected expression,
4543          *  @param env    The current environment.
4544          *  @param resultInfo The current result.
4545          */
4546         private Symbol selectSym(JCFieldAccess tree,
4547                                  Symbol location,
4548                                  Type site,
4549                                  Env<AttrContext> env,
4550                                  ResultInfo resultInfo) {
4551             DiagnosticPosition pos = tree.pos();
4552             Name name = tree.name;
4553             switch (site.getTag()) {
4554             case PACKAGE:
4555                 return rs.accessBase(
4556                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4557                     pos, location, site, name, true);
4558             case ARRAY:
4559             case CLASS:
4560                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4561                     return rs.resolveQualifiedMethod(
4562                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4563                 } else if (name == names._this || name == names._super) {
4564                     return rs.resolveSelf(pos, env, site.tsym, tree);
4565                 } else if (name == names._class) {
4566                     // In this case, we have already made sure in
4567                     // visitSelect that qualifier expression is a type.
4568                     return syms.getClassField(site, types);
4569                 } else {
4570                     // We are seeing a plain identifier as selector.
4571                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4572                         sym = rs.accessBase(sym, pos, location, site, name, true);
4573                     return sym;
4574                 }
4575             case WILDCARD:
4576                 throw new AssertionError(tree);
4577             case TYPEVAR:
4578                 // Normally, site.getUpperBound() shouldn't be null.
4579                 // It should only happen during memberEnter/attribBase
4580                 // when determining the supertype which *must* be
4581                 // done before attributing the type variables.  In
4582                 // other words, we are seeing this illegal program:
4583                 // class B<T> extends A<T.foo> {}
4584                 Symbol sym = (site.getUpperBound() != null)
4585                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4586                     : null;
4587                 if (sym == null) {
4588                     log.error(pos, Errors.TypeVarCantBeDeref);
4589                     return syms.errSymbol;
4590                 } else {
4591                     // JLS 4.9 specifies the members are derived by inheritance.
4592                     // We skip inducing a whole class by filtering members that
4593                     // can never be inherited:
4594                     Symbol sym2;
4595                     if (sym.isPrivate()) {
4596                         // Private members
4597                         sym2 = rs.new AccessError(env, site, sym);
4598                     } else if (sym.owner.isInterface() && sym.kind == MTH && (sym.flags() & STATIC) != 0) {
4599                         // Interface static methods
4600                         sym2 = rs.new SymbolNotFoundError(ABSENT_MTH);
4601                     } else {
4602                         sym2 = sym;
4603                     }
4604                     rs.accessBase(sym2, pos, location, site, name, true);
4605                     return sym;
4606                 }
4607             case ERROR:
4608                 // preserve identifier names through errors
4609                 return types.createErrorType(name, site.tsym, site).tsym;
4610             default:
4611                 // The qualifier expression is of a primitive type -- only
4612                 // .class is allowed for these.
4613                 if (name == names._class) {
4614                     // In this case, we have already made sure in Select that
4615                     // qualifier expression is a type.
4616                     return syms.getClassField(site, types);
4617                 } else {
4618                     log.error(pos, Errors.CantDeref(site));
4619                     return syms.errSymbol;
4620                 }
4621             }
4622         }
4623 
4624         /** Determine type of identifier or select expression and check that
4625          *  (1) the referenced symbol is not deprecated
4626          *  (2) the symbol's type is safe (@see checkSafe)
4627          *  (3) if symbol is a variable, check that its type and kind are
4628          *      compatible with the prototype and protokind.
4629          *  (4) if symbol is an instance field of a raw type,
4630          *      which is being assigned to, issue an unchecked warning if its
4631          *      type changes under erasure.
4632          *  (5) if symbol is an instance method of a raw type, issue an
4633          *      unchecked warning if its argument types change under erasure.
4634          *  If checks succeed:
4635          *    If symbol is a constant, return its constant type
4636          *    else if symbol is a method, return its result type
4637          *    otherwise return its type.
4638          *  Otherwise return errType.
4639          *
4640          *  @param tree       The syntax tree representing the identifier
4641          *  @param site       If this is a select, the type of the selected
4642          *                    expression, otherwise the type of the current class.
4643          *  @param sym        The symbol representing the identifier.
4644          *  @param env        The current environment.
4645          *  @param resultInfo    The expected result
4646          */
4647         Type checkId(JCTree tree,
4648                      Type site,
4649                      Symbol sym,
4650                      Env<AttrContext> env,
4651                      ResultInfo resultInfo) {
4652             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
4653                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
4654                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4655         }
4656 
4657         Type checkMethodIdInternal(JCTree tree,
4658                      Type site,
4659                      Symbol sym,
4660                      Env<AttrContext> env,
4661                      ResultInfo resultInfo) {
4662             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4663                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4664             } else {
4665                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4666             }
4667         }
4668 
4669         Type checkIdInternal(JCTree tree,
4670                      Type site,
4671                      Symbol sym,
4672                      Type pt,
4673                      Env<AttrContext> env,
4674                      ResultInfo resultInfo) {
4675             Type owntype; // The computed type of this identifier occurrence.
4676             switch (sym.kind) {
4677             case TYP:
4678                 // For types, the computed type equals the symbol's type,
4679                 // except for two situations:
4680                 owntype = sym.type;
4681                 if (owntype.hasTag(CLASS)) {
4682                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4683                     Type ownOuter = owntype.getEnclosingType();
4684 
4685                     // (a) If the symbol's type is parameterized, erase it
4686                     // because no type parameters were given.
4687                     // We recover generic outer type later in visitTypeApply.
4688                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4689                         owntype = types.erasure(owntype);
4690                     }
4691 
4692                     // (b) If the symbol's type is an inner class, then
4693                     // we have to interpret its outer type as a superclass
4694                     // of the site type. Example:
4695                     //
4696                     // class Tree<A> { class Visitor { ... } }
4697                     // class PointTree extends Tree<Point> { ... }
4698                     // ...PointTree.Visitor...
4699                     //
4700                     // Then the type of the last expression above is
4701                     // Tree<Point>.Visitor.
4702                     else if ((ownOuter.hasTag(CLASS) || ownOuter.hasTag(TYPEVAR)) && site != ownOuter) {
4703                         Type normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4704                         if (normOuter == null) // perhaps from an import
4705                             normOuter = types.erasure(ownOuter);
4706                         if (normOuter != ownOuter)
4707                             owntype = new ClassType(
4708                                 normOuter, List.nil(), owntype.tsym,
4709                                 owntype.getMetadata());
4710                     }
4711                 }
4712                 break;
4713             case VAR:
4714                 VarSymbol v = (VarSymbol)sym;
4715 
4716                 if (env.info.enclVar != null
4717                         && v.type.hasTag(NONE)) {
4718                     //self reference to implicitly typed variable declaration
4719                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4720                     return tree.type = v.type = types.createErrorType(v.type);
4721                 }
4722 
4723                 // Test (4): if symbol is an instance field of a raw type,
4724                 // which is being assigned to, issue an unchecked warning if
4725                 // its type changes under erasure.
4726                 if (KindSelector.ASG.subset(pkind()) &&
4727                     v.owner.kind == TYP &&
4728                     (v.flags() & STATIC) == 0 &&
4729                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4730                     Type s = types.asOuterSuper(site, v.owner);
4731                     if (s != null &&
4732                         s.isRaw() &&
4733                         !types.isSameType(v.type, v.erasure(types))) {
4734                         chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
4735                     }
4736                 }
4737                 // The computed type of a variable is the type of the
4738                 // variable symbol, taken as a member of the site type.
4739                 owntype = (sym.owner.kind == TYP &&
4740                            sym.name != names._this && sym.name != names._super)
4741                     ? types.memberType(site, sym)
4742                     : sym.type;
4743 
4744                 // If the variable is a constant, record constant value in
4745                 // computed type.
4746                 if (v.getConstValue() != null && isStaticReference(tree))
4747                     owntype = owntype.constType(v.getConstValue());
4748 
4749                 if (resultInfo.pkind == KindSelector.VAL) {
4750                     owntype = capture(owntype); // capture "names as expressions"
4751                 }
4752                 break;
4753             case MTH: {
4754                 owntype = checkMethod(site, sym,
4755                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4756                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4757                         resultInfo.pt.getTypeArguments());
4758                 chk.checkRestricted(tree.pos(), sym);
4759                 break;
4760             }
4761             case PCK: case ERR:
4762                 owntype = sym.type;
4763                 break;
4764             default:
4765                 throw new AssertionError("unexpected kind: " + sym.kind +
4766                                          " in tree " + tree);
4767             }
4768 
4769             // Emit a `deprecation' warning if symbol is deprecated.
4770             // (for constructors (but not for constructor references), the error
4771             // was given when the constructor was resolved)
4772 
4773             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4774                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4775                 chk.checkSunAPI(tree.pos(), sym);
4776                 chk.checkProfile(tree.pos(), sym);
4777                 chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym);
4778             }
4779 
4780             if (pt.isErroneous()) {
4781                 owntype = types.createErrorType(owntype);
4782             }
4783 
4784             // If symbol is a variable, check that its type and
4785             // kind are compatible with the prototype and protokind.
4786             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4787         }
4788 
4789         /** Check that variable is initialized and evaluate the variable's
4790          *  initializer, if not yet done. Also check that variable is not
4791          *  referenced before it is defined.
4792          *  @param tree    The tree making up the variable reference.
4793          *  @param env     The current environment.
4794          *  @param v       The variable's symbol.
4795          */
4796         private void checkInit(JCTree tree,
4797                                Env<AttrContext> env,
4798                                VarSymbol v,
4799                                boolean onlyWarning) {
4800             // A forward reference is diagnosed if the declaration position
4801             // of the variable is greater than the current tree position
4802             // and the tree and variable definition occur in the same class
4803             // definition.  Note that writes don't count as references.
4804             // This check applies only to class and instance
4805             // variables.  Local variables follow different scope rules,
4806             // and are subject to definite assignment checking.
4807             Env<AttrContext> initEnv = enclosingInitEnv(env);
4808             if (initEnv != null &&
4809                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4810                 v.owner.kind == TYP &&
4811                 v.owner == env.info.scope.owner.enclClass() &&
4812                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4813                 (!env.tree.hasTag(ASSIGN) ||
4814                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4815                 if (!onlyWarning || isStaticEnumField(v)) {
4816                     Error errkey = (initEnv.info.enclVar == v) ?
4817                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4818                     log.error(tree.pos(), errkey);
4819                 } else if (useBeforeDeclarationWarning) {
4820                     Warning warnkey = (initEnv.info.enclVar == v) ?
4821                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4822                     log.warning(tree.pos(), warnkey);
4823                 }
4824             }
4825 
4826             v.getConstValue(); // ensure initializer is evaluated
4827 
4828             checkEnumInitializer(tree, env, v);
4829         }
4830 
4831         /**
4832          * Returns the enclosing init environment associated with this env (if any). An init env
4833          * can be either a field declaration env or a static/instance initializer env.
4834          */
4835         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4836             while (true) {
4837                 switch (env.tree.getTag()) {
4838                     case VARDEF:
4839                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4840                         if (vdecl.sym.owner.kind == TYP) {
4841                             //field
4842                             return env;
4843                         }
4844                         break;
4845                     case BLOCK:
4846                         if (env.next.tree.hasTag(CLASSDEF)) {
4847                             //instance/static initializer
4848                             return env;
4849                         }
4850                         break;
4851                     case METHODDEF:
4852                     case CLASSDEF:
4853                     case TOPLEVEL:
4854                         return null;
4855                 }
4856                 Assert.checkNonNull(env.next);
4857                 env = env.next;
4858             }
4859         }
4860 
4861         /**
4862          * Check for illegal references to static members of enum.  In
4863          * an enum type, constructors and initializers may not
4864          * reference its static members unless they are constant.
4865          *
4866          * @param tree    The tree making up the variable reference.
4867          * @param env     The current environment.
4868          * @param v       The variable's symbol.
4869          * @jls 8.9 Enum Types
4870          */
4871         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4872             // JLS:
4873             //
4874             // "It is a compile-time error to reference a static field
4875             // of an enum type that is not a compile-time constant
4876             // (15.28) from constructors, instance initializer blocks,
4877             // or instance variable initializer expressions of that
4878             // type. It is a compile-time error for the constructors,
4879             // instance initializer blocks, or instance variable
4880             // initializer expressions of an enum constant e to refer
4881             // to itself or to an enum constant of the same type that
4882             // is declared to the right of e."
4883             if (isStaticEnumField(v)) {
4884                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4885 
4886                 if (enclClass == null || enclClass.owner == null)
4887                     return;
4888 
4889                 // See if the enclosing class is the enum (or a
4890                 // subclass thereof) declaring v.  If not, this
4891                 // reference is OK.
4892                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4893                     return;
4894 
4895                 // If the reference isn't from an initializer, then
4896                 // the reference is OK.
4897                 if (!Resolve.isInitializer(env))
4898                     return;
4899 
4900                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4901             }
4902         }
4903 
4904         /** Is the given symbol a static, non-constant field of an Enum?
4905          *  Note: enum literals should not be regarded as such
4906          */
4907         private boolean isStaticEnumField(VarSymbol v) {
4908             return Flags.isEnum(v.owner) &&
4909                    Flags.isStatic(v) &&
4910                    !Flags.isConstant(v) &&
4911                    v.name != names._class;
4912         }
4913 
4914     /**
4915      * Check that method arguments conform to its instantiation.
4916      **/
4917     public Type checkMethod(Type site,
4918                             final Symbol sym,
4919                             ResultInfo resultInfo,
4920                             Env<AttrContext> env,
4921                             final List<JCExpression> argtrees,
4922                             List<Type> argtypes,
4923                             List<Type> typeargtypes) {
4924         // Test (5): if symbol is an instance method of a raw type, issue
4925         // an unchecked warning if its argument types change under erasure.
4926         if ((sym.flags() & STATIC) == 0 &&
4927             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4928             Type s = types.asOuterSuper(site, sym.owner);
4929             if (s != null && s.isRaw() &&
4930                 !types.isSameTypes(sym.type.getParameterTypes(),
4931                                    sym.erasure(types).getParameterTypes())) {
4932                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
4933             }
4934         }
4935 
4936         if (env.info.defaultSuperCallSite != null) {
4937             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4938                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4939                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4940                 List<MethodSymbol> icand_sup =
4941                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4942                 if (icand_sup.nonEmpty() &&
4943                         icand_sup.head != sym &&
4944                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4945                     log.error(env.tree.pos(),
4946                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4947                     break;
4948                 }
4949             }
4950             env.info.defaultSuperCallSite = null;
4951         }
4952 
4953         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4954             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4955             if (app.meth.hasTag(SELECT) &&
4956                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4957                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4958             }
4959         }
4960 
4961         // Compute the identifier's instantiated type.
4962         // For methods, we need to compute the instance type by
4963         // Resolve.instantiate from the symbol's type as well as
4964         // any type arguments and value arguments.
4965         Warner noteWarner = new Warner();
4966         try {
4967             Type owntype = rs.checkMethod(
4968                     env,
4969                     site,
4970                     sym,
4971                     resultInfo,
4972                     argtypes,
4973                     typeargtypes,
4974                     noteWarner);
4975 
4976             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4977                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4978 
4979             argtypes = argtypes.map(checkDeferredMap);
4980 
4981             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4982                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
4983                         sym.name,
4984                         rs.methodArguments(sym.type.getParameterTypes()),
4985                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4986                         kindName(sym.location()),
4987                         sym.location()));
4988                 if (resultInfo.pt != Infer.anyPoly ||
4989                         !owntype.hasTag(METHOD) ||
4990                         !owntype.isPartial()) {
4991                     //if this is not a partially inferred method type, erase return type. Otherwise,
4992                     //erasure is carried out in PartiallyInferredMethodType.check().
4993                     owntype = new MethodType(owntype.getParameterTypes(),
4994                             types.erasure(owntype.getReturnType()),
4995                             types.erasure(owntype.getThrownTypes()),
4996                             syms.methodClass);
4997                 }
4998             }
4999 
5000             PolyKind pkind = (sym.type.hasTag(FORALL) &&
5001                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
5002                  PolyKind.POLY : PolyKind.STANDALONE;
5003             TreeInfo.setPolyKind(env.tree, pkind);
5004 
5005             return (resultInfo.pt == Infer.anyPoly) ?
5006                     owntype :
5007                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
5008                             resultInfo.checkContext.inferenceContext());
5009         } catch (Infer.InferenceException ex) {
5010             //invalid target type - propagate exception outwards or report error
5011             //depending on the current check context
5012             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5013             return types.createErrorType(site);
5014         } catch (Resolve.InapplicableMethodException ex) {
5015             final JCDiagnostic diag = ex.getDiagnostic();
5016             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5017                 @Override
5018                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5019                     return new Pair<>(sym, diag);
5020                 }
5021             };
5022             List<Type> argtypes2 = argtypes.map(
5023                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5024             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5025                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5026             log.report(errDiag);
5027             return types.createErrorType(site);
5028         }
5029     }
5030 
5031     public void visitLiteral(JCLiteral tree) {
5032         result = check(tree, litType(tree.typetag).constType(tree.value),
5033                 KindSelector.VAL, resultInfo);
5034     }
5035     //where
5036     /** Return the type of a literal with given type tag.
5037      */
5038     Type litType(TypeTag tag) {
5039         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5040     }
5041 
5042     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5043         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5044     }
5045 
5046     public void visitTypeArray(JCArrayTypeTree tree) {
5047         Type etype = attribType(tree.elemtype, env);
5048         Type type = new ArrayType(etype, syms.arrayClass);
5049         result = check(tree, type, KindSelector.TYP, resultInfo);
5050     }
5051 
5052     /** Visitor method for parameterized types.
5053      *  Bound checking is left until later, since types are attributed
5054      *  before supertype structure is completely known
5055      */
5056     public void visitTypeApply(JCTypeApply tree) {
5057         Type owntype = types.createErrorType(tree.type);
5058 
5059         // Attribute functor part of application and make sure it's a class.
5060         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5061 
5062         // Attribute type parameters
5063         List<Type> actuals = attribTypes(tree.arguments, env);
5064 
5065         if (clazztype.hasTag(CLASS)) {
5066             List<Type> formals = clazztype.tsym.type.getTypeArguments();
5067             if (actuals.isEmpty()) //diamond
5068                 actuals = formals;
5069 
5070             if (actuals.length() == formals.length()) {
5071                 List<Type> a = actuals;
5072                 List<Type> f = formals;
5073                 while (a.nonEmpty()) {
5074                     a.head = a.head.withTypeVar(f.head);
5075                     a = a.tail;
5076                     f = f.tail;
5077                 }
5078                 // Compute the proper generic outer
5079                 Type clazzOuter = clazztype.getEnclosingType();
5080                 if (clazzOuter.hasTag(CLASS)) {
5081                     Type site;
5082                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5083                     if (clazz.hasTag(IDENT)) {
5084                         site = env.enclClass.sym.type;
5085                     } else if (clazz.hasTag(SELECT)) {
5086                         site = ((JCFieldAccess) clazz).selected.type;
5087                     } else throw new AssertionError(""+tree);
5088                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5089                         if (site.hasTag(CLASS) || site.hasTag(TYPEVAR))
5090                             site = types.asEnclosingSuper(site, clazzOuter.tsym);
5091                         if (site == null)
5092                             site = types.erasure(clazzOuter);
5093                         clazzOuter = site;
5094                     }
5095                 }
5096                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5097                                         clazztype.getMetadata());
5098             } else {
5099                 if (formals.length() != 0) {
5100                     log.error(tree.pos(),
5101                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5102                 } else {
5103                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5104                 }
5105                 owntype = types.createErrorType(tree.type);
5106             }
5107         } else if (clazztype.hasTag(ERROR)) {
5108             ErrorType parameterizedErroneous =
5109                     new ErrorType(clazztype.getOriginalType(),
5110                                   clazztype.tsym,
5111                                   clazztype.getMetadata());
5112 
5113             parameterizedErroneous.typarams_field = actuals;
5114             owntype = parameterizedErroneous;
5115         }
5116         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5117     }
5118 
5119     public void visitTypeUnion(JCTypeUnion tree) {
5120         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5121         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5122         for (JCExpression typeTree : tree.alternatives) {
5123             Type ctype = attribType(typeTree, env);
5124             ctype = chk.checkType(typeTree.pos(),
5125                           chk.checkClassType(typeTree.pos(), ctype),
5126                           syms.throwableType);
5127             if (!ctype.isErroneous()) {
5128                 //check that alternatives of a union type are pairwise
5129                 //unrelated w.r.t. subtyping
5130                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
5131                     for (Type t : multicatchTypes) {
5132                         boolean sub = types.isSubtype(ctype, t);
5133                         boolean sup = types.isSubtype(t, ctype);
5134                         if (sub || sup) {
5135                             //assume 'a' <: 'b'
5136                             Type a = sub ? ctype : t;
5137                             Type b = sub ? t : ctype;
5138                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5139                         }
5140                     }
5141                 }
5142                 multicatchTypes.append(ctype);
5143                 if (all_multicatchTypes != null)
5144                     all_multicatchTypes.append(ctype);
5145             } else {
5146                 if (all_multicatchTypes == null) {
5147                     all_multicatchTypes = new ListBuffer<>();
5148                     all_multicatchTypes.appendList(multicatchTypes);
5149                 }
5150                 all_multicatchTypes.append(ctype);
5151             }
5152         }
5153         Type t = check(tree, types.lub(multicatchTypes.toList()),
5154                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5155         if (t.hasTag(CLASS)) {
5156             List<Type> alternatives =
5157                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5158             t = new UnionClassType((ClassType) t, alternatives);
5159         }
5160         tree.type = result = t;
5161     }
5162 
5163     public void visitTypeIntersection(JCTypeIntersection tree) {
5164         attribTypes(tree.bounds, env);
5165         tree.type = result = checkIntersection(tree, tree.bounds);
5166     }
5167 
5168     public void visitTypeParameter(JCTypeParameter tree) {
5169         TypeVar typeVar = (TypeVar) tree.type;
5170 
5171         if (tree.annotations != null && tree.annotations.nonEmpty()) {
5172             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5173         }
5174 
5175         if (!typeVar.getUpperBound().isErroneous()) {
5176             //fixup type-parameter bound computed in 'attribTypeVariables'
5177             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5178         }
5179     }
5180 
5181     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5182         Set<Symbol> boundSet = new HashSet<>();
5183         if (bounds.nonEmpty()) {
5184             // accept class or interface or typevar as first bound.
5185             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5186             boundSet.add(types.erasure(bounds.head.type).tsym);
5187             if (bounds.head.type.isErroneous()) {
5188                 return bounds.head.type;
5189             }
5190             else if (bounds.head.type.hasTag(TYPEVAR)) {
5191                 // if first bound was a typevar, do not accept further bounds.
5192                 if (bounds.tail.nonEmpty()) {
5193                     log.error(bounds.tail.head.pos(),
5194                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
5195                     return bounds.head.type;
5196                 }
5197             } else {
5198                 // if first bound was a class or interface, accept only interfaces
5199                 // as further bounds.
5200                 for (JCExpression bound : bounds.tail) {
5201                     bound.type = checkBase(bound.type, bound, env, false, true, false);
5202                     if (bound.type.isErroneous()) {
5203                         bounds = List.of(bound);
5204                     }
5205                     else if (bound.type.hasTag(CLASS)) {
5206                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5207                     }
5208                 }
5209             }
5210         }
5211 
5212         if (bounds.length() == 0) {
5213             return syms.objectType;
5214         } else if (bounds.length() == 1) {
5215             return bounds.head.type;
5216         } else {
5217             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5218             // ... the variable's bound is a class type flagged COMPOUND
5219             // (see comment for TypeVar.bound).
5220             // In this case, generate a class tree that represents the
5221             // bound class, ...
5222             JCExpression extending;
5223             List<JCExpression> implementing;
5224             if (!bounds.head.type.isInterface()) {
5225                 extending = bounds.head;
5226                 implementing = bounds.tail;
5227             } else {
5228                 extending = null;
5229                 implementing = bounds;
5230             }
5231             JCClassDecl cd = make.at(tree).ClassDef(
5232                 make.Modifiers(PUBLIC | ABSTRACT),
5233                 names.empty, List.nil(),
5234                 extending, implementing, List.nil());
5235 
5236             ClassSymbol c = (ClassSymbol)owntype.tsym;
5237             Assert.check((c.flags() & COMPOUND) != 0);
5238             cd.sym = c;
5239             c.sourcefile = env.toplevel.sourcefile;
5240 
5241             // ... and attribute the bound class
5242             c.flags_field |= UNATTRIBUTED;
5243             Env<AttrContext> cenv = enter.classEnv(cd, env);
5244             typeEnvs.put(c, cenv);
5245             attribClass(c);
5246             return owntype;
5247         }
5248     }
5249 
5250     public void visitWildcard(JCWildcard tree) {
5251         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5252         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5253             ? syms.objectType
5254             : attribType(tree.inner, env);
5255         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5256                                               tree.kind.kind,
5257                                               syms.boundClass),
5258                 KindSelector.TYP, resultInfo);
5259     }
5260 
5261     public void visitAnnotation(JCAnnotation tree) {
5262         Assert.error("should be handled in annotate");
5263     }
5264 
5265     @Override
5266     public void visitModifiers(JCModifiers tree) {
5267         //error recovery only:
5268         Assert.check(resultInfo.pkind == KindSelector.ERR);
5269 
5270         attribAnnotationTypes(tree.annotations, env);
5271     }
5272 
5273     public void visitAnnotatedType(JCAnnotatedType tree) {
5274         attribAnnotationTypes(tree.annotations, env);
5275         Type underlyingType = attribTree(tree.underlyingType, env, resultInfo);
5276         if (underlyingType.getTag() == PACKAGE) {
5277             result = tree.type = underlyingType;
5278         } else {
5279             Type annotatedType = underlyingType.preannotatedType();
5280 
5281             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5282             result = tree.type = annotatedType;
5283         }
5284     }
5285 
5286     public void visitErroneous(JCErroneous tree) {
5287         if (tree.errs != null) {
5288             WriteableScope newScope = env.info.scope;
5289 
5290             if (env.tree instanceof JCClassDecl) {
5291                 Symbol fakeOwner =
5292                     new MethodSymbol(BLOCK, names.empty, null,
5293                         env.info.scope.owner);
5294                 newScope = newScope.dupUnshared(fakeOwner);
5295             }
5296 
5297             Env<AttrContext> errEnv =
5298                     env.dup(env.tree,
5299                             env.info.dup(newScope));
5300             errEnv.info.returnResult = unknownExprInfo;
5301             for (JCTree err : tree.errs)
5302                 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5303         }
5304         result = tree.type = syms.errType;
5305     }
5306 
5307     /** Default visitor method for all other trees.
5308      */
5309     public void visitTree(JCTree tree) {
5310         throw new AssertionError();
5311     }
5312 
5313     /**
5314      * Attribute an env for either a top level tree or class or module declaration.
5315      */
5316     public void attrib(Env<AttrContext> env) {
5317         switch (env.tree.getTag()) {
5318             case MODULEDEF:
5319                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5320                 break;
5321             case PACKAGEDEF:
5322                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5323                 break;
5324             default:
5325                 attribClass(env.tree.pos(), env.enclClass.sym);
5326         }
5327 
5328         annotate.flush();
5329 
5330         // Now that this tree is attributed, we can calculate the Lint configuration everywhere within it
5331         lintMapper.calculateLints(env.toplevel.sourcefile, env.tree);
5332     }
5333 
5334     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5335         try {
5336             annotate.flush();
5337             attribPackage(p);
5338         } catch (CompletionFailure ex) {
5339             chk.completionError(pos, ex);
5340         }
5341     }
5342 
5343     void attribPackage(PackageSymbol p) {
5344         attribWithLint(p,
5345                        env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5346     }
5347 
5348     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5349         try {
5350             annotate.flush();
5351             attribModule(m);
5352         } catch (CompletionFailure ex) {
5353             chk.completionError(pos, ex);
5354         }
5355     }
5356 
5357     void attribModule(ModuleSymbol m) {
5358         attribWithLint(m, env -> attribStat(env.tree, env));
5359     }
5360 
5361     private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5362         Env<AttrContext> env = typeEnvs.get(sym);
5363 
5364         Env<AttrContext> lintEnv = env;
5365         while (lintEnv.info.lint == null)
5366             lintEnv = lintEnv.next;
5367 
5368         Lint lint = lintEnv.info.lint.augment(sym);
5369 
5370         Lint prevLint = chk.setLint(lint);
5371         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5372 
5373         try {
5374             attrib.accept(env);
5375         } finally {
5376             log.useSource(prev);
5377             chk.setLint(prevLint);
5378         }
5379     }
5380 
5381     /** Main method: attribute class definition associated with given class symbol.
5382      *  reporting completion failures at the given position.
5383      *  @param pos The source position at which completion errors are to be
5384      *             reported.
5385      *  @param c   The class symbol whose definition will be attributed.
5386      */
5387     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5388         try {
5389             annotate.flush();
5390             attribClass(c);
5391         } catch (CompletionFailure ex) {
5392             chk.completionError(pos, ex);
5393         }
5394     }
5395 
5396     /** Attribute class definition associated with given class symbol.
5397      *  @param c   The class symbol whose definition will be attributed.
5398      */
5399     void attribClass(ClassSymbol c) throws CompletionFailure {
5400         if (c.type.hasTag(ERROR)) return;
5401 
5402         // Check for cycles in the inheritance graph, which can arise from
5403         // ill-formed class files.
5404         chk.checkNonCyclic(null, c.type);
5405 
5406         Type st = types.supertype(c.type);
5407         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5408             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0 &&
5409             breakTree == null) {
5410             // First, attribute superclass.
5411             if (st.hasTag(CLASS))
5412                 attribClass((ClassSymbol)st.tsym);
5413 
5414             // Next attribute owner, if it is a class.
5415             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5416                 attribClass((ClassSymbol)c.owner);
5417 
5418             c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5419         }
5420 
5421         // The previous operations might have attributed the current class
5422         // if there was a cycle. So we test first whether the class is still
5423         // UNATTRIBUTED.
5424         if ((c.flags_field & UNATTRIBUTED) != 0) {
5425             c.flags_field &= ~UNATTRIBUTED;
5426 
5427             // Get environment current at the point of class definition.
5428             Env<AttrContext> env = typeEnvs.get(c);
5429 
5430             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5431             // because the annotations were not available at the time the env was created. Therefore,
5432             // we look up the environment chain for the first enclosing environment for which the
5433             // lint value is set. Typically, this is the parent env, but might be further if there
5434             // are any envs created as a result of TypeParameter nodes.
5435             Env<AttrContext> lintEnv = env;
5436             while (lintEnv.info.lint == null)
5437                 lintEnv = lintEnv.next;
5438 
5439             // Having found the enclosing lint value, we can initialize the lint value for this class
5440             env.info.lint = lintEnv.info.lint.augment(c);
5441 
5442             Lint prevLint = chk.setLint(env.info.lint);
5443             JavaFileObject prev = log.useSource(c.sourcefile);
5444             ResultInfo prevReturnRes = env.info.returnResult;
5445 
5446             try {
5447                 if (c.isSealed() &&
5448                         !c.isEnum() &&
5449                         !c.isPermittedExplicit &&
5450                         c.getPermittedSubclasses().isEmpty()) {
5451                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5452                 }
5453 
5454                 if (c.isSealed()) {
5455                     Set<Symbol> permittedTypes = new HashSet<>();
5456                     boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5457                     for (Type subType : c.getPermittedSubclasses()) {
5458                         if (subType.isErroneous()) {
5459                             // the type already caused errors, don't produce more potentially misleading errors
5460                             continue;
5461                         }
5462                         boolean isTypeVar = false;
5463                         if (subType.getTag() == TYPEVAR) {
5464                             isTypeVar = true; //error recovery
5465                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5466                                     Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5467                         }
5468                         if (subType.tsym.isAnonymous() && !c.isEnum()) {
5469                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),  Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5470                         }
5471                         if (permittedTypes.contains(subType.tsym)) {
5472                             DiagnosticPosition pos =
5473                                     env.enclClass.permitting.stream()
5474                                             .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5475                                             .limit(2).collect(List.collector()).get(1);
5476                             log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5477                         } else {
5478                             permittedTypes.add(subType.tsym);
5479                         }
5480                         if (sealedInUnnamed) {
5481                             if (subType.tsym.packge() != c.packge()) {
5482                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5483                                         Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5484                                 );
5485                             }
5486                         } else if (subType.tsym.packge().modle != c.packge().modle) {
5487                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5488                                     Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5489                             );
5490                         }
5491                         if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5492                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5493                                     Errors.InvalidPermitsClause(
5494                                             subType.tsym == c.type.tsym ?
5495                                                     Fragments.MustNotBeSameClass :
5496                                                     Fragments.MustNotBeSupertype(subType)
5497                                     )
5498                             );
5499                         } else if (!isTypeVar) {
5500                             boolean thisIsASuper = types.directSupertypes(subType)
5501                                                         .stream()
5502                                                         .anyMatch(d -> d.tsym == c);
5503                             if (!thisIsASuper) {
5504                                 if(c.isInterface()) {
5505                                     log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5506                                             Errors.InvalidPermitsClause(Fragments.DoesntImplementSealed(kindName(subType.tsym), subType)));
5507                                 } else {
5508                                     log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5509                                             Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5510                                 }
5511                             }
5512                         }
5513                     }
5514                 }
5515 
5516                 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5517                                                       .stream()
5518                                                       .filter(s -> s.tsym.isSealed())
5519                                                       .map(s -> (ClassSymbol) s.tsym)
5520                                                       .collect(List.collector());
5521 
5522                 if (sealedSupers.isEmpty()) {
5523                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5524                         boolean hasErrorSuper = false;
5525 
5526                         hasErrorSuper |= types.directSupertypes(c.type)
5527                                               .stream()
5528                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5529 
5530                         ClassType ct = (ClassType) c.type;
5531 
5532                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5533 
5534                         if (!hasErrorSuper) {
5535                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5536                         }
5537                     }
5538                 } else {
5539                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5540                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5541                     }
5542 
5543                     if (!c.type.isCompound()) {
5544                         for (ClassSymbol supertypeSym : sealedSupers) {
5545                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5546                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5547                             }
5548                         }
5549                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5550                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5551                                     c.isInterface() ?
5552                                             Errors.NonSealedOrSealedExpected :
5553                                             Errors.NonSealedSealedOrFinalExpected);
5554                         }
5555                     }
5556                 }
5557 
5558                 env.info.returnResult = null;
5559                 // java.lang.Enum may not be subclassed by a non-enum
5560                 if (st.tsym == syms.enumSym &&
5561                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5562                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5563 
5564                 // Enums may not be extended by source-level classes
5565                 if (st.tsym != null &&
5566                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5567                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5568                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5569                 }
5570 
5571                 if (rs.isSerializable(c.type)) {
5572                     env.info.isSerializable = true;
5573                 }
5574 
5575                 attribClassBody(env, c);
5576 
5577                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5578                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5579                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5580                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5581 
5582                 if (c.isImplicit()) {
5583                     chk.checkHasMain(env.tree.pos(), c);
5584                 }
5585             } finally {
5586                 env.info.returnResult = prevReturnRes;
5587                 log.useSource(prev);
5588                 chk.setLint(prevLint);
5589             }
5590 
5591         }
5592     }
5593 
5594     public void visitImport(JCImport tree) {
5595         // nothing to do
5596     }
5597 
5598     public void visitModuleDef(JCModuleDecl tree) {
5599         tree.sym.completeUsesProvides();
5600         ModuleSymbol msym = tree.sym;
5601         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5602         Lint prevLint = chk.setLint(lint);
5603         try {
5604             chk.checkModuleName(tree);
5605             chk.checkDeprecatedAnnotation(tree, msym);
5606         } finally {
5607             chk.setLint(prevLint);
5608         }
5609     }
5610 
5611     /** Finish the attribution of a class. */
5612     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5613         JCClassDecl tree = (JCClassDecl)env.tree;
5614         Assert.check(c == tree.sym);
5615 
5616         // Validate type parameters, supertype and interfaces.
5617         attribStats(tree.typarams, env);
5618         if (!c.isAnonymous()) {
5619             //already checked if anonymous
5620             chk.validate(tree.typarams, env);
5621             chk.validate(tree.extending, env);
5622             chk.validate(tree.implementing, env);
5623         }
5624 
5625         chk.checkRequiresIdentity(tree, env.info.lint);
5626 
5627         c.markAbstractIfNeeded(types);
5628 
5629         // If this is a non-abstract class, check that it has no abstract
5630         // methods or unimplemented methods of an implemented interface.
5631         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
5632             chk.checkAllDefined(tree.pos(), c);
5633         }
5634 
5635         if ((c.flags() & ANNOTATION) != 0) {
5636             if (tree.implementing.nonEmpty())
5637                 log.error(tree.implementing.head.pos(),
5638                           Errors.CantExtendIntfAnnotation);
5639             if (tree.typarams.nonEmpty()) {
5640                 log.error(tree.typarams.head.pos(),
5641                           Errors.IntfAnnotationCantHaveTypeParams(c));
5642             }
5643 
5644             // If this annotation type has a @Repeatable, validate
5645             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
5646             // If this annotation type has a @Repeatable, validate
5647             if (repeatable != null) {
5648                 // get diagnostic position for error reporting
5649                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
5650                 Assert.checkNonNull(cbPos);
5651 
5652                 chk.validateRepeatable(c, repeatable, cbPos);
5653             }
5654         } else {
5655             try {
5656                 // Check that all extended classes and interfaces
5657                 // are compatible (i.e. no two define methods with same arguments
5658                 // yet different return types).  (JLS 8.4.8.3)
5659                 chk.checkCompatibleSupertypes(tree.pos(), c.type);
5660                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
5661                 chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
5662             } catch (CompletionFailure cf) {
5663                 chk.completionError(tree.pos(), cf);
5664             }
5665         }
5666 
5667         // Check that class does not import the same parameterized interface
5668         // with two different argument lists.
5669         chk.checkClassBounds(tree.pos(), c.type);
5670 
5671         tree.type = c.type;
5672 
5673         for (List<JCTypeParameter> l = tree.typarams;
5674              l.nonEmpty(); l = l.tail) {
5675              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
5676         }
5677 
5678         // Check that a generic class doesn't extend Throwable
5679         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
5680             log.error(tree.extending.pos(), Errors.GenericThrowable);
5681 
5682         // Check that all methods which implement some
5683         // method conform to the method they implement.
5684         chk.checkImplementations(tree);
5685 
5686         //check that a resource implementing AutoCloseable cannot throw InterruptedException
5687         checkAutoCloseable(env, tree, false);
5688 
5689         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
5690             // Attribute declaration
5691             attribStat(l.head, env);
5692             // Check that declarations in inner classes are not static (JLS 8.1.2)
5693             // Make an exception for static constants.
5694             if (!allowRecords &&
5695                     c.owner.kind != PCK &&
5696                     ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
5697                     (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
5698                 VarSymbol sym = null;
5699                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
5700                 if (sym == null ||
5701                         sym.kind != VAR ||
5702                         sym.getConstValue() == null)
5703                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5704             }
5705         }
5706 
5707         // Check for proper placement of super()/this() calls.
5708         chk.checkSuperInitCalls(tree);
5709 
5710         // Check for cycles among non-initial constructors.
5711         chk.checkCyclicConstructors(tree);
5712 
5713         // Check for cycles among annotation elements.
5714         chk.checkNonCyclicElements(tree);
5715 
5716         // Check for proper use of serialVersionUID and other
5717         // serialization-related fields and methods
5718         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5719                 && rs.isSerializable(c.type)
5720                 && !c.isAnonymous()) {
5721             chk.checkSerialStructure(tree, c);
5722         }
5723         // Correctly organize the positions of the type annotations
5724         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5725 
5726         // Check type annotations applicability rules
5727         validateTypeAnnotations(tree, false);
5728     }
5729         // where
5730         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5731         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5732             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5733                 if (types.isSameType(al.head.annotationType.type, t))
5734                     return al.head.pos();
5735             }
5736 
5737             return null;
5738         }
5739 
5740     private Type capture(Type type) {
5741         return types.capture(type);
5742     }
5743 
5744     private void setupImplicitlyTypedVariable(JCVariableDecl tree, Type type) {
5745         Assert.check(tree.isImplicitlyTyped());
5746 
5747         type.complete();
5748 
5749         if (tree.vartype == null) {
5750             return ;
5751         }
5752 
5753         Assert.check(tree.vartype.hasTag(VARTYPE));
5754 
5755         JCVarType vartype = (JCVarType) tree.vartype;
5756 
5757         vartype.type = type;
5758     }
5759 
5760     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
5761         tree.accept(new TypeAnnotationsValidator(sigOnly));
5762     }
5763     //where
5764     private final class TypeAnnotationsValidator extends TreeScanner {
5765 
5766         private final boolean sigOnly;
5767         public TypeAnnotationsValidator(boolean sigOnly) {
5768             this.sigOnly = sigOnly;
5769         }
5770 
5771         public void visitAnnotation(JCAnnotation tree) {
5772             chk.validateTypeAnnotation(tree, null, false);
5773             super.visitAnnotation(tree);
5774         }
5775         public void visitAnnotatedType(JCAnnotatedType tree) {
5776             if (!tree.underlyingType.type.isErroneous()) {
5777                 super.visitAnnotatedType(tree);
5778             }
5779         }
5780         public void visitTypeParameter(JCTypeParameter tree) {
5781             chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
5782             scan(tree.bounds);
5783             // Don't call super.
5784             // This is needed because above we call validateTypeAnnotation with
5785             // false, which would forbid annotations on type parameters.
5786             // super.visitTypeParameter(tree);
5787         }
5788         public void visitMethodDef(JCMethodDecl tree) {
5789             if (tree.recvparam != null &&
5790                     !tree.recvparam.vartype.type.isErroneous()) {
5791                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
5792             }
5793             if (tree.restype != null && tree.restype.type != null) {
5794                 validateAnnotatedType(tree.restype, tree.restype.type);
5795             }
5796             if (sigOnly) {
5797                 scan(tree.mods);
5798                 scan(tree.restype);
5799                 scan(tree.typarams);
5800                 scan(tree.recvparam);
5801                 scan(tree.params);
5802                 scan(tree.thrown);
5803             } else {
5804                 scan(tree.defaultValue);
5805                 scan(tree.body);
5806             }
5807         }
5808         public void visitVarDef(final JCVariableDecl tree) {
5809             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
5810             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
5811                 validateAnnotatedType(tree.vartype, tree.sym.type);
5812             scan(tree.mods);
5813             scan(tree.vartype);
5814             if (!sigOnly) {
5815                 scan(tree.init);
5816             }
5817         }
5818         public void visitTypeCast(JCTypeCast tree) {
5819             if (tree.clazz != null && tree.clazz.type != null)
5820                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5821             super.visitTypeCast(tree);
5822         }
5823         public void visitTypeTest(JCInstanceOf tree) {
5824             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
5825                 validateAnnotatedType(tree.pattern, tree.pattern.type);
5826             super.visitTypeTest(tree);
5827         }
5828         public void visitNewClass(JCNewClass tree) {
5829             if (tree.clazz != null && tree.clazz.type != null) {
5830                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5831                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5832                             tree.clazz.type.tsym);
5833                 }
5834                 if (tree.def != null) {
5835                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5836                 }
5837 
5838                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5839             }
5840             super.visitNewClass(tree);
5841         }
5842         public void visitNewArray(JCNewArray tree) {
5843             if (tree.elemtype != null && tree.elemtype.type != null) {
5844                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5845                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5846                             tree.elemtype.type.tsym);
5847                 }
5848                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5849             }
5850             super.visitNewArray(tree);
5851         }
5852         public void visitClassDef(JCClassDecl tree) {
5853             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5854             if (sigOnly) {
5855                 scan(tree.mods);
5856                 scan(tree.typarams);
5857                 scan(tree.extending);
5858                 scan(tree.implementing);
5859             }
5860             for (JCTree member : tree.defs) {
5861                 if (member.hasTag(Tag.CLASSDEF)) {
5862                     continue;
5863                 }
5864                 scan(member);
5865             }
5866         }
5867         public void visitBlock(JCBlock tree) {
5868             if (!sigOnly) {
5869                 scan(tree.stats);
5870             }
5871         }
5872 
5873         /* I would want to model this after
5874          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5875          * and override visitSelect and visitTypeApply.
5876          * However, we only set the annotated type in the top-level type
5877          * of the symbol.
5878          * Therefore, we need to override each individual location where a type
5879          * can occur.
5880          */
5881         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5882             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5883 
5884             if (type.isPrimitiveOrVoid()) {
5885                 return;
5886             }
5887 
5888             JCTree enclTr = errtree;
5889             Type enclTy = type;
5890 
5891             boolean repeat = true;
5892             while (repeat) {
5893                 if (enclTr.hasTag(TYPEAPPLY)) {
5894                     List<Type> tyargs = enclTy.getTypeArguments();
5895                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5896                     if (trargs.length() > 0) {
5897                         // Nothing to do for diamonds
5898                         if (tyargs.length() == trargs.length()) {
5899                             for (int i = 0; i < tyargs.length(); ++i) {
5900                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5901                             }
5902                         }
5903                         // If the lengths don't match, it's either a diamond
5904                         // or some nested type that redundantly provides
5905                         // type arguments in the tree.
5906                     }
5907 
5908                     // Look at the clazz part of a generic type
5909                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5910                 }
5911 
5912                 if (enclTr.hasTag(SELECT)) {
5913                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5914                     if (enclTy != null &&
5915                             !enclTy.hasTag(NONE)) {
5916                         enclTy = enclTy.getEnclosingType();
5917                     }
5918                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5919                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5920                     if (enclTy == null || enclTy.hasTag(NONE)) {
5921                         ListBuffer<Attribute.TypeCompound> onlyTypeAnnotationsBuf = new ListBuffer<>();
5922                         for (JCAnnotation an : at.getAnnotations()) {
5923                             if (chk.isTypeAnnotation(an, false)) {
5924                                 onlyTypeAnnotationsBuf.add((Attribute.TypeCompound) an.attribute);
5925                             }
5926                         }
5927                         List<Attribute.TypeCompound> onlyTypeAnnotations = onlyTypeAnnotationsBuf.toList();
5928                         if (!onlyTypeAnnotations.isEmpty()) {
5929                             Fragment annotationFragment = onlyTypeAnnotations.size() == 1 ?
5930                                     Fragments.TypeAnnotation1(onlyTypeAnnotations.head) :
5931                                     Fragments.TypeAnnotation(onlyTypeAnnotations);
5932                             JCDiagnostic.AnnotatedType annotatedType = new JCDiagnostic.AnnotatedType(
5933                                     type.stripMetadata().annotatedType(onlyTypeAnnotations));
5934                             log.error(at.underlyingType.pos(), Errors.TypeAnnotationInadmissible(annotationFragment,
5935                                     type.tsym.owner, annotatedType));
5936                         }
5937                         repeat = false;
5938                     }
5939                     enclTr = at.underlyingType;
5940                     // enclTy doesn't need to be changed
5941                 } else if (enclTr.hasTag(IDENT)) {
5942                     repeat = false;
5943                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5944                     JCWildcard wc = (JCWildcard) enclTr;
5945                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5946                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5947                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5948                     } else {
5949                         // Nothing to do for UNBOUND
5950                     }
5951                     repeat = false;
5952                 } else if (enclTr.hasTag(TYPEARRAY)) {
5953                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5954                     validateAnnotatedType(art.getType(), art.elemtype.type);
5955                     repeat = false;
5956                 } else if (enclTr.hasTag(TYPEUNION)) {
5957                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5958                     for (JCTree t : ut.getTypeAlternatives()) {
5959                         validateAnnotatedType(t, t.type);
5960                     }
5961                     repeat = false;
5962                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5963                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5964                     for (JCTree t : it.getBounds()) {
5965                         validateAnnotatedType(t, t.type);
5966                     }
5967                     repeat = false;
5968                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5969                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5970                     repeat = false;
5971                 } else {
5972                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5973                             " within: "+ errtree + " with kind: " + errtree.getKind());
5974                 }
5975             }
5976         }
5977 
5978         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5979                 Symbol sym) {
5980             // Ensure that no declaration annotations are present.
5981             // Note that a tree type might be an AnnotatedType with
5982             // empty annotations, if only declaration annotations were given.
5983             // This method will raise an error for such a type.
5984             for (JCAnnotation ai : annotations) {
5985                 if (!ai.type.isErroneous() &&
5986                         typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5987                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5988                 }
5989             }
5990         }
5991     }
5992 
5993     // <editor-fold desc="post-attribution visitor">
5994 
5995     /**
5996      * Handle missing types/symbols in an AST. This routine is useful when
5997      * the compiler has encountered some errors (which might have ended up
5998      * terminating attribution abruptly); if the compiler is used in fail-over
5999      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
6000      * prevents NPE to be propagated during subsequent compilation steps.
6001      */
6002     public void postAttr(JCTree tree) {
6003         new PostAttrAnalyzer().scan(tree);
6004     }
6005 
6006     class PostAttrAnalyzer extends TreeScanner {
6007 
6008         private void initTypeIfNeeded(JCTree that) {
6009             if (that.type == null) {
6010                 if (that.hasTag(METHODDEF)) {
6011                     that.type = dummyMethodType((JCMethodDecl)that);
6012                 } else {
6013                     that.type = syms.unknownType;
6014                 }
6015             }
6016         }
6017 
6018         /* Construct a dummy method type. If we have a method declaration,
6019          * and the declared return type is void, then use that return type
6020          * instead of UNKNOWN to avoid spurious error messages in lambda
6021          * bodies (see:JDK-8041704).
6022          */
6023         private Type dummyMethodType(JCMethodDecl md) {
6024             Type restype = syms.unknownType;
6025             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
6026                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
6027                 if (prim.typetag == VOID)
6028                     restype = syms.voidType;
6029             }
6030             return new MethodType(List.nil(), restype,
6031                                   List.nil(), syms.methodClass);
6032         }
6033         private Type dummyMethodType() {
6034             return dummyMethodType(null);
6035         }
6036 
6037         @Override
6038         public void scan(JCTree tree) {
6039             if (tree == null) return;
6040             if (tree instanceof JCExpression) {
6041                 initTypeIfNeeded(tree);
6042             }
6043             super.scan(tree);
6044         }
6045 
6046         @Override
6047         public void visitIdent(JCIdent that) {
6048             if (that.sym == null) {
6049                 that.sym = syms.unknownSymbol;
6050             }
6051         }
6052 
6053         @Override
6054         public void visitSelect(JCFieldAccess that) {
6055             if (that.sym == null) {
6056                 that.sym = syms.unknownSymbol;
6057             }
6058             super.visitSelect(that);
6059         }
6060 
6061         @Override
6062         public void visitClassDef(JCClassDecl that) {
6063             initTypeIfNeeded(that);
6064             if (that.sym == null) {
6065                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6066             }
6067             super.visitClassDef(that);
6068         }
6069 
6070         @Override
6071         public void visitMethodDef(JCMethodDecl that) {
6072             initTypeIfNeeded(that);
6073             if (that.sym == null) {
6074                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6075             }
6076             super.visitMethodDef(that);
6077         }
6078 
6079         @Override
6080         public void visitVarDef(JCVariableDecl that) {
6081             initTypeIfNeeded(that);
6082             if (that.sym == null) {
6083                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6084                 that.sym.adr = 0;
6085             }
6086             super.visitVarDef(that);
6087         }
6088 
6089         @Override
6090         public void visitBindingPattern(JCBindingPattern that) {
6091             initTypeIfNeeded(that);
6092             initTypeIfNeeded(that.var);
6093             if (that.var.sym == null) {
6094                 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6095                 that.var.sym.adr = 0;
6096             }
6097             super.visitBindingPattern(that);
6098         }
6099 
6100         @Override
6101         public void visitRecordPattern(JCRecordPattern that) {
6102             initTypeIfNeeded(that);
6103             if (that.record == null) {
6104                 that.record = new ClassSymbol(0, TreeInfo.name(that.deconstructor),
6105                                               that.type, syms.noSymbol);
6106             }
6107             if (that.fullComponentTypes == null) {
6108                 that.fullComponentTypes = List.nil();
6109             }
6110             super.visitRecordPattern(that);
6111         }
6112 
6113         @Override
6114         public void visitNewClass(JCNewClass that) {
6115             if (that.constructor == null) {
6116                 that.constructor = new MethodSymbol(0, names.init,
6117                         dummyMethodType(), syms.noSymbol);
6118             }
6119             if (that.constructorType == null) {
6120                 that.constructorType = syms.unknownType;
6121             }
6122             super.visitNewClass(that);
6123         }
6124 
6125         @Override
6126         public void visitAssignop(JCAssignOp that) {
6127             if (that.operator == null) {
6128                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6129                         -1, syms.noSymbol);
6130             }
6131             super.visitAssignop(that);
6132         }
6133 
6134         @Override
6135         public void visitBinary(JCBinary that) {
6136             if (that.operator == null) {
6137                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6138                         -1, syms.noSymbol);
6139             }
6140             super.visitBinary(that);
6141         }
6142 
6143         @Override
6144         public void visitUnary(JCUnary that) {
6145             if (that.operator == null) {
6146                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6147                         -1, syms.noSymbol);
6148             }
6149             super.visitUnary(that);
6150         }
6151 
6152         @Override
6153         public void visitReference(JCMemberReference that) {
6154             super.visitReference(that);
6155             if (that.sym == null) {
6156                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6157                         syms.noSymbol);
6158             }
6159         }
6160 
6161         @Override
6162         public void visitVarType(JCVarType that) {
6163             initTypeIfNeeded(that);
6164         }
6165     }
6166     // </editor-fold>
6167 
6168     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6169         new TreeScanner() {
6170             Symbol packge = pkg;
6171             @Override
6172             public void visitIdent(JCIdent that) {
6173                 that.sym = packge;
6174             }
6175 
6176             @Override
6177             public void visitSelect(JCFieldAccess that) {
6178                 that.sym = packge;
6179                 packge = packge.owner;
6180                 super.visitSelect(that);
6181             }
6182         }.scan(pid);
6183     }
6184 
6185 }