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