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