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