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