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