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