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