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         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 170         allowRecords = Feature.RECORDS.allowedInSource(source);
 171         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 172                              Feature.PATTERN_SWITCH.allowedInSource(source);
 173         allowUnconditionalPatternsInstanceOf =
 174                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 175         sourceName = source.name;
 176         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 177 
 178         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 179         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 180         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 181         methodAttrInfo = new MethodAttrInfo();
 182         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 183         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 184         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 185     }
 186 
 187     /** Switch: reifiable types in instanceof enabled?
 188      */
 189     boolean allowReifiableTypesInInstanceof;
 190 
 191     /** Are records allowed
 192      */
 193     private final boolean allowRecords;
 194 
 195     /** Are patterns in switch allowed
 196      */
 197     private final boolean allowPatternSwitch;
 198 
 199     /** Are unconditional patterns in instanceof allowed
 200      */
 201     private final boolean allowUnconditionalPatternsInstanceOf;
 202 
 203     /**
 204      * Switch: warn about use of variable before declaration?
 205      * RFE: 6425594
 206      */
 207     boolean useBeforeDeclarationWarning;
 208 
 209     /**
 210      * Switch: name of source level; used for error reporting.
 211      */
 212     String sourceName;
 213 
 214     /** Check kind and type of given tree against protokind and prototype.
 215      *  If check succeeds, store type in tree and return it.
 216      *  If check fails, store errType in tree and return it.
 217      *  No checks are performed if the prototype is a method type.
 218      *  It is not necessary in this case since we know that kind and type
 219      *  are correct.
 220      *
 221      *  @param tree     The tree whose kind and type is checked
 222      *  @param found    The computed type of the tree
 223      *  @param ownkind  The computed kind of the tree
 224      *  @param resultInfo  The expected result of the tree
 225      */
 226     Type check(final JCTree tree,
 227                final Type found,
 228                final KindSelector ownkind,
 229                final ResultInfo resultInfo) {
 230         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 231         Type owntype;
 232         boolean shouldCheck = !found.hasTag(ERROR) &&
 233                 !resultInfo.pt.hasTag(METHOD) &&
 234                 !resultInfo.pt.hasTag(FORALL);
 235         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 236             log.error(tree.pos(),
 237                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 238                                             ownkind.kindNames()));
 239             owntype = types.createErrorType(found);
 240         } else if (inferenceContext.free(found)) {
 241             //delay the check if there are inference variables in the found type
 242             //this means we are dealing with a partially inferred poly expression
 243             owntype = shouldCheck ? resultInfo.pt : found;
 244             if (resultInfo.checkMode.installPostInferenceHook()) {
 245                 inferenceContext.addFreeTypeListener(List.of(found),
 246                         instantiatedContext -> {
 247                             ResultInfo pendingResult =
 248                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 249                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 250                         });
 251             }
 252         } else {
 253             owntype = shouldCheck ?
 254             resultInfo.check(tree, found) :
 255             found;
 256         }
 257         if (resultInfo.checkMode.updateTreeType()) {
 258             tree.type = owntype;
 259         }
 260         return owntype;
 261     }
 262 
 263     /** Is given blank final variable assignable, i.e. in a scope where it
 264      *  may be assigned to even though it is final?
 265      *  @param v      The blank final variable.
 266      *  @param env    The current environment.
 267      */
 268     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 269         Symbol owner = env.info.scope.owner;
 270            // owner refers to the innermost variable, method or
 271            // initializer block declaration at this point.
 272         boolean isAssignable =
 273             v.owner == owner
 274             ||
 275             ((owner.name == names.init ||    // i.e. we are in a constructor
 276               owner.kind == VAR ||           // i.e. we are in a variable initializer
 277               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 278              &&
 279              v.owner == owner.owner
 280              &&
 281              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 282         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 283         return isAssignable & !insideCompactConstructor;
 284     }
 285 
 286     /** Check that variable can be assigned to.
 287      *  @param pos    The current source code position.
 288      *  @param v      The assigned variable
 289      *  @param base   If the variable is referred to in a Select, the part
 290      *                to the left of the `.', null otherwise.
 291      *  @param env    The current environment.
 292      */
 293     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 294         if (v.name == names._this) {
 295             log.error(pos, Errors.CantAssignValToThis);
 296         } else if ((v.flags() & FINAL) != 0 &&
 297             ((v.flags() & HASINIT) != 0
 298              ||
 299              !((base == null ||
 300                TreeInfo.isThisQualifier(base)) &&
 301                isAssignableAsBlankFinal(v, env)))) {
 302             if (v.isResourceVariable()) { //TWR resource
 303                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 304             } else {
 305                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 306             }
 307         }
 308     }
 309 
 310     /** Does tree represent a static reference to an identifier?
 311      *  It is assumed that tree is either a SELECT or an IDENT.
 312      *  We have to weed out selects from non-type names here.
 313      *  @param tree    The candidate tree.
 314      */
 315     boolean isStaticReference(JCTree tree) {
 316         if (tree.hasTag(SELECT)) {
 317             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 318             if (lsym == null || lsym.kind != TYP) {
 319                 return false;
 320             }
 321         }
 322         return true;
 323     }
 324 
 325     /** Is this symbol a type?
 326      */
 327     static boolean isType(Symbol sym) {
 328         return sym != null && sym.kind == TYP;
 329     }
 330 
 331     /** The current `this' symbol.
 332      *  @param env    The current environment.
 333      */
 334     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
 335         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
 336     }
 337 
 338     /** Attribute a parsed identifier.
 339      * @param tree Parsed identifier name
 340      * @param topLevel The toplevel to use
 341      */
 342     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 343         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 344         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 345                                            syms.errSymbol.name,
 346                                            null, null, null, null);
 347         localEnv.enclClass.sym = syms.errSymbol;
 348         return attribIdent(tree, localEnv);
 349     }
 350 
 351     /** Attribute a parsed identifier.
 352      * @param tree Parsed identifier name
 353      * @param env The env to use
 354      */
 355     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
 356         return tree.accept(identAttributer, env);
 357     }
 358     // where
 359         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 360         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 361             @Override @DefinedBy(Api.COMPILER_TREE)
 362             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 363                 Symbol site = visit(node.getExpression(), env);
 364                 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
 365                     return site;
 366                 Name name = (Name)node.getIdentifier();
 367                 if (site.kind == PCK) {
 368                     env.toplevel.packge = (PackageSymbol)site;
 369                     return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
 370                             KindSelector.TYP_PCK);
 371                 } else {
 372                     env.enclClass.sym = (ClassSymbol)site;
 373                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 374                 }
 375             }
 376 
 377             @Override @DefinedBy(Api.COMPILER_TREE)
 378             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 379                 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
 380             }
 381         }
 382 
 383     public Type coerce(Type etype, Type ttype) {
 384         return cfolder.coerce(etype, ttype);
 385     }
 386 
 387     public Type attribType(JCTree node, TypeSymbol sym) {
 388         Env<AttrContext> env = typeEnvs.get(sym);
 389         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 390         return attribTree(node, localEnv, unknownTypeInfo);
 391     }
 392 
 393     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
 394         // Attribute qualifying package or class.
 395         JCFieldAccess s = tree.qualid;
 396         return attribTree(s.selected, env,
 397                           new ResultInfo(tree.staticImport ?
 398                                          KindSelector.TYP : KindSelector.TYP_PCK,
 399                        Type.noType));
 400     }
 401 
 402     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 403         return attribToTree(expr, env, tree, unknownExprInfo);
 404     }
 405 
 406     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 407         return attribToTree(stmt, env, tree, statInfo);
 408     }
 409 
 410     private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) {
 411         breakTree = tree;
 412         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 413         try {
 414             deferredAttr.attribSpeculative(root, env, resultInfo,
 415                     null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE,
 416                     argumentAttr.withLocalCacheContext());
 417             attrRecover.doRecovery();
 418         } catch (BreakAttr b) {
 419             return b.env;
 420         } catch (AssertionError ae) {
 421             if (ae.getCause() instanceof BreakAttr breakAttr) {
 422                 return breakAttr.env;
 423             } else {
 424                 throw ae;
 425             }
 426         } finally {
 427             breakTree = null;
 428             log.useSource(prev);
 429         }
 430         return env;
 431     }
 432 
 433     private JCTree breakTree = null;
 434 
 435     private static class BreakAttr extends RuntimeException {
 436         static final long serialVersionUID = -6924771130405446405L;
 437         private transient Env<AttrContext> env;
 438         private BreakAttr(Env<AttrContext> env) {
 439             this.env = env;
 440         }
 441     }
 442 
 443     /**
 444      * Mode controlling behavior of Attr.Check
 445      */
 446     enum CheckMode {
 447 
 448         NORMAL,
 449 
 450         /**
 451          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
 452          * that the captured var cache in {@code InferenceContext} will be used in read-only
 453          * mode when performing inference checks.
 454          */
 455         NO_TREE_UPDATE {
 456             @Override
 457             public boolean updateTreeType() {
 458                 return false;
 459             }
 460         },
 461         /**
 462          * Mode signalling that caller will manage free types in tree decorations.
 463          */
 464         NO_INFERENCE_HOOK {
 465             @Override
 466             public boolean installPostInferenceHook() {
 467                 return false;
 468             }
 469         };
 470 
 471         public boolean updateTreeType() {
 472             return true;
 473         }
 474         public boolean installPostInferenceHook() {
 475             return true;
 476         }
 477     }
 478 
 479 
 480     class ResultInfo {
 481         final KindSelector pkind;
 482         final Type pt;
 483         final CheckContext checkContext;
 484         final CheckMode checkMode;
 485 
 486         ResultInfo(KindSelector pkind, Type pt) {
 487             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
 488         }
 489 
 490         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
 491             this(pkind, pt, chk.basicHandler, checkMode);
 492         }
 493 
 494         protected ResultInfo(KindSelector pkind,
 495                              Type pt, CheckContext checkContext) {
 496             this(pkind, pt, checkContext, CheckMode.NORMAL);
 497         }
 498 
 499         protected ResultInfo(KindSelector pkind,
 500                              Type pt, CheckContext checkContext, CheckMode checkMode) {
 501             this.pkind = pkind;
 502             this.pt = pt;
 503             this.checkContext = checkContext;
 504             this.checkMode = checkMode;
 505         }
 506 
 507         /**
 508          * Should {@link Attr#attribTree} use the {@code ArgumentAttr} visitor instead of this one?
 509          * @param tree The tree to be type-checked.
 510          * @return true if {@code ArgumentAttr} should be used.
 511          */
 512         protected boolean needsArgumentAttr(JCTree tree) { return false; }
 513 
 514         protected Type check(final DiagnosticPosition pos, final Type found) {
 515             return chk.checkType(pos, found, pt, checkContext);
 516         }
 517 
 518         protected ResultInfo dup(Type newPt) {
 519             return new ResultInfo(pkind, newPt, checkContext, checkMode);
 520         }
 521 
 522         protected ResultInfo dup(CheckContext newContext) {
 523             return new ResultInfo(pkind, pt, newContext, checkMode);
 524         }
 525 
 526         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 527             return new ResultInfo(pkind, newPt, newContext, checkMode);
 528         }
 529 
 530         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 531             return new ResultInfo(pkind, newPt, newContext, newMode);
 532         }
 533 
 534         protected ResultInfo dup(CheckMode newMode) {
 535             return new ResultInfo(pkind, pt, checkContext, newMode);
 536         }
 537 
 538         @Override
 539         public String toString() {
 540             if (pt != null) {
 541                 return pt.toString();
 542             } else {
 543                 return "";
 544             }
 545         }
 546     }
 547 
 548     class MethodAttrInfo extends ResultInfo {
 549         public MethodAttrInfo() {
 550             this(chk.basicHandler);
 551         }
 552 
 553         public MethodAttrInfo(CheckContext checkContext) {
 554             super(KindSelector.VAL, Infer.anyPoly, checkContext);
 555         }
 556 
 557         @Override
 558         protected boolean needsArgumentAttr(JCTree tree) {
 559             return true;
 560         }
 561 
 562         protected ResultInfo dup(Type newPt) {
 563             throw new IllegalStateException();
 564         }
 565 
 566         protected ResultInfo dup(CheckContext newContext) {
 567             return new MethodAttrInfo(newContext);
 568         }
 569 
 570         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 571             throw new IllegalStateException();
 572         }
 573 
 574         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 575             throw new IllegalStateException();
 576         }
 577 
 578         protected ResultInfo dup(CheckMode newMode) {
 579             throw new IllegalStateException();
 580         }
 581     }
 582 
 583     class RecoveryInfo extends ResultInfo {
 584 
 585         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
 586             this(deferredAttrContext, Type.recoveryType);
 587         }
 588 
 589         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
 590             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
 591                 @Override
 592                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
 593                     return deferredAttrContext;
 594                 }
 595                 @Override
 596                 public boolean compatible(Type found, Type req, Warner warn) {
 597                     return true;
 598                 }
 599                 @Override
 600                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 601                     boolean needsReport = pt == Type.recoveryType ||
 602                             (details.getDiagnosticPosition() != null &&
 603                             details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
 604                     if (needsReport) {
 605                         chk.basicHandler.report(pos, details);
 606                     }
 607                 }
 608             });
 609         }
 610     }
 611 
 612     final ResultInfo statInfo;
 613     final ResultInfo varAssignmentInfo;
 614     final ResultInfo methodAttrInfo;
 615     final ResultInfo unknownExprInfo;
 616     final ResultInfo unknownTypeInfo;
 617     final ResultInfo unknownTypeExprInfo;
 618     final ResultInfo recoveryInfo;
 619 
 620     Type pt() {
 621         return resultInfo.pt;
 622     }
 623 
 624     KindSelector pkind() {
 625         return resultInfo.pkind;
 626     }
 627 
 628 /* ************************************************************************
 629  * Visitor methods
 630  *************************************************************************/
 631 
 632     /** Visitor argument: the current environment.
 633      */
 634     Env<AttrContext> env;
 635 
 636     /** Visitor argument: the currently expected attribution result.
 637      */
 638     ResultInfo resultInfo;
 639 
 640     /** Visitor result: the computed type.
 641      */
 642     Type result;
 643 
 644     MatchBindings matchBindings = MatchBindingsComputer.EMPTY;
 645 
 646     /** Visitor method: attribute a tree, catching any completion failure
 647      *  exceptions. Return the tree's type.
 648      *
 649      *  @param tree    The tree to be visited.
 650      *  @param env     The environment visitor argument.
 651      *  @param resultInfo   The result info visitor argument.
 652      */
 653     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
 654         Env<AttrContext> prevEnv = this.env;
 655         ResultInfo prevResult = this.resultInfo;
 656         try {
 657             this.env = env;
 658             this.resultInfo = resultInfo;
 659             if (resultInfo.needsArgumentAttr(tree)) {
 660                 result = argumentAttr.attribArg(tree, env);
 661             } else {
 662                 tree.accept(this);
 663             }
 664             matchBindings = matchBindingsComputer.finishBindings(tree,
 665                                                                  matchBindings);
 666             if (tree == breakTree &&
 667                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
 668                 breakTreeFound(copyEnv(env));
 669             }
 670             return result;
 671         } catch (CompletionFailure ex) {
 672             tree.type = syms.errType;
 673             return chk.completionError(tree.pos(), ex);
 674         } finally {
 675             this.env = prevEnv;
 676             this.resultInfo = prevResult;
 677         }
 678     }
 679 
 680     protected void breakTreeFound(Env<AttrContext> env) {
 681         throw new BreakAttr(env);
 682     }
 683 
 684     Env<AttrContext> copyEnv(Env<AttrContext> env) {
 685         Env<AttrContext> newEnv =
 686                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
 687         if (newEnv.outer != null) {
 688             newEnv.outer = copyEnv(newEnv.outer);
 689         }
 690         return newEnv;
 691     }
 692 
 693     WriteableScope copyScope(WriteableScope sc) {
 694         WriteableScope newScope = WriteableScope.create(sc.owner);
 695         List<Symbol> elemsList = List.nil();
 696         for (Symbol sym : sc.getSymbols()) {
 697             elemsList = elemsList.prepend(sym);
 698         }
 699         for (Symbol s : elemsList) {
 700             newScope.enter(s);
 701         }
 702         return newScope;
 703     }
 704 
 705     /** Derived visitor method: attribute an expression tree.
 706      */
 707     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 708         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
 709     }
 710 
 711     /** Derived visitor method: attribute an expression tree with
 712      *  no constraints on the computed type.
 713      */
 714     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
 715         return attribTree(tree, env, unknownExprInfo);
 716     }
 717 
 718     /** Derived visitor method: attribute a type tree.
 719      */
 720     public Type attribType(JCTree tree, Env<AttrContext> env) {
 721         Type result = attribType(tree, env, Type.noType);
 722         return result;
 723     }
 724 
 725     /** Derived visitor method: attribute a type tree.
 726      */
 727     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 728         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
 729         return result;
 730     }
 731 
 732     /** Derived visitor method: attribute a statement or definition tree.
 733      */
 734     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 735         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
 736         Type result = attribTree(tree, env, statInfo);
 737         analyzer.analyzeIfNeeded(tree, analyzeEnv);
 738         attrRecover.doRecovery();
 739         return result;
 740     }
 741 
 742     /** Attribute a list of expressions, returning a list of types.
 743      */
 744     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 745         ListBuffer<Type> ts = new ListBuffer<>();
 746         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 747             ts.append(attribExpr(l.head, env, pt));
 748         return ts.toList();
 749     }
 750 
 751     /** Attribute a list of statements, returning nothing.
 752      */
 753     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 754         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 755             attribStat(l.head, env);
 756     }
 757 
 758     /** Attribute the arguments in a method call, returning the method kind.
 759      */
 760     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
 761         KindSelector kind = initialKind;
 762         for (JCExpression arg : trees) {
 763             Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, methodAttrInfo));
 764             if (argtype.hasTag(DEFERRED)) {
 765                 kind = KindSelector.of(KindSelector.POLY, kind);
 766             }
 767             argtypes.append(argtype);
 768         }
 769         return kind;
 770     }
 771 
 772     /** Attribute a type argument list, returning a list of types.
 773      *  Caller is responsible for calling checkRefTypes.
 774      */
 775     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 776         ListBuffer<Type> argtypes = new ListBuffer<>();
 777         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 778             argtypes.append(attribType(l.head, env));
 779         return argtypes.toList();
 780     }
 781 
 782     /** Attribute a type argument list, returning a list of types.
 783      *  Check that all the types are references.
 784      */
 785     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 786         List<Type> types = attribAnyTypes(trees, env);
 787         return chk.checkRefTypes(trees, types);
 788     }
 789 
 790     /**
 791      * Attribute type variables (of generic classes or methods).
 792      * Compound types are attributed later in attribBounds.
 793      * @param typarams the type variables to enter
 794      * @param env      the current environment
 795      */
 796     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 797         for (JCTypeParameter tvar : typarams) {
 798             TypeVar a = (TypeVar)tvar.type;
 799             a.tsym.flags_field |= UNATTRIBUTED;
 800             a.setUpperBound(Type.noType);
 801             if (!tvar.bounds.isEmpty()) {
 802                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 803                 for (JCExpression bound : tvar.bounds.tail)
 804                     bounds = bounds.prepend(attribType(bound, env));
 805                 types.setBounds(a, bounds.reverse());
 806             } else {
 807                 // if no bounds are given, assume a single bound of
 808                 // java.lang.Object.
 809                 types.setBounds(a, List.of(syms.objectType));
 810             }
 811             a.tsym.flags_field &= ~UNATTRIBUTED;
 812         }
 813         if (checkCyclic) {
 814             for (JCTypeParameter tvar : typarams) {
 815                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 816             }
 817         }
 818     }
 819 
 820     /**
 821      * Attribute the type references in a list of annotations.
 822      */
 823     void attribAnnotationTypes(List<JCAnnotation> annotations,
 824                                Env<AttrContext> env) {
 825         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 826             JCAnnotation a = al.head;
 827             attribType(a.annotationType, env);
 828         }
 829     }
 830 
 831     /**
 832      * Attribute a "lazy constant value".
 833      *  @param env         The env for the const value
 834      *  @param variable    The initializer for the const value
 835      *  @param type        The expected type, or null
 836      *  @see VarSymbol#setLazyConstValue
 837      */
 838     public Object attribLazyConstantValue(Env<AttrContext> env,
 839                                       JCVariableDecl variable,
 840                                       Type type) {
 841 
 842         DiagnosticPosition prevLintPos
 843                 = deferredLintHandler.setPos(variable.pos());
 844 
 845         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 846         try {
 847             Type itype = attribExpr(variable.init, env, type);
 848             if (variable.isImplicitlyTyped()) {
 849                 //fixup local variable type
 850                 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype, variable.name);
 851             }
 852             if (itype.constValue() != null) {
 853                 return coerce(itype, type).constValue();
 854             } else {
 855                 return null;
 856             }
 857         } finally {
 858             log.useSource(prevSource);
 859             deferredLintHandler.setPos(prevLintPos);
 860         }
 861     }
 862 
 863     /** Attribute type reference in an `extends' or `implements' clause.
 864      *  Supertypes of anonymous inner classes are usually already attributed.
 865      *
 866      *  @param tree              The tree making up the type reference.
 867      *  @param env               The environment current at the reference.
 868      *  @param classExpected     true if only a class is expected here.
 869      *  @param interfaceExpected true if only an interface is expected here.
 870      */
 871     Type attribBase(JCTree tree,
 872                     Env<AttrContext> env,
 873                     boolean classExpected,
 874                     boolean interfaceExpected,
 875                     boolean checkExtensible) {
 876         Type t = tree.type != null ?
 877             tree.type :
 878             attribType(tree, env);
 879         try {
 880             return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 881         } catch (CompletionFailure ex) {
 882             chk.completionError(tree.pos(), ex);
 883             return t;
 884         }
 885     }
 886     Type checkBase(Type t,
 887                    JCTree tree,
 888                    Env<AttrContext> env,
 889                    boolean classExpected,
 890                    boolean interfaceExpected,
 891                    boolean checkExtensible) {
 892         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
 893                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
 894         if (t.tsym.isAnonymous()) {
 895             log.error(pos, Errors.CantInheritFromAnon);
 896             return types.createErrorType(t);
 897         }
 898         if (t.isErroneous())
 899             return t;
 900         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
 901             // check that type variable is already visible
 902             if (t.getUpperBound() == null) {
 903                 log.error(pos, Errors.IllegalForwardRef);
 904                 return types.createErrorType(t);
 905             }
 906         } else {
 907             t = chk.checkClassType(pos, t, checkExtensible);
 908         }
 909         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 910             log.error(pos, Errors.IntfExpectedHere);
 911             // return errType is necessary since otherwise there might
 912             // be undetected cycles which cause attribution to loop
 913             return types.createErrorType(t);
 914         } else if (checkExtensible &&
 915                    classExpected &&
 916                    (t.tsym.flags() & INTERFACE) != 0) {
 917             log.error(pos, Errors.NoIntfExpectedHere);
 918             return types.createErrorType(t);
 919         }
 920         if (checkExtensible &&
 921             ((t.tsym.flags() & FINAL) != 0)) {
 922             log.error(pos,
 923                       Errors.CantInheritFromFinal(t.tsym));
 924         }
 925         chk.checkNonCyclic(pos, t);
 926         return t;
 927     }
 928 
 929     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
 930         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
 931         id.type = env.info.scope.owner.enclClass().type;
 932         id.sym = env.info.scope.owner.enclClass();
 933         return id.type;
 934     }
 935 
 936     public void visitClassDef(JCClassDecl tree) {
 937         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
 938                 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
 939                         argumentAttr.withLocalCacheContext() : null);
 940         try {
 941             // Local and anonymous classes have not been entered yet, so we need to
 942             // do it now.
 943             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
 944                 enter.classEnter(tree, env);
 945             } else {
 946                 // If this class declaration is part of a class level annotation,
 947                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
 948                 // order to simplify later steps and allow for sensible error
 949                 // messages.
 950                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
 951                     enter.classEnter(tree, env);
 952             }
 953 
 954             ClassSymbol c = tree.sym;
 955             if (c == null) {
 956                 // exit in case something drastic went wrong during enter.
 957                 result = null;
 958             } else {
 959                 // make sure class has been completed:
 960                 c.complete();
 961 
 962                 // If this class appears as an anonymous class
 963                 // in a superclass constructor call
 964                 // disable implicit outer instance from being passed.
 965                 // (This would be an illegal access to "this before super").
 966                 if (env.info.isSelfCall &&
 967                         env.tree.hasTag(NEWCLASS)) {
 968                     c.flags_field |= NOOUTERTHIS;
 969                 }
 970                 attribClass(tree.pos(), c);
 971                 result = tree.type = c.type;
 972             }
 973         } finally {
 974             localCacheContext.ifPresent(LocalCacheContext::leave);
 975         }
 976     }
 977 
 978     public void visitMethodDef(JCMethodDecl tree) {
 979         MethodSymbol m = tree.sym;
 980         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
 981 
 982         Lint lint = env.info.lint.augment(m);
 983         Lint prevLint = chk.setLint(lint);
 984         MethodSymbol prevMethod = chk.setMethod(m);
 985         try {
 986             deferredLintHandler.flush(tree.pos());
 987             chk.checkDeprecatedAnnotation(tree.pos(), m);
 988 
 989 
 990             // Create a new environment with local scope
 991             // for attributing the method.
 992             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
 993             localEnv.info.lint = lint;
 994 
 995             attribStats(tree.typarams, localEnv);
 996 
 997             // If we override any other methods, check that we do so properly.
 998             // JLS ???
 999             if (m.isStatic()) {
1000                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1001             } else {
1002                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1003             }
1004             chk.checkOverride(env, tree, m);
1005 
1006             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1007                 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1008             }
1009 
1010             // Enter all type parameters into the local method scope.
1011             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1012                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1013 
1014             ClassSymbol owner = env.enclClass.sym;
1015             if ((owner.flags() & ANNOTATION) != 0 &&
1016                     (tree.params.nonEmpty() ||
1017                     tree.recvparam != null))
1018                 log.error(tree.params.nonEmpty() ?
1019                         tree.params.head.pos() :
1020                         tree.recvparam.pos(),
1021                         Errors.IntfAnnotationMembersCantHaveParams);
1022 
1023             // Attribute all value parameters.
1024             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1025                 attribStat(l.head, localEnv);
1026             }
1027 
1028             chk.checkVarargsMethodDecl(localEnv, tree);
1029 
1030             // Check that type parameters are well-formed.
1031             chk.validate(tree.typarams, localEnv);
1032 
1033             // Check that result type is well-formed.
1034             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
1035                 chk.validate(tree.restype, localEnv);
1036 
1037             // Check that receiver type is well-formed.
1038             if (tree.recvparam != null) {
1039                 // Use a new environment to check the receiver parameter.
1040                 // Otherwise I get "might not have been initialized" errors.
1041                 // Is there a better way?
1042                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1043                 attribType(tree.recvparam, newEnv);
1044                 chk.validate(tree.recvparam, newEnv);
1045             }
1046 
1047             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP) {
1048                 // lets find if this method is an accessor
1049                 Optional<? extends RecordComponent> recordComponent = env.enclClass.sym.getRecordComponents().stream()
1050                         .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
1051                 if (recordComponent.isPresent()) {
1052                     // the method is a user defined accessor lets check that everything is fine
1053                     if (!tree.sym.isPublic()) {
1054                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1055                     }
1056                     if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1057                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1058                                 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1059                     }
1060                     if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1061                         log.error(tree,
1062                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1063                     }
1064                     if (!tree.typarams.isEmpty()) {
1065                         log.error(tree,
1066                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1067                     }
1068                     if (tree.sym.isStatic()) {
1069                         log.error(tree,
1070                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1071                     }
1072                 }
1073 
1074                 if (tree.name == names.init) {
1075                     // if this a constructor other than the canonical one
1076                     if ((tree.sym.flags_field & RECORD) == 0) {
1077                         JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1078                         if (app == null ||
1079                                 TreeInfo.name(app.meth) != names._this ||
1080                                 !checkFirstConstructorStat(app, tree, false)) {
1081                             log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1082                         }
1083                     } else {
1084                         // but if it is the canonical:
1085 
1086                         /* if user generated, then it shouldn't:
1087                          *     - have an accessibility stricter than that of the record type
1088                          *     - explicitly invoke any other constructor
1089                          */
1090                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1091                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1092                                 log.error(tree,
1093                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1094                                             Errors.InvalidCanonicalConstructorInRecord(
1095                                                 Fragments.Canonical,
1096                                                 env.enclClass.sym.name,
1097                                                 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1098                                             ) :
1099                                             Errors.InvalidCanonicalConstructorInRecord(
1100                                                     Fragments.Canonical,
1101                                                     env.enclClass.sym.name,
1102                                                     Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1103                                             )
1104                                 );
1105                             }
1106 
1107                             JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1108                             if (app != null &&
1109                                     (TreeInfo.name(app.meth) == names._this ||
1110                                             TreeInfo.name(app.meth) == names._super) &&
1111                                     checkFirstConstructorStat(app, tree, false)) {
1112                                 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1113                                         Fragments.Canonical, env.enclClass.sym.name,
1114                                         Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1115                             }
1116                         }
1117 
1118                         // also we want to check that no type variables have been defined
1119                         if (!tree.typarams.isEmpty()) {
1120                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1121                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1122                         }
1123 
1124                         /* and now we need to check that the constructor's arguments are exactly the same as those of the
1125                          * record components
1126                          */
1127                         List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1128                         List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1129                         for (JCVariableDecl param: tree.params) {
1130                             boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1131                             if (!types.isSameType(param.type, recordFieldTypes.head) ||
1132                                     (recordComponents.head.isVarargs() != paramIsVarArgs)) {
1133                                 log.error(param, Errors.InvalidCanonicalConstructorInRecord(
1134                                         Fragments.Canonical, env.enclClass.sym.name,
1135                                         Fragments.TypeMustBeIdenticalToCorrespondingRecordComponentType));
1136                             }
1137                             recordComponents = recordComponents.tail;
1138                             recordFieldTypes = recordFieldTypes.tail;
1139                         }
1140                     }
1141                 }
1142             }
1143 
1144             // annotation method checks
1145             if ((owner.flags() & ANNOTATION) != 0) {
1146                 // annotation method cannot have throws clause
1147                 if (tree.thrown.nonEmpty()) {
1148                     log.error(tree.thrown.head.pos(),
1149                               Errors.ThrowsNotAllowedInIntfAnnotation);
1150                 }
1151                 // annotation method cannot declare type-parameters
1152                 if (tree.typarams.nonEmpty()) {
1153                     log.error(tree.typarams.head.pos(),
1154                               Errors.IntfAnnotationMembersCantHaveTypeParams);
1155                 }
1156                 // validate annotation method's return type (could be an annotation type)
1157                 chk.validateAnnotationType(tree.restype);
1158                 // ensure that annotation method does not clash with members of Object/Annotation
1159                 chk.validateAnnotationMethod(tree.pos(), m);
1160             }
1161 
1162             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1163                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1164 
1165             if (tree.body == null) {
1166                 // Empty bodies are only allowed for
1167                 // abstract, native, or interface methods, or for methods
1168                 // in a retrofit signature class.
1169                 if (tree.defaultValue != null) {
1170                     if ((owner.flags() & ANNOTATION) == 0)
1171                         log.error(tree.pos(),
1172                                   Errors.DefaultAllowedInIntfAnnotationMember);
1173                 }
1174                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1175                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1176             } else {
1177                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1178                     if ((owner.flags() & INTERFACE) != 0) {
1179                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1180                     } else {
1181                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1182                     }
1183                 } else if ((tree.mods.flags & NATIVE) != 0) {
1184                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1185                 }
1186                 // Add an implicit super() call unless an explicit call to
1187                 // super(...) or this(...) is given
1188                 // or we are compiling class java.lang.Object.
1189                 if (tree.name == names.init && owner.type != syms.objectType) {
1190                     JCBlock body = tree.body;
1191                     if (body.stats.isEmpty() ||
1192                             TreeInfo.getConstructorInvocationName(body.stats, names) == names.empty) {
1193                         JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1194                                 make.Ident(names._super), make.Idents(List.nil())));
1195                         body.stats = body.stats.prepend(supCall);
1196                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1197                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1198                             TreeInfo.isSuperCall(body.stats.head)) {
1199                         // enum constructors are not allowed to call super
1200                         // directly, so make sure there aren't any super calls
1201                         // in enum constructors, except in the compiler
1202                         // generated one.
1203                         log.error(tree.body.stats.head.pos(),
1204                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1205                     }
1206                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1207                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1208                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1209                         if (!initParamNames.equals(recordComponentNames)) {
1210                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1211                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1212                         }
1213                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1214                             log.error(tree,
1215                                     Errors.InvalidCanonicalConstructorInRecord(
1216                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1217                                             env.enclClass.sym.name,
1218                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1219                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1220                         }
1221                     }
1222                 }
1223 
1224                 // Attribute all type annotations in the body
1225                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1226                 annotate.flush();
1227 
1228                 // Attribute method body.
1229                 attribStat(tree.body, localEnv);
1230             }
1231 
1232             localEnv.info.scope.leave();
1233             result = tree.type = m.type;
1234         } finally {
1235             chk.setLint(prevLint);
1236             chk.setMethod(prevMethod);
1237         }
1238     }
1239 
1240     public void visitVarDef(JCVariableDecl tree) {
1241         // Local variables have not been entered yet, so we need to do it now:
1242         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1243             if (tree.sym != null) {
1244                 // parameters have already been entered
1245                 env.info.scope.enter(tree.sym);
1246             } else {
1247                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1248                     if (tree.init == null) {
1249                         //cannot use 'var' without initializer
1250                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1251                         tree.vartype = make.Erroneous();
1252                     } else {
1253                         Fragment msg = canInferLocalVarType(tree);
1254                         if (msg != null) {
1255                             //cannot use 'var' with initializer which require an explicit target
1256                             //(e.g. lambda, method reference, array initializer).
1257                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1258                             tree.vartype = make.Erroneous();
1259                         }
1260                     }
1261                 }
1262                 try {
1263                     annotate.blockAnnotations();
1264                     memberEnter.memberEnter(tree, env);
1265                 } finally {
1266                     annotate.unblockAnnotations();
1267                 }
1268             }
1269         } else {
1270             if (tree.init != null) {
1271                 // Field initializer expression need to be entered.
1272                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1273                 annotate.flush();
1274             }
1275         }
1276 
1277         VarSymbol v = tree.sym;
1278         Lint lint = env.info.lint.augment(v);
1279         Lint prevLint = chk.setLint(lint);
1280 
1281         // Check that the variable's declared type is well-formed.
1282         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1283                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1284                 (tree.sym.flags() & PARAMETER) != 0;
1285         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1286 
1287         try {
1288             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1289             deferredLintHandler.flush(tree.pos());
1290             chk.checkDeprecatedAnnotation(tree.pos(), v);
1291 
1292             if (tree.init != null) {
1293                 if ((v.flags_field & FINAL) == 0 ||
1294                     !memberEnter.needsLazyConstValue(tree.init)) {
1295                     // Not a compile-time constant
1296                     // Attribute initializer in a new environment
1297                     // with the declared variable as owner.
1298                     // Check that initializer conforms to variable's declared type.
1299                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1300                     initEnv.info.lint = lint;
1301                     // In order to catch self-references, we set the variable's
1302                     // declaration position to maximal possible value, effectively
1303                     // marking the variable as undefined.
1304                     initEnv.info.enclVar = v;
1305                     attribExpr(tree.init, initEnv, v.type);
1306                     if (tree.isImplicitlyTyped()) {
1307                         //fixup local variable type
1308                         v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1309                     }
1310                 }
1311                 if (tree.isImplicitlyTyped()) {
1312                     setSyntheticVariableType(tree, v.type);
1313                 }
1314             }
1315             result = tree.type = v.type;
1316             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1317                 if (isNonArgsMethodInObject(v.name)) {
1318                     log.error(tree, Errors.IllegalRecordComponentName(v));
1319                 }
1320             }
1321         }
1322         finally {
1323             chk.setLint(prevLint);
1324         }
1325     }
1326 
1327     private boolean isNonArgsMethodInObject(Name name) {
1328         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1329             if (s.type.getParameterTypes().isEmpty()) {
1330                 return true;
1331             }
1332         }
1333         return false;
1334     }
1335 
1336     Fragment canInferLocalVarType(JCVariableDecl tree) {
1337         LocalInitScanner lis = new LocalInitScanner();
1338         lis.scan(tree.init);
1339         return lis.badInferenceMsg;
1340     }
1341 
1342     static class LocalInitScanner extends TreeScanner {
1343         Fragment badInferenceMsg = null;
1344         boolean needsTarget = true;
1345 
1346         @Override
1347         public void visitNewArray(JCNewArray tree) {
1348             if (tree.elemtype == null && needsTarget) {
1349                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1350             }
1351         }
1352 
1353         @Override
1354         public void visitLambda(JCLambda tree) {
1355             if (needsTarget) {
1356                 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1357             }
1358         }
1359 
1360         @Override
1361         public void visitTypeCast(JCTypeCast tree) {
1362             boolean prevNeedsTarget = needsTarget;
1363             try {
1364                 needsTarget = false;
1365                 super.visitTypeCast(tree);
1366             } finally {
1367                 needsTarget = prevNeedsTarget;
1368             }
1369         }
1370 
1371         @Override
1372         public void visitReference(JCMemberReference tree) {
1373             if (needsTarget) {
1374                 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1375             }
1376         }
1377 
1378         @Override
1379         public void visitNewClass(JCNewClass tree) {
1380             boolean prevNeedsTarget = needsTarget;
1381             try {
1382                 needsTarget = false;
1383                 super.visitNewClass(tree);
1384             } finally {
1385                 needsTarget = prevNeedsTarget;
1386             }
1387         }
1388 
1389         @Override
1390         public void visitApply(JCMethodInvocation tree) {
1391             boolean prevNeedsTarget = needsTarget;
1392             try {
1393                 needsTarget = false;
1394                 super.visitApply(tree);
1395             } finally {
1396                 needsTarget = prevNeedsTarget;
1397             }
1398         }
1399     }
1400 
1401     public void visitSkip(JCSkip tree) {
1402         result = null;
1403     }
1404 
1405     public void visitBlock(JCBlock tree) {
1406         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1407             // Block is a static or instance initializer;
1408             // let the owner of the environment be a freshly
1409             // created BLOCK-method.
1410             Symbol fakeOwner =
1411                 new MethodSymbol(tree.flags | BLOCK |
1412                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1413                     env.info.scope.owner);
1414             final Env<AttrContext> localEnv =
1415                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1416 
1417             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1418             // Attribute all type annotations in the block
1419             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1420             annotate.flush();
1421             attribStats(tree.stats, localEnv);
1422 
1423             {
1424                 // Store init and clinit type annotations with the ClassSymbol
1425                 // to allow output in Gen.normalizeDefs.
1426                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1427                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1428                 if ((tree.flags & STATIC) != 0) {
1429                     cs.appendClassInitTypeAttributes(tas);
1430                 } else {
1431                     cs.appendInitTypeAttributes(tas);
1432                 }
1433             }
1434         } else {
1435             // Create a new local environment with a local scope.
1436             Env<AttrContext> localEnv =
1437                 env.dup(tree, env.info.dup(env.info.scope.dup()));
1438             try {
1439                 attribStats(tree.stats, localEnv);
1440             } finally {
1441                 localEnv.info.scope.leave();
1442             }
1443         }
1444         result = null;
1445     }
1446 
1447     public void visitDoLoop(JCDoWhileLoop tree) {
1448         attribStat(tree.body, env.dup(tree));
1449         attribExpr(tree.cond, env, syms.booleanType);
1450         handleLoopConditionBindings(matchBindings, tree, tree.body);
1451         result = null;
1452     }
1453 
1454     public void visitWhileLoop(JCWhileLoop tree) {
1455         attribExpr(tree.cond, env, syms.booleanType);
1456         MatchBindings condBindings = matchBindings;
1457         // include condition's bindings when true in the body:
1458         Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1459         try {
1460             attribStat(tree.body, whileEnv.dup(tree));
1461         } finally {
1462             whileEnv.info.scope.leave();
1463         }
1464         handleLoopConditionBindings(condBindings, tree, tree.body);
1465         result = null;
1466     }
1467 
1468     public void visitForLoop(JCForLoop tree) {
1469         Env<AttrContext> loopEnv =
1470             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1471         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1472         try {
1473             attribStats(tree.init, loopEnv);
1474             if (tree.cond != null) {
1475                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1476                 // include condition's bindings when true in the body and step:
1477                 condBindings = matchBindings;
1478             }
1479             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1480             try {
1481                 bodyEnv.tree = tree; // before, we were not in loop!
1482                 attribStats(tree.step, bodyEnv);
1483                 attribStat(tree.body, bodyEnv);
1484             } finally {
1485                 bodyEnv.info.scope.leave();
1486             }
1487             result = null;
1488         }
1489         finally {
1490             loopEnv.info.scope.leave();
1491         }
1492         handleLoopConditionBindings(condBindings, tree, tree.body);
1493     }
1494 
1495     /**
1496      * Include condition's bindings when false after the loop, if cannot get out of the loop
1497      */
1498     private void handleLoopConditionBindings(MatchBindings condBindings,
1499                                              JCStatement loop,
1500                                              JCStatement loopBody) {
1501         if (condBindings.bindingsWhenFalse.nonEmpty() &&
1502             !breaksTo(env, loop, loopBody)) {
1503             addBindings2Scope(loop, condBindings.bindingsWhenFalse);
1504         }
1505     }
1506 
1507     private boolean breaksTo(Env<AttrContext> env, JCTree loop, JCTree body) {
1508         preFlow(body);
1509         return flow.breaksToTree(env, loop, body, make);
1510     }
1511 
1512     /**
1513      * Add given bindings to the current scope, unless there's a break to
1514      * an immediately enclosing labeled statement.
1515      */
1516     private void addBindings2Scope(JCStatement introducingStatement,
1517                                    List<BindingSymbol> bindings) {
1518         if (bindings.isEmpty()) {
1519             return ;
1520         }
1521 
1522         var searchEnv = env;
1523         while (searchEnv.tree instanceof JCLabeledStatement labeled &&
1524                labeled.body == introducingStatement) {
1525             if (breaksTo(env, labeled, labeled.body)) {
1526                 //breaking to an immediately enclosing labeled statement
1527                 return ;
1528             }
1529             searchEnv = searchEnv.next;
1530             introducingStatement = labeled;
1531         }
1532 
1533         //include condition's body when false after the while, if cannot get out of the loop
1534         bindings.forEach(env.info.scope::enter);
1535         bindings.forEach(BindingSymbol::preserveBinding);
1536     }
1537 
1538     public void visitForeachLoop(JCEnhancedForLoop tree) {
1539         Env<AttrContext> loopEnv =
1540             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1541         try {
1542             //the Formal Parameter of a for-each loop is not in the scope when
1543             //attributing the for-each expression; we mimic this by attributing
1544             //the for-each expression first (against original scope).
1545             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1546             chk.checkNonVoid(tree.pos(), exprType);
1547             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1548             if (elemtype == null) {
1549                 // or perhaps expr implements Iterable<T>?
1550                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1551                 if (base == null) {
1552                     log.error(tree.expr.pos(),
1553                               Errors.ForeachNotApplicableToType(exprType,
1554                                                                 Fragments.TypeReqArrayOrIterable));
1555                     elemtype = types.createErrorType(exprType);
1556                 } else {
1557                     List<Type> iterableParams = base.allparams();
1558                     elemtype = iterableParams.isEmpty()
1559                         ? syms.objectType
1560                         : types.wildUpperBound(iterableParams.head);
1561 
1562                     // Check the return type of the method iterator().
1563                     // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1564                     Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1565                             loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1566                     if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1567                         log.error(tree.pos(),
1568                                 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1569                     }
1570                 }
1571             }
1572             if (tree.var.isImplicitlyTyped()) {
1573                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1574                 setSyntheticVariableType(tree.var, inferredType);
1575             }
1576             attribStat(tree.var, loopEnv);
1577             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1578             loopEnv.tree = tree; // before, we were not in loop!
1579             attribStat(tree.body, loopEnv);
1580             result = null;
1581         }
1582         finally {
1583             loopEnv.info.scope.leave();
1584         }
1585     }
1586 
1587     public void visitLabelled(JCLabeledStatement tree) {
1588         // Check that label is not used in an enclosing statement
1589         Env<AttrContext> env1 = env;
1590         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1591             if (env1.tree.hasTag(LABELLED) &&
1592                 ((JCLabeledStatement) env1.tree).label == tree.label) {
1593                 log.error(tree.pos(),
1594                           Errors.LabelAlreadyInUse(tree.label));
1595                 break;
1596             }
1597             env1 = env1.next;
1598         }
1599 
1600         attribStat(tree.body, env.dup(tree));
1601         result = null;
1602     }
1603 
1604     public void visitSwitch(JCSwitch tree) {
1605         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1606             attribStats(c.stats, caseEnv);
1607         });
1608         result = null;
1609     }
1610 
1611     public void visitSwitchExpression(JCSwitchExpression tree) {
1612         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
1613                 PolyKind.STANDALONE : PolyKind.POLY;
1614 
1615         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1616             //this means we are returning a poly conditional from void-compatible lambda expression
1617             resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
1618             result = tree.type = types.createErrorType(resultInfo.pt);
1619             return;
1620         }
1621 
1622         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1623                 unknownExprInfo :
1624                 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
1625 
1626         ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
1627         ListBuffer<Type> caseTypes = new ListBuffer<>();
1628 
1629         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1630             caseEnv.info.yieldResult = condInfo;
1631             attribStats(c.stats, caseEnv);
1632             new TreeScanner() {
1633                 @Override
1634                 public void visitYield(JCYield brk) {
1635                     if (brk.target == tree) {
1636                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
1637                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
1638                     }
1639                     super.visitYield(brk);
1640                 }
1641 
1642                 @Override public void visitClassDef(JCClassDecl tree) {}
1643                 @Override public void visitLambda(JCLambda tree) {}
1644             }.scan(c.stats);
1645         });
1646 
1647         if (tree.cases.isEmpty()) {
1648             log.error(tree.pos(),
1649                       Errors.SwitchExpressionEmpty);
1650         } else if (caseTypes.isEmpty()) {
1651             log.error(tree.pos(),
1652                       Errors.SwitchExpressionNoResultExpressions);
1653         }
1654 
1655         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
1656 
1657         result = tree.type = check(tree, owntype, KindSelector.VAL, resultInfo);
1658     }
1659     //where:
1660         CheckContext switchExpressionContext(CheckContext checkContext) {
1661             return new Check.NestedCheckContext(checkContext) {
1662                 //this will use enclosing check context to check compatibility of
1663                 //subexpression against target type; if we are in a method check context,
1664                 //depending on whether boxing is allowed, we could have incompatibilities
1665                 @Override
1666                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1667                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
1668                 }
1669             };
1670         }
1671 
1672     private void handleSwitch(JCTree switchTree,
1673                               JCExpression selector,
1674                               List<JCCase> cases,
1675                               BiConsumer<JCCase, Env<AttrContext>> attribCase) {
1676         Type seltype = attribExpr(selector, env);
1677 
1678         Env<AttrContext> switchEnv =
1679             env.dup(switchTree, env.info.dup(env.info.scope.dup()));
1680 
1681         try {
1682             boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1683             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
1684             boolean errorEnumSwitch = TreeInfo.isErrorEnumSwitch(selector, cases);
1685             boolean intSwitch = types.isAssignable(seltype, syms.intType);
1686             boolean errorPrimitiveSwitch = seltype.isPrimitive() && !intSwitch;
1687             boolean patternSwitch;
1688             if (!enumSwitch && !stringSwitch && !errorEnumSwitch &&
1689                 !intSwitch && !errorPrimitiveSwitch) {
1690                 preview.checkSourceLevel(selector.pos(), Feature.PATTERN_SWITCH);
1691                 patternSwitch = true;
1692             } else {
1693                 if (errorPrimitiveSwitch) {
1694                     log.error(selector.pos(), Errors.SelectorTypeNotAllowed(seltype));
1695                 }
1696                 patternSwitch = cases.stream()
1697                                      .flatMap(c -> c.labels.stream())
1698                                      .anyMatch(l -> l.hasTag(PATTERNCASELABEL) ||
1699                                                     TreeInfo.isNullCaseLabel(l));
1700             }
1701 
1702             // Attribute all cases and
1703             // check that there are no duplicate case labels or default clauses.
1704             Set<Object> constants = new HashSet<>(); // The set of case constants.
1705             boolean hasDefault = false;           // Is there a default label?
1706             boolean hasUnconditionalPattern = false; // Is there a unconditional pattern?
1707             boolean lastPatternErroneous = false; // Has the last pattern erroneous type?
1708             boolean hasNullPattern = false;       // Is there a null pattern?
1709             CaseTree.CaseKind caseKind = null;
1710             boolean wasError = false;
1711             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
1712                 JCCase c = l.head;
1713                 if (caseKind == null) {
1714                     caseKind = c.caseKind;
1715                 } else if (caseKind != c.caseKind && !wasError) {
1716                     log.error(c.pos(),
1717                               Errors.SwitchMixingCaseTypes);
1718                     wasError = true;
1719                 }
1720                 MatchBindings currentBindings = null;
1721                 MatchBindings guardBindings = null;
1722                 for (List<JCCaseLabel> labels = c.labels; labels.nonEmpty(); labels = labels.tail) {
1723                     JCCaseLabel label = labels.head;
1724                     if (label instanceof JCConstantCaseLabel constLabel) {
1725                         JCExpression expr = constLabel.expr;
1726                         if (TreeInfo.isNull(expr)) {
1727                             preview.checkSourceLevel(expr.pos(), Feature.CASE_NULL);
1728                             if (hasNullPattern) {
1729                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
1730                             }
1731                             hasNullPattern = true;
1732                             attribExpr(expr, switchEnv, seltype);
1733                             matchBindings = new MatchBindings(matchBindings.bindingsWhenTrue, matchBindings.bindingsWhenFalse, true);
1734                         } else if (enumSwitch) {
1735                             Symbol sym = enumConstant(expr, seltype);
1736                             if (sym == null) {
1737                                 if (allowPatternSwitch) {
1738                                     attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
1739                                     Symbol enumSym = TreeInfo.symbol(expr);
1740                                     if (enumSym == null || !enumSym.isEnum() || enumSym.kind != VAR) {
1741                                         log.error(expr.pos(), Errors.EnumLabelMustBeEnumConstant);
1742                                     } else if (!constants.add(enumSym)) {
1743                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
1744                                     }
1745                                 } else {
1746                                     log.error(expr.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
1747                                 }
1748                             } else if (!constants.add(sym)) {
1749                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
1750                             }
1751                         } else if (errorEnumSwitch) {
1752                             //error recovery: the selector is erroneous, and all the case labels
1753                             //are identifiers. This could be an enum switch - don't report resolve
1754                             //error for the case label:
1755                             var prevResolveHelper = rs.basicLogResolveHelper;
1756                             try {
1757                                 rs.basicLogResolveHelper = rs.silentLogResolveHelper;
1758                                 attribExpr(expr, switchEnv, seltype);
1759                             } finally {
1760                                 rs.basicLogResolveHelper = prevResolveHelper;
1761                             }
1762                         } else {
1763                             Type pattype = attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
1764                             if (!pattype.hasTag(ERROR)) {
1765                                 if (pattype.constValue() == null) {
1766                                     Symbol s = TreeInfo.symbol(expr);
1767                                     if (s != null && s.kind == TYP) {
1768                                         log.error(expr.pos(),
1769                                                   Errors.PatternExpected);
1770                                     } else if (s == null || !s.isEnum()) {
1771                                         log.error(expr.pos(),
1772                                                   (stringSwitch ? Errors.StringConstReq
1773                                                                 : intSwitch ? Errors.ConstExprReq
1774                                                                             : Errors.PatternOrEnumReq));
1775                                     } else if (!constants.add(s)) {
1776                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
1777                                     }
1778                                 } else if (!stringSwitch && !intSwitch && !errorPrimitiveSwitch) {
1779                                     log.error(label.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype));
1780                                 } else if (!constants.add(pattype.constValue())) {
1781                                     log.error(c.pos(), Errors.DuplicateCaseLabel);
1782                                 }
1783                             }
1784                         }
1785                     } else if (label instanceof JCDefaultCaseLabel def) {
1786                         if (hasDefault) {
1787                             log.error(label.pos(), Errors.DuplicateDefaultLabel);
1788                         } else if (hasUnconditionalPattern) {
1789                             log.error(label.pos(), Errors.UnconditionalPatternAndDefault);
1790                         }
1791                         hasDefault = true;
1792                         matchBindings = MatchBindingsComputer.EMPTY;
1793                     } else if (label instanceof JCPatternCaseLabel patternlabel) {
1794                         //pattern
1795                         JCPattern pat = patternlabel.pat;
1796                         attribExpr(pat, switchEnv, seltype);
1797                         Type primaryType = TreeInfo.primaryPatternType(pat);
1798                         if (!primaryType.hasTag(TYPEVAR)) {
1799                             primaryType = chk.checkClassOrArrayType(pat.pos(), primaryType);
1800                         }
1801                         if (!errorPrimitiveSwitch) {
1802                             checkCastablePattern(pat.pos(), seltype, primaryType);
1803                         }
1804                         Type patternType = types.erasure(primaryType);
1805                         JCExpression guard = c.guard;
1806                         if (guardBindings == null && guard != null) {
1807                             MatchBindings afterPattern = matchBindings;
1808                             Env<AttrContext> bodyEnv = bindingEnv(switchEnv, matchBindings.bindingsWhenTrue);
1809                             try {
1810                                 attribExpr(guard, bodyEnv, syms.booleanType);
1811                             } finally {
1812                                 bodyEnv.info.scope.leave();
1813                             }
1814 
1815                             guardBindings = matchBindings;
1816                             matchBindings = afterPattern;
1817 
1818                             if (TreeInfo.isBooleanWithValue(guard, 0)) {
1819                                 log.error(guard.pos(), Errors.GuardHasConstantExpressionFalse);
1820                             }
1821                         }
1822                         boolean unguarded = TreeInfo.unguardedCase(c) && !pat.hasTag(RECORDPATTERN);
1823                         boolean unconditional =
1824                                 unguarded &&
1825                                 !patternType.isErroneous() &&
1826                                 types.isSubtype(types.boxedTypeOrType(types.erasure(seltype)),
1827                                                 patternType);
1828                         if (unconditional) {
1829                             if (hasUnconditionalPattern) {
1830                                 log.error(pat.pos(), Errors.DuplicateUnconditionalPattern);
1831                             } else if (hasDefault) {
1832                                 log.error(pat.pos(), Errors.UnconditionalPatternAndDefault);
1833                             }
1834                             hasUnconditionalPattern = true;
1835                         }
1836                         lastPatternErroneous = patternType.isErroneous();
1837                     } else {
1838                         Assert.error();
1839                     }
1840                     currentBindings = matchBindingsComputer.switchCase(label, currentBindings, matchBindings);
1841                 }
1842 
1843                 if (guardBindings != null) {
1844                     currentBindings = matchBindingsComputer.caseGuard(c, currentBindings, guardBindings);
1845                 }
1846 
1847                 Env<AttrContext> caseEnv =
1848                         bindingEnv(switchEnv, c, currentBindings.bindingsWhenTrue);
1849                 try {
1850                     attribCase.accept(c, caseEnv);
1851                 } finally {
1852                     caseEnv.info.scope.leave();
1853                 }
1854                 addVars(c.stats, switchEnv.info.scope);
1855 
1856                 preFlow(c);
1857                 c.completesNormally = flow.aliveAfter(caseEnv, c, make);
1858             }
1859             if (patternSwitch) {
1860                 chk.checkSwitchCaseStructure(cases);
1861                 chk.checkSwitchCaseLabelDominated(cases);
1862             }
1863             if (switchTree.hasTag(SWITCH)) {
1864                 ((JCSwitch) switchTree).hasUnconditionalPattern =
1865                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
1866                 ((JCSwitch) switchTree).patternSwitch = patternSwitch;
1867             } else if (switchTree.hasTag(SWITCH_EXPRESSION)) {
1868                 ((JCSwitchExpression) switchTree).hasUnconditionalPattern =
1869                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
1870                 ((JCSwitchExpression) switchTree).patternSwitch = patternSwitch;
1871             } else {
1872                 Assert.error(switchTree.getTag().name());
1873             }
1874         } finally {
1875             switchEnv.info.scope.leave();
1876         }
1877     }
1878     // where
1879         private ResultInfo caseLabelResultInfo(Type seltype) {
1880             return new ResultInfo(KindSelector.VAL_TYP,
1881                                   !seltype.hasTag(ERROR) ? seltype
1882                                                          : Type.noType);
1883         }
1884         /** Add any variables defined in stats to the switch scope. */
1885         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1886             for (;stats.nonEmpty(); stats = stats.tail) {
1887                 JCTree stat = stats.head;
1888                 if (stat.hasTag(VARDEF))
1889                     switchScope.enter(((JCVariableDecl) stat).sym);
1890             }
1891         }
1892     // where
1893     /** Return the selected enumeration constant symbol, or null. */
1894     private Symbol enumConstant(JCTree tree, Type enumType) {
1895         if (tree.hasTag(IDENT)) {
1896             JCIdent ident = (JCIdent)tree;
1897             Name name = ident.name;
1898             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1899                 if (sym.kind == VAR) {
1900                     Symbol s = ident.sym = sym;
1901                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1902                     ident.type = s.type;
1903                     return ((s.flags_field & Flags.ENUM) == 0)
1904                         ? null : s;
1905                 }
1906             }
1907         }
1908         return null;
1909     }
1910 
1911     public void visitSynchronized(JCSynchronized tree) {
1912         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1913         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1914             log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1915         }
1916         attribStat(tree.body, env);
1917         result = null;
1918     }
1919         // where
1920         private boolean isValueBased(Type t) {
1921             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1922         }
1923 
1924 
1925     public void visitTry(JCTry tree) {
1926         // Create a new local environment with a local
1927         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1928         try {
1929             boolean isTryWithResource = tree.resources.nonEmpty();
1930             // Create a nested environment for attributing the try block if needed
1931             Env<AttrContext> tryEnv = isTryWithResource ?
1932                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1933                 localEnv;
1934             try {
1935                 // Attribute resource declarations
1936                 for (JCTree resource : tree.resources) {
1937                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1938                         @Override
1939                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1940                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1941                         }
1942                     };
1943                     ResultInfo twrResult =
1944                         new ResultInfo(KindSelector.VAR,
1945                                        syms.autoCloseableType,
1946                                        twrContext);
1947                     if (resource.hasTag(VARDEF)) {
1948                         attribStat(resource, tryEnv);
1949                         twrResult.check(resource, resource.type);
1950 
1951                         //check that resource type cannot throw InterruptedException
1952                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
1953 
1954                         VarSymbol var = ((JCVariableDecl) resource).sym;
1955 
1956                         var.flags_field |= Flags.FINAL;
1957                         var.setData(ElementKind.RESOURCE_VARIABLE);
1958                     } else {
1959                         attribTree(resource, tryEnv, twrResult);
1960                     }
1961                 }
1962                 // Attribute body
1963                 attribStat(tree.body, tryEnv);
1964             } finally {
1965                 if (isTryWithResource)
1966                     tryEnv.info.scope.leave();
1967             }
1968 
1969             // Attribute catch clauses
1970             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1971                 JCCatch c = l.head;
1972                 Env<AttrContext> catchEnv =
1973                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1974                 try {
1975                     Type ctype = attribStat(c.param, catchEnv);
1976                     if (TreeInfo.isMultiCatch(c)) {
1977                         //multi-catch parameter is implicitly marked as final
1978                         c.param.sym.flags_field |= FINAL | UNION;
1979                     }
1980                     if (c.param.sym.kind == VAR) {
1981                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1982                     }
1983                     chk.checkType(c.param.vartype.pos(),
1984                                   chk.checkClassType(c.param.vartype.pos(), ctype),
1985                                   syms.throwableType);
1986                     attribStat(c.body, catchEnv);
1987                 } finally {
1988                     catchEnv.info.scope.leave();
1989                 }
1990             }
1991 
1992             // Attribute finalizer
1993             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1994             result = null;
1995         }
1996         finally {
1997             localEnv.info.scope.leave();
1998         }
1999     }
2000 
2001     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
2002         if (!resource.isErroneous() &&
2003             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
2004             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2005             Symbol close = syms.noSymbol;
2006             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
2007             try {
2008                 close = rs.resolveQualifiedMethod(pos,
2009                         env,
2010                         types.skipTypeVars(resource, false),
2011                         names.close,
2012                         List.nil(),
2013                         List.nil());
2014             }
2015             finally {
2016                 log.popDiagnosticHandler(discardHandler);
2017             }
2018             if (close.kind == MTH &&
2019                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2020                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
2021                     env.info.lint.isEnabled(LintCategory.TRY)) {
2022                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
2023             }
2024         }
2025     }
2026 
2027     public void visitConditional(JCConditional tree) {
2028         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
2029         MatchBindings condBindings = matchBindings;
2030 
2031         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
2032                 isBooleanOrNumeric(env, tree)) ?
2033                 PolyKind.STANDALONE : PolyKind.POLY;
2034 
2035         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2036             //this means we are returning a poly conditional from void-compatible lambda expression
2037             resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
2038             result = tree.type = types.createErrorType(resultInfo.pt);
2039             return;
2040         }
2041 
2042         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2043                 unknownExprInfo :
2044                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
2045 
2046 
2047         // x ? y : z
2048         // include x's bindings when true in y
2049         // include x's bindings when false in z
2050 
2051         Type truetype;
2052         Env<AttrContext> trueEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2053         try {
2054             truetype = attribTree(tree.truepart, trueEnv, condInfo);
2055         } finally {
2056             trueEnv.info.scope.leave();
2057         }
2058 
2059         MatchBindings trueBindings = matchBindings;
2060 
2061         Type falsetype;
2062         Env<AttrContext> falseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2063         try {
2064             falsetype = attribTree(tree.falsepart, falseEnv, condInfo);
2065         } finally {
2066             falseEnv.info.scope.leave();
2067         }
2068 
2069         MatchBindings falseBindings = matchBindings;
2070 
2071         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
2072                 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
2073                          List.of(truetype, falsetype)) : pt();
2074         if (condtype.constValue() != null &&
2075                 truetype.constValue() != null &&
2076                 falsetype.constValue() != null &&
2077                 !owntype.hasTag(NONE)) {
2078             //constant folding
2079             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
2080         }
2081         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2082         matchBindings = matchBindingsComputer.conditional(tree, condBindings, trueBindings, falseBindings);
2083     }
2084     //where
2085         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
2086             switch (tree.getTag()) {
2087                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
2088                               ((JCLiteral)tree).typetag == BOOLEAN ||
2089                               ((JCLiteral)tree).typetag == BOT;
2090                 case LAMBDA: case REFERENCE: return false;
2091                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
2092                 case CONDEXPR:
2093                     JCConditional condTree = (JCConditional)tree;
2094                     return isBooleanOrNumeric(env, condTree.truepart) &&
2095                             isBooleanOrNumeric(env, condTree.falsepart);
2096                 case APPLY:
2097                     JCMethodInvocation speculativeMethodTree =
2098                             (JCMethodInvocation)deferredAttr.attribSpeculative(
2099                                     tree, env, unknownExprInfo,
2100                                     argumentAttr.withLocalCacheContext());
2101                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
2102                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
2103                             env.enclClass.type :
2104                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
2105                     Type owntype = types.memberType(receiverType, msym).getReturnType();
2106                     return primitiveOrBoxed(owntype);
2107                 case NEWCLASS:
2108                     JCExpression className =
2109                             removeClassParams.translate(((JCNewClass)tree).clazz);
2110                     JCExpression speculativeNewClassTree =
2111                             (JCExpression)deferredAttr.attribSpeculative(
2112                                     className, env, unknownTypeInfo,
2113                                     argumentAttr.withLocalCacheContext());
2114                     return primitiveOrBoxed(speculativeNewClassTree.type);
2115                 default:
2116                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
2117                             argumentAttr.withLocalCacheContext()).type;
2118                     return primitiveOrBoxed(speculativeType);
2119             }
2120         }
2121         //where
2122             boolean primitiveOrBoxed(Type t) {
2123                 return (!t.hasTag(TYPEVAR) && !t.isErroneous() && types.unboxedTypeOrType(t).isPrimitive());
2124             }
2125 
2126             TreeTranslator removeClassParams = new TreeTranslator() {
2127                 @Override
2128                 public void visitTypeApply(JCTypeApply tree) {
2129                     result = translate(tree.clazz);
2130                 }
2131             };
2132 
2133         CheckContext conditionalContext(CheckContext checkContext) {
2134             return new Check.NestedCheckContext(checkContext) {
2135                 //this will use enclosing check context to check compatibility of
2136                 //subexpression against target type; if we are in a method check context,
2137                 //depending on whether boxing is allowed, we could have incompatibilities
2138                 @Override
2139                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2140                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
2141                 }
2142             };
2143         }
2144 
2145         /** Compute the type of a conditional expression, after
2146          *  checking that it exists.  See JLS 15.25. Does not take into
2147          *  account the special case where condition and both arms
2148          *  are constants.
2149          *
2150          *  @param pos      The source position to be used for error
2151          *                  diagnostics.
2152          *  @param thentype The type of the expression's then-part.
2153          *  @param elsetype The type of the expression's else-part.
2154          */
2155         Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
2156             if (condTypes.isEmpty()) {
2157                 return syms.objectType; //TODO: how to handle?
2158             }
2159             Type first = condTypes.head;
2160             // If same type, that is the result
2161             if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
2162                 return first.baseType();
2163 
2164             List<Type> unboxedTypes = condTypes.stream()
2165                                                .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
2166                                                .collect(List.collector());
2167 
2168             // Otherwise, if both arms can be converted to a numeric
2169             // type, return the least numeric type that fits both arms
2170             // (i.e. return larger of the two, or return int if one
2171             // arm is short, the other is char).
2172             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2173                 // If one arm has an integer subrange type (i.e., byte,
2174                 // short, or char), and the other is an integer constant
2175                 // that fits into the subrange, return the subrange type.
2176                 for (Type type : unboxedTypes) {
2177                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2178                         continue;
2179                     }
2180                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2181                         return type.baseType();
2182                 }
2183 
2184                 for (TypeTag tag : primitiveTags) {
2185                     Type candidate = syms.typeOfTag[tag.ordinal()];
2186                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2187                         return candidate;
2188                     }
2189                 }
2190             }
2191 
2192             // Those were all the cases that could result in a primitive
2193             condTypes = condTypes.stream()
2194                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
2195                                  .collect(List.collector());
2196 
2197             for (Type type : condTypes) {
2198                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2199                     return type.baseType();
2200             }
2201 
2202             Iterator<DiagnosticPosition> posIt = positions.iterator();
2203 
2204             condTypes = condTypes.stream()
2205                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
2206                                  .collect(List.collector());
2207 
2208             // both are known to be reference types.  The result is
2209             // lub(thentype,elsetype). This cannot fail, as it will
2210             // always be possible to infer "Object" if nothing better.
2211             return types.lub(condTypes.stream()
2212                         .map(t -> t.baseType())
2213                         .filter(t -> !t.hasTag(BOT))
2214                         .collect(List.collector()));
2215         }
2216 
2217     static final TypeTag[] primitiveTags = new TypeTag[]{
2218         BYTE,
2219         CHAR,
2220         SHORT,
2221         INT,
2222         LONG,
2223         FLOAT,
2224         DOUBLE,
2225         BOOLEAN,
2226     };
2227 
2228     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2229         return bindingEnv(env, env.tree, bindings);
2230     }
2231 
2232     Env<AttrContext> bindingEnv(Env<AttrContext> env, JCTree newTree, List<BindingSymbol> bindings) {
2233         Env<AttrContext> env1 = env.dup(newTree, env.info.dup(env.info.scope.dup()));
2234         bindings.forEach(env1.info.scope::enter);
2235         return env1;
2236     }
2237 
2238     public void visitIf(JCIf tree) {
2239         attribExpr(tree.cond, env, syms.booleanType);
2240 
2241         // if (x) { y } [ else z ]
2242         // include x's bindings when true in y
2243         // include x's bindings when false in z
2244 
2245         MatchBindings condBindings = matchBindings;
2246         Env<AttrContext> thenEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2247 
2248         try {
2249             attribStat(tree.thenpart, thenEnv);
2250         } finally {
2251             thenEnv.info.scope.leave();
2252         }
2253 
2254         preFlow(tree.thenpart);
2255         boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make);
2256         boolean aliveAfterElse;
2257 
2258         if (tree.elsepart != null) {
2259             Env<AttrContext> elseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2260             try {
2261                 attribStat(tree.elsepart, elseEnv);
2262             } finally {
2263                 elseEnv.info.scope.leave();
2264             }
2265             preFlow(tree.elsepart);
2266             aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make);
2267         } else {
2268             aliveAfterElse = true;
2269         }
2270 
2271         chk.checkEmptyIf(tree);
2272 
2273         List<BindingSymbol> afterIfBindings = List.nil();
2274 
2275         if (aliveAfterThen && !aliveAfterElse) {
2276             afterIfBindings = condBindings.bindingsWhenTrue;
2277         } else if (aliveAfterElse && !aliveAfterThen) {
2278             afterIfBindings = condBindings.bindingsWhenFalse;
2279         }
2280 
2281         addBindings2Scope(tree, afterIfBindings);
2282 
2283         result = null;
2284     }
2285 
2286         void preFlow(JCTree tree) {
2287             attrRecover.doRecovery();
2288             new PostAttrAnalyzer() {
2289                 @Override
2290                 public void scan(JCTree tree) {
2291                     if (tree == null ||
2292                             (tree.type != null &&
2293                             tree.type == Type.stuckType)) {
2294                         //don't touch stuck expressions!
2295                         return;
2296                     }
2297                     super.scan(tree);
2298                 }
2299 
2300                 @Override
2301                 public void visitClassDef(JCClassDecl that) {
2302                     if (that.sym != null) {
2303                         // Method preFlow shouldn't visit class definitions
2304                         // that have not been entered and attributed.
2305                         // See JDK-8254557 and JDK-8203277 for more details.
2306                         super.visitClassDef(that);
2307                     }
2308                 }
2309 
2310                 @Override
2311                 public void visitLambda(JCLambda that) {
2312                     if (that.type != null) {
2313                         // Method preFlow shouldn't visit lambda expressions
2314                         // that have not been entered and attributed.
2315                         // See JDK-8254557 and JDK-8203277 for more details.
2316                         super.visitLambda(that);
2317                     }
2318                 }
2319             }.scan(tree);
2320         }
2321 
2322     public void visitExec(JCExpressionStatement tree) {
2323         //a fresh environment is required for 292 inference to work properly ---
2324         //see Infer.instantiatePolymorphicSignatureInstance()
2325         Env<AttrContext> localEnv = env.dup(tree);
2326         attribExpr(tree.expr, localEnv);
2327         result = null;
2328     }
2329 
2330     public void visitBreak(JCBreak tree) {
2331         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2332         result = null;
2333     }
2334 
2335     public void visitYield(JCYield tree) {
2336         if (env.info.yieldResult != null) {
2337             attribTree(tree.value, env, env.info.yieldResult);
2338             tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
2339         } else {
2340             log.error(tree.pos(), tree.value.hasTag(PARENS)
2341                     ? Errors.NoSwitchExpressionQualify
2342                     : Errors.NoSwitchExpression);
2343             attribTree(tree.value, env, unknownExprInfo);
2344         }
2345         result = null;
2346     }
2347 
2348     public void visitContinue(JCContinue tree) {
2349         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2350         result = null;
2351     }
2352     //where
2353         /** Return the target of a break, continue or yield statement,
2354          *  if it exists, report an error if not.
2355          *  Note: The target of a labelled break or continue is the
2356          *  (non-labelled) statement tree referred to by the label,
2357          *  not the tree representing the labelled statement itself.
2358          *
2359          *  @param pos     The position to be used for error diagnostics
2360          *  @param tag     The tag of the jump statement. This is either
2361          *                 Tree.BREAK or Tree.CONTINUE.
2362          *  @param label   The label of the jump statement, or null if no
2363          *                 label is given.
2364          *  @param env     The environment current at the jump statement.
2365          */
2366         private JCTree findJumpTarget(DiagnosticPosition pos,
2367                                                    JCTree.Tag tag,
2368                                                    Name label,
2369                                                    Env<AttrContext> env) {
2370             Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
2371 
2372             if (jumpTarget.snd != null) {
2373                 log.error(pos, jumpTarget.snd);
2374             }
2375 
2376             return jumpTarget.fst;
2377         }
2378         /** Return the target of a break or continue statement, if it exists,
2379          *  report an error if not.
2380          *  Note: The target of a labelled break or continue is the
2381          *  (non-labelled) statement tree referred to by the label,
2382          *  not the tree representing the labelled statement itself.
2383          *
2384          *  @param tag     The tag of the jump statement. This is either
2385          *                 Tree.BREAK or Tree.CONTINUE.
2386          *  @param label   The label of the jump statement, or null if no
2387          *                 label is given.
2388          *  @param env     The environment current at the jump statement.
2389          */
2390         private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
2391                                                                        Name label,
2392                                                                        Env<AttrContext> env) {
2393             // Search environments outwards from the point of jump.
2394             Env<AttrContext> env1 = env;
2395             JCDiagnostic.Error pendingError = null;
2396             LOOP:
2397             while (env1 != null) {
2398                 switch (env1.tree.getTag()) {
2399                     case LABELLED:
2400                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
2401                         if (label == labelled.label) {
2402                             // If jump is a continue, check that target is a loop.
2403                             if (tag == CONTINUE) {
2404                                 if (!labelled.body.hasTag(DOLOOP) &&
2405                                         !labelled.body.hasTag(WHILELOOP) &&
2406                                         !labelled.body.hasTag(FORLOOP) &&
2407                                         !labelled.body.hasTag(FOREACHLOOP)) {
2408                                     pendingError = Errors.NotLoopLabel(label);
2409                                 }
2410                                 // Found labelled statement target, now go inwards
2411                                 // to next non-labelled tree.
2412                                 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
2413                             } else {
2414                                 return Pair.of(labelled, pendingError);
2415                             }
2416                         }
2417                         break;
2418                     case DOLOOP:
2419                     case WHILELOOP:
2420                     case FORLOOP:
2421                     case FOREACHLOOP:
2422                         if (label == null) return Pair.of(env1.tree, pendingError);
2423                         break;
2424                     case SWITCH:
2425                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
2426                         break;
2427                     case SWITCH_EXPRESSION:
2428                         if (tag == YIELD) {
2429                             return Pair.of(env1.tree, null);
2430                         } else if (tag == BREAK) {
2431                             pendingError = Errors.BreakOutsideSwitchExpression;
2432                         } else {
2433                             pendingError = Errors.ContinueOutsideSwitchExpression;
2434                         }
2435                         break;
2436                     case LAMBDA:
2437                     case METHODDEF:
2438                     case CLASSDEF:
2439                         break LOOP;
2440                     default:
2441                 }
2442                 env1 = env1.next;
2443             }
2444             if (label != null)
2445                 return Pair.of(null, Errors.UndefLabel(label));
2446             else if (pendingError != null)
2447                 return Pair.of(null, pendingError);
2448             else if (tag == CONTINUE)
2449                 return Pair.of(null, Errors.ContOutsideLoop);
2450             else
2451                 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
2452         }
2453 
2454     public void visitReturn(JCReturn tree) {
2455         // Check that there is an enclosing method which is
2456         // nested within than the enclosing class.
2457         if (env.info.returnResult == null) {
2458             log.error(tree.pos(), Errors.RetOutsideMeth);
2459         } else if (env.info.yieldResult != null) {
2460             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
2461         } else if (!env.info.isLambda &&
2462                 !env.info.isNewClass &&
2463                 env.enclMethod != null &&
2464                 TreeInfo.isCompactConstructor(env.enclMethod)) {
2465             log.error(env.enclMethod,
2466                     Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement));
2467         } else {
2468             // Attribute return expression, if it exists, and check that
2469             // it conforms to result type of enclosing method.
2470             if (tree.expr != null) {
2471                 if (env.info.returnResult.pt.hasTag(VOID)) {
2472                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2473                               diags.fragment(Fragments.UnexpectedRetVal));
2474                 }
2475                 attribTree(tree.expr, env, env.info.returnResult);
2476             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2477                     !env.info.returnResult.pt.hasTag(NONE)) {
2478                 env.info.returnResult.checkContext.report(tree.pos(),
2479                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2480             }
2481         }
2482         result = null;
2483     }
2484 
2485     public void visitThrow(JCThrow tree) {
2486         Type owntype = attribExpr(tree.expr, env, Type.noType);
2487         chk.checkType(tree, owntype, syms.throwableType);
2488         result = null;
2489     }
2490 
2491     public void visitAssert(JCAssert tree) {
2492         attribExpr(tree.cond, env, syms.booleanType);
2493         if (tree.detail != null) {
2494             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2495         }
2496         result = null;
2497     }
2498 
2499      /** Visitor method for method invocations.
2500      *  NOTE: The method part of an application will have in its type field
2501      *        the return type of the method, not the method's type itself!
2502      */
2503     public void visitApply(JCMethodInvocation tree) {
2504         // The local environment of a method application is
2505         // a new environment nested in the current one.
2506         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2507 
2508         // The types of the actual method arguments.
2509         List<Type> argtypes;
2510 
2511         // The types of the actual method type arguments.
2512         List<Type> typeargtypes = null;
2513 
2514         Name methName = TreeInfo.name(tree.meth);
2515 
2516         boolean isConstructorCall =
2517             methName == names._this || methName == names._super;
2518 
2519         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2520         if (isConstructorCall) {
2521             // We are seeing a ...this(...) or ...super(...) call.
2522             // Check that this is the first statement in a constructor.
2523             checkFirstConstructorStat(tree, env.enclMethod, true);
2524 
2525             // Record the fact
2526             // that this is a constructor call (using isSelfCall).
2527             localEnv.info.isSelfCall = true;
2528 
2529             // Attribute arguments, yielding list of argument types.
2530             localEnv.info.constructorArgs = true;
2531             KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2532             localEnv.info.constructorArgs = false;
2533             argtypes = argtypesBuf.toList();
2534             typeargtypes = attribTypes(tree.typeargs, localEnv);
2535 
2536             // Variable `site' points to the class in which the called
2537             // constructor is defined.
2538             Type site = env.enclClass.sym.type;
2539             if (methName == names._super) {
2540                 if (site == syms.objectType) {
2541                     log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2542                     site = types.createErrorType(syms.objectType);
2543                 } else {
2544                     site = types.supertype(site);
2545                 }
2546             }
2547 
2548             if (site.hasTag(CLASS)) {
2549                 Type encl = site.getEnclosingType();
2550                 while (encl != null && encl.hasTag(TYPEVAR))
2551                     encl = encl.getUpperBound();
2552                 if (encl.hasTag(CLASS)) {
2553                     // we are calling a nested class
2554 
2555                     if (tree.meth.hasTag(SELECT)) {
2556                         JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2557 
2558                         // We are seeing a prefixed call, of the form
2559                         //     <expr>.super(...).
2560                         // Check that the prefix expression conforms
2561                         // to the outer instance type of the class.
2562                         chk.checkRefType(qualifier.pos(),
2563                                          attribExpr(qualifier, localEnv,
2564                                                     encl));
2565                     } else if (methName == names._super) {
2566                         // qualifier omitted; check for existence
2567                         // of an appropriate implicit qualifier.
2568                         rs.resolveImplicitThis(tree.meth.pos(),
2569                                                localEnv, site, true);
2570                     }
2571                 } else if (tree.meth.hasTag(SELECT)) {
2572                     log.error(tree.meth.pos(),
2573                               Errors.IllegalQualNotIcls(site.tsym));
2574                     attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2575                 }
2576 
2577                 // if we're calling a java.lang.Enum constructor,
2578                 // prefix the implicit String and int parameters
2579                 if (site.tsym == syms.enumSym)
2580                     argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
2581 
2582                 // Resolve the called constructor under the assumption
2583                 // that we are referring to a superclass instance of the
2584                 // current instance (JLS ???).
2585                 boolean selectSuperPrev = localEnv.info.selectSuper;
2586                 localEnv.info.selectSuper = true;
2587                 localEnv.info.pendingResolutionPhase = null;
2588                 Symbol sym = rs.resolveConstructor(
2589                     tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
2590                 localEnv.info.selectSuper = selectSuperPrev;
2591 
2592                 // Set method symbol to resolved constructor...
2593                 TreeInfo.setSymbol(tree.meth, sym);
2594 
2595                 // ...and check that it is legal in the current context.
2596                 // (this will also set the tree's type)
2597                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2598                 checkId(tree.meth, site, sym, localEnv,
2599                         new ResultInfo(kind, mpt));
2600             } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) {
2601                 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2602             }
2603             // Otherwise, `site' is an error type and we do nothing
2604             result = tree.type = syms.voidType;
2605         } else {
2606             // Otherwise, we are seeing a regular method call.
2607             // Attribute the arguments, yielding list of argument types, ...
2608             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2609             argtypes = argtypesBuf.toList();
2610             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
2611 
2612             // ... and attribute the method using as a prototype a methodtype
2613             // whose formal argument types is exactly the list of actual
2614             // arguments (this will also set the method symbol).
2615             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2616             localEnv.info.pendingResolutionPhase = null;
2617             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2618 
2619             // Compute the result type.
2620             Type restype = mtype.getReturnType();
2621             if (restype.hasTag(WILDCARD))
2622                 throw new AssertionError(mtype);
2623 
2624             Type qualifier = (tree.meth.hasTag(SELECT))
2625                     ? ((JCFieldAccess) tree.meth).selected.type
2626                     : env.enclClass.sym.type;
2627             Symbol msym = TreeInfo.symbol(tree.meth);
2628             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2629 
2630             chk.checkRefTypes(tree.typeargs, typeargtypes);
2631 
2632             // Check that value of resulting type is admissible in the
2633             // current context.  Also, capture the return type
2634             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2635             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2636         }
2637         chk.validate(tree.typeargs, localEnv);
2638     }
2639     //where
2640         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2641             if (msym != null &&
2642                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2643                     methodName == names.getClass &&
2644                     argtypes.isEmpty()) {
2645                 // as a special case, x.getClass() has type Class<? extends |X|>
2646                 return new ClassType(restype.getEnclosingType(),
2647                         List.of(new WildcardType(types.erasure(qualifierType.baseType()),
2648                                 BoundKind.EXTENDS,
2649                                 syms.boundClass)),
2650                         restype.tsym,
2651                         restype.getMetadata());
2652             } else if (msym != null &&
2653                     msym.owner == syms.arrayClass &&
2654                     methodName == names.clone &&
2655                     types.isArray(qualifierType)) {
2656                 // as a special case, array.clone() has a result that is
2657                 // the same as static type of the array being cloned
2658                 return qualifierType;
2659             } else {
2660                 return restype;
2661             }
2662         }
2663 
2664         /** Check that given application node appears as first statement
2665          *  in a constructor call.
2666          *  @param tree          The application node
2667          *  @param enclMethod    The enclosing method of the application.
2668          *  @param error         Should an error be issued?
2669          */
2670         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2671             if (enclMethod != null && enclMethod.name == names.init) {
2672                 JCBlock body = enclMethod.body;
2673                 if (body.stats.head.hasTag(EXEC) &&
2674                     ((JCExpressionStatement) body.stats.head).expr == tree)
2675                     return true;
2676             }
2677             if (error) {
2678                 log.error(tree.pos(),
2679                         Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2680             }
2681             return false;
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         // In a constructor body,
4357         // if symbol is a field or instance method, check that it is
4358         // not accessed before the supertype constructor is called.
4359         if (symEnv.info.isSelfCall &&
4360             sym.kind.matches(KindSelector.VAL_MTH) &&
4361             sym.owner.kind == TYP &&
4362             (sym.flags() & STATIC) == 0) {
4363             chk.earlyRefError(tree.pos(), sym.kind == VAR ?
4364                                           sym : thisSym(tree.pos(), env));
4365         }
4366         Env<AttrContext> env1 = env;
4367         if (sym.kind != ERR && sym.kind != TYP &&
4368             sym.owner != null && sym.owner != env1.enclClass.sym) {
4369             // If the found symbol is inaccessible, then it is
4370             // accessed through an enclosing instance.  Locate this
4371             // enclosing instance:
4372             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4373                 env1 = env1.outer;
4374         }
4375 
4376         if (env.info.isSerializable) {
4377             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4378         }
4379 
4380         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4381     }
4382 
4383     public void visitSelect(JCFieldAccess tree) {
4384         // Determine the expected kind of the qualifier expression.
4385         KindSelector skind = KindSelector.NIL;
4386         if (tree.name == names._this || tree.name == names._super ||
4387                 tree.name == names._class)
4388         {
4389             skind = KindSelector.TYP;
4390         } else {
4391             if (pkind().contains(KindSelector.PCK))
4392                 skind = KindSelector.of(skind, KindSelector.PCK);
4393             if (pkind().contains(KindSelector.TYP))
4394                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4395             if (pkind().contains(KindSelector.VAL_MTH))
4396                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4397         }
4398 
4399         // Attribute the qualifier expression, and determine its symbol (if any).
4400         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4401         if (!pkind().contains(KindSelector.TYP_PCK))
4402             site = capture(site); // Capture field access
4403 
4404         // don't allow T.class T[].class, etc
4405         if (skind == KindSelector.TYP) {
4406             Type elt = site;
4407             while (elt.hasTag(ARRAY))
4408                 elt = ((ArrayType)elt).elemtype;
4409             if (elt.hasTag(TYPEVAR)) {
4410                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4411                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4412                 tree.sym = tree.type.tsym;
4413                 return ;
4414             }
4415         }
4416 
4417         // If qualifier symbol is a type or `super', assert `selectSuper'
4418         // for the selection. This is relevant for determining whether
4419         // protected symbols are accessible.
4420         Symbol sitesym = TreeInfo.symbol(tree.selected);
4421         boolean selectSuperPrev = env.info.selectSuper;
4422         env.info.selectSuper =
4423             sitesym != null &&
4424             sitesym.name == names._super;
4425 
4426         // Determine the symbol represented by the selection.
4427         env.info.pendingResolutionPhase = null;
4428         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4429         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4430             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4431             sym = syms.errSymbol;
4432         }
4433         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4434             site = capture(site);
4435             sym = selectSym(tree, sitesym, site, env, resultInfo);
4436         }
4437         boolean varArgs = env.info.lastResolveVarargs();
4438         tree.sym = sym;
4439 
4440         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4441             site = types.skipTypeVars(site, true);
4442         }
4443 
4444         // If that symbol is a variable, ...
4445         if (sym.kind == VAR) {
4446             VarSymbol v = (VarSymbol)sym;
4447 
4448             // ..., evaluate its initializer, if it has one, and check for
4449             // illegal forward reference.
4450             checkInit(tree, env, v, true);
4451 
4452             // If we are expecting a variable (as opposed to a value), check
4453             // that the variable is assignable in the current environment.
4454             if (KindSelector.ASG.subset(pkind()))
4455                 checkAssignable(tree.pos(), v, tree.selected, env);
4456         }
4457 
4458         if (sitesym != null &&
4459                 sitesym.kind == VAR &&
4460                 ((VarSymbol)sitesym).isResourceVariable() &&
4461                 sym.kind == MTH &&
4462                 sym.name.equals(names.close) &&
4463                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
4464                 env.info.lint.isEnabled(LintCategory.TRY)) {
4465             log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall);
4466         }
4467 
4468         // Disallow selecting a type from an expression
4469         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4470             tree.type = check(tree.selected, pt(),
4471                               sitesym == null ?
4472                                       KindSelector.VAL : sitesym.kind.toSelector(),
4473                               new ResultInfo(KindSelector.TYP_PCK, pt()));
4474         }
4475 
4476         if (isType(sitesym)) {
4477             if (sym.name == names._this || sym.name == names._super) {
4478                 // If `C' is the currently compiled class, check that
4479                 // `C.this' does not appear in an explicit call to a constructor
4480                 // also make sure that `super` is not used in constructor invocations
4481                 if (env.info.isSelfCall &&
4482                         ((sym.name == names._this &&
4483                         site.tsym == env.enclClass.sym) ||
4484                         sym.name == names._super && env.info.constructorArgs &&
4485                         (sitesym.isInterface() || site.tsym == env.enclClass.sym))) {
4486                     chk.earlyRefError(tree.pos(), sym);
4487                 }
4488             } else {
4489                 // Check if type-qualified fields or methods are static (JLS)
4490                 if ((sym.flags() & STATIC) == 0 &&
4491                     sym.name != names._super &&
4492                     (sym.kind == VAR || sym.kind == MTH)) {
4493                     rs.accessBase(rs.new StaticError(sym),
4494                               tree.pos(), site, sym.name, true);
4495                 }
4496             }
4497         } else if (sym.kind != ERR &&
4498                    (sym.flags() & STATIC) != 0 &&
4499                    sym.name != names._class) {
4500             // If the qualified item is not a type and the selected item is static, report
4501             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4502             if (!sym.owner.isAnonymous()) {
4503                 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4504             } else {
4505                 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4506             }
4507         }
4508 
4509         // If we are selecting an instance member via a `super', ...
4510         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4511 
4512             // Check that super-qualified symbols are not abstract (JLS)
4513             rs.checkNonAbstract(tree.pos(), sym);
4514 
4515             if (site.isRaw()) {
4516                 // Determine argument types for site.
4517                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4518                 if (site1 != null) site = site1;
4519             }
4520         }
4521 
4522         if (env.info.isSerializable) {
4523             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4524         }
4525 
4526         env.info.selectSuper = selectSuperPrev;
4527         result = checkId(tree, site, sym, env, resultInfo);
4528     }
4529     //where
4530         /** Determine symbol referenced by a Select expression,
4531          *
4532          *  @param tree   The select tree.
4533          *  @param site   The type of the selected expression,
4534          *  @param env    The current environment.
4535          *  @param resultInfo The current result.
4536          */
4537         private Symbol selectSym(JCFieldAccess tree,
4538                                  Symbol location,
4539                                  Type site,
4540                                  Env<AttrContext> env,
4541                                  ResultInfo resultInfo) {
4542             DiagnosticPosition pos = tree.pos();
4543             Name name = tree.name;
4544             switch (site.getTag()) {
4545             case PACKAGE:
4546                 return rs.accessBase(
4547                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4548                     pos, location, site, name, true);
4549             case ARRAY:
4550             case CLASS:
4551                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4552                     return rs.resolveQualifiedMethod(
4553                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4554                 } else if (name == names._this || name == names._super) {
4555                     return rs.resolveSelf(pos, env, site.tsym, name);
4556                 } else if (name == names._class) {
4557                     // In this case, we have already made sure in
4558                     // visitSelect that qualifier expression is a type.
4559                     return syms.getClassField(site, types);
4560                 } else {
4561                     // We are seeing a plain identifier as selector.
4562                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4563                         sym = rs.accessBase(sym, pos, location, site, name, true);
4564                     return sym;
4565                 }
4566             case WILDCARD:
4567                 throw new AssertionError(tree);
4568             case TYPEVAR:
4569                 // Normally, site.getUpperBound() shouldn't be null.
4570                 // It should only happen during memberEnter/attribBase
4571                 // when determining the supertype which *must* be
4572                 // done before attributing the type variables.  In
4573                 // other words, we are seeing this illegal program:
4574                 // class B<T> extends A<T.foo> {}
4575                 Symbol sym = (site.getUpperBound() != null)
4576                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4577                     : null;
4578                 if (sym == null) {
4579                     log.error(pos, Errors.TypeVarCantBeDeref);
4580                     return syms.errSymbol;
4581                 } else {
4582                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
4583                         rs.new AccessError(env, site, sym) :
4584                                 sym;
4585                     rs.accessBase(sym2, pos, location, site, name, true);
4586                     return sym;
4587                 }
4588             case ERROR:
4589                 // preserve identifier names through errors
4590                 return types.createErrorType(name, site.tsym, site).tsym;
4591             default:
4592                 // The qualifier expression is of a primitive type -- only
4593                 // .class is allowed for these.
4594                 if (name == names._class) {
4595                     // In this case, we have already made sure in Select that
4596                     // qualifier expression is a type.
4597                     return syms.getClassField(site, types);
4598                 } else {
4599                     log.error(pos, Errors.CantDeref(site));
4600                     return syms.errSymbol;
4601                 }
4602             }
4603         }
4604 
4605         /** Determine type of identifier or select expression and check that
4606          *  (1) the referenced symbol is not deprecated
4607          *  (2) the symbol's type is safe (@see checkSafe)
4608          *  (3) if symbol is a variable, check that its type and kind are
4609          *      compatible with the prototype and protokind.
4610          *  (4) if symbol is an instance field of a raw type,
4611          *      which is being assigned to, issue an unchecked warning if its
4612          *      type changes under erasure.
4613          *  (5) if symbol is an instance method of a raw type, issue an
4614          *      unchecked warning if its argument types change under erasure.
4615          *  If checks succeed:
4616          *    If symbol is a constant, return its constant type
4617          *    else if symbol is a method, return its result type
4618          *    otherwise return its type.
4619          *  Otherwise return errType.
4620          *
4621          *  @param tree       The syntax tree representing the identifier
4622          *  @param site       If this is a select, the type of the selected
4623          *                    expression, otherwise the type of the current class.
4624          *  @param sym        The symbol representing the identifier.
4625          *  @param env        The current environment.
4626          *  @param resultInfo    The expected result
4627          */
4628         Type checkId(JCTree tree,
4629                      Type site,
4630                      Symbol sym,
4631                      Env<AttrContext> env,
4632                      ResultInfo resultInfo) {
4633             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
4634                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
4635                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4636         }
4637 
4638         Type checkMethodIdInternal(JCTree tree,
4639                      Type site,
4640                      Symbol sym,
4641                      Env<AttrContext> env,
4642                      ResultInfo resultInfo) {
4643             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4644                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4645             } else {
4646                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4647             }
4648         }
4649 
4650         Type checkIdInternal(JCTree tree,
4651                      Type site,
4652                      Symbol sym,
4653                      Type pt,
4654                      Env<AttrContext> env,
4655                      ResultInfo resultInfo) {
4656             if (pt.isErroneous()) {
4657                 return types.createErrorType(site);
4658             }
4659             Type owntype; // The computed type of this identifier occurrence.
4660             switch (sym.kind) {
4661             case TYP:
4662                 // For types, the computed type equals the symbol's type,
4663                 // except for two situations:
4664                 owntype = sym.type;
4665                 if (owntype.hasTag(CLASS)) {
4666                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4667                     Type ownOuter = owntype.getEnclosingType();
4668 
4669                     // (a) If the symbol's type is parameterized, erase it
4670                     // because no type parameters were given.
4671                     // We recover generic outer type later in visitTypeApply.
4672                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4673                         owntype = types.erasure(owntype);
4674                     }
4675 
4676                     // (b) If the symbol's type is an inner class, then
4677                     // we have to interpret its outer type as a superclass
4678                     // of the site type. Example:
4679                     //
4680                     // class Tree<A> { class Visitor { ... } }
4681                     // class PointTree extends Tree<Point> { ... }
4682                     // ...PointTree.Visitor...
4683                     //
4684                     // Then the type of the last expression above is
4685                     // Tree<Point>.Visitor.
4686                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4687                         Type normOuter = site;
4688                         if (normOuter.hasTag(CLASS)) {
4689                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4690                         }
4691                         if (normOuter == null) // perhaps from an import
4692                             normOuter = types.erasure(ownOuter);
4693                         if (normOuter != ownOuter)
4694                             owntype = new ClassType(
4695                                 normOuter, List.nil(), owntype.tsym,
4696                                 owntype.getMetadata());
4697                     }
4698                 }
4699                 break;
4700             case VAR:
4701                 VarSymbol v = (VarSymbol)sym;
4702 
4703                 if (env.info.enclVar != null
4704                         && v.type.hasTag(NONE)) {
4705                     //self reference to implicitly typed variable declaration
4706                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4707                     return tree.type = v.type = types.createErrorType(v.type);
4708                 }
4709 
4710                 // Test (4): if symbol is an instance field of a raw type,
4711                 // which is being assigned to, issue an unchecked warning if
4712                 // its type changes under erasure.
4713                 if (KindSelector.ASG.subset(pkind()) &&
4714                     v.owner.kind == TYP &&
4715                     (v.flags() & STATIC) == 0 &&
4716                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4717                     Type s = types.asOuterSuper(site, v.owner);
4718                     if (s != null &&
4719                         s.isRaw() &&
4720                         !types.isSameType(v.type, v.erasure(types))) {
4721                         chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s));
4722                     }
4723                 }
4724                 // The computed type of a variable is the type of the
4725                 // variable symbol, taken as a member of the site type.
4726                 owntype = (sym.owner.kind == TYP &&
4727                            sym.name != names._this && sym.name != names._super)
4728                     ? types.memberType(site, sym)
4729                     : sym.type;
4730 
4731                 // If the variable is a constant, record constant value in
4732                 // computed type.
4733                 if (v.getConstValue() != null && isStaticReference(tree))
4734                     owntype = owntype.constType(v.getConstValue());
4735 
4736                 if (resultInfo.pkind == KindSelector.VAL) {
4737                     owntype = capture(owntype); // capture "names as expressions"
4738                 }
4739                 break;
4740             case MTH: {
4741                 owntype = checkMethod(site, sym,
4742                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4743                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4744                         resultInfo.pt.getTypeArguments());
4745                 break;
4746             }
4747             case PCK: case ERR:
4748                 owntype = sym.type;
4749                 break;
4750             default:
4751                 throw new AssertionError("unexpected kind: " + sym.kind +
4752                                          " in tree " + tree);
4753             }
4754 
4755             // Emit a `deprecation' warning if symbol is deprecated.
4756             // (for constructors (but not for constructor references), the error
4757             // was given when the constructor was resolved)
4758 
4759             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4760                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4761                 chk.checkSunAPI(tree.pos(), sym);
4762                 chk.checkProfile(tree.pos(), sym);
4763                 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4764             }
4765 
4766             // If symbol is a variable, check that its type and
4767             // kind are compatible with the prototype and protokind.
4768             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4769         }
4770 
4771         /** Check that variable is initialized and evaluate the variable's
4772          *  initializer, if not yet done. Also check that variable is not
4773          *  referenced before it is defined.
4774          *  @param tree    The tree making up the variable reference.
4775          *  @param env     The current environment.
4776          *  @param v       The variable's symbol.
4777          */
4778         private void checkInit(JCTree tree,
4779                                Env<AttrContext> env,
4780                                VarSymbol v,
4781                                boolean onlyWarning) {
4782             // A forward reference is diagnosed if the declaration position
4783             // of the variable is greater than the current tree position
4784             // and the tree and variable definition occur in the same class
4785             // definition.  Note that writes don't count as references.
4786             // This check applies only to class and instance
4787             // variables.  Local variables follow different scope rules,
4788             // and are subject to definite assignment checking.
4789             Env<AttrContext> initEnv = enclosingInitEnv(env);
4790             if (initEnv != null &&
4791                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4792                 v.owner.kind == TYP &&
4793                 v.owner == env.info.scope.owner.enclClass() &&
4794                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4795                 (!env.tree.hasTag(ASSIGN) ||
4796                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4797                 if (!onlyWarning || isStaticEnumField(v)) {
4798                     Error errkey = (initEnv.info.enclVar == v) ?
4799                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4800                     log.error(tree.pos(), errkey);
4801                 } else if (useBeforeDeclarationWarning) {
4802                     Warning warnkey = (initEnv.info.enclVar == v) ?
4803                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4804                     log.warning(tree.pos(), warnkey);
4805                 }
4806             }
4807 
4808             v.getConstValue(); // ensure initializer is evaluated
4809 
4810             checkEnumInitializer(tree, env, v);
4811         }
4812 
4813         /**
4814          * Returns the enclosing init environment associated with this env (if any). An init env
4815          * can be either a field declaration env or a static/instance initializer env.
4816          */
4817         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4818             while (true) {
4819                 switch (env.tree.getTag()) {
4820                     case VARDEF:
4821                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4822                         if (vdecl.sym.owner.kind == TYP) {
4823                             //field
4824                             return env;
4825                         }
4826                         break;
4827                     case BLOCK:
4828                         if (env.next.tree.hasTag(CLASSDEF)) {
4829                             //instance/static initializer
4830                             return env;
4831                         }
4832                         break;
4833                     case METHODDEF:
4834                     case CLASSDEF:
4835                     case TOPLEVEL:
4836                         return null;
4837                 }
4838                 Assert.checkNonNull(env.next);
4839                 env = env.next;
4840             }
4841         }
4842 
4843         /**
4844          * Check for illegal references to static members of enum.  In
4845          * an enum type, constructors and initializers may not
4846          * reference its static members unless they are constant.
4847          *
4848          * @param tree    The tree making up the variable reference.
4849          * @param env     The current environment.
4850          * @param v       The variable's symbol.
4851          * @jls 8.9 Enum Types
4852          */
4853         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4854             // JLS:
4855             //
4856             // "It is a compile-time error to reference a static field
4857             // of an enum type that is not a compile-time constant
4858             // (15.28) from constructors, instance initializer blocks,
4859             // or instance variable initializer expressions of that
4860             // type. It is a compile-time error for the constructors,
4861             // instance initializer blocks, or instance variable
4862             // initializer expressions of an enum constant e to refer
4863             // to itself or to an enum constant of the same type that
4864             // is declared to the right of e."
4865             if (isStaticEnumField(v)) {
4866                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4867 
4868                 if (enclClass == null || enclClass.owner == null)
4869                     return;
4870 
4871                 // See if the enclosing class is the enum (or a
4872                 // subclass thereof) declaring v.  If not, this
4873                 // reference is OK.
4874                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4875                     return;
4876 
4877                 // If the reference isn't from an initializer, then
4878                 // the reference is OK.
4879                 if (!Resolve.isInitializer(env))
4880                     return;
4881 
4882                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4883             }
4884         }
4885 
4886         /** Is the given symbol a static, non-constant field of an Enum?
4887          *  Note: enum literals should not be regarded as such
4888          */
4889         private boolean isStaticEnumField(VarSymbol v) {
4890             return Flags.isEnum(v.owner) &&
4891                    Flags.isStatic(v) &&
4892                    !Flags.isConstant(v) &&
4893                    v.name != names._class;
4894         }
4895 
4896     /**
4897      * Check that method arguments conform to its instantiation.
4898      **/
4899     public Type checkMethod(Type site,
4900                             final Symbol sym,
4901                             ResultInfo resultInfo,
4902                             Env<AttrContext> env,
4903                             final List<JCExpression> argtrees,
4904                             List<Type> argtypes,
4905                             List<Type> typeargtypes) {
4906         // Test (5): if symbol is an instance method of a raw type, issue
4907         // an unchecked warning if its argument types change under erasure.
4908         if ((sym.flags() & STATIC) == 0 &&
4909             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4910             Type s = types.asOuterSuper(site, sym.owner);
4911             if (s != null && s.isRaw() &&
4912                 !types.isSameTypes(sym.type.getParameterTypes(),
4913                                    sym.erasure(types).getParameterTypes())) {
4914                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s));
4915             }
4916         }
4917 
4918         if (env.info.defaultSuperCallSite != null) {
4919             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4920                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4921                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4922                 List<MethodSymbol> icand_sup =
4923                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4924                 if (icand_sup.nonEmpty() &&
4925                         icand_sup.head != sym &&
4926                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4927                     log.error(env.tree.pos(),
4928                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4929                     break;
4930                 }
4931             }
4932             env.info.defaultSuperCallSite = null;
4933         }
4934 
4935         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4936             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4937             if (app.meth.hasTag(SELECT) &&
4938                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4939                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4940             }
4941         }
4942 
4943         // Compute the identifier's instantiated type.
4944         // For methods, we need to compute the instance type by
4945         // Resolve.instantiate from the symbol's type as well as
4946         // any type arguments and value arguments.
4947         Warner noteWarner = new Warner();
4948         try {
4949             Type owntype = rs.checkMethod(
4950                     env,
4951                     site,
4952                     sym,
4953                     resultInfo,
4954                     argtypes,
4955                     typeargtypes,
4956                     noteWarner);
4957 
4958             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4959                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4960 
4961             argtypes = argtypes.map(checkDeferredMap);
4962 
4963             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4964                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym),
4965                         sym.name,
4966                         rs.methodArguments(sym.type.getParameterTypes()),
4967                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4968                         kindName(sym.location()),
4969                         sym.location()));
4970                 if (resultInfo.pt != Infer.anyPoly ||
4971                         !owntype.hasTag(METHOD) ||
4972                         !owntype.isPartial()) {
4973                     //if this is not a partially inferred method type, erase return type. Otherwise,
4974                     //erasure is carried out in PartiallyInferredMethodType.check().
4975                     owntype = new MethodType(owntype.getParameterTypes(),
4976                             types.erasure(owntype.getReturnType()),
4977                             types.erasure(owntype.getThrownTypes()),
4978                             syms.methodClass);
4979                 }
4980             }
4981 
4982             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4983                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4984                  PolyKind.POLY : PolyKind.STANDALONE;
4985             TreeInfo.setPolyKind(env.tree, pkind);
4986 
4987             return (resultInfo.pt == Infer.anyPoly) ?
4988                     owntype :
4989                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4990                             resultInfo.checkContext.inferenceContext());
4991         } catch (Infer.InferenceException ex) {
4992             //invalid target type - propagate exception outwards or report error
4993             //depending on the current check context
4994             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4995             return types.createErrorType(site);
4996         } catch (Resolve.InapplicableMethodException ex) {
4997             final JCDiagnostic diag = ex.getDiagnostic();
4998             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4999                 @Override
5000                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5001                     return new Pair<>(sym, diag);
5002                 }
5003             };
5004             List<Type> argtypes2 = argtypes.map(
5005                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5006             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5007                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5008             log.report(errDiag);
5009             return types.createErrorType(site);
5010         }
5011     }
5012 
5013     public void visitLiteral(JCLiteral tree) {
5014         result = check(tree, litType(tree.typetag).constType(tree.value),
5015                 KindSelector.VAL, resultInfo);
5016     }
5017     //where
5018     /** Return the type of a literal with given type tag.
5019      */
5020     Type litType(TypeTag tag) {
5021         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5022     }
5023 
5024     public void visitStringTemplate(JCStringTemplate tree) {
5025         JCExpression processor = tree.processor;
5026         Type resultType = syms.stringTemplateType;
5027 
5028         if (processor != null) {
5029             resultType = attribTree(processor, env, new ResultInfo(KindSelector.VAL, Type.noType));
5030             resultType = chk.checkProcessorType(processor, resultType, env);
5031         }
5032 
5033         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
5034 
5035         for (JCExpression arg : tree.expressions) {
5036             chk.checkNonVoid(arg.pos(), attribExpr(arg, localEnv));
5037         }
5038 
5039         tree.type = resultType;
5040         result = resultType;
5041 
5042         check(tree, resultType, KindSelector.VAL, resultInfo);
5043     }
5044 
5045     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5046         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5047     }
5048 
5049     public void visitTypeArray(JCArrayTypeTree tree) {
5050         Type etype = attribType(tree.elemtype, env);
5051         Type type = new ArrayType(etype, syms.arrayClass);
5052         result = check(tree, type, KindSelector.TYP, resultInfo);
5053     }
5054 
5055     /** Visitor method for parameterized types.
5056      *  Bound checking is left until later, since types are attributed
5057      *  before supertype structure is completely known
5058      */
5059     public void visitTypeApply(JCTypeApply tree) {
5060         Type owntype = types.createErrorType(tree.type);
5061 
5062         // Attribute functor part of application and make sure it's a class.
5063         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5064 
5065         // Attribute type parameters
5066         List<Type> actuals = attribTypes(tree.arguments, env);
5067 
5068         if (clazztype.hasTag(CLASS)) {
5069             List<Type> formals = clazztype.tsym.type.getTypeArguments();
5070             if (actuals.isEmpty()) //diamond
5071                 actuals = formals;
5072 
5073             if (actuals.length() == formals.length()) {
5074                 List<Type> a = actuals;
5075                 List<Type> f = formals;
5076                 while (a.nonEmpty()) {
5077                     a.head = a.head.withTypeVar(f.head);
5078                     a = a.tail;
5079                     f = f.tail;
5080                 }
5081                 // Compute the proper generic outer
5082                 Type clazzOuter = clazztype.getEnclosingType();
5083                 if (clazzOuter.hasTag(CLASS)) {
5084                     Type site;
5085                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5086                     if (clazz.hasTag(IDENT)) {
5087                         site = env.enclClass.sym.type;
5088                     } else if (clazz.hasTag(SELECT)) {
5089                         site = ((JCFieldAccess) clazz).selected.type;
5090                     } else throw new AssertionError(""+tree);
5091                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5092                         if (site.hasTag(CLASS))
5093                             site = types.asOuterSuper(site, clazzOuter.tsym);
5094                         if (site == null)
5095                             site = types.erasure(clazzOuter);
5096                         clazzOuter = site;
5097                     }
5098                 }
5099                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5100                                         clazztype.getMetadata());
5101             } else {
5102                 if (formals.length() != 0) {
5103                     log.error(tree.pos(),
5104                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5105                 } else {
5106                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5107                 }
5108                 owntype = types.createErrorType(tree.type);
5109             }
5110         }
5111         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5112     }
5113 
5114     public void visitTypeUnion(JCTypeUnion tree) {
5115         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5116         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5117         for (JCExpression typeTree : tree.alternatives) {
5118             Type ctype = attribType(typeTree, env);
5119             ctype = chk.checkType(typeTree.pos(),
5120                           chk.checkClassType(typeTree.pos(), ctype),
5121                           syms.throwableType);
5122             if (!ctype.isErroneous()) {
5123                 //check that alternatives of a union type are pairwise
5124                 //unrelated w.r.t. subtyping
5125                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
5126                     for (Type t : multicatchTypes) {
5127                         boolean sub = types.isSubtype(ctype, t);
5128                         boolean sup = types.isSubtype(t, ctype);
5129                         if (sub || sup) {
5130                             //assume 'a' <: 'b'
5131                             Type a = sub ? ctype : t;
5132                             Type b = sub ? t : ctype;
5133                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5134                         }
5135                     }
5136                 }
5137                 multicatchTypes.append(ctype);
5138                 if (all_multicatchTypes != null)
5139                     all_multicatchTypes.append(ctype);
5140             } else {
5141                 if (all_multicatchTypes == null) {
5142                     all_multicatchTypes = new ListBuffer<>();
5143                     all_multicatchTypes.appendList(multicatchTypes);
5144                 }
5145                 all_multicatchTypes.append(ctype);
5146             }
5147         }
5148         Type t = check(tree, types.lub(multicatchTypes.toList()),
5149                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5150         if (t.hasTag(CLASS)) {
5151             List<Type> alternatives =
5152                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5153             t = new UnionClassType((ClassType) t, alternatives);
5154         }
5155         tree.type = result = t;
5156     }
5157 
5158     public void visitTypeIntersection(JCTypeIntersection tree) {
5159         attribTypes(tree.bounds, env);
5160         tree.type = result = checkIntersection(tree, tree.bounds);
5161     }
5162 
5163     public void visitTypeParameter(JCTypeParameter tree) {
5164         TypeVar typeVar = (TypeVar) tree.type;
5165 
5166         if (tree.annotations != null && tree.annotations.nonEmpty()) {
5167             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5168         }
5169 
5170         if (!typeVar.getUpperBound().isErroneous()) {
5171             //fixup type-parameter bound computed in 'attribTypeVariables'
5172             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5173         }
5174     }
5175 
5176     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5177         Set<Symbol> boundSet = new HashSet<>();
5178         if (bounds.nonEmpty()) {
5179             // accept class or interface or typevar as first bound.
5180             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5181             boundSet.add(types.erasure(bounds.head.type).tsym);
5182             if (bounds.head.type.isErroneous()) {
5183                 return bounds.head.type;
5184             }
5185             else if (bounds.head.type.hasTag(TYPEVAR)) {
5186                 // if first bound was a typevar, do not accept further bounds.
5187                 if (bounds.tail.nonEmpty()) {
5188                     log.error(bounds.tail.head.pos(),
5189                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
5190                     return bounds.head.type;
5191                 }
5192             } else {
5193                 // if first bound was a class or interface, accept only interfaces
5194                 // as further bounds.
5195                 for (JCExpression bound : bounds.tail) {
5196                     bound.type = checkBase(bound.type, bound, env, false, true, false);
5197                     if (bound.type.isErroneous()) {
5198                         bounds = List.of(bound);
5199                     }
5200                     else if (bound.type.hasTag(CLASS)) {
5201                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5202                     }
5203                 }
5204             }
5205         }
5206 
5207         if (bounds.length() == 0) {
5208             return syms.objectType;
5209         } else if (bounds.length() == 1) {
5210             return bounds.head.type;
5211         } else {
5212             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5213             // ... the variable's bound is a class type flagged COMPOUND
5214             // (see comment for TypeVar.bound).
5215             // In this case, generate a class tree that represents the
5216             // bound class, ...
5217             JCExpression extending;
5218             List<JCExpression> implementing;
5219             if (!bounds.head.type.isInterface()) {
5220                 extending = bounds.head;
5221                 implementing = bounds.tail;
5222             } else {
5223                 extending = null;
5224                 implementing = bounds;
5225             }
5226             JCClassDecl cd = make.at(tree).ClassDef(
5227                 make.Modifiers(PUBLIC | ABSTRACT),
5228                 names.empty, List.nil(),
5229                 extending, implementing, List.nil());
5230 
5231             ClassSymbol c = (ClassSymbol)owntype.tsym;
5232             Assert.check((c.flags() & COMPOUND) != 0);
5233             cd.sym = c;
5234             c.sourcefile = env.toplevel.sourcefile;
5235 
5236             // ... and attribute the bound class
5237             c.flags_field |= UNATTRIBUTED;
5238             Env<AttrContext> cenv = enter.classEnv(cd, env);
5239             typeEnvs.put(c, cenv);
5240             attribClass(c);
5241             return owntype;
5242         }
5243     }
5244 
5245     public void visitWildcard(JCWildcard tree) {
5246         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5247         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5248             ? syms.objectType
5249             : attribType(tree.inner, env);
5250         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5251                                               tree.kind.kind,
5252                                               syms.boundClass),
5253                 KindSelector.TYP, resultInfo);
5254     }
5255 
5256     public void visitAnnotation(JCAnnotation tree) {
5257         Assert.error("should be handled in annotate");
5258     }
5259 
5260     @Override
5261     public void visitModifiers(JCModifiers tree) {
5262         //error recovery only:
5263         Assert.check(resultInfo.pkind == KindSelector.ERR);
5264 
5265         attribAnnotationTypes(tree.annotations, env);
5266     }
5267 
5268     public void visitAnnotatedType(JCAnnotatedType tree) {
5269         attribAnnotationTypes(tree.annotations, env);
5270         Type underlyingType = attribType(tree.underlyingType, env);
5271         Type annotatedType = underlyingType.preannotatedType();
5272 
5273         if (!env.info.isNewClass)
5274             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5275         result = tree.type = annotatedType;
5276     }
5277 
5278     public void visitErroneous(JCErroneous tree) {
5279         if (tree.errs != null) {
5280             Env<AttrContext> errEnv = env.dup(env.tree, env.info.dup());
5281             errEnv.info.returnResult = unknownExprInfo;
5282             for (JCTree err : tree.errs)
5283                 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5284         }
5285         result = tree.type = syms.errType;
5286     }
5287 
5288     /** Default visitor method for all other trees.
5289      */
5290     public void visitTree(JCTree tree) {
5291         throw new AssertionError();
5292     }
5293 
5294     /**
5295      * Attribute an env for either a top level tree or class or module declaration.
5296      */
5297     public void attrib(Env<AttrContext> env) {
5298         switch (env.tree.getTag()) {
5299             case MODULEDEF:
5300                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5301                 break;
5302             case PACKAGEDEF:
5303                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5304                 break;
5305             default:
5306                 attribClass(env.tree.pos(), env.enclClass.sym);
5307         }
5308     }
5309 
5310     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5311         try {
5312             annotate.flush();
5313             attribPackage(p);
5314         } catch (CompletionFailure ex) {
5315             chk.completionError(pos, ex);
5316         }
5317     }
5318 
5319     void attribPackage(PackageSymbol p) {
5320         attribWithLint(p,
5321                        env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5322     }
5323 
5324     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5325         try {
5326             annotate.flush();
5327             attribModule(m);
5328         } catch (CompletionFailure ex) {
5329             chk.completionError(pos, ex);
5330         }
5331     }
5332 
5333     void attribModule(ModuleSymbol m) {
5334         attribWithLint(m, env -> attribStat(env.tree, env));
5335     }
5336 
5337     private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5338         Env<AttrContext> env = typeEnvs.get(sym);
5339 
5340         Env<AttrContext> lintEnv = env;
5341         while (lintEnv.info.lint == null)
5342             lintEnv = lintEnv.next;
5343 
5344         Lint lint = lintEnv.info.lint.augment(sym);
5345 
5346         Lint prevLint = chk.setLint(lint);
5347         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5348 
5349         try {
5350             deferredLintHandler.flush(env.tree.pos());
5351             attrib.accept(env);
5352         } finally {
5353             log.useSource(prev);
5354             chk.setLint(prevLint);
5355         }
5356     }
5357 
5358     /** Main method: attribute class definition associated with given class symbol.
5359      *  reporting completion failures at the given position.
5360      *  @param pos The source position at which completion errors are to be
5361      *             reported.
5362      *  @param c   The class symbol whose definition will be attributed.
5363      */
5364     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5365         try {
5366             annotate.flush();
5367             attribClass(c);
5368         } catch (CompletionFailure ex) {
5369             chk.completionError(pos, ex);
5370         }
5371     }
5372 
5373     /** Attribute class definition associated with given class symbol.
5374      *  @param c   The class symbol whose definition will be attributed.
5375      */
5376     void attribClass(ClassSymbol c) throws CompletionFailure {
5377         if (c.type.hasTag(ERROR)) return;
5378 
5379         // Check for cycles in the inheritance graph, which can arise from
5380         // ill-formed class files.
5381         chk.checkNonCyclic(null, c.type);
5382 
5383         Type st = types.supertype(c.type);
5384         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5385             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5386             // First, attribute superclass.
5387             if (st.hasTag(CLASS))
5388                 attribClass((ClassSymbol)st.tsym);
5389 
5390             // Next attribute owner, if it is a class.
5391             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5392                 attribClass((ClassSymbol)c.owner);
5393 
5394             c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5395         }
5396 
5397         // The previous operations might have attributed the current class
5398         // if there was a cycle. So we test first whether the class is still
5399         // UNATTRIBUTED.
5400         if ((c.flags_field & UNATTRIBUTED) != 0) {
5401             c.flags_field &= ~UNATTRIBUTED;
5402 
5403             // Get environment current at the point of class definition.
5404             Env<AttrContext> env = typeEnvs.get(c);
5405 
5406             if (c.isSealed() &&
5407                     !c.isEnum() &&
5408                     !c.isPermittedExplicit &&
5409                     c.getPermittedSubclasses().isEmpty()) {
5410                 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5411             }
5412 
5413             if (c.isSealed()) {
5414                 Set<Symbol> permittedTypes = new HashSet<>();
5415                 boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5416                 for (Type subType : c.getPermittedSubclasses()) {
5417                     boolean isTypeVar = false;
5418                     if (subType.getTag() == TYPEVAR) {
5419                         isTypeVar = true; //error recovery
5420                         log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5421                                 Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5422                     }
5423                     if (subType.tsym.isAnonymous() && !c.isEnum()) {
5424                         log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),  Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5425                     }
5426                     if (permittedTypes.contains(subType.tsym)) {
5427                         DiagnosticPosition pos =
5428                                 env.enclClass.permitting.stream()
5429                                         .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5430                                         .limit(2).collect(List.collector()).get(1);
5431                         log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5432                     } else {
5433                         permittedTypes.add(subType.tsym);
5434                     }
5435                     if (sealedInUnnamed) {
5436                         if (subType.tsym.packge() != c.packge()) {
5437                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5438                                     Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5439                             );
5440                         }
5441                     } else if (subType.tsym.packge().modle != c.packge().modle) {
5442                         log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5443                                 Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5444                         );
5445                     }
5446                     if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5447                         log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5448                                 Errors.InvalidPermitsClause(
5449                                         subType.tsym == c.type.tsym ?
5450                                                 Fragments.MustNotBeSameClass :
5451                                                 Fragments.MustNotBeSupertype(subType)
5452                                 )
5453                         );
5454                     } else if (!isTypeVar) {
5455                         boolean thisIsASuper = types.directSupertypes(subType)
5456                                                     .stream()
5457                                                     .anyMatch(d -> d.tsym == c);
5458                         if (!thisIsASuper) {
5459                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5460                                     Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5461                         }
5462                     }
5463                 }
5464             }
5465 
5466             List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5467                                                   .stream()
5468                                                   .filter(s -> s.tsym.isSealed())
5469                                                   .map(s -> (ClassSymbol) s.tsym)
5470                                                   .collect(List.collector());
5471 
5472             if (sealedSupers.isEmpty()) {
5473                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5474                     boolean hasErrorSuper = false;
5475 
5476                     hasErrorSuper |= types.directSupertypes(c.type)
5477                                           .stream()
5478                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5479 
5480                     ClassType ct = (ClassType) c.type;
5481 
5482                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5483 
5484                     if (!hasErrorSuper) {
5485                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5486                     }
5487                 }
5488             } else {
5489                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5490                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5491                 }
5492 
5493                 if (!c.type.isCompound()) {
5494                     for (ClassSymbol supertypeSym : sealedSupers) {
5495                         if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5496                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5497                         }
5498                     }
5499                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5500                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5501                                 c.isInterface() ?
5502                                         Errors.NonSealedOrSealedExpected :
5503                                         Errors.NonSealedSealedOrFinalExpected);
5504                     }
5505                 }
5506             }
5507 
5508             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5509             // because the annotations were not available at the time the env was created. Therefore,
5510             // we look up the environment chain for the first enclosing environment for which the
5511             // lint value is set. Typically, this is the parent env, but might be further if there
5512             // are any envs created as a result of TypeParameter nodes.
5513             Env<AttrContext> lintEnv = env;
5514             while (lintEnv.info.lint == null)
5515                 lintEnv = lintEnv.next;
5516 
5517             // Having found the enclosing lint value, we can initialize the lint value for this class
5518             env.info.lint = lintEnv.info.lint.augment(c);
5519 
5520             Lint prevLint = chk.setLint(env.info.lint);
5521             JavaFileObject prev = log.useSource(c.sourcefile);
5522             ResultInfo prevReturnRes = env.info.returnResult;
5523 
5524             try {
5525                 deferredLintHandler.flush(env.tree);
5526                 env.info.returnResult = null;
5527                 // java.lang.Enum may not be subclassed by a non-enum
5528                 if (st.tsym == syms.enumSym &&
5529                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5530                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5531 
5532                 // Enums may not be extended by source-level classes
5533                 if (st.tsym != null &&
5534                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5535                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5536                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5537                 }
5538 
5539                 if (rs.isSerializable(c.type)) {
5540                     env.info.isSerializable = true;
5541                 }
5542 
5543                 attribClassBody(env, c);
5544 
5545                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5546                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5547                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5548                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5549 
5550                 if ((c.flags_field & Flags.UNNAMED_CLASS) != 0) {
5551                     chk.checkHasMain(env.tree.pos(), c);
5552                 }
5553             } finally {
5554                 env.info.returnResult = prevReturnRes;
5555                 log.useSource(prev);
5556                 chk.setLint(prevLint);
5557             }
5558 
5559         }
5560     }
5561 
5562     public void visitImport(JCImport tree) {
5563         // nothing to do
5564     }
5565 
5566     public void visitModuleDef(JCModuleDecl tree) {
5567         tree.sym.completeUsesProvides();
5568         ModuleSymbol msym = tree.sym;
5569         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5570         Lint prevLint = chk.setLint(lint);
5571         chk.checkModuleName(tree);
5572         chk.checkDeprecatedAnnotation(tree, msym);
5573 
5574         try {
5575             deferredLintHandler.flush(tree.pos());
5576         } finally {
5577             chk.setLint(prevLint);
5578         }
5579     }
5580 
5581     /** Finish the attribution of a class. */
5582     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5583         JCClassDecl tree = (JCClassDecl)env.tree;
5584         Assert.check(c == tree.sym);
5585 
5586         // Validate type parameters, supertype and interfaces.
5587         attribStats(tree.typarams, env);
5588         if (!c.isAnonymous()) {
5589             //already checked if anonymous
5590             chk.validate(tree.typarams, env);
5591             chk.validate(tree.extending, env);
5592             chk.validate(tree.implementing, env);
5593         }
5594 
5595         c.markAbstractIfNeeded(types);
5596 
5597         // If this is a non-abstract class, check that it has no abstract
5598         // methods or unimplemented methods of an implemented interface.
5599         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
5600             chk.checkAllDefined(tree.pos(), c);
5601         }
5602 
5603         if ((c.flags() & ANNOTATION) != 0) {
5604             if (tree.implementing.nonEmpty())
5605                 log.error(tree.implementing.head.pos(),
5606                           Errors.CantExtendIntfAnnotation);
5607             if (tree.typarams.nonEmpty()) {
5608                 log.error(tree.typarams.head.pos(),
5609                           Errors.IntfAnnotationCantHaveTypeParams(c));
5610             }
5611 
5612             // If this annotation type has a @Repeatable, validate
5613             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
5614             // If this annotation type has a @Repeatable, validate
5615             if (repeatable != null) {
5616                 // get diagnostic position for error reporting
5617                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
5618                 Assert.checkNonNull(cbPos);
5619 
5620                 chk.validateRepeatable(c, repeatable, cbPos);
5621             }
5622         } else {
5623             // Check that all extended classes and interfaces
5624             // are compatible (i.e. no two define methods with same arguments
5625             // yet different return types).  (JLS 8.4.8.3)
5626             chk.checkCompatibleSupertypes(tree.pos(), c.type);
5627             chk.checkDefaultMethodClashes(tree.pos(), c.type);
5628             chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
5629         }
5630 
5631         // Check that class does not import the same parameterized interface
5632         // with two different argument lists.
5633         chk.checkClassBounds(tree.pos(), c.type);
5634 
5635         tree.type = c.type;
5636 
5637         for (List<JCTypeParameter> l = tree.typarams;
5638              l.nonEmpty(); l = l.tail) {
5639              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
5640         }
5641 
5642         // Check that a generic class doesn't extend Throwable
5643         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
5644             log.error(tree.extending.pos(), Errors.GenericThrowable);
5645 
5646         // Check that all methods which implement some
5647         // method conform to the method they implement.
5648         chk.checkImplementations(tree);
5649 
5650         //check that a resource implementing AutoCloseable cannot throw InterruptedException
5651         checkAutoCloseable(tree.pos(), env, c.type);
5652 
5653         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
5654             // Attribute declaration
5655             attribStat(l.head, env);
5656             // Check that declarations in inner classes are not static (JLS 8.1.2)
5657             // Make an exception for static constants.
5658             if (!allowRecords &&
5659                     c.owner.kind != PCK &&
5660                     ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
5661                     (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
5662                 VarSymbol sym = null;
5663                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
5664                 if (sym == null ||
5665                         sym.kind != VAR ||
5666                         sym.getConstValue() == null)
5667                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5668             }
5669         }
5670 
5671         // Check for cycles among non-initial constructors.
5672         chk.checkCyclicConstructors(tree);
5673 
5674         // Check for cycles among annotation elements.
5675         chk.checkNonCyclicElements(tree);
5676 
5677         // Check for proper use of serialVersionUID and other
5678         // serialization-related fields and methods
5679         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5680                 && rs.isSerializable(c.type)
5681                 && !c.isAnonymous()) {
5682             chk.checkSerialStructure(tree, c);
5683         }
5684         // Correctly organize the positions of the type annotations
5685         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5686 
5687         // Check type annotations applicability rules
5688         validateTypeAnnotations(tree, false);
5689     }
5690         // where
5691         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5692         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5693             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5694                 if (types.isSameType(al.head.annotationType.type, t))
5695                     return al.head.pos();
5696             }
5697 
5698             return null;
5699         }
5700 
5701     private Type capture(Type type) {
5702         return types.capture(type);
5703     }
5704 
5705     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
5706         if (type.isErroneous()) {
5707             tree.vartype = make.at(Position.NOPOS).Erroneous();
5708         } else {
5709             tree.vartype = make.at(Position.NOPOS).Type(type);
5710         }
5711     }
5712 
5713     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
5714         tree.accept(new TypeAnnotationsValidator(sigOnly));
5715     }
5716     //where
5717     private final class TypeAnnotationsValidator extends TreeScanner {
5718 
5719         private final boolean sigOnly;
5720         public TypeAnnotationsValidator(boolean sigOnly) {
5721             this.sigOnly = sigOnly;
5722         }
5723 
5724         public void visitAnnotation(JCAnnotation tree) {
5725             chk.validateTypeAnnotation(tree, null, false);
5726             super.visitAnnotation(tree);
5727         }
5728         public void visitAnnotatedType(JCAnnotatedType tree) {
5729             if (!tree.underlyingType.type.isErroneous()) {
5730                 super.visitAnnotatedType(tree);
5731             }
5732         }
5733         public void visitTypeParameter(JCTypeParameter tree) {
5734             chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
5735             scan(tree.bounds);
5736             // Don't call super.
5737             // This is needed because above we call validateTypeAnnotation with
5738             // false, which would forbid annotations on type parameters.
5739             // super.visitTypeParameter(tree);
5740         }
5741         public void visitMethodDef(JCMethodDecl tree) {
5742             if (tree.recvparam != null &&
5743                     !tree.recvparam.vartype.type.isErroneous()) {
5744                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
5745             }
5746             if (tree.restype != null && tree.restype.type != null) {
5747                 validateAnnotatedType(tree.restype, tree.restype.type);
5748             }
5749             if (sigOnly) {
5750                 scan(tree.mods);
5751                 scan(tree.restype);
5752                 scan(tree.typarams);
5753                 scan(tree.recvparam);
5754                 scan(tree.params);
5755                 scan(tree.thrown);
5756             } else {
5757                 scan(tree.defaultValue);
5758                 scan(tree.body);
5759             }
5760         }
5761         public void visitVarDef(final JCVariableDecl tree) {
5762             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
5763             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
5764                 validateAnnotatedType(tree.vartype, tree.sym.type);
5765             scan(tree.mods);
5766             scan(tree.vartype);
5767             if (!sigOnly) {
5768                 scan(tree.init);
5769             }
5770         }
5771         public void visitTypeCast(JCTypeCast tree) {
5772             if (tree.clazz != null && tree.clazz.type != null)
5773                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5774             super.visitTypeCast(tree);
5775         }
5776         public void visitTypeTest(JCInstanceOf tree) {
5777             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
5778                 validateAnnotatedType(tree.pattern, tree.pattern.type);
5779             super.visitTypeTest(tree);
5780         }
5781         public void visitNewClass(JCNewClass tree) {
5782             if (tree.clazz != null && tree.clazz.type != null) {
5783                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5784                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5785                             tree.clazz.type.tsym);
5786                 }
5787                 if (tree.def != null) {
5788                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5789                 }
5790 
5791                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5792             }
5793             super.visitNewClass(tree);
5794         }
5795         public void visitNewArray(JCNewArray tree) {
5796             if (tree.elemtype != null && tree.elemtype.type != null) {
5797                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5798                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5799                             tree.elemtype.type.tsym);
5800                 }
5801                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5802             }
5803             super.visitNewArray(tree);
5804         }
5805         public void visitClassDef(JCClassDecl tree) {
5806             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5807             if (sigOnly) {
5808                 scan(tree.mods);
5809                 scan(tree.typarams);
5810                 scan(tree.extending);
5811                 scan(tree.implementing);
5812             }
5813             for (JCTree member : tree.defs) {
5814                 if (member.hasTag(Tag.CLASSDEF)) {
5815                     continue;
5816                 }
5817                 scan(member);
5818             }
5819         }
5820         public void visitBlock(JCBlock tree) {
5821             if (!sigOnly) {
5822                 scan(tree.stats);
5823             }
5824         }
5825 
5826         /* I would want to model this after
5827          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5828          * and override visitSelect and visitTypeApply.
5829          * However, we only set the annotated type in the top-level type
5830          * of the symbol.
5831          * Therefore, we need to override each individual location where a type
5832          * can occur.
5833          */
5834         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5835             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5836 
5837             if (type.isPrimitiveOrVoid()) {
5838                 return;
5839             }
5840 
5841             JCTree enclTr = errtree;
5842             Type enclTy = type;
5843 
5844             boolean repeat = true;
5845             while (repeat) {
5846                 if (enclTr.hasTag(TYPEAPPLY)) {
5847                     List<Type> tyargs = enclTy.getTypeArguments();
5848                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5849                     if (trargs.length() > 0) {
5850                         // Nothing to do for diamonds
5851                         if (tyargs.length() == trargs.length()) {
5852                             for (int i = 0; i < tyargs.length(); ++i) {
5853                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5854                             }
5855                         }
5856                         // If the lengths don't match, it's either a diamond
5857                         // or some nested type that redundantly provides
5858                         // type arguments in the tree.
5859                     }
5860 
5861                     // Look at the clazz part of a generic type
5862                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5863                 }
5864 
5865                 if (enclTr.hasTag(SELECT)) {
5866                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5867                     if (enclTy != null &&
5868                             !enclTy.hasTag(NONE)) {
5869                         enclTy = enclTy.getEnclosingType();
5870                     }
5871                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5872                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5873                     if (enclTy == null || enclTy.hasTag(NONE)) {
5874                         if (at.getAnnotations().size() == 1) {
5875                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping1(at.getAnnotations().head.attribute));
5876                         } else {
5877                             ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
5878                             for (JCAnnotation an : at.getAnnotations()) {
5879                                 comps.add(an.attribute);
5880                             }
5881                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping(comps.toList()));
5882                         }
5883                         repeat = false;
5884                     }
5885                     enclTr = at.underlyingType;
5886                     // enclTy doesn't need to be changed
5887                 } else if (enclTr.hasTag(IDENT)) {
5888                     repeat = false;
5889                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5890                     JCWildcard wc = (JCWildcard) enclTr;
5891                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5892                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5893                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5894                     } else {
5895                         // Nothing to do for UNBOUND
5896                     }
5897                     repeat = false;
5898                 } else if (enclTr.hasTag(TYPEARRAY)) {
5899                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5900                     validateAnnotatedType(art.getType(), art.elemtype.type);
5901                     repeat = false;
5902                 } else if (enclTr.hasTag(TYPEUNION)) {
5903                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5904                     for (JCTree t : ut.getTypeAlternatives()) {
5905                         validateAnnotatedType(t, t.type);
5906                     }
5907                     repeat = false;
5908                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5909                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5910                     for (JCTree t : it.getBounds()) {
5911                         validateAnnotatedType(t, t.type);
5912                     }
5913                     repeat = false;
5914                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5915                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5916                     repeat = false;
5917                 } else {
5918                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5919                             " within: "+ errtree + " with kind: " + errtree.getKind());
5920                 }
5921             }
5922         }
5923 
5924         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5925                 Symbol sym) {
5926             // Ensure that no declaration annotations are present.
5927             // Note that a tree type might be an AnnotatedType with
5928             // empty annotations, if only declaration annotations were given.
5929             // This method will raise an error for such a type.
5930             for (JCAnnotation ai : annotations) {
5931                 if (!ai.type.isErroneous() &&
5932                         typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5933                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5934                 }
5935             }
5936         }
5937     }
5938 
5939     // <editor-fold desc="post-attribution visitor">
5940 
5941     /**
5942      * Handle missing types/symbols in an AST. This routine is useful when
5943      * the compiler has encountered some errors (which might have ended up
5944      * terminating attribution abruptly); if the compiler is used in fail-over
5945      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5946      * prevents NPE to be propagated during subsequent compilation steps.
5947      */
5948     public void postAttr(JCTree tree) {
5949         new PostAttrAnalyzer().scan(tree);
5950     }
5951 
5952     class PostAttrAnalyzer extends TreeScanner {
5953 
5954         private void initTypeIfNeeded(JCTree that) {
5955             if (that.type == null) {
5956                 if (that.hasTag(METHODDEF)) {
5957                     that.type = dummyMethodType((JCMethodDecl)that);
5958                 } else {
5959                     that.type = syms.unknownType;
5960                 }
5961             }
5962         }
5963 
5964         /* Construct a dummy method type. If we have a method declaration,
5965          * and the declared return type is void, then use that return type
5966          * instead of UNKNOWN to avoid spurious error messages in lambda
5967          * bodies (see:JDK-8041704).
5968          */
5969         private Type dummyMethodType(JCMethodDecl md) {
5970             Type restype = syms.unknownType;
5971             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5972                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5973                 if (prim.typetag == VOID)
5974                     restype = syms.voidType;
5975             }
5976             return new MethodType(List.nil(), restype,
5977                                   List.nil(), syms.methodClass);
5978         }
5979         private Type dummyMethodType() {
5980             return dummyMethodType(null);
5981         }
5982 
5983         @Override
5984         public void scan(JCTree tree) {
5985             if (tree == null) return;
5986             if (tree instanceof JCExpression) {
5987                 initTypeIfNeeded(tree);
5988             }
5989             super.scan(tree);
5990         }
5991 
5992         @Override
5993         public void visitIdent(JCIdent that) {
5994             if (that.sym == null) {
5995                 that.sym = syms.unknownSymbol;
5996             }
5997         }
5998 
5999         @Override
6000         public void visitSelect(JCFieldAccess that) {
6001             if (that.sym == null) {
6002                 that.sym = syms.unknownSymbol;
6003             }
6004             super.visitSelect(that);
6005         }
6006 
6007         @Override
6008         public void visitClassDef(JCClassDecl that) {
6009             initTypeIfNeeded(that);
6010             if (that.sym == null) {
6011                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6012             }
6013             super.visitClassDef(that);
6014         }
6015 
6016         @Override
6017         public void visitMethodDef(JCMethodDecl that) {
6018             initTypeIfNeeded(that);
6019             if (that.sym == null) {
6020                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6021             }
6022             super.visitMethodDef(that);
6023         }
6024 
6025         @Override
6026         public void visitVarDef(JCVariableDecl that) {
6027             initTypeIfNeeded(that);
6028             if (that.sym == null) {
6029                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6030                 that.sym.adr = 0;
6031             }
6032             if (that.vartype == null) {
6033                 that.vartype = make.at(Position.NOPOS).Erroneous();
6034             }
6035             super.visitVarDef(that);
6036         }
6037 
6038         @Override
6039         public void visitBindingPattern(JCBindingPattern that) {
6040             initTypeIfNeeded(that);
6041             initTypeIfNeeded(that.var);
6042             if (that.var.sym == null) {
6043                 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6044                 that.var.sym.adr = 0;
6045             }
6046             super.visitBindingPattern(that);
6047         }
6048 
6049         @Override
6050         public void visitNewClass(JCNewClass that) {
6051             if (that.constructor == null) {
6052                 that.constructor = new MethodSymbol(0, names.init,
6053                         dummyMethodType(), syms.noSymbol);
6054             }
6055             if (that.constructorType == null) {
6056                 that.constructorType = syms.unknownType;
6057             }
6058             super.visitNewClass(that);
6059         }
6060 
6061         @Override
6062         public void visitAssignop(JCAssignOp that) {
6063             if (that.operator == null) {
6064                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6065                         -1, syms.noSymbol);
6066             }
6067             super.visitAssignop(that);
6068         }
6069 
6070         @Override
6071         public void visitBinary(JCBinary that) {
6072             if (that.operator == null) {
6073                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6074                         -1, syms.noSymbol);
6075             }
6076             super.visitBinary(that);
6077         }
6078 
6079         @Override
6080         public void visitUnary(JCUnary that) {
6081             if (that.operator == null) {
6082                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6083                         -1, syms.noSymbol);
6084             }
6085             super.visitUnary(that);
6086         }
6087 
6088         @Override
6089         public void visitReference(JCMemberReference that) {
6090             super.visitReference(that);
6091             if (that.sym == null) {
6092                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6093                         syms.noSymbol);
6094             }
6095         }
6096     }
6097     // </editor-fold>
6098 
6099     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6100         new TreeScanner() {
6101             Symbol packge = pkg;
6102             @Override
6103             public void visitIdent(JCIdent that) {
6104                 that.sym = packge;
6105             }
6106 
6107             @Override
6108             public void visitSelect(JCFieldAccess that) {
6109                 that.sym = packge;
6110                 packge = packge.owner;
6111                 super.visitSelect(that);
6112             }
6113         }.scan(pid);
6114     }
6115 
6116 }