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