1 /*
   2  * Copyright (c) 1999, 2025, 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.LintWarnings;
  62 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  63 import com.sun.tools.javac.tree.*;
  64 import com.sun.tools.javac.tree.JCTree.*;
  65 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  66 import com.sun.tools.javac.util.*;
  67 import com.sun.tools.javac.util.DefinedBy.Api;
  68 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  69 import com.sun.tools.javac.util.JCDiagnostic.Error;
  70 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  71 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  72 import com.sun.tools.javac.util.List;
  73 
  74 import static com.sun.tools.javac.code.Flags.*;
  75 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  76 import static com.sun.tools.javac.code.Flags.BLOCK;
  77 import static com.sun.tools.javac.code.Kinds.*;
  78 import static com.sun.tools.javac.code.Kinds.Kind.*;
  79 import static com.sun.tools.javac.code.TypeTag.*;
  80 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  82 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  83 
  84 /** This is the main context-dependent analysis phase in GJC. It
  85  *  encompasses name resolution, type checking and constant folding as
  86  *  subtasks. Some subtasks involve auxiliary classes.
  87  *  @see Check
  88  *  @see Resolve
  89  *  @see ConstFold
  90  *  @see Infer
  91  *
  92  *  <p><b>This is NOT part of any supported API.
  93  *  If you write code that depends on this, you do so at your own risk.
  94  *  This code and its internal interfaces are subject to change or
  95  *  deletion without notice.</b>
  96  */
  97 public class Attr extends JCTree.Visitor {
  98     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
  99 
 100     final Names names;
 101     final Log log;
 102     final Symtab syms;
 103     final Resolve rs;
 104     final Operators operators;
 105     final Infer infer;
 106     final Analyzer analyzer;
 107     final DeferredAttr deferredAttr;
 108     final Check chk;
 109     final Flow flow;
 110     final MemberEnter memberEnter;
 111     final TypeEnter typeEnter;
 112     final TreeMaker make;
 113     final ConstFold cfolder;
 114     final Enter enter;
 115     final Target target;
 116     final Types types;
 117     final Preview preview;
 118     final JCDiagnostic.Factory diags;
 119     final TypeAnnotations typeAnnotations;
 120     final DeferredLintHandler deferredLintHandler;
 121     final TypeEnvs typeEnvs;
 122     final Dependencies dependencies;
 123     final Annotate annotate;
 124     final ArgumentAttr argumentAttr;
 125     final MatchBindingsComputer matchBindingsComputer;
 126     final AttrRecover attrRecover;
 127 
 128     public static Attr instance(Context context) {
 129         Attr instance = context.get(attrKey);
 130         if (instance == null)
 131             instance = new Attr(context);
 132         return instance;
 133     }
 134 
 135     @SuppressWarnings("this-escape")
 136     protected Attr(Context context) {
 137         context.put(attrKey, this);
 138 
 139         names = Names.instance(context);
 140         log = Log.instance(context);
 141         syms = Symtab.instance(context);
 142         rs = Resolve.instance(context);
 143         operators = Operators.instance(context);
 144         chk = Check.instance(context);
 145         flow = Flow.instance(context);
 146         memberEnter = MemberEnter.instance(context);
 147         typeEnter = TypeEnter.instance(context);
 148         make = TreeMaker.instance(context);
 149         enter = Enter.instance(context);
 150         infer = Infer.instance(context);
 151         analyzer = Analyzer.instance(context);
 152         deferredAttr = DeferredAttr.instance(context);
 153         cfolder = ConstFold.instance(context);
 154         target = Target.instance(context);
 155         types = Types.instance(context);
 156         preview = Preview.instance(context);
 157         diags = JCDiagnostic.Factory.instance(context);
 158         annotate = Annotate.instance(context);
 159         typeAnnotations = TypeAnnotations.instance(context);
 160         deferredLintHandler = DeferredLintHandler.instance(context);
 161         typeEnvs = TypeEnvs.instance(context);
 162         dependencies = Dependencies.instance(context);
 163         argumentAttr = ArgumentAttr.instance(context);
 164         matchBindingsComputer = MatchBindingsComputer.instance(context);
 165         attrRecover = AttrRecover.instance(context);
 166 
 167         Options options = Options.instance(context);
 168 
 169         Source source = Source.instance(context);
 170         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 171         allowRecords = Feature.RECORDS.allowedInSource(source);
 172         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 173                              Feature.PATTERN_SWITCH.allowedInSource(source);
 174         allowUnconditionalPatternsInstanceOf =
 175                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 176         sourceName = source.name;
 177         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 178 
 179         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 180         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 181         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 182         methodAttrInfo = new MethodAttrInfo();
 183         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 184         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 185         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 186         initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
 187     }
 188 
 189     /** Switch: reifiable types in instanceof enabled?
 190      */
 191     boolean allowReifiableTypesInInstanceof;
 192 
 193     /** Are records allowed
 194      */
 195     private final boolean allowRecords;
 196 
 197     /** Are patterns in switch allowed
 198      */
 199     private final boolean allowPatternSwitch;
 200 
 201     /** Are unconditional patterns in instanceof allowed
 202      */
 203     private final boolean allowUnconditionalPatternsInstanceOf;
 204 
 205     /**
 206      * Switch: warn about use of variable before declaration?
 207      * RFE: 6425594
 208      */
 209     boolean useBeforeDeclarationWarning;
 210 
 211     /**
 212      * Switch: name of source level; used for error reporting.
 213      */
 214     String sourceName;
 215 
 216     /** Check kind and type of given tree against protokind and prototype.
 217      *  If check succeeds, store type in tree and return it.
 218      *  If check fails, store errType in tree and return it.
 219      *  No checks are performed if the prototype is a method type.
 220      *  It is not necessary in this case since we know that kind and type
 221      *  are correct.
 222      *
 223      *  @param tree     The tree whose kind and type is checked
 224      *  @param found    The computed type of the tree
 225      *  @param ownkind  The computed kind of the tree
 226      *  @param resultInfo  The expected result of the tree
 227      */
 228     Type check(final JCTree tree,
 229                final Type found,
 230                final KindSelector ownkind,
 231                final ResultInfo resultInfo) {
 232         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 233         Type owntype;
 234         boolean shouldCheck = !found.hasTag(ERROR) &&
 235                 !resultInfo.pt.hasTag(METHOD) &&
 236                 !resultInfo.pt.hasTag(FORALL);
 237         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 238             log.error(tree.pos(),
 239                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 240                                             ownkind.kindNames()));
 241             owntype = types.createErrorType(found);
 242         } else if (inferenceContext.free(found)) {
 243             //delay the check if there are inference variables in the found type
 244             //this means we are dealing with a partially inferred poly expression
 245             owntype = shouldCheck ? resultInfo.pt : found;
 246             if (resultInfo.checkMode.installPostInferenceHook()) {
 247                 inferenceContext.addFreeTypeListener(List.of(found),
 248                         instantiatedContext -> {
 249                             ResultInfo pendingResult =
 250                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 251                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 252                         });
 253             }
 254         } else {
 255             owntype = shouldCheck ?
 256             resultInfo.check(tree, found) :
 257             found;
 258         }
 259         if (resultInfo.checkMode.updateTreeType()) {
 260             tree.type = owntype;
 261         }
 262         return owntype;
 263     }
 264 
 265     /** Is given blank final variable assignable, i.e. in a scope where it
 266      *  may be assigned to even though it is final?
 267      *  @param v      The blank final variable.
 268      *  @param env    The current environment.
 269      */
 270     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 271         Symbol owner = env.info.scope.owner;
 272            // owner refers to the innermost variable, method or
 273            // initializer block declaration at this point.
 274         boolean isAssignable =
 275             v.owner == owner
 276             ||
 277             ((owner.name == names.init ||    // i.e. we are in a constructor
 278               owner.kind == VAR ||           // i.e. we are in a variable initializer
 279               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 280              &&
 281              v.owner == owner.owner
 282              &&
 283              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 284         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 285         return isAssignable & !insideCompactConstructor;
 286     }
 287 
 288     /** Check that variable can be assigned to.
 289      *  @param pos    The current source code position.
 290      *  @param v      The assigned variable
 291      *  @param base   If the variable is referred to in a Select, the part
 292      *                to the left of the `.', null otherwise.
 293      *  @param env    The current environment.
 294      */
 295     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 296         if (v.name == names._this) {
 297             log.error(pos, Errors.CantAssignValToThis);
 298             return;
 299         }
 300         if ((v.flags() & FINAL) != 0 &&
 301             ((v.flags() & HASINIT) != 0
 302              ||
 303              !((base == null ||
 304                TreeInfo.isThisQualifier(base)) &&
 305                isAssignableAsBlankFinal(v, env)))) {
 306             if (v.isResourceVariable()) { //TWR resource
 307                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 308             } else {
 309                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 310             }
 311             return;
 312         }
 313 
 314         // Check instance field assignments that appear in constructor prologues
 315         if (rs.isEarlyReference(env, base, v)) {
 316 
 317             // Field may not be inherited from a superclass
 318             if (v.owner != env.enclClass.sym) {
 319                 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
 320                 return;
 321             }
 322 
 323             // Field may not have an initializer
 324             if ((v.flags() & HASINIT) != 0) {
 325                 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
 326                 return;
 327             }
 328         }










 329     }
 330 
 331     /** Does tree represent a static reference to an identifier?
 332      *  It is assumed that tree is either a SELECT or an IDENT.
 333      *  We have to weed out selects from non-type names here.
 334      *  @param tree    The candidate tree.
 335      */
 336     boolean isStaticReference(JCTree tree) {
 337         if (tree.hasTag(SELECT)) {
 338             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 339             if (lsym == null || lsym.kind != TYP) {
 340                 return false;
 341             }
 342         }
 343         return true;
 344     }
 345 
 346     /** Is this symbol a type?
 347      */
 348     static boolean isType(Symbol sym) {
 349         return sym != null && sym.kind == TYP;
 350     }
 351 
 352     /** Attribute a parsed identifier.
 353      * @param tree Parsed identifier name
 354      * @param topLevel The toplevel to use
 355      */
 356     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 357         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 358         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 359                                            syms.errSymbol.name,
 360                                            null, null, null, null);
 361         localEnv.enclClass.sym = syms.errSymbol;
 362         return attribIdent(tree, localEnv);
 363     }
 364 
 365     /** Attribute a parsed identifier.
 366      * @param tree Parsed identifier name
 367      * @param env The env to use
 368      */
 369     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
 370         return tree.accept(identAttributer, env);
 371     }
 372     // where
 373         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 374         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 375             @Override @DefinedBy(Api.COMPILER_TREE)
 376             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 377                 Symbol site = visit(node.getExpression(), env);
 378                 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
 379                     return site;
 380                 Name name = (Name)node.getIdentifier();
 381                 if (site.kind == PCK) {
 382                     env.toplevel.packge = (PackageSymbol)site;
 383                     return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
 384                             KindSelector.TYP_PCK);
 385                 } else {
 386                     env.enclClass.sym = (ClassSymbol)site;
 387                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 388                 }
 389             }
 390 
 391             @Override @DefinedBy(Api.COMPILER_TREE)
 392             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 393                 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
 394             }
 395         }
 396 
 397     public Type coerce(Type etype, Type ttype) {
 398         return cfolder.coerce(etype, ttype);
 399     }
 400 
 401     public Type attribType(JCTree node, TypeSymbol sym) {
 402         Env<AttrContext> env = typeEnvs.get(sym);
 403         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 404         return attribTree(node, localEnv, unknownTypeInfo);
 405     }
 406 
 407     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
 408         // Attribute qualifying package or class.
 409         JCFieldAccess s = tree.qualid;
 410         return attribTree(s.selected, env,
 411                           new ResultInfo(tree.staticImport ?
 412                                          KindSelector.TYP : KindSelector.TYP_PCK,
 413                        Type.noType));
 414     }
 415 
 416     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 417         return attribToTree(expr, env, tree, unknownExprInfo);
 418     }
 419 
 420     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 421         return attribToTree(stmt, env, tree, statInfo);
 422     }
 423 
 424     private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) {
 425         breakTree = tree;
 426         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 427         try {
 428             deferredAttr.attribSpeculative(root, env, resultInfo,
 429                     null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE,
 430                     argumentAttr.withLocalCacheContext());
 431             attrRecover.doRecovery();
 432         } catch (BreakAttr b) {
 433             return b.env;
 434         } catch (AssertionError ae) {
 435             if (ae.getCause() instanceof BreakAttr breakAttr) {
 436                 return breakAttr.env;
 437             } else {
 438                 throw ae;
 439             }
 440         } finally {
 441             breakTree = null;
 442             log.useSource(prev);
 443         }
 444         return env;
 445     }
 446 
 447     private JCTree breakTree = null;
 448 
 449     private static class BreakAttr extends RuntimeException {
 450         static final long serialVersionUID = -6924771130405446405L;
 451         private transient Env<AttrContext> env;
 452         private BreakAttr(Env<AttrContext> env) {
 453             this.env = env;
 454         }
 455     }
 456 
 457     /**
 458      * Mode controlling behavior of Attr.Check
 459      */
 460     enum CheckMode {
 461 
 462         NORMAL,
 463 
 464         /**
 465          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
 466          * that the captured var cache in {@code InferenceContext} will be used in read-only
 467          * mode when performing inference checks.
 468          */
 469         NO_TREE_UPDATE {
 470             @Override
 471             public boolean updateTreeType() {
 472                 return false;
 473             }
 474         },
 475         /**
 476          * Mode signalling that caller will manage free types in tree decorations.
 477          */
 478         NO_INFERENCE_HOOK {
 479             @Override
 480             public boolean installPostInferenceHook() {
 481                 return false;
 482             }
 483         };
 484 
 485         public boolean updateTreeType() {
 486             return true;
 487         }
 488         public boolean installPostInferenceHook() {
 489             return true;
 490         }
 491     }
 492 
 493 
 494     class ResultInfo {
 495         final KindSelector pkind;
 496         final Type pt;
 497         final CheckContext checkContext;
 498         final CheckMode checkMode;
 499 
 500         ResultInfo(KindSelector pkind, Type pt) {
 501             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
 502         }
 503 
 504         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
 505             this(pkind, pt, chk.basicHandler, checkMode);
 506         }
 507 
 508         protected ResultInfo(KindSelector pkind,
 509                              Type pt, CheckContext checkContext) {
 510             this(pkind, pt, checkContext, CheckMode.NORMAL);
 511         }
 512 
 513         protected ResultInfo(KindSelector pkind,
 514                              Type pt, CheckContext checkContext, CheckMode checkMode) {
 515             this.pkind = pkind;
 516             this.pt = pt;
 517             this.checkContext = checkContext;
 518             this.checkMode = checkMode;
 519         }
 520 
 521         /**
 522          * Should {@link Attr#attribTree} use the {@code ArgumentAttr} visitor instead of this one?
 523          * @param tree The tree to be type-checked.
 524          * @return true if {@code ArgumentAttr} should be used.
 525          */
 526         protected boolean needsArgumentAttr(JCTree tree) { return false; }
 527 
 528         protected Type check(final DiagnosticPosition pos, final Type found) {
 529             return chk.checkType(pos, found, pt, checkContext);
 530         }
 531 
 532         protected ResultInfo dup(Type newPt) {
 533             return new ResultInfo(pkind, newPt, checkContext, checkMode);
 534         }
 535 
 536         protected ResultInfo dup(CheckContext newContext) {
 537             return new ResultInfo(pkind, pt, newContext, checkMode);
 538         }
 539 
 540         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 541             return new ResultInfo(pkind, newPt, newContext, checkMode);
 542         }
 543 
 544         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 545             return new ResultInfo(pkind, newPt, newContext, newMode);
 546         }
 547 
 548         protected ResultInfo dup(CheckMode newMode) {
 549             return new ResultInfo(pkind, pt, checkContext, newMode);
 550         }
 551 
 552         @Override
 553         public String toString() {
 554             if (pt != null) {
 555                 return pt.toString();
 556             } else {
 557                 return "";
 558             }
 559         }
 560     }
 561 
 562     class MethodAttrInfo extends ResultInfo {
 563         public MethodAttrInfo() {
 564             this(chk.basicHandler);
 565         }
 566 
 567         public MethodAttrInfo(CheckContext checkContext) {
 568             super(KindSelector.VAL, Infer.anyPoly, checkContext);
 569         }
 570 
 571         @Override
 572         protected boolean needsArgumentAttr(JCTree tree) {
 573             return true;
 574         }
 575 
 576         protected ResultInfo dup(Type newPt) {
 577             throw new IllegalStateException();
 578         }
 579 
 580         protected ResultInfo dup(CheckContext newContext) {
 581             return new MethodAttrInfo(newContext);
 582         }
 583 
 584         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 585             throw new IllegalStateException();
 586         }
 587 
 588         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 589             throw new IllegalStateException();
 590         }
 591 
 592         protected ResultInfo dup(CheckMode newMode) {
 593             throw new IllegalStateException();
 594         }
 595     }
 596 
 597     class RecoveryInfo extends ResultInfo {
 598 
 599         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
 600             this(deferredAttrContext, Type.recoveryType);
 601         }
 602 
 603         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
 604             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
 605                 @Override
 606                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
 607                     return deferredAttrContext;
 608                 }
 609                 @Override
 610                 public boolean compatible(Type found, Type req, Warner warn) {
 611                     return true;
 612                 }
 613                 @Override
 614                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 615                     boolean needsReport = pt == Type.recoveryType ||
 616                             (details.getDiagnosticPosition() != null &&
 617                             details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
 618                     if (needsReport) {
 619                         chk.basicHandler.report(pos, details);
 620                     }
 621                 }
 622             });
 623         }
 624     }
 625 
 626     final ResultInfo statInfo;
 627     final ResultInfo varAssignmentInfo;
 628     final ResultInfo methodAttrInfo;
 629     final ResultInfo unknownExprInfo;
 630     final ResultInfo unknownTypeInfo;
 631     final ResultInfo unknownTypeExprInfo;
 632     final ResultInfo recoveryInfo;
 633     final MethodType initBlockType;
 634 
 635     Type pt() {
 636         return resultInfo.pt;
 637     }
 638 
 639     KindSelector pkind() {
 640         return resultInfo.pkind;
 641     }
 642 
 643 /* ************************************************************************
 644  * Visitor methods
 645  *************************************************************************/
 646 
 647     /** Visitor argument: the current environment.
 648      */
 649     Env<AttrContext> env;
 650 
 651     /** Visitor argument: the currently expected attribution result.
 652      */
 653     ResultInfo resultInfo;
 654 
 655     /** Visitor result: the computed type.
 656      */
 657     Type result;
 658 
 659     MatchBindings matchBindings = MatchBindingsComputer.EMPTY;
 660 
 661     /** Visitor method: attribute a tree, catching any completion failure
 662      *  exceptions. Return the tree's type.
 663      *
 664      *  @param tree    The tree to be visited.
 665      *  @param env     The environment visitor argument.
 666      *  @param resultInfo   The result info visitor argument.
 667      */
 668     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
 669         Env<AttrContext> prevEnv = this.env;
 670         ResultInfo prevResult = this.resultInfo;
 671         try {
 672             this.env = env;
 673             this.resultInfo = resultInfo;
 674             if (resultInfo.needsArgumentAttr(tree)) {
 675                 result = argumentAttr.attribArg(tree, env);
 676             } else {
 677                 tree.accept(this);
 678             }
 679             matchBindings = matchBindingsComputer.finishBindings(tree,
 680                                                                  matchBindings);
 681             if (tree == breakTree &&
 682                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
 683                 breakTreeFound(copyEnv(env));
 684             }
 685             return result;
 686         } catch (CompletionFailure ex) {
 687             tree.type = syms.errType;
 688             return chk.completionError(tree.pos(), ex);
 689         } finally {
 690             this.env = prevEnv;
 691             this.resultInfo = prevResult;
 692         }
 693     }
 694 
 695     protected void breakTreeFound(Env<AttrContext> env) {
 696         throw new BreakAttr(env);
 697     }
 698 
 699     Env<AttrContext> copyEnv(Env<AttrContext> env) {
 700         Env<AttrContext> newEnv =
 701                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
 702         if (newEnv.outer != null) {
 703             newEnv.outer = copyEnv(newEnv.outer);
 704         }
 705         return newEnv;
 706     }
 707 
 708     WriteableScope copyScope(WriteableScope sc) {
 709         WriteableScope newScope = WriteableScope.create(sc.owner);
 710         List<Symbol> elemsList = List.nil();
 711         for (Symbol sym : sc.getSymbols()) {
 712             elemsList = elemsList.prepend(sym);
 713         }
 714         for (Symbol s : elemsList) {
 715             newScope.enter(s);
 716         }
 717         return newScope;
 718     }
 719 
 720     /** Derived visitor method: attribute an expression tree.
 721      */
 722     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 723         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
 724     }
 725 
 726     /** Derived visitor method: attribute an expression tree with
 727      *  no constraints on the computed type.
 728      */
 729     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
 730         return attribTree(tree, env, unknownExprInfo);
 731     }
 732 
 733     /** Derived visitor method: attribute a type tree.
 734      */
 735     public Type attribType(JCTree tree, Env<AttrContext> env) {
 736         Type result = attribType(tree, env, Type.noType);
 737         return result;
 738     }
 739 
 740     /** Derived visitor method: attribute a type tree.
 741      */
 742     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 743         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
 744         return result;
 745     }
 746 
 747     /** Derived visitor method: attribute a statement or definition tree.
 748      */
 749     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 750         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
 751         Type result = attribTree(tree, env, statInfo);
 752         analyzer.analyzeIfNeeded(tree, analyzeEnv);
 753         attrRecover.doRecovery();
 754         return result;
 755     }
 756 
 757     /** Attribute a list of expressions, returning a list of types.
 758      */
 759     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 760         ListBuffer<Type> ts = new ListBuffer<>();
 761         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 762             ts.append(attribExpr(l.head, env, pt));
 763         return ts.toList();
 764     }
 765 
 766     /** Attribute a list of statements, returning nothing.
 767      */
 768     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 769         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 770             attribStat(l.head, env);
 771     }
 772 
 773     /** Attribute the arguments in a method call, returning the method kind.
 774      */
 775     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
 776         KindSelector kind = initialKind;
 777         for (JCExpression arg : trees) {
 778             Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, methodAttrInfo));
 779             if (argtype.hasTag(DEFERRED)) {
 780                 kind = KindSelector.of(KindSelector.POLY, kind);
 781             }
 782             argtypes.append(argtype);
 783         }
 784         return kind;
 785     }
 786 
 787     /** Attribute a type argument list, returning a list of types.
 788      *  Caller is responsible for calling checkRefTypes.
 789      */
 790     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 791         ListBuffer<Type> argtypes = new ListBuffer<>();
 792         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 793             argtypes.append(attribType(l.head, env));
 794         return argtypes.toList();
 795     }
 796 
 797     /** Attribute a type argument list, returning a list of types.
 798      *  Check that all the types are references.
 799      */
 800     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 801         List<Type> types = attribAnyTypes(trees, env);
 802         return chk.checkRefTypes(trees, types);
 803     }
 804 
 805     /**
 806      * Attribute type variables (of generic classes or methods).
 807      * Compound types are attributed later in attribBounds.
 808      * @param typarams the type variables to enter
 809      * @param env      the current environment
 810      */
 811     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 812         for (JCTypeParameter tvar : typarams) {
 813             TypeVar a = (TypeVar)tvar.type;
 814             a.tsym.flags_field |= UNATTRIBUTED;
 815             a.setUpperBound(Type.noType);
 816             if (!tvar.bounds.isEmpty()) {
 817                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 818                 for (JCExpression bound : tvar.bounds.tail)
 819                     bounds = bounds.prepend(attribType(bound, env));
 820                 types.setBounds(a, bounds.reverse());
 821             } else {
 822                 // if no bounds are given, assume a single bound of
 823                 // java.lang.Object.
 824                 types.setBounds(a, List.of(syms.objectType));
 825             }
 826             a.tsym.flags_field &= ~UNATTRIBUTED;
 827         }
 828         if (checkCyclic) {
 829             for (JCTypeParameter tvar : typarams) {
 830                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 831             }
 832         }
 833     }
 834 
 835     /**
 836      * Attribute the type references in a list of annotations.
 837      */
 838     void attribAnnotationTypes(List<JCAnnotation> annotations,
 839                                Env<AttrContext> env) {
 840         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 841             JCAnnotation a = al.head;
 842             attribType(a.annotationType, env);
 843         }
 844     }
 845 
 846     /**
 847      * Attribute a "lazy constant value".
 848      *  @param env         The env for the const value
 849      *  @param variable    The initializer for the const value
 850      *  @param type        The expected type, or null
 851      *  @see VarSymbol#setLazyConstValue
 852      */
 853     public Object attribLazyConstantValue(Env<AttrContext> env,
 854                                       Env<AttrContext> enclosingEnv,
 855                                       JCVariableDecl variable,
 856                                       Type type) {
 857         deferredLintHandler.push(variable);
 858         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 859         try {
 860             doQueueScanTreeAndTypeAnnotateForVarInit(variable, enclosingEnv);
 861             Type itype = attribExpr(variable.init, env, type);
 862             if (variable.isImplicitlyTyped()) {
 863                 //fixup local variable type
 864                 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype, variable.name);
 865             }
 866             if (itype.constValue() != null) {
 867                 return coerce(itype, type).constValue();
 868             } else {
 869                 return null;
 870             }
 871         } finally {
 872             log.useSource(prevSource);
 873             deferredLintHandler.pop();
 874         }
 875     }
 876 
 877     /** Attribute type reference in an `extends', `implements', or 'permits' clause.
 878      *  Supertypes of anonymous inner classes are usually already attributed.
 879      *
 880      *  @param tree              The tree making up the type reference.
 881      *  @param env               The environment current at the reference.
 882      *  @param classExpected     true if only a class is expected here.
 883      *  @param interfaceExpected true if only an interface is expected here.
 884      */
 885     Type attribBase(JCTree tree,
 886                     Env<AttrContext> env,
 887                     boolean classExpected,
 888                     boolean interfaceExpected,
 889                     boolean checkExtensible) {
 890         Type t = tree.type != null ?
 891             tree.type :
 892             attribType(tree, env);
 893         try {
 894             return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 895         } catch (CompletionFailure ex) {
 896             chk.completionError(tree.pos(), ex);
 897             return t;
 898         }
 899     }
 900     Type checkBase(Type t,
 901                    JCTree tree,
 902                    Env<AttrContext> env,
 903                    boolean classExpected,
 904                    boolean interfaceExpected,
 905                    boolean checkExtensible) {
 906         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
 907                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
 908         if (t.tsym.isAnonymous()) {
 909             log.error(pos, Errors.CantInheritFromAnon);
 910             return types.createErrorType(t);
 911         }
 912         if (t.isErroneous())
 913             return t;
 914         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
 915             // check that type variable is already visible
 916             if (t.getUpperBound() == null) {
 917                 log.error(pos, Errors.IllegalForwardRef);
 918                 return types.createErrorType(t);
 919             }
 920         } else {
 921             t = chk.checkClassType(pos, t, checkExtensible);
 922         }
 923         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 924             log.error(pos, Errors.IntfExpectedHere);
 925             // return errType is necessary since otherwise there might
 926             // be undetected cycles which cause attribution to loop
 927             return types.createErrorType(t);
 928         } else if (checkExtensible &&
 929                    classExpected &&
 930                    (t.tsym.flags() & INTERFACE) != 0) {
 931             log.error(pos, Errors.NoIntfExpectedHere);
 932             return types.createErrorType(t);
 933         }
 934         if (checkExtensible &&
 935             ((t.tsym.flags() & FINAL) != 0)) {
 936             log.error(pos,
 937                       Errors.CantInheritFromFinal(t.tsym));
 938         }
 939         chk.checkNonCyclic(pos, t);
 940         return t;
 941     }
 942 
 943     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
 944         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
 945         id.type = env.info.scope.owner.enclClass().type;
 946         id.sym = env.info.scope.owner.enclClass();
 947         return id.type;
 948     }
 949 
 950     public void visitClassDef(JCClassDecl tree) {
 951         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
 952                 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
 953                         argumentAttr.withLocalCacheContext() : null);
 954         boolean ctorProloguePrev = env.info.ctorPrologue;
 955         try {
 956             // Local and anonymous classes have not been entered yet, so we need to
 957             // do it now.
 958             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
 959                 enter.classEnter(tree, env);
 960             } else {
 961                 // If this class declaration is part of a class level annotation,
 962                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
 963                 // order to simplify later steps and allow for sensible error
 964                 // messages.
 965                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
 966                     enter.classEnter(tree, env);
 967             }
 968 
 969             ClassSymbol c = tree.sym;
 970             if (c == null) {
 971                 // exit in case something drastic went wrong during enter.
 972                 result = null;
 973             } else {
 974                 // make sure class has been completed:
 975                 c.complete();
 976 
 977                 // If a class declaration appears in a constructor prologue,
 978                 // that means it's either a local class or an anonymous class.
 979                 // Either way, there is no immediately enclosing instance.
 980                 if (ctorProloguePrev) {
 981                     c.flags_field |= NOOUTERTHIS;
 982                 }
 983                 attribClass(tree.pos(), c);
 984                 result = tree.type = c.type;
 985             }
 986         } finally {
 987             localCacheContext.ifPresent(LocalCacheContext::leave);
 988             env.info.ctorPrologue = ctorProloguePrev;
 989         }
 990     }
 991 
 992     public void visitMethodDef(JCMethodDecl tree) {
 993         MethodSymbol m = tree.sym;
 994         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
 995 
 996         Lint lint = env.info.lint.augment(m);
 997         Lint prevLint = chk.setLint(lint);
 998         boolean ctorProloguePrev = env.info.ctorPrologue;
 999         Assert.check(!env.info.ctorPrologue);
1000         MethodSymbol prevMethod = chk.setMethod(m);
1001         try {
1002             deferredLintHandler.flush(tree, lint);
1003             chk.checkDeprecatedAnnotation(tree.pos(), m);
1004 
1005 
1006             // Create a new environment with local scope
1007             // for attributing the method.
1008             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
1009             localEnv.info.lint = lint;
1010 
1011             attribStats(tree.typarams, localEnv);
1012 
1013             // If we override any other methods, check that we do so properly.
1014             // JLS ???
1015             if (m.isStatic()) {
1016                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1017             } else {
1018                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1019             }
1020             chk.checkOverride(env, tree, m);
1021 
1022             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1023                 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1024             }
1025 
1026             // Enter all type parameters into the local method scope.
1027             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1028                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1029 
1030             ClassSymbol owner = env.enclClass.sym;
1031             if ((owner.flags() & ANNOTATION) != 0 &&
1032                     (tree.params.nonEmpty() ||
1033                     tree.recvparam != null))
1034                 log.error(tree.params.nonEmpty() ?
1035                         tree.params.head.pos() :
1036                         tree.recvparam.pos(),
1037                         Errors.IntfAnnotationMembersCantHaveParams);
1038 
1039             // Attribute all value parameters.
1040             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1041                 attribStat(l.head, localEnv);
1042             }
1043 
1044             chk.checkVarargsMethodDecl(localEnv, tree);
1045 
1046             // Check that type parameters are well-formed.
1047             chk.validate(tree.typarams, localEnv);
1048 
1049             // Check that result type is well-formed.
1050             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
1051                 chk.validate(tree.restype, localEnv);
1052 
1053             // Check that receiver type is well-formed.
1054             if (tree.recvparam != null) {
1055                 // Use a new environment to check the receiver parameter.
1056                 // Otherwise I get "might not have been initialized" errors.
1057                 // Is there a better way?
1058                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1059                 attribType(tree.recvparam, newEnv);
1060                 chk.validate(tree.recvparam, newEnv);
1061             }
1062 
1063             // Is this method a constructor?
1064             boolean isConstructor = TreeInfo.isConstructor(tree);
1065 
1066             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP) {
1067                 // lets find if this method is an accessor
1068                 Optional<? extends RecordComponent> recordComponent = env.enclClass.sym.getRecordComponents().stream()
1069                         .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
1070                 if (recordComponent.isPresent()) {
1071                     // the method is a user defined accessor lets check that everything is fine
1072                     if (!tree.sym.isPublic()) {
1073                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1074                     }
1075                     if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1076                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1077                                 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1078                     }
1079                     if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1080                         log.error(tree,
1081                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1082                     }
1083                     if (!tree.typarams.isEmpty()) {
1084                         log.error(tree,
1085                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1086                     }
1087                     if (tree.sym.isStatic()) {
1088                         log.error(tree,
1089                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1090                     }
1091                 }
1092 
1093                 if (isConstructor) {
1094                     // if this a constructor other than the canonical one
1095                     if ((tree.sym.flags_field & RECORD) == 0) {
1096                         if (!TreeInfo.hasConstructorCall(tree, names._this)) {
1097                             log.error(tree, Errors.NonCanonicalConstructorInvokeAnotherConstructor(env.enclClass.sym));
1098                         }
1099                     } else {
1100                         // but if it is the canonical:
1101 
1102                         /* if user generated, then it shouldn't:
1103                          *     - have an accessibility stricter than that of the record type
1104                          *     - explicitly invoke any other constructor
1105                          */
1106                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1107                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1108                                 log.error(tree,
1109                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1110                                             Errors.InvalidCanonicalConstructorInRecord(
1111                                                 Fragments.Canonical,
1112                                                 env.enclClass.sym.name,
1113                                                 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1114                                             ) :
1115                                             Errors.InvalidCanonicalConstructorInRecord(
1116                                                     Fragments.Canonical,
1117                                                     env.enclClass.sym.name,
1118                                                     Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1119                                             )
1120                                 );
1121                             }
1122 
1123                             if (TreeInfo.hasAnyConstructorCall(tree)) {
1124                                 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1125                                         Fragments.Canonical, env.enclClass.sym.name,
1126                                         Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1127                             }
1128                         }
1129 
1130                         // also we want to check that no type variables have been defined
1131                         if (!tree.typarams.isEmpty()) {
1132                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1133                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1134                         }
1135 
1136                         /* and now we need to check that the constructor's arguments are exactly the same as those of the
1137                          * record components
1138                          */
1139                         List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1140                         List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1141                         for (JCVariableDecl param: tree.params) {
1142                             boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1143                             if (!types.isSameType(param.type, recordFieldTypes.head) ||
1144                                     (recordComponents.head.isVarargs() != paramIsVarArgs)) {
1145                                 log.error(param, Errors.InvalidCanonicalConstructorInRecord(
1146                                         Fragments.Canonical, env.enclClass.sym.name,
1147                                         Fragments.TypeMustBeIdenticalToCorrespondingRecordComponentType));
1148                             }
1149                             recordComponents = recordComponents.tail;
1150                             recordFieldTypes = recordFieldTypes.tail;
1151                         }
1152                     }
1153                 }
1154             }
1155 
1156             // annotation method checks
1157             if ((owner.flags() & ANNOTATION) != 0) {
1158                 // annotation method cannot have throws clause
1159                 if (tree.thrown.nonEmpty()) {
1160                     log.error(tree.thrown.head.pos(),
1161                               Errors.ThrowsNotAllowedInIntfAnnotation);
1162                 }
1163                 // annotation method cannot declare type-parameters
1164                 if (tree.typarams.nonEmpty()) {
1165                     log.error(tree.typarams.head.pos(),
1166                               Errors.IntfAnnotationMembersCantHaveTypeParams);
1167                 }
1168                 // validate annotation method's return type (could be an annotation type)
1169                 chk.validateAnnotationType(tree.restype);
1170                 // ensure that annotation method does not clash with members of Object/Annotation
1171                 chk.validateAnnotationMethod(tree.pos(), m);
1172             }
1173 
1174             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1175                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1176 
1177             if (tree.body == null) {
1178                 // Empty bodies are only allowed for
1179                 // abstract, native, or interface methods, or for methods
1180                 // in a retrofit signature class.
1181                 if (tree.defaultValue != null) {
1182                     if ((owner.flags() & ANNOTATION) == 0)
1183                         log.error(tree.pos(),
1184                                   Errors.DefaultAllowedInIntfAnnotationMember);
1185                 }
1186                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1187                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1188             } else {
1189                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1190                     if ((owner.flags() & INTERFACE) != 0) {
1191                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1192                     } else {
1193                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1194                     }
1195                 } else if ((tree.mods.flags & NATIVE) != 0) {
1196                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1197                 }
1198                 // Add an implicit super() call unless an explicit call to
1199                 // super(...) or this(...) is given
1200                 // or we are compiling class java.lang.Object.
1201                 if (isConstructor && owner.type != syms.objectType) {
1202                     if (!TreeInfo.hasAnyConstructorCall(tree)) {
1203                         JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1204                                 make.Ident(names._super), make.Idents(List.nil())));
1205                         tree.body.stats = tree.body.stats.prepend(supCall);




1206                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1207                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1208                             TreeInfo.hasConstructorCall(tree, names._super)) {
1209                         // enum constructors are not allowed to call super
1210                         // directly, so make sure there aren't any super calls
1211                         // in enum constructors, except in the compiler
1212                         // generated one.
1213                         log.error(tree.body.stats.head.pos(),
1214                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1215                     }
1216                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1217                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1218                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1219                         if (!initParamNames.equals(recordComponentNames)) {
1220                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1221                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1222                         }
1223                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1224                             log.error(tree,
1225                                     Errors.InvalidCanonicalConstructorInRecord(
1226                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1227                                             env.enclClass.sym.name,
1228                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1229                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1230                         }
1231                     }
1232                 }
1233 
1234                 // Attribute all type annotations in the body
1235                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1236                 annotate.flush();
1237 
1238                 // Start of constructor prologue
1239                 localEnv.info.ctorPrologue = isConstructor;
1240 
1241                 // Attribute method body.
1242                 attribStat(tree.body, localEnv);
1243             }
1244 
1245             localEnv.info.scope.leave();
1246             result = tree.type = m.type;
1247         } finally {
1248             chk.setLint(prevLint);
1249             chk.setMethod(prevMethod);
1250             env.info.ctorPrologue = ctorProloguePrev;
1251         }
1252     }
1253 
1254     public void visitVarDef(JCVariableDecl tree) {
1255         // Local variables have not been entered yet, so we need to do it now:
1256         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1257             if (tree.sym != null) {
1258                 // parameters have already been entered
1259                 env.info.scope.enter(tree.sym);
1260             } else {
1261                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1262                     if (tree.init == null) {
1263                         //cannot use 'var' without initializer
1264                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1265                         tree.vartype = make.Erroneous();
1266                     } else {
1267                         Fragment msg = canInferLocalVarType(tree);
1268                         if (msg != null) {
1269                             //cannot use 'var' with initializer which require an explicit target
1270                             //(e.g. lambda, method reference, array initializer).
1271                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1272                             tree.vartype = make.Erroneous();
1273                         }
1274                     }
1275                 }
1276                 try {
1277                     annotate.blockAnnotations();
1278                     memberEnter.memberEnter(tree, env);
1279                 } finally {
1280                     annotate.unblockAnnotations();
1281                 }
1282             }
1283         } else {
1284             doQueueScanTreeAndTypeAnnotateForVarInit(tree, env);
1285         }
1286 
1287         VarSymbol v = tree.sym;
1288         Lint lint = env.info.lint.augment(v);
1289         Lint prevLint = chk.setLint(lint);
1290 
1291         // Check that the variable's declared type is well-formed.
1292         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1293                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1294                 (tree.sym.flags() & PARAMETER) != 0;
1295         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1296 
1297         try {
1298             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1299             deferredLintHandler.flush(tree, lint);
1300             chk.checkDeprecatedAnnotation(tree.pos(), v);
1301 
1302             if (tree.init != null) {
1303                 if ((v.flags_field & FINAL) == 0 ||
1304                     !memberEnter.needsLazyConstValue(tree.init)) {
1305                     // Not a compile-time constant
1306                     // Attribute initializer in a new environment
1307                     // with the declared variable as owner.
1308                     // Check that initializer conforms to variable's declared type.
1309                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1310                     initEnv.info.lint = lint;
1311                     // In order to catch self-references, we set the variable's
1312                     // declaration position to maximal possible value, effectively
1313                     // marking the variable as undefined.
1314                     initEnv.info.enclVar = v;
1315                     attribExpr(tree.init, initEnv, v.type);
1316                     if (tree.isImplicitlyTyped()) {
1317                         //fixup local variable type
1318                         v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);









1319                     }
1320                 }
1321                 if (tree.isImplicitlyTyped()) {
1322                     setSyntheticVariableType(tree, v.type);
1323                 }
1324             }
1325             result = tree.type = v.type;
1326             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1327                 if (isNonArgsMethodInObject(v.name)) {
1328                     log.error(tree, Errors.IllegalRecordComponentName(v));
1329                 }
1330             }
1331         }
1332         finally {
1333             chk.setLint(prevLint);
1334         }
1335     }
1336 
1337     private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1338         if (tree.init != null &&
1339             (tree.mods.flags & Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED) == 0 &&
1340             env.info.scope.owner.kind != MTH && env.info.scope.owner.kind != VAR) {
1341             tree.mods.flags |= Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED;
1342             // Field initializer expression need to be entered.
1343             annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree);
1344             annotate.flush();
1345         }
1346     }
1347 
1348     private boolean isNonArgsMethodInObject(Name name) {
1349         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1350             if (s.type.getParameterTypes().isEmpty()) {
1351                 return true;
1352             }
1353         }
1354         return false;
1355     }
1356 
1357     Fragment canInferLocalVarType(JCVariableDecl tree) {
1358         LocalInitScanner lis = new LocalInitScanner();
1359         lis.scan(tree.init);
1360         return lis.badInferenceMsg;
1361     }
1362 
1363     static class LocalInitScanner extends TreeScanner {
1364         Fragment badInferenceMsg = null;
1365         boolean needsTarget = true;
1366 
1367         @Override
1368         public void visitNewArray(JCNewArray tree) {
1369             if (tree.elemtype == null && needsTarget) {
1370                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1371             }
1372         }
1373 
1374         @Override
1375         public void visitLambda(JCLambda tree) {
1376             if (needsTarget) {
1377                 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1378             }
1379         }
1380 
1381         @Override
1382         public void visitTypeCast(JCTypeCast tree) {
1383             boolean prevNeedsTarget = needsTarget;
1384             try {
1385                 needsTarget = false;
1386                 super.visitTypeCast(tree);
1387             } finally {
1388                 needsTarget = prevNeedsTarget;
1389             }
1390         }
1391 
1392         @Override
1393         public void visitReference(JCMemberReference tree) {
1394             if (needsTarget) {
1395                 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1396             }
1397         }
1398 
1399         @Override
1400         public void visitNewClass(JCNewClass tree) {
1401             boolean prevNeedsTarget = needsTarget;
1402             try {
1403                 needsTarget = false;
1404                 super.visitNewClass(tree);
1405             } finally {
1406                 needsTarget = prevNeedsTarget;
1407             }
1408         }
1409 
1410         @Override
1411         public void visitApply(JCMethodInvocation tree) {
1412             boolean prevNeedsTarget = needsTarget;
1413             try {
1414                 needsTarget = false;
1415                 super.visitApply(tree);
1416             } finally {
1417                 needsTarget = prevNeedsTarget;
1418             }
1419         }
1420     }
1421 
1422     public void visitSkip(JCSkip tree) {
1423         result = null;
1424     }
1425 
1426     public void visitBlock(JCBlock tree) {
1427         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1428             // Block is a static or instance initializer;
1429             // let the owner of the environment be a freshly
1430             // created BLOCK-method.
1431             Symbol fakeOwner =
1432                 new MethodSymbol(tree.flags | BLOCK |
1433                     env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1434                     env.info.scope.owner);
1435             final Env<AttrContext> localEnv =
1436                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1437 
1438             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;




1439             // Attribute all type annotations in the block
1440             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1441             annotate.flush();
1442             attribStats(tree.stats, localEnv);
1443 
1444             {
1445                 // Store init and clinit type annotations with the ClassSymbol
1446                 // to allow output in Gen.normalizeDefs.
1447                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1448                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1449                 if ((tree.flags & STATIC) != 0) {
1450                     cs.appendClassInitTypeAttributes(tas);
1451                 } else {
1452                     cs.appendInitTypeAttributes(tas);
1453                 }
1454             }
1455         } else {
1456             // Create a new local environment with a local scope.
1457             Env<AttrContext> localEnv =
1458                 env.dup(tree, env.info.dup(env.info.scope.dup()));
1459             try {
1460                 attribStats(tree.stats, localEnv);
1461             } finally {
1462                 localEnv.info.scope.leave();
1463             }
1464         }
1465         result = null;
1466     }
1467 
1468     public void visitDoLoop(JCDoWhileLoop tree) {
1469         attribStat(tree.body, env.dup(tree));
1470         attribExpr(tree.cond, env, syms.booleanType);
1471         handleLoopConditionBindings(matchBindings, tree, tree.body);
1472         result = null;
1473     }
1474 
1475     public void visitWhileLoop(JCWhileLoop tree) {
1476         attribExpr(tree.cond, env, syms.booleanType);
1477         MatchBindings condBindings = matchBindings;
1478         // include condition's bindings when true in the body:
1479         Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1480         try {
1481             attribStat(tree.body, whileEnv.dup(tree));
1482         } finally {
1483             whileEnv.info.scope.leave();
1484         }
1485         handleLoopConditionBindings(condBindings, tree, tree.body);
1486         result = null;
1487     }
1488 
1489     public void visitForLoop(JCForLoop tree) {
1490         Env<AttrContext> loopEnv =
1491             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1492         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1493         try {
1494             attribStats(tree.init, loopEnv);
1495             if (tree.cond != null) {
1496                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1497                 // include condition's bindings when true in the body and step:
1498                 condBindings = matchBindings;
1499             }
1500             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1501             try {
1502                 bodyEnv.tree = tree; // before, we were not in loop!
1503                 attribStats(tree.step, bodyEnv);
1504                 attribStat(tree.body, bodyEnv);
1505             } finally {
1506                 bodyEnv.info.scope.leave();
1507             }
1508             result = null;
1509         }
1510         finally {
1511             loopEnv.info.scope.leave();
1512         }
1513         handleLoopConditionBindings(condBindings, tree, tree.body);
1514     }
1515 
1516     /**
1517      * Include condition's bindings when false after the loop, if cannot get out of the loop
1518      */
1519     private void handleLoopConditionBindings(MatchBindings condBindings,
1520                                              JCStatement loop,
1521                                              JCStatement loopBody) {
1522         if (condBindings.bindingsWhenFalse.nonEmpty() &&
1523             !breaksTo(env, loop, loopBody)) {
1524             addBindings2Scope(loop, condBindings.bindingsWhenFalse);
1525         }
1526     }
1527 
1528     private boolean breaksTo(Env<AttrContext> env, JCTree loop, JCTree body) {
1529         preFlow(body);
1530         return flow.breaksToTree(env, loop, body, make);
1531     }
1532 
1533     /**
1534      * Add given bindings to the current scope, unless there's a break to
1535      * an immediately enclosing labeled statement.
1536      */
1537     private void addBindings2Scope(JCStatement introducingStatement,
1538                                    List<BindingSymbol> bindings) {
1539         if (bindings.isEmpty()) {
1540             return ;
1541         }
1542 
1543         var searchEnv = env;
1544         while (searchEnv.tree instanceof JCLabeledStatement labeled &&
1545                labeled.body == introducingStatement) {
1546             if (breaksTo(env, labeled, labeled.body)) {
1547                 //breaking to an immediately enclosing labeled statement
1548                 return ;
1549             }
1550             searchEnv = searchEnv.next;
1551             introducingStatement = labeled;
1552         }
1553 
1554         //include condition's body when false after the while, if cannot get out of the loop
1555         bindings.forEach(env.info.scope::enter);
1556         bindings.forEach(BindingSymbol::preserveBinding);
1557     }
1558 
1559     public void visitForeachLoop(JCEnhancedForLoop tree) {
1560         Env<AttrContext> loopEnv =
1561             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1562         try {
1563             //the Formal Parameter of a for-each loop is not in the scope when
1564             //attributing the for-each expression; we mimic this by attributing
1565             //the for-each expression first (against original scope).
1566             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1567             chk.checkNonVoid(tree.pos(), exprType);
1568             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1569             if (elemtype == null) {
1570                 // or perhaps expr implements Iterable<T>?
1571                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1572                 if (base == null) {
1573                     log.error(tree.expr.pos(),
1574                               Errors.ForeachNotApplicableToType(exprType,
1575                                                                 Fragments.TypeReqArrayOrIterable));
1576                     elemtype = types.createErrorType(exprType);
1577                 } else {
1578                     List<Type> iterableParams = base.allparams();
1579                     elemtype = iterableParams.isEmpty()
1580                         ? syms.objectType
1581                         : types.wildUpperBound(iterableParams.head);
1582 
1583                     // Check the return type of the method iterator().
1584                     // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1585                     Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1586                             loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1587                     if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1588                         log.error(tree.pos(),
1589                                 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1590                     }
1591                 }
1592             }
1593             if (tree.var.isImplicitlyTyped()) {
1594                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1595                 setSyntheticVariableType(tree.var, inferredType);
1596             }
1597             attribStat(tree.var, loopEnv);
1598             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1599             loopEnv.tree = tree; // before, we were not in loop!
1600             attribStat(tree.body, loopEnv);
1601             result = null;
1602         }
1603         finally {
1604             loopEnv.info.scope.leave();
1605         }
1606     }
1607 
1608     public void visitLabelled(JCLabeledStatement tree) {
1609         // Check that label is not used in an enclosing statement
1610         Env<AttrContext> env1 = env;
1611         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1612             if (env1.tree.hasTag(LABELLED) &&
1613                 ((JCLabeledStatement) env1.tree).label == tree.label) {
1614                 log.error(tree.pos(),
1615                           Errors.LabelAlreadyInUse(tree.label));
1616                 break;
1617             }
1618             env1 = env1.next;
1619         }
1620 
1621         attribStat(tree.body, env.dup(tree));
1622         result = null;
1623     }
1624 
1625     public void visitSwitch(JCSwitch tree) {
1626         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1627             attribStats(c.stats, caseEnv);
1628         });
1629         result = null;
1630     }
1631 
1632     public void visitSwitchExpression(JCSwitchExpression tree) {
1633         boolean wrongContext = false;
1634 
1635         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
1636                 PolyKind.STANDALONE : PolyKind.POLY;
1637 
1638         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1639             //this means we are returning a poly conditional from void-compatible lambda expression
1640             resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
1641             resultInfo = recoveryInfo;
1642             wrongContext = true;
1643         }
1644 
1645         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1646                 unknownExprInfo :
1647                 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
1648 
1649         ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
1650         ListBuffer<Type> caseTypes = new ListBuffer<>();
1651 
1652         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1653             caseEnv.info.yieldResult = condInfo;
1654             attribStats(c.stats, caseEnv);
1655             new TreeScanner() {
1656                 @Override
1657                 public void visitYield(JCYield brk) {
1658                     if (brk.target == tree) {
1659                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
1660                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
1661                     }
1662                     super.visitYield(brk);
1663                 }
1664 
1665                 @Override public void visitClassDef(JCClassDecl tree) {}
1666                 @Override public void visitLambda(JCLambda tree) {}
1667             }.scan(c.stats);
1668         });
1669 
1670         if (tree.cases.isEmpty()) {
1671             log.error(tree.pos(),
1672                       Errors.SwitchExpressionEmpty);
1673         } else if (caseTypes.isEmpty()) {
1674             log.error(tree.pos(),
1675                       Errors.SwitchExpressionNoResultExpressions);
1676         }
1677 
1678         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
1679 
1680         result = tree.type = wrongContext? types.createErrorType(pt()) : check(tree, owntype, KindSelector.VAL, resultInfo);
1681     }
1682     //where:
1683         CheckContext switchExpressionContext(CheckContext checkContext) {
1684             return new Check.NestedCheckContext(checkContext) {
1685                 //this will use enclosing check context to check compatibility of
1686                 //subexpression against target type; if we are in a method check context,
1687                 //depending on whether boxing is allowed, we could have incompatibilities
1688                 @Override
1689                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1690                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
1691                 }
1692             };
1693         }
1694 
1695     private void handleSwitch(JCTree switchTree,
1696                               JCExpression selector,
1697                               List<JCCase> cases,
1698                               BiConsumer<JCCase, Env<AttrContext>> attribCase) {
1699         Type seltype = attribExpr(selector, env);
1700 
1701         Env<AttrContext> switchEnv =
1702             env.dup(switchTree, env.info.dup(env.info.scope.dup()));
1703 
1704         try {
1705             boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1706             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
1707             boolean booleanSwitch = types.isSameType(types.unboxedTypeOrType(seltype), syms.booleanType);
1708             boolean errorEnumSwitch = TreeInfo.isErrorEnumSwitch(selector, cases);
1709             boolean intSwitch = types.isAssignable(seltype, syms.intType);
1710             boolean patternSwitch;
1711             if (seltype.isPrimitive() && !intSwitch) {
1712                 preview.checkSourceLevel(selector.pos(), Feature.PRIMITIVE_PATTERNS);
1713                 patternSwitch = true;
1714             }
1715             if (!enumSwitch && !stringSwitch && !errorEnumSwitch &&
1716                 !intSwitch) {
1717                 preview.checkSourceLevel(selector.pos(), Feature.PATTERN_SWITCH);
1718                 patternSwitch = true;
1719             } else {
1720                 patternSwitch = cases.stream()
1721                                      .flatMap(c -> c.labels.stream())
1722                                      .anyMatch(l -> l.hasTag(PATTERNCASELABEL) ||
1723                                                     TreeInfo.isNullCaseLabel(l));
1724             }
1725 
1726             // Attribute all cases and
1727             // check that there are no duplicate case labels or default clauses.
1728             Set<Object> constants = new HashSet<>(); // The set of case constants.
1729             boolean hasDefault = false;           // Is there a default label?
1730             boolean hasUnconditionalPattern = false; // Is there a unconditional pattern?
1731             boolean lastPatternErroneous = false; // Has the last pattern erroneous type?
1732             boolean hasNullPattern = false;       // Is there a null pattern?
1733             CaseTree.CaseKind caseKind = null;
1734             boolean wasError = false;
1735             JCCaseLabel unconditionalCaseLabel = null;
1736             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
1737                 JCCase c = l.head;
1738                 if (caseKind == null) {
1739                     caseKind = c.caseKind;
1740                 } else if (caseKind != c.caseKind && !wasError) {
1741                     log.error(c.pos(),
1742                               Errors.SwitchMixingCaseTypes);
1743                     wasError = true;
1744                 }
1745                 MatchBindings currentBindings = null;
1746                 MatchBindings guardBindings = null;
1747                 for (List<JCCaseLabel> labels = c.labels; labels.nonEmpty(); labels = labels.tail) {
1748                     JCCaseLabel label = labels.head;
1749                     if (label instanceof JCConstantCaseLabel constLabel) {
1750                         JCExpression expr = constLabel.expr;
1751                         if (TreeInfo.isNull(expr)) {
1752                             preview.checkSourceLevel(expr.pos(), Feature.CASE_NULL);
1753                             if (hasNullPattern) {
1754                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
1755                             }
1756                             hasNullPattern = true;
1757                             attribExpr(expr, switchEnv, seltype);
1758                             matchBindings = new MatchBindings(matchBindings.bindingsWhenTrue, matchBindings.bindingsWhenFalse, true);
1759                         } else if (enumSwitch) {
1760                             Symbol sym = enumConstant(expr, seltype);
1761                             if (sym == null) {
1762                                 if (allowPatternSwitch) {
1763                                     attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
1764                                     Symbol enumSym = TreeInfo.symbol(expr);
1765                                     if (enumSym == null || !enumSym.isEnum() || enumSym.kind != VAR) {
1766                                         log.error(expr.pos(), Errors.EnumLabelMustBeEnumConstant);
1767                                     } else if (!constants.add(enumSym)) {
1768                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
1769                                     }
1770                                 } else {
1771                                     log.error(expr.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
1772                                 }
1773                             } else if (!constants.add(sym)) {
1774                                 log.error(label.pos(), Errors.DuplicateCaseLabel);
1775                             }
1776                         } else if (errorEnumSwitch) {
1777                             //error recovery: the selector is erroneous, and all the case labels
1778                             //are identifiers. This could be an enum switch - don't report resolve
1779                             //error for the case label:
1780                             var prevResolveHelper = rs.basicLogResolveHelper;
1781                             try {
1782                                 rs.basicLogResolveHelper = rs.silentLogResolveHelper;
1783                                 attribExpr(expr, switchEnv, seltype);
1784                             } finally {
1785                                 rs.basicLogResolveHelper = prevResolveHelper;
1786                             }
1787                         } else {
1788                             Type pattype = attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
1789                             if (!pattype.hasTag(ERROR)) {
1790                                 if (pattype.constValue() == null) {
1791                                     Symbol s = TreeInfo.symbol(expr);
1792                                     if (s != null && s.kind == TYP) {
1793                                         log.error(expr.pos(),
1794                                                   Errors.PatternExpected);
1795                                     } else if (s == null || !s.isEnum()) {
1796                                         log.error(expr.pos(),
1797                                                   (stringSwitch ? Errors.StringConstReq
1798                                                                 : intSwitch ? Errors.ConstExprReq
1799                                                                             : Errors.PatternOrEnumReq));
1800                                     } else if (!constants.add(s)) {
1801                                         log.error(label.pos(), Errors.DuplicateCaseLabel);
1802                                     }
1803                                 }
1804                                 else {
1805                                     if (!stringSwitch && !intSwitch &&
1806                                             !((pattype.getTag().isInSuperClassesOf(LONG) || pattype.getTag().equals(BOOLEAN)) &&
1807                                               types.isSameType(types.unboxedTypeOrType(seltype), pattype))) {
1808                                         log.error(label.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype));
1809                                     } else if (!constants.add(pattype.constValue())) {
1810                                         log.error(c.pos(), Errors.DuplicateCaseLabel);
1811                                     }
1812                                 }
1813                             }
1814                         }
1815                     } else if (label instanceof JCDefaultCaseLabel def) {
1816                         if (hasDefault) {
1817                             log.error(label.pos(), Errors.DuplicateDefaultLabel);
1818                         } else if (hasUnconditionalPattern) {
1819                             log.error(label.pos(), Errors.UnconditionalPatternAndDefault);
1820                         }  else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
1821                             log.error(label.pos(), Errors.DefaultAndBothBooleanValues);
1822                         }
1823                         hasDefault = true;
1824                         matchBindings = MatchBindingsComputer.EMPTY;
1825                     } else if (label instanceof JCPatternCaseLabel patternlabel) {
1826                         //pattern
1827                         JCPattern pat = patternlabel.pat;
1828                         attribExpr(pat, switchEnv, seltype);
1829                         Type primaryType = TreeInfo.primaryPatternType(pat);
1830 
1831                         if (primaryType.isPrimitive()) {
1832                             preview.checkSourceLevel(pat.pos(), Feature.PRIMITIVE_PATTERNS);
1833                         } else if (!primaryType.hasTag(TYPEVAR)) {
1834                             primaryType = chk.checkClassOrArrayType(pat.pos(), primaryType);
1835                         }
1836                         checkCastablePattern(pat.pos(), seltype, primaryType);
1837                         Type patternType = types.erasure(primaryType);
1838                         JCExpression guard = c.guard;
1839                         if (guardBindings == null && guard != null) {
1840                             MatchBindings afterPattern = matchBindings;
1841                             Env<AttrContext> bodyEnv = bindingEnv(switchEnv, matchBindings.bindingsWhenTrue);
1842                             try {
1843                                 attribExpr(guard, bodyEnv, syms.booleanType);
1844                             } finally {
1845                                 bodyEnv.info.scope.leave();
1846                             }
1847 
1848                             guardBindings = matchBindings;
1849                             matchBindings = afterPattern;
1850 
1851                             if (TreeInfo.isBooleanWithValue(guard, 0)) {
1852                                 log.error(guard.pos(), Errors.GuardHasConstantExpressionFalse);
1853                             }
1854                         }
1855                         boolean unguarded = TreeInfo.unguardedCase(c) && !pat.hasTag(RECORDPATTERN);
1856                         boolean unconditional =
1857                                 unguarded &&
1858                                 !patternType.isErroneous() &&
1859                                 types.isUnconditionallyExact(seltype, patternType);
1860                         if (unconditional) {
1861                             if (hasUnconditionalPattern) {
1862                                 log.error(pat.pos(), Errors.DuplicateUnconditionalPattern);
1863                             } else if (hasDefault) {
1864                                 log.error(pat.pos(), Errors.UnconditionalPatternAndDefault);
1865                             } else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
1866                                 log.error(pat.pos(), Errors.UnconditionalPatternAndBothBooleanValues);
1867                             }
1868                             hasUnconditionalPattern = true;
1869                             unconditionalCaseLabel = label;
1870                         }
1871                         lastPatternErroneous = patternType.isErroneous();
1872                     } else {
1873                         Assert.error();
1874                     }
1875                     currentBindings = matchBindingsComputer.switchCase(label, currentBindings, matchBindings);
1876                 }
1877 
1878                 if (guardBindings != null) {
1879                     currentBindings = matchBindingsComputer.caseGuard(c, currentBindings, guardBindings);
1880                 }
1881 
1882                 Env<AttrContext> caseEnv =
1883                         bindingEnv(switchEnv, c, currentBindings.bindingsWhenTrue);
1884                 try {
1885                     attribCase.accept(c, caseEnv);
1886                 } finally {
1887                     caseEnv.info.scope.leave();
1888                 }
1889                 addVars(c.stats, switchEnv.info.scope);
1890 
1891                 preFlow(c);
1892                 c.completesNormally = flow.aliveAfter(caseEnv, c, make);
1893             }
1894             if (patternSwitch) {
1895                 chk.checkSwitchCaseStructure(cases);
1896                 chk.checkSwitchCaseLabelDominated(unconditionalCaseLabel, cases);
1897             }
1898             if (switchTree.hasTag(SWITCH)) {
1899                 ((JCSwitch) switchTree).hasUnconditionalPattern =
1900                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
1901                 ((JCSwitch) switchTree).patternSwitch = patternSwitch;
1902             } else if (switchTree.hasTag(SWITCH_EXPRESSION)) {
1903                 ((JCSwitchExpression) switchTree).hasUnconditionalPattern =
1904                         hasDefault || hasUnconditionalPattern || lastPatternErroneous;
1905                 ((JCSwitchExpression) switchTree).patternSwitch = patternSwitch;
1906             } else {
1907                 Assert.error(switchTree.getTag().name());
1908             }
1909         } finally {
1910             switchEnv.info.scope.leave();
1911         }
1912     }
1913     // where
1914         private ResultInfo caseLabelResultInfo(Type seltype) {
1915             return new ResultInfo(KindSelector.VAL_TYP,
1916                                   !seltype.hasTag(ERROR) ? seltype
1917                                                          : Type.noType);
1918         }
1919         /** Add any variables defined in stats to the switch scope. */
1920         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1921             for (;stats.nonEmpty(); stats = stats.tail) {
1922                 JCTree stat = stats.head;
1923                 if (stat.hasTag(VARDEF))
1924                     switchScope.enter(((JCVariableDecl) stat).sym);
1925             }
1926         }
1927     // where
1928     /** Return the selected enumeration constant symbol, or null. */
1929     private Symbol enumConstant(JCTree tree, Type enumType) {
1930         if (tree.hasTag(IDENT)) {
1931             JCIdent ident = (JCIdent)tree;
1932             Name name = ident.name;
1933             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1934                 if (sym.kind == VAR) {
1935                     Symbol s = ident.sym = sym;
1936                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1937                     ident.type = s.type;
1938                     return ((s.flags_field & Flags.ENUM) == 0)
1939                         ? null : s;
1940                 }
1941             }
1942         }
1943         return null;
1944     }
1945 
1946     public void visitSynchronized(JCSynchronized tree) {
1947         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1948         if (isValueBased(tree.lock.type)) {
1949             env.info.lint.logIfEnabled(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1950         }
1951         attribStat(tree.body, env);
1952         result = null;
1953     }
1954         // where
1955         private boolean isValueBased(Type t) {
1956             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1957         }
1958 
1959 
1960     public void visitTry(JCTry tree) {
1961         // Create a new local environment with a local
1962         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1963         try {
1964             boolean isTryWithResource = tree.resources.nonEmpty();
1965             // Create a nested environment for attributing the try block if needed
1966             Env<AttrContext> tryEnv = isTryWithResource ?
1967                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1968                 localEnv;
1969             try {
1970                 // Attribute resource declarations
1971                 for (JCTree resource : tree.resources) {
1972                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1973                         @Override
1974                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1975                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1976                         }
1977                     };
1978                     ResultInfo twrResult =
1979                         new ResultInfo(KindSelector.VAR,
1980                                        syms.autoCloseableType,
1981                                        twrContext);
1982                     if (resource.hasTag(VARDEF)) {
1983                         attribStat(resource, tryEnv);
1984                         twrResult.check(resource, resource.type);
1985 
1986                         //check that resource type cannot throw InterruptedException
1987                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
1988 
1989                         VarSymbol var = ((JCVariableDecl) resource).sym;
1990 
1991                         var.flags_field |= Flags.FINAL;
1992                         var.setData(ElementKind.RESOURCE_VARIABLE);
1993                     } else {
1994                         attribTree(resource, tryEnv, twrResult);
1995                     }
1996                 }
1997                 // Attribute body
1998                 attribStat(tree.body, tryEnv);
1999             } finally {
2000                 if (isTryWithResource)
2001                     tryEnv.info.scope.leave();
2002             }
2003 
2004             // Attribute catch clauses
2005             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
2006                 JCCatch c = l.head;
2007                 Env<AttrContext> catchEnv =
2008                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
2009                 try {
2010                     Type ctype = attribStat(c.param, catchEnv);
2011                     if (TreeInfo.isMultiCatch(c)) {
2012                         //multi-catch parameter is implicitly marked as final
2013                         c.param.sym.flags_field |= FINAL | UNION;
2014                     }
2015                     if (c.param.sym.kind == VAR) {
2016                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
2017                     }
2018                     chk.checkType(c.param.vartype.pos(),
2019                                   chk.checkClassType(c.param.vartype.pos(), ctype),
2020                                   syms.throwableType);
2021                     attribStat(c.body, catchEnv);
2022                 } finally {
2023                     catchEnv.info.scope.leave();
2024                 }
2025             }
2026 
2027             // Attribute finalizer
2028             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
2029             result = null;
2030         }
2031         finally {
2032             localEnv.info.scope.leave();
2033         }
2034     }
2035 
2036     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
2037         if (!resource.isErroneous() &&
2038             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
2039             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2040             Symbol close = syms.noSymbol;
2041             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
2042             try {
2043                 close = rs.resolveQualifiedMethod(pos,
2044                         env,
2045                         types.skipTypeVars(resource, false),
2046                         names.close,
2047                         List.nil(),
2048                         List.nil());
2049             }
2050             finally {
2051                 log.popDiagnosticHandler(discardHandler);
2052             }
2053             if (close.kind == MTH &&
2054                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2055                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes())) {
2056                 env.info.lint.logIfEnabled(pos, LintWarnings.TryResourceThrowsInterruptedExc(resource));
2057             }
2058         }
2059     }
2060 
2061     public void visitConditional(JCConditional tree) {
2062         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
2063         MatchBindings condBindings = matchBindings;
2064 
2065         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
2066                 isBooleanOrNumeric(env, tree)) ?
2067                 PolyKind.STANDALONE : PolyKind.POLY;
2068 
2069         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2070             //this means we are returning a poly conditional from void-compatible lambda expression
2071             resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
2072             result = tree.type = types.createErrorType(resultInfo.pt);
2073             return;
2074         }
2075 
2076         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2077                 unknownExprInfo :
2078                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
2079 
2080 
2081         // x ? y : z
2082         // include x's bindings when true in y
2083         // include x's bindings when false in z
2084 
2085         Type truetype;
2086         Env<AttrContext> trueEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2087         try {
2088             truetype = attribTree(tree.truepart, trueEnv, condInfo);
2089         } finally {
2090             trueEnv.info.scope.leave();
2091         }
2092 
2093         MatchBindings trueBindings = matchBindings;
2094 
2095         Type falsetype;
2096         Env<AttrContext> falseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2097         try {
2098             falsetype = attribTree(tree.falsepart, falseEnv, condInfo);
2099         } finally {
2100             falseEnv.info.scope.leave();
2101         }
2102 
2103         MatchBindings falseBindings = matchBindings;
2104 
2105         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
2106                 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
2107                          List.of(truetype, falsetype)) : pt();
2108         if (condtype.constValue() != null &&
2109                 truetype.constValue() != null &&
2110                 falsetype.constValue() != null &&
2111                 !owntype.hasTag(NONE)) {
2112             //constant folding
2113             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
2114         }
2115         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2116         matchBindings = matchBindingsComputer.conditional(tree, condBindings, trueBindings, falseBindings);
2117     }
2118     //where
2119         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
2120             switch (tree.getTag()) {
2121                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
2122                               ((JCLiteral)tree).typetag == BOOLEAN ||
2123                               ((JCLiteral)tree).typetag == BOT;
2124                 case LAMBDA: case REFERENCE: return false;
2125                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
2126                 case CONDEXPR:
2127                     JCConditional condTree = (JCConditional)tree;
2128                     return isBooleanOrNumeric(env, condTree.truepart) &&
2129                             isBooleanOrNumeric(env, condTree.falsepart);
2130                 case APPLY:
2131                     JCMethodInvocation speculativeMethodTree =
2132                             (JCMethodInvocation)deferredAttr.attribSpeculative(
2133                                     tree, env, unknownExprInfo,
2134                                     argumentAttr.withLocalCacheContext());
2135                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
2136                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
2137                             env.enclClass.type :
2138                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
2139                     Type owntype = types.memberType(receiverType, msym).getReturnType();
2140                     return primitiveOrBoxed(owntype);
2141                 case NEWCLASS:
2142                     JCExpression className =
2143                             removeClassParams.translate(((JCNewClass)tree).clazz);
2144                     JCExpression speculativeNewClassTree =
2145                             (JCExpression)deferredAttr.attribSpeculative(
2146                                     className, env, unknownTypeInfo,
2147                                     argumentAttr.withLocalCacheContext());
2148                     return primitiveOrBoxed(speculativeNewClassTree.type);
2149                 default:
2150                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
2151                             argumentAttr.withLocalCacheContext()).type;
2152                     return primitiveOrBoxed(speculativeType);
2153             }
2154         }
2155         //where
2156             boolean primitiveOrBoxed(Type t) {
2157                 return (!t.hasTag(TYPEVAR) && !t.isErroneous() && types.unboxedTypeOrType(t).isPrimitive());
2158             }
2159 
2160             TreeTranslator removeClassParams = new TreeTranslator() {
2161                 @Override
2162                 public void visitTypeApply(JCTypeApply tree) {
2163                     result = translate(tree.clazz);
2164                 }
2165             };
2166 
2167         CheckContext conditionalContext(CheckContext checkContext) {
2168             return new Check.NestedCheckContext(checkContext) {
2169                 //this will use enclosing check context to check compatibility of
2170                 //subexpression against target type; if we are in a method check context,
2171                 //depending on whether boxing is allowed, we could have incompatibilities
2172                 @Override
2173                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2174                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
2175                 }
2176             };
2177         }
2178 
2179         /** Compute the type of a conditional expression, after
2180          *  checking that it exists.  See JLS 15.25. Does not take into
2181          *  account the special case where condition and both arms
2182          *  are constants.
2183          *
2184          *  @param pos      The source position to be used for error
2185          *                  diagnostics.
2186          *  @param thentype The type of the expression's then-part.
2187          *  @param elsetype The type of the expression's else-part.
2188          */
2189         Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
2190             if (condTypes.isEmpty()) {
2191                 return syms.objectType; //TODO: how to handle?
2192             }
2193             Type first = condTypes.head;
2194             // If same type, that is the result
2195             if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
2196                 return first.baseType();
2197 
2198             List<Type> unboxedTypes = condTypes.stream()
2199                                                .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
2200                                                .collect(List.collector());
2201 
2202             // Otherwise, if both arms can be converted to a numeric
2203             // type, return the least numeric type that fits both arms
2204             // (i.e. return larger of the two, or return int if one
2205             // arm is short, the other is char).
2206             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2207                 // If one arm has an integer subrange type (i.e., byte,
2208                 // short, or char), and the other is an integer constant
2209                 // that fits into the subrange, return the subrange type.
2210                 for (Type type : unboxedTypes) {
2211                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2212                         continue;
2213                     }
2214                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2215                         return type.baseType();
2216                 }
2217 
2218                 for (TypeTag tag : primitiveTags) {
2219                     Type candidate = syms.typeOfTag[tag.ordinal()];
2220                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2221                         return candidate;
2222                     }
2223                 }
2224             }
2225 
2226             // Those were all the cases that could result in a primitive
2227             condTypes = condTypes.stream()
2228                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
2229                                  .collect(List.collector());
2230 
2231             for (Type type : condTypes) {
2232                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2233                     return type.baseType();
2234             }
2235 
2236             Iterator<DiagnosticPosition> posIt = positions.iterator();
2237 
2238             condTypes = condTypes.stream()
2239                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
2240                                  .collect(List.collector());
2241 
2242             // both are known to be reference types.  The result is
2243             // lub(thentype,elsetype). This cannot fail, as it will
2244             // always be possible to infer "Object" if nothing better.
2245             return types.lub(condTypes.stream()
2246                         .map(t -> t.baseType())
2247                         .filter(t -> !t.hasTag(BOT))
2248                         .collect(List.collector()));
2249         }
2250 
2251     static final TypeTag[] primitiveTags = new TypeTag[]{
2252         BYTE,
2253         CHAR,
2254         SHORT,
2255         INT,
2256         LONG,
2257         FLOAT,
2258         DOUBLE,
2259         BOOLEAN,
2260     };
2261 
2262     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2263         return bindingEnv(env, env.tree, bindings);
2264     }
2265 
2266     Env<AttrContext> bindingEnv(Env<AttrContext> env, JCTree newTree, List<BindingSymbol> bindings) {
2267         Env<AttrContext> env1 = env.dup(newTree, env.info.dup(env.info.scope.dup()));
2268         bindings.forEach(env1.info.scope::enter);
2269         return env1;
2270     }
2271 
2272     public void visitIf(JCIf tree) {
2273         attribExpr(tree.cond, env, syms.booleanType);
2274 
2275         // if (x) { y } [ else z ]
2276         // include x's bindings when true in y
2277         // include x's bindings when false in z
2278 
2279         MatchBindings condBindings = matchBindings;
2280         Env<AttrContext> thenEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2281 
2282         try {
2283             attribStat(tree.thenpart, thenEnv);
2284         } finally {
2285             thenEnv.info.scope.leave();
2286         }
2287 
2288         preFlow(tree.thenpart);
2289         boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make);
2290         boolean aliveAfterElse;
2291 
2292         if (tree.elsepart != null) {
2293             Env<AttrContext> elseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2294             try {
2295                 attribStat(tree.elsepart, elseEnv);
2296             } finally {
2297                 elseEnv.info.scope.leave();
2298             }
2299             preFlow(tree.elsepart);
2300             aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make);
2301         } else {
2302             aliveAfterElse = true;
2303         }
2304 
2305         chk.checkEmptyIf(tree);
2306 
2307         List<BindingSymbol> afterIfBindings = List.nil();
2308 
2309         if (aliveAfterThen && !aliveAfterElse) {
2310             afterIfBindings = condBindings.bindingsWhenTrue;
2311         } else if (aliveAfterElse && !aliveAfterThen) {
2312             afterIfBindings = condBindings.bindingsWhenFalse;
2313         }
2314 
2315         addBindings2Scope(tree, afterIfBindings);
2316 
2317         result = null;
2318     }
2319 
2320         void preFlow(JCTree tree) {
2321             attrRecover.doRecovery();
2322             new PostAttrAnalyzer() {
2323                 @Override
2324                 public void scan(JCTree tree) {
2325                     if (tree == null ||
2326                             (tree.type != null &&
2327                             tree.type == Type.stuckType)) {
2328                         //don't touch stuck expressions!
2329                         return;
2330                     }
2331                     super.scan(tree);
2332                 }
2333 
2334                 @Override
2335                 public void visitClassDef(JCClassDecl that) {
2336                     if (that.sym != null) {
2337                         // Method preFlow shouldn't visit class definitions
2338                         // that have not been entered and attributed.
2339                         // See JDK-8254557 and JDK-8203277 for more details.
2340                         super.visitClassDef(that);
2341                     }
2342                 }
2343 
2344                 @Override
2345                 public void visitLambda(JCLambda that) {
2346                     if (that.type != null) {
2347                         // Method preFlow shouldn't visit lambda expressions
2348                         // that have not been entered and attributed.
2349                         // See JDK-8254557 and JDK-8203277 for more details.
2350                         super.visitLambda(that);
2351                     }
2352                 }
2353             }.scan(tree);
2354         }
2355 
2356     public void visitExec(JCExpressionStatement tree) {
2357         //a fresh environment is required for 292 inference to work properly ---
2358         //see Infer.instantiatePolymorphicSignatureInstance()
2359         Env<AttrContext> localEnv = env.dup(tree);
2360         attribExpr(tree.expr, localEnv);
2361         result = null;
2362     }
2363 
2364     public void visitBreak(JCBreak tree) {
2365         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2366         result = null;
2367     }
2368 
2369     public void visitYield(JCYield tree) {
2370         if (env.info.yieldResult != null) {
2371             attribTree(tree.value, env, env.info.yieldResult);
2372             tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
2373         } else {
2374             log.error(tree.pos(), tree.value.hasTag(PARENS)
2375                     ? Errors.NoSwitchExpressionQualify
2376                     : Errors.NoSwitchExpression);
2377             attribTree(tree.value, env, unknownExprInfo);
2378         }
2379         result = null;
2380     }
2381 
2382     public void visitContinue(JCContinue tree) {
2383         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2384         result = null;
2385     }
2386     //where
2387         /** Return the target of a break, continue or yield statement,
2388          *  if it exists, report an error if not.
2389          *  Note: The target of a labelled break or continue is the
2390          *  (non-labelled) statement tree referred to by the label,
2391          *  not the tree representing the labelled statement itself.
2392          *
2393          *  @param pos     The position to be used for error diagnostics
2394          *  @param tag     The tag of the jump statement. This is either
2395          *                 Tree.BREAK or Tree.CONTINUE.
2396          *  @param label   The label of the jump statement, or null if no
2397          *                 label is given.
2398          *  @param env     The environment current at the jump statement.
2399          */
2400         private JCTree findJumpTarget(DiagnosticPosition pos,
2401                                                    JCTree.Tag tag,
2402                                                    Name label,
2403                                                    Env<AttrContext> env) {
2404             Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
2405 
2406             if (jumpTarget.snd != null) {
2407                 log.error(pos, jumpTarget.snd);
2408             }
2409 
2410             return jumpTarget.fst;
2411         }
2412         /** Return the target of a break or continue statement, if it exists,
2413          *  report an error if not.
2414          *  Note: The target of a labelled break or continue is the
2415          *  (non-labelled) statement tree referred to by the label,
2416          *  not the tree representing the labelled statement itself.
2417          *
2418          *  @param tag     The tag of the jump statement. This is either
2419          *                 Tree.BREAK or Tree.CONTINUE.
2420          *  @param label   The label of the jump statement, or null if no
2421          *                 label is given.
2422          *  @param env     The environment current at the jump statement.
2423          */
2424         private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
2425                                                                        Name label,
2426                                                                        Env<AttrContext> env) {
2427             // Search environments outwards from the point of jump.
2428             Env<AttrContext> env1 = env;
2429             JCDiagnostic.Error pendingError = null;
2430             LOOP:
2431             while (env1 != null) {
2432                 switch (env1.tree.getTag()) {
2433                     case LABELLED:
2434                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
2435                         if (label == labelled.label) {
2436                             // If jump is a continue, check that target is a loop.
2437                             if (tag == CONTINUE) {
2438                                 if (!labelled.body.hasTag(DOLOOP) &&
2439                                         !labelled.body.hasTag(WHILELOOP) &&
2440                                         !labelled.body.hasTag(FORLOOP) &&
2441                                         !labelled.body.hasTag(FOREACHLOOP)) {
2442                                     pendingError = Errors.NotLoopLabel(label);
2443                                 }
2444                                 // Found labelled statement target, now go inwards
2445                                 // to next non-labelled tree.
2446                                 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
2447                             } else {
2448                                 return Pair.of(labelled, pendingError);
2449                             }
2450                         }
2451                         break;
2452                     case DOLOOP:
2453                     case WHILELOOP:
2454                     case FORLOOP:
2455                     case FOREACHLOOP:
2456                         if (label == null) return Pair.of(env1.tree, pendingError);
2457                         break;
2458                     case SWITCH:
2459                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
2460                         break;
2461                     case SWITCH_EXPRESSION:
2462                         if (tag == YIELD) {
2463                             return Pair.of(env1.tree, null);
2464                         } else if (tag == BREAK) {
2465                             pendingError = Errors.BreakOutsideSwitchExpression;
2466                         } else {
2467                             pendingError = Errors.ContinueOutsideSwitchExpression;
2468                         }
2469                         break;
2470                     case LAMBDA:
2471                     case METHODDEF:
2472                     case CLASSDEF:
2473                         break LOOP;
2474                     default:
2475                 }
2476                 env1 = env1.next;
2477             }
2478             if (label != null)
2479                 return Pair.of(null, Errors.UndefLabel(label));
2480             else if (pendingError != null)
2481                 return Pair.of(null, pendingError);
2482             else if (tag == CONTINUE)
2483                 return Pair.of(null, Errors.ContOutsideLoop);
2484             else
2485                 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
2486         }
2487 
2488     public void visitReturn(JCReturn tree) {
2489         // Check that there is an enclosing method which is
2490         // nested within than the enclosing class.
2491         if (env.info.returnResult == null) {
2492             log.error(tree.pos(), Errors.RetOutsideMeth);
2493         } else if (env.info.yieldResult != null) {
2494             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
2495             if (tree.expr != null) {
2496                 attribExpr(tree.expr, env, env.info.yieldResult.pt);
2497             }
2498         } else if (!env.info.isLambda &&
2499                 !env.info.isNewClass &&
2500                 env.enclMethod != null &&
2501                 TreeInfo.isCompactConstructor(env.enclMethod)) {
2502             log.error(env.enclMethod,
2503                     Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement));
2504         } else {
2505             // Attribute return expression, if it exists, and check that
2506             // it conforms to result type of enclosing method.
2507             if (tree.expr != null) {
2508                 if (env.info.returnResult.pt.hasTag(VOID)) {
2509                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2510                               diags.fragment(Fragments.UnexpectedRetVal));
2511                 }
2512                 attribTree(tree.expr, env, env.info.returnResult);
2513             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2514                     !env.info.returnResult.pt.hasTag(NONE)) {
2515                 env.info.returnResult.checkContext.report(tree.pos(),
2516                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2517             }
2518         }
2519         result = null;
2520     }
2521 
2522     public void visitThrow(JCThrow tree) {
2523         Type owntype = attribExpr(tree.expr, env, Type.noType);
2524         chk.checkType(tree, owntype, syms.throwableType);
2525         result = null;
2526     }
2527 
2528     public void visitAssert(JCAssert tree) {
2529         attribExpr(tree.cond, env, syms.booleanType);
2530         if (tree.detail != null) {
2531             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2532         }
2533         result = null;
2534     }
2535 
2536      /** Visitor method for method invocations.
2537      *  NOTE: The method part of an application will have in its type field
2538      *        the return type of the method, not the method's type itself!
2539      */
2540     public void visitApply(JCMethodInvocation tree) {
2541         // The local environment of a method application is
2542         // a new environment nested in the current one.
2543         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2544 
2545         // The types of the actual method arguments.
2546         List<Type> argtypes;
2547 
2548         // The types of the actual method type arguments.
2549         List<Type> typeargtypes = null;
2550 
2551         Name methName = TreeInfo.name(tree.meth);
2552 
2553         boolean isConstructorCall =
2554             methName == names._this || methName == names._super;
2555 
2556         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2557         if (isConstructorCall) {
2558 
2559             // Attribute arguments, yielding list of argument types.
2560             KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2561             argtypes = argtypesBuf.toList();
2562             typeargtypes = attribTypes(tree.typeargs, localEnv);
2563 
2564             // Done with this()/super() parameters. End of constructor prologue.
2565             env.info.ctorPrologue = false;
2566 
2567             // Variable `site' points to the class in which the called
2568             // constructor is defined.
2569             Type site = env.enclClass.sym.type;
2570             if (methName == names._super) {
2571                 if (site == syms.objectType) {
2572                     log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2573                     site = types.createErrorType(syms.objectType);
2574                 } else {
2575                     site = types.supertype(site);
2576                 }
2577             }
2578 
2579             if (site.hasTag(CLASS)) {
2580                 Type encl = site.getEnclosingType();
2581                 while (encl != null && encl.hasTag(TYPEVAR))
2582                     encl = encl.getUpperBound();
2583                 if (encl.hasTag(CLASS)) {
2584                     // we are calling a nested class
2585 
2586                     if (tree.meth.hasTag(SELECT)) {
2587                         JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2588 
2589                         // We are seeing a prefixed call, of the form
2590                         //     <expr>.super(...).
2591                         // Check that the prefix expression conforms
2592                         // to the outer instance type of the class.
2593                         chk.checkRefType(qualifier.pos(),
2594                                          attribExpr(qualifier, localEnv,
2595                                                     encl));
2596                     }
2597                 } else if (tree.meth.hasTag(SELECT)) {
2598                     log.error(tree.meth.pos(),
2599                               Errors.IllegalQualNotIcls(site.tsym));
2600                     attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2601                 }
2602 
2603                 if (tree.meth.hasTag(IDENT)) {
2604                     // non-qualified super(...) call; check whether explicit constructor
2605                     // invocation is well-formed. If the super class is an inner class,
2606                     // make sure that an appropriate implicit qualifier exists. If the super
2607                     // class is a local class, make sure that the current class is defined
2608                     // in the same context as the local class.
2609                     checkNewInnerClass(tree.meth.pos(), localEnv, site, true);
2610                 }
2611 
2612                 // if we're calling a java.lang.Enum constructor,
2613                 // prefix the implicit String and int parameters
2614                 if (site.tsym == syms.enumSym)
2615                     argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
2616 
2617                 // Resolve the called constructor under the assumption
2618                 // that we are referring to a superclass instance of the
2619                 // current instance (JLS ???).
2620                 boolean selectSuperPrev = localEnv.info.selectSuper;
2621                 localEnv.info.selectSuper = true;
2622                 localEnv.info.pendingResolutionPhase = null;
2623                 Symbol sym = rs.resolveConstructor(
2624                     tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
2625                 localEnv.info.selectSuper = selectSuperPrev;
2626 
2627                 // Set method symbol to resolved constructor...
2628                 TreeInfo.setSymbol(tree.meth, sym);
2629 
2630                 // ...and check that it is legal in the current context.
2631                 // (this will also set the tree's type)
2632                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2633                 checkId(tree.meth, site, sym, localEnv,
2634                         new ResultInfo(kind, mpt));
2635             } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) {
2636                 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2637             }
2638             // Otherwise, `site' is an error type and we do nothing
2639             result = tree.type = syms.voidType;
2640         } else {
2641             // Otherwise, we are seeing a regular method call.
2642             // Attribute the arguments, yielding list of argument types, ...
2643             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2644             argtypes = argtypesBuf.toList();
2645             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
2646 
2647             // ... and attribute the method using as a prototype a methodtype
2648             // whose formal argument types is exactly the list of actual
2649             // arguments (this will also set the method symbol).
2650             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2651             localEnv.info.pendingResolutionPhase = null;
2652             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2653 
2654             // Compute the result type.
2655             Type restype = mtype.getReturnType();
2656             if (restype.hasTag(WILDCARD))
2657                 throw new AssertionError(mtype);
2658 
2659             Type qualifier = (tree.meth.hasTag(SELECT))
2660                     ? ((JCFieldAccess) tree.meth).selected.type
2661                     : env.enclClass.sym.type;
2662             Symbol msym = TreeInfo.symbol(tree.meth);
2663             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2664 
2665             chk.checkRefTypes(tree.typeargs, typeargtypes);
2666 
2667             // Check that value of resulting type is admissible in the
2668             // current context.  Also, capture the return type
2669             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2670             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2671         }
2672         chk.validate(tree.typeargs, localEnv);
2673     }
2674     //where
2675         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2676             if (msym != null &&
2677                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2678                     methodName == names.getClass &&
2679                     argtypes.isEmpty()) {
2680                 // as a special case, x.getClass() has type Class<? extends |X|>
2681                 return new ClassType(restype.getEnclosingType(),
2682                         List.of(new WildcardType(types.erasure(qualifierType.baseType()),
2683                                 BoundKind.EXTENDS,
2684                                 syms.boundClass)),
2685                         restype.tsym,
2686                         restype.getMetadata());
2687             } else if (msym != null &&
2688                     msym.owner == syms.arrayClass &&
2689                     methodName == names.clone &&
2690                     types.isArray(qualifierType)) {
2691                 // as a special case, array.clone() has a result that is
2692                 // the same as static type of the array being cloned
2693                 return qualifierType;
2694             } else {
2695                 return restype;
2696             }
2697         }
2698 
2699         /** Obtain a method type with given argument types.
2700          */
2701         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2702             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2703             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2704         }
2705 
2706     public void visitNewClass(final JCNewClass tree) {
2707         Type owntype = types.createErrorType(tree.type);
2708 
2709         // The local environment of a class creation is
2710         // a new environment nested in the current one.
2711         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2712 
2713         // The anonymous inner class definition of the new expression,
2714         // if one is defined by it.
2715         JCClassDecl cdef = tree.def;
2716 
2717         // If enclosing class is given, attribute it, and
2718         // complete class name to be fully qualified
2719         JCExpression clazz = tree.clazz; // Class field following new
2720         JCExpression clazzid;            // Identifier in class field
2721         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
2722         annoclazzid = null;
2723 
2724         if (clazz.hasTag(TYPEAPPLY)) {
2725             clazzid = ((JCTypeApply) clazz).clazz;
2726             if (clazzid.hasTag(ANNOTATED_TYPE)) {
2727                 annoclazzid = (JCAnnotatedType) clazzid;
2728                 clazzid = annoclazzid.underlyingType;
2729             }
2730         } else {
2731             if (clazz.hasTag(ANNOTATED_TYPE)) {
2732                 annoclazzid = (JCAnnotatedType) clazz;
2733                 clazzid = annoclazzid.underlyingType;
2734             } else {
2735                 clazzid = clazz;
2736             }
2737         }
2738 
2739         JCExpression clazzid1 = clazzid; // The same in fully qualified form
2740 
2741         if (tree.encl != null) {
2742             // We are seeing a qualified new, of the form
2743             //    <expr>.new C <...> (...) ...
2744             // In this case, we let clazz stand for the name of the
2745             // allocated class C prefixed with the type of the qualifier
2746             // expression, so that we can
2747             // resolve it with standard techniques later. I.e., if
2748             // <expr> has type T, then <expr>.new C <...> (...)
2749             // yields a clazz T.C.
2750             Type encltype = chk.checkRefType(tree.encl.pos(),
2751                                              attribExpr(tree.encl, env));
2752             // TODO 308: in <expr>.new C, do we also want to add the type annotations
2753             // from expr to the combined type, or not? Yes, do this.
2754             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
2755                                                  ((JCIdent) clazzid).name);
2756 
2757             EndPosTable endPosTable = this.env.toplevel.endPositions;
2758             endPosTable.storeEnd(clazzid1, clazzid.getEndPosition(endPosTable));
2759             if (clazz.hasTag(ANNOTATED_TYPE)) {
2760                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
2761                 List<JCAnnotation> annos = annoType.annotations;
2762 
2763                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
2764                     clazzid1 = make.at(tree.pos).
2765                         TypeApply(clazzid1,
2766                                   ((JCTypeApply) clazz).arguments);
2767                 }
2768 
2769                 clazzid1 = make.at(tree.pos).
2770                     AnnotatedType(annos, clazzid1);
2771             } else if (clazz.hasTag(TYPEAPPLY)) {
2772                 clazzid1 = make.at(tree.pos).
2773                     TypeApply(clazzid1,
2774                               ((JCTypeApply) clazz).arguments);
2775             }
2776 
2777             clazz = clazzid1;
2778         }
2779 
2780         // Attribute clazz expression and store
2781         // symbol + type back into the attributed tree.
2782         Type clazztype;
2783 
2784         try {
2785             env.info.isNewClass = true;
2786             clazztype = TreeInfo.isEnumInit(env.tree) ?
2787                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2788                 attribType(clazz, env);
2789         } finally {
2790             env.info.isNewClass = false;
2791         }
2792 
2793         clazztype = chk.checkDiamond(tree, clazztype);
2794         chk.validate(clazz, localEnv);
2795         if (tree.encl != null) {
2796             // We have to work in this case to store
2797             // symbol + type back into the attributed tree.
2798             tree.clazz.type = clazztype;
2799             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2800             clazzid.type = ((JCIdent) clazzid).sym.type;
2801             if (annoclazzid != null) {
2802                 annoclazzid.type = clazzid.type;
2803             }
2804             if (!clazztype.isErroneous()) {
2805                 if (cdef != null && clazztype.tsym.isInterface()) {
2806                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2807                 } else if (clazztype.tsym.isStatic()) {
2808                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
2809                 }
2810             }
2811         } else {
2812             // Check for the existence of an apropos outer instance
2813             checkNewInnerClass(tree.pos(), env, clazztype, false);
2814         }
2815 
2816         // Attribute constructor arguments.
2817         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2818         final KindSelector pkind =
2819             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2820         List<Type> argtypes = argtypesBuf.toList();
2821         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2822 
2823         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2824             // Enums may not be instantiated except implicitly
2825             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2826                 (!env.tree.hasTag(VARDEF) ||
2827                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2828                  ((JCVariableDecl) env.tree).init != tree))
2829                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2830 
2831             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2832                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2833             boolean skipNonDiamondPath = false;
2834             // Check that class is not abstract
2835             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2836                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2837                 log.error(tree.pos(),
2838                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2839                 skipNonDiamondPath = true;
2840             } else if (cdef != null && clazztype.tsym.isInterface()) {
2841                 // Check that no constructor arguments are given to
2842                 // anonymous classes implementing an interface
2843                 if (!argtypes.isEmpty())
2844                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2845 
2846                 if (!typeargtypes.isEmpty())
2847                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2848 
2849                 // Error recovery: pretend no arguments were supplied.
2850                 argtypes = List.nil();
2851                 typeargtypes = List.nil();
2852                 skipNonDiamondPath = true;
2853             }
2854             if (TreeInfo.isDiamond(tree)) {
2855                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2856                             clazztype.tsym.type.getTypeArguments(),
2857                                                clazztype.tsym,
2858                                                clazztype.getMetadata());
2859 
2860                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2861                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2862                 diamondEnv.info.pendingResolutionPhase = null;
2863 
2864                 //if the type of the instance creation expression is a class type
2865                 //apply method resolution inference (JLS 15.12.2.7). The return type
2866                 //of the resolved constructor will be a partially instantiated type
2867                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2868                             diamondEnv,
2869                             site,
2870                             argtypes,
2871                             typeargtypes);
2872                 tree.constructor = constructor.baseSymbol();
2873 
2874                 final TypeSymbol csym = clazztype.tsym;
2875                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2876                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2877                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2878                 constructorType = checkId(tree, site,
2879                         constructor,
2880                         diamondEnv,
2881                         diamondResult);
2882 
2883                 tree.clazz.type = types.createErrorType(clazztype);
2884                 if (!constructorType.isErroneous()) {
2885                     tree.clazz.type = clazz.type = constructorType.getReturnType();
2886                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2887                 }
2888                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2889             }
2890 
2891             // Resolve the called constructor under the assumption
2892             // that we are referring to a superclass instance of the
2893             // current instance (JLS ???).
2894             else if (!skipNonDiamondPath) {
2895                 //the following code alters some of the fields in the current
2896                 //AttrContext - hence, the current context must be dup'ed in
2897                 //order to avoid downstream failures
2898                 Env<AttrContext> rsEnv = localEnv.dup(tree);
2899                 rsEnv.info.selectSuper = cdef != null;
2900                 rsEnv.info.pendingResolutionPhase = null;
2901                 tree.constructor = rs.resolveConstructor(
2902                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2903                 if (cdef == null) { //do not check twice!
2904                     tree.constructorType = checkId(tree,
2905                             clazztype,
2906                             tree.constructor,
2907                             rsEnv,
2908                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2909                     if (rsEnv.info.lastResolveVarargs())
2910                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2911                 }
2912             }
2913 
2914             if (cdef != null) {
2915                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2916                 return;
2917             }
2918 
2919             if (tree.constructor != null && tree.constructor.kind == MTH)
2920                 owntype = clazztype;
2921         }
2922         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2923         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2924         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2925             //we need to wait for inference to finish and then replace inference vars in the constructor type
2926             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2927                     instantiatedContext -> {
2928                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2929                     });
2930         }
2931         chk.validate(tree.typeargs, localEnv);
2932     }
2933 
2934         // where
2935         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2936                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
2937                                                    List<Type> argtypes, List<Type> typeargtypes,
2938                                                    KindSelector pkind) {
2939             // We are seeing an anonymous class instance creation.
2940             // In this case, the class instance creation
2941             // expression
2942             //
2943             //    E.new <typeargs1>C<typargs2>(args) { ... }
2944             //
2945             // is represented internally as
2946             //
2947             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2948             //
2949             // This expression is then *transformed* as follows:
2950             //
2951             // (1) add an extends or implements clause
2952             // (2) add a constructor.
2953             //
2954             // For instance, if C is a class, and ET is the type of E,
2955             // the expression
2956             //
2957             //    E.new <typeargs1>C<typargs2>(args) { ... }
2958             //
2959             // is translated to (where X is a fresh name and typarams is the
2960             // parameter list of the super constructor):
2961             //
2962             //   new <typeargs1>X(<*nullchk*>E, args) where
2963             //     X extends C<typargs2> {
2964             //       <typarams> X(ET e, args) {
2965             //         e.<typeargs1>super(args)
2966             //       }
2967             //       ...
2968             //     }
2969             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2970             Type enclType = clazztype.getEnclosingType();
2971             if (enclType != null &&
2972                     enclType.hasTag(CLASS) &&
2973                     !chk.checkDenotable((ClassType)enclType)) {
2974                 log.error(tree.encl, Errors.EnclosingClassTypeNonDenotable(enclType));
2975             }
2976             final boolean isDiamond = TreeInfo.isDiamond(tree);
2977             if (isDiamond
2978                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2979                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2980                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2981                 Env<AttrContext> dupLocalEnv = copyEnv(localEnv);
2982                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2983                         instantiatedContext -> {
2984                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2985                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
2986                             ResultInfo prevResult = this.resultInfo;
2987                             try {
2988                                 this.resultInfo = resultInfoForClassDefinition;
2989                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
2990                                         dupLocalEnv, argtypes, typeargtypes, pkind);
2991                             } finally {
2992                                 this.resultInfo = prevResult;
2993                             }
2994                         });
2995             } else {
2996                 if (isDiamond && clazztype.hasTag(CLASS)) {
2997                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2998                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2999                         // One or more types inferred in the previous steps is non-denotable.
3000                         Fragment fragment = Diamond(clazztype.tsym);
3001                         log.error(tree.clazz.pos(),
3002                                 Errors.CantApplyDiamond1(
3003                                         fragment,
3004                                         invalidDiamondArgs.size() > 1 ?
3005                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3006                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3007                     }
3008                     // For <>(){}, inferred types must also be accessible.
3009                     for (Type t : clazztype.getTypeArguments()) {
3010                         rs.checkAccessibleType(env, t);
3011                     }
3012                 }
3013 
3014                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3015                 // false for isInterface call even when the original type is an interface.
3016                 boolean implementing = clazztype.tsym.isInterface() ||
3017                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3018                         clazztype.getOriginalType().tsym.isInterface();
3019 
3020                 if (implementing) {
3021                     cdef.implementing = List.of(clazz);
3022                 } else {
3023                     cdef.extending = clazz;
3024                 }
3025 
3026                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3027                     rs.isSerializable(clazztype)) {
3028                     localEnv.info.isSerializable = true;
3029                 }
3030 
3031                 attribStat(cdef, localEnv);
3032 
3033                 List<Type> finalargtypes;
3034                 // If an outer instance is given,
3035                 // prefix it to the constructor arguments
3036                 // and delete it from the new expression
3037                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
3038                     finalargtypes = argtypes.prepend(tree.encl.type);
3039                 } else {
3040                     finalargtypes = argtypes;
3041                 }
3042 
3043                 // Reassign clazztype and recompute constructor. As this necessarily involves
3044                 // another attribution pass for deferred types in the case of <>, replicate
3045                 // them. Original arguments have right decorations already.
3046                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
3047                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
3048                 }
3049 
3050                 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
3051                                                     : cdef.sym.type;
3052                 Symbol sym = tree.constructor = rs.resolveConstructor(
3053                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
3054                 Assert.check(!sym.kind.isResolutionError());
3055                 tree.constructor = sym;
3056                 tree.constructorType = checkId(tree,
3057                         clazztype,
3058                         tree.constructor,
3059                         localEnv,
3060                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3061             }
3062             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
3063                                 clazztype : types.createErrorType(tree.type);
3064             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3065             chk.validate(tree.typeargs, localEnv);
3066         }
3067 
3068         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3069             return new Check.NestedCheckContext(checkContext) {
3070                 @Override
3071                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3072                     enclosingContext.report(clazz.clazz,
3073                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3074                 }
3075             };
3076         }
3077 
3078         void checkNewInnerClass(DiagnosticPosition pos, Env<AttrContext> env, Type type, boolean isSuper) {
3079             boolean isLocal = type.tsym.owner.kind == VAR || type.tsym.owner.kind == MTH;
3080             if ((type.tsym.flags() & (INTERFACE | ENUM | RECORD)) != 0 ||
3081                     (!isLocal && !type.tsym.isInner()) ||
3082                     (isSuper && env.enclClass.sym.isAnonymous())) {
3083                 // nothing to check
3084                 return;
3085             }
3086             Symbol res = isLocal ?
3087                     rs.findLocalClassOwner(env, type.tsym) :
3088                     rs.findSelfContaining(pos, env, type.getEnclosingType().tsym, isSuper);
3089             if (res.exists()) {
3090                 rs.accessBase(res, pos, env.enclClass.sym.type, names._this, true);
3091             } else {
3092                 log.error(pos, Errors.EnclClassRequired(type.tsym));
3093             }
3094         }
3095 
3096     /** Make an attributed null check tree.
3097      */
3098     public JCExpression makeNullCheck(JCExpression arg) {
3099         // optimization: new Outer() can never be null; skip null check
3100         if (arg.getTag() == NEWCLASS)
3101             return arg;
3102         // optimization: X.this is never null; skip null check
3103         Name name = TreeInfo.name(arg);
3104         if (name == names._this || name == names._super) return arg;
3105 
3106         JCTree.Tag optag = NULLCHK;
3107         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3108         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3109         tree.type = arg.type;
3110         return tree;
3111     }
3112 
3113     public void visitNewArray(JCNewArray tree) {
3114         Type owntype = types.createErrorType(tree.type);
3115         Env<AttrContext> localEnv = env.dup(tree);
3116         Type elemtype;
3117         if (tree.elemtype != null) {
3118             elemtype = attribType(tree.elemtype, localEnv);
3119             chk.validate(tree.elemtype, localEnv);
3120             owntype = elemtype;
3121             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3122                 attribExpr(l.head, localEnv, syms.intType);
3123                 owntype = new ArrayType(owntype, syms.arrayClass);
3124             }
3125         } else {
3126             // we are seeing an untyped aggregate { ... }
3127             // this is allowed only if the prototype is an array
3128             if (pt().hasTag(ARRAY)) {
3129                 elemtype = types.elemtype(pt());
3130             } else {
3131                 if (!pt().hasTag(ERROR) &&
3132                         (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3133                     log.error(tree.pos(),
3134                               Errors.IllegalInitializerForType(pt()));
3135                 }
3136                 elemtype = types.createErrorType(pt());
3137             }
3138         }
3139         if (tree.elems != null) {
3140             attribExprs(tree.elems, localEnv, elemtype);
3141             owntype = new ArrayType(elemtype, syms.arrayClass);
3142         }
3143         if (!types.isReifiable(elemtype))
3144             log.error(tree.pos(), Errors.GenericArrayCreation);
3145         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3146     }
3147 
3148     /*
3149      * A lambda expression can only be attributed when a target-type is available.
3150      * In addition, if the target-type is that of a functional interface whose
3151      * descriptor contains inference variables in argument position the lambda expression
3152      * is 'stuck' (see DeferredAttr).
3153      */
3154     @Override
3155     public void visitLambda(final JCLambda that) {
3156         boolean wrongContext = false;
3157         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3158             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3159                 //lambda only allowed in assignment or method invocation/cast context
3160                 log.error(that.pos(), Errors.UnexpectedLambda);
3161             }
3162             resultInfo = recoveryInfo;
3163             wrongContext = true;
3164         }
3165         //create an environment for attribution of the lambda expression
3166         final Env<AttrContext> localEnv = lambdaEnv(that, env);
3167         boolean needsRecovery =
3168                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
3169         try {
3170             if (needsRecovery && rs.isSerializable(pt())) {
3171                 localEnv.info.isSerializable = true;
3172                 localEnv.info.isSerializableLambda = true;
3173             }
3174             List<Type> explicitParamTypes = null;
3175             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
3176                 //attribute lambda parameters
3177                 attribStats(that.params, localEnv);
3178                 explicitParamTypes = TreeInfo.types(that.params);
3179             }
3180 
3181             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
3182             Type currentTarget = targetInfo.target;
3183             Type lambdaType = targetInfo.descriptor;
3184 
3185             if (currentTarget.isErroneous()) {
3186                 result = that.type = currentTarget;
3187                 return;
3188             }
3189 
3190             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
3191 
3192             if (lambdaType.hasTag(FORALL)) {
3193                 //lambda expression target desc cannot be a generic method
3194                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3195                                                                     kindName(currentTarget.tsym),
3196                                                                     currentTarget.tsym);
3197                 resultInfo.checkContext.report(that, diags.fragment(msg));
3198                 result = that.type = types.createErrorType(pt());
3199                 return;
3200             }
3201 
3202             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
3203                 //add param type info in the AST
3204                 List<Type> actuals = lambdaType.getParameterTypes();
3205                 List<JCVariableDecl> params = that.params;
3206 
3207                 boolean arityMismatch = false;
3208 
3209                 while (params.nonEmpty()) {
3210                     if (actuals.isEmpty()) {
3211                         //not enough actuals to perform lambda parameter inference
3212                         arityMismatch = true;
3213                     }
3214                     //reset previously set info
3215                     Type argType = arityMismatch ?
3216                             syms.errType :
3217                             actuals.head;
3218                     if (params.head.isImplicitlyTyped()) {
3219                         setSyntheticVariableType(params.head, argType);
3220                     }
3221                     params.head.sym = null;
3222                     actuals = actuals.isEmpty() ?
3223                             actuals :
3224                             actuals.tail;
3225                     params = params.tail;
3226                 }
3227 
3228                 //attribute lambda parameters
3229                 attribStats(that.params, localEnv);
3230 
3231                 if (arityMismatch) {
3232                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3233                         result = that.type = types.createErrorType(currentTarget);
3234                         return;
3235                 }
3236             }
3237 
3238             //from this point on, no recovery is needed; if we are in assignment context
3239             //we will be able to attribute the whole lambda body, regardless of errors;
3240             //if we are in a 'check' method context, and the lambda is not compatible
3241             //with the target-type, it will be recovered anyway in Attr.checkId
3242             needsRecovery = false;
3243 
3244             ResultInfo bodyResultInfo = localEnv.info.returnResult =
3245                     lambdaBodyResult(that, lambdaType, resultInfo);
3246 
3247             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
3248                 attribTree(that.getBody(), localEnv, bodyResultInfo);
3249             } else {
3250                 JCBlock body = (JCBlock)that.body;
3251                 if (body == breakTree &&
3252                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3253                     breakTreeFound(copyEnv(localEnv));
3254                 }
3255                 attribStats(body.stats, localEnv);
3256             }
3257 
3258             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3259 
3260             boolean isSpeculativeRound =
3261                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3262 
3263             preFlow(that);
3264             flow.analyzeLambda(env, that, make, isSpeculativeRound);
3265 
3266             that.type = currentTarget; //avoids recovery at this stage
3267             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
3268 
3269             if (!isSpeculativeRound) {
3270                 //add thrown types as bounds to the thrown types free variables if needed:
3271                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
3272                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
3273                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
3274                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
3275                     }
3276                 }
3277 
3278                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
3279             }
3280             result = wrongContext ? that.type = types.createErrorType(pt())
3281                                   : check(that, currentTarget, KindSelector.VAL, resultInfo);
3282         } catch (Types.FunctionDescriptorLookupError ex) {
3283             JCDiagnostic cause = ex.getDiagnostic();
3284             resultInfo.checkContext.report(that, cause);
3285             result = that.type = types.createErrorType(pt());
3286             return;
3287         } catch (CompletionFailure cf) {
3288             chk.completionError(that.pos(), cf);
3289         } catch (Throwable t) {
3290             //when an unexpected exception happens, avoid attempts to attribute the same tree again
3291             //as that would likely cause the same exception again.
3292             needsRecovery = false;
3293             throw t;
3294         } finally {
3295             localEnv.info.scope.leave();
3296             if (needsRecovery) {
3297                 Type prevResult = result;
3298                 try {
3299                     attribTree(that, env, recoveryInfo);
3300                 } finally {
3301                     if (result == Type.recoveryType) {
3302                         result = prevResult;
3303                     }
3304                 }
3305             }
3306         }
3307     }
3308     //where
3309         class TargetInfo {
3310             Type target;
3311             Type descriptor;
3312 
3313             public TargetInfo(Type target, Type descriptor) {
3314                 this.target = target;
3315                 this.descriptor = descriptor;
3316             }
3317         }
3318 
3319         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
3320             Type lambdaType;
3321             Type currentTarget = resultInfo.pt;
3322             if (resultInfo.pt != Type.recoveryType) {
3323                 /* We need to adjust the target. If the target is an
3324                  * intersection type, for example: SAM & I1 & I2 ...
3325                  * the target will be updated to SAM
3326                  */
3327                 currentTarget = targetChecker.visit(currentTarget, that);
3328                 if (!currentTarget.isIntersection()) {
3329                     if (explicitParamTypes != null) {
3330                         currentTarget = infer.instantiateFunctionalInterface(that,
3331                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
3332                     }
3333                     currentTarget = types.removeWildcards(currentTarget);
3334                     lambdaType = types.findDescriptorType(currentTarget);
3335                 } else {
3336                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
3337                     ListBuffer<Type> components = new ListBuffer<>();
3338                     for (Type bound : ict.getExplicitComponents()) {
3339                         if (explicitParamTypes != null) {
3340                             try {
3341                                 bound = infer.instantiateFunctionalInterface(that,
3342                                         bound, explicitParamTypes, resultInfo.checkContext);
3343                             } catch (FunctionDescriptorLookupError t) {
3344                                 // do nothing
3345                             }
3346                         }
3347                         bound = types.removeWildcards(bound);
3348                         components.add(bound);
3349                     }
3350                     currentTarget = types.makeIntersectionType(components.toList());
3351                     currentTarget.tsym.flags_field |= INTERFACE;
3352                     lambdaType = types.findDescriptorType(currentTarget);
3353                 }
3354 
3355             } else {
3356                 currentTarget = Type.recoveryType;
3357                 lambdaType = fallbackDescriptorType(that);
3358             }
3359             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
3360                 //lambda expression target desc cannot be a generic method
3361                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3362                                                                     kindName(currentTarget.tsym),
3363                                                                     currentTarget.tsym);
3364                 resultInfo.checkContext.report(that, diags.fragment(msg));
3365                 currentTarget = types.createErrorType(pt());
3366             }
3367             return new TargetInfo(currentTarget, lambdaType);
3368         }
3369 
3370         void preFlow(JCLambda tree) {
3371             attrRecover.doRecovery();
3372             new PostAttrAnalyzer() {
3373                 @Override
3374                 public void scan(JCTree tree) {
3375                     if (tree == null ||
3376                             (tree.type != null &&
3377                             tree.type == Type.stuckType)) {
3378                         //don't touch stuck expressions!
3379                         return;
3380                     }
3381                     super.scan(tree);
3382                 }
3383 
3384                 @Override
3385                 public void visitClassDef(JCClassDecl that) {
3386                     // or class declaration trees!
3387                 }
3388 
3389                 public void visitLambda(JCLambda that) {
3390                     // or lambda expressions!
3391                 }
3392             }.scan(tree.body);
3393         }
3394 
3395         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
3396 
3397             @Override
3398             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
3399                 return t.isIntersection() ?
3400                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
3401             }
3402 
3403             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
3404                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
3405                 return ict;
3406             }
3407 
3408             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
3409                 ListBuffer<Type> targs = new ListBuffer<>();
3410                 ListBuffer<Type> supertypes = new ListBuffer<>();
3411                 for (Type i : ict.interfaces_field) {
3412                     if (i.isParameterized()) {
3413                         targs.appendList(i.tsym.type.allparams());
3414                     }
3415                     supertypes.append(i.tsym.type);
3416                 }
3417                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
3418                 notionalIntf.allparams_field = targs.toList();
3419                 notionalIntf.tsym.flags_field |= INTERFACE;
3420                 return notionalIntf.tsym;
3421             }
3422         };
3423 
3424         private Type fallbackDescriptorType(JCExpression tree) {
3425             switch (tree.getTag()) {
3426                 case LAMBDA:
3427                     JCLambda lambda = (JCLambda)tree;
3428                     List<Type> argtypes = List.nil();
3429                     for (JCVariableDecl param : lambda.params) {
3430                         argtypes = param.vartype != null && param.vartype.type != null ?
3431                                 argtypes.append(param.vartype.type) :
3432                                 argtypes.append(syms.errType);
3433                     }
3434                     return new MethodType(argtypes, Type.recoveryType,
3435                             List.of(syms.throwableType), syms.methodClass);
3436                 case REFERENCE:
3437                     return new MethodType(List.nil(), Type.recoveryType,
3438                             List.of(syms.throwableType), syms.methodClass);
3439                 default:
3440                     Assert.error("Cannot get here!");
3441             }
3442             return null;
3443         }
3444 
3445         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3446                 final InferenceContext inferenceContext, final Type... ts) {
3447             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
3448         }
3449 
3450         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3451                 final InferenceContext inferenceContext, final List<Type> ts) {
3452             if (inferenceContext.free(ts)) {
3453                 inferenceContext.addFreeTypeListener(ts,
3454                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
3455             } else {
3456                 for (Type t : ts) {
3457                     rs.checkAccessibleType(env, t);
3458                 }
3459             }
3460         }
3461 
3462         /**
3463          * Lambda/method reference have a special check context that ensures
3464          * that i.e. a lambda return type is compatible with the expected
3465          * type according to both the inherited context and the assignment
3466          * context.
3467          */
3468         class FunctionalReturnContext extends Check.NestedCheckContext {
3469 
3470             FunctionalReturnContext(CheckContext enclosingContext) {
3471                 super(enclosingContext);
3472             }
3473 
3474             @Override
3475             public boolean compatible(Type found, Type req, Warner warn) {
3476                 //return type must be compatible in both current context and assignment context
3477                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
3478             }
3479 
3480             @Override
3481             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3482                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
3483             }
3484         }
3485 
3486         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
3487 
3488             JCExpression expr;
3489             boolean expStmtExpected;
3490 
3491             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
3492                 super(enclosingContext);
3493                 this.expr = expr;
3494             }
3495 
3496             @Override
3497             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3498                 if (expStmtExpected) {
3499                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
3500                 } else {
3501                     super.report(pos, details);
3502                 }
3503             }
3504 
3505             @Override
3506             public boolean compatible(Type found, Type req, Warner warn) {
3507                 //a void return is compatible with an expression statement lambda
3508                 if (req.hasTag(VOID)) {
3509                     expStmtExpected = true;
3510                     return TreeInfo.isExpressionStatement(expr);
3511                 } else {
3512                     return super.compatible(found, req, warn);
3513                 }
3514             }
3515         }
3516 
3517         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
3518             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
3519                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
3520                     new FunctionalReturnContext(resultInfo.checkContext);
3521 
3522             return descriptor.getReturnType() == Type.recoveryType ?
3523                     recoveryInfo :
3524                     new ResultInfo(KindSelector.VAL,
3525                             descriptor.getReturnType(), funcContext);
3526         }
3527 
3528         /**
3529         * Lambda compatibility. Check that given return types, thrown types, parameter types
3530         * are compatible with the expected functional interface descriptor. This means that:
3531         * (i) parameter types must be identical to those of the target descriptor; (ii) return
3532         * types must be compatible with the return type of the expected descriptor.
3533         */
3534         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3535             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3536 
3537             //return values have already been checked - but if lambda has no return
3538             //values, we must ensure that void/value compatibility is correct;
3539             //this amounts at checking that, if a lambda body can complete normally,
3540             //the descriptor's return type must be void
3541             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3542                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3543                 Fragment msg =
3544                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3545                 checkContext.report(tree,
3546                                     diags.fragment(msg));
3547             }
3548 
3549             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3550             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3551                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3552             }
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 (e.g. if the lambda occurs in a field initializer), then
3560          * a synthetic method symbol owner is created.
3561          */
3562         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3563             Env<AttrContext> lambdaEnv;
3564             Symbol owner = env.info.scope.owner;
3565             if (owner.kind == VAR && owner.owner.kind == TYP) {
3566                 // If the lambda is nested in a field initializer, we need to create a fake init method.
3567                 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3568                 // init symbol's owner).
3569                 ClassSymbol enclClass = owner.enclClass();
3570                 Name initName = owner.isStatic() ? names.clinit : names.init;
3571                 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3572                         initName, initBlockType, enclClass);
3573                 initSym.params = List.nil();
3574                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3575             } else {
3576                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3577             }
3578             lambdaEnv.info.yieldResult = null;
3579             lambdaEnv.info.isLambda = true;
3580             return lambdaEnv;
3581         }
3582 
3583     @Override
3584     public void visitReference(final JCMemberReference that) {
3585         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3586             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3587                 //method reference only allowed in assignment or method invocation/cast context
3588                 log.error(that.pos(), Errors.UnexpectedMref);
3589             }
3590             result = that.type = types.createErrorType(pt());
3591             return;
3592         }
3593         final Env<AttrContext> localEnv = env.dup(that);
3594         try {
3595             //attribute member reference qualifier - if this is a constructor
3596             //reference, the expected kind must be a type
3597             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3598 
3599             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3600                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3601                 if (!exprType.isErroneous() &&
3602                     exprType.isRaw() &&
3603                     that.typeargs != null) {
3604                     log.error(that.expr.pos(),
3605                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3606                                                  Fragments.MrefInferAndExplicitParams));
3607                     exprType = types.createErrorType(exprType);
3608                 }
3609             }
3610 
3611             if (exprType.isErroneous()) {
3612                 //if the qualifier expression contains problems,
3613                 //give up attribution of method reference
3614                 result = that.type = exprType;
3615                 return;
3616             }
3617 
3618             if (TreeInfo.isStaticSelector(that.expr, names)) {
3619                 //if the qualifier is a type, validate it; raw warning check is
3620                 //omitted as we don't know at this stage as to whether this is a
3621                 //raw selector (because of inference)
3622                 chk.validate(that.expr, env, false);
3623             } else {
3624                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3625                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3626             }
3627             //attrib type-arguments
3628             List<Type> typeargtypes = List.nil();
3629             if (that.typeargs != null) {
3630                 typeargtypes = attribTypes(that.typeargs, localEnv);
3631             }
3632 
3633             boolean isTargetSerializable =
3634                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3635                     rs.isSerializable(pt());
3636             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3637             Type currentTarget = targetInfo.target;
3638             Type desc = targetInfo.descriptor;
3639 
3640             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3641             List<Type> argtypes = desc.getParameterTypes();
3642             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3643 
3644             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3645                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3646             }
3647 
3648             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3649             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3650             try {
3651                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3652                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3653                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3654             } finally {
3655                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3656             }
3657 
3658             Symbol refSym = refResult.fst;
3659             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3660 
3661             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3662              *  JDK-8075541
3663              */
3664             if (refSym.kind != MTH) {
3665                 boolean targetError;
3666                 switch (refSym.kind) {
3667                     case ABSENT_MTH:
3668                         targetError = false;
3669                         break;
3670                     case WRONG_MTH:
3671                     case WRONG_MTHS:
3672                     case AMBIGUOUS:
3673                     case HIDDEN:
3674                     case STATICERR:
3675                         targetError = true;
3676                         break;
3677                     default:
3678                         Assert.error("unexpected result kind " + refSym.kind);
3679                         targetError = false;
3680                 }
3681 
3682                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3683                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3684                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3685 
3686                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3687                         targetError ?
3688                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3689                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3690 
3691                 if (targetError && currentTarget == Type.recoveryType) {
3692                     //a target error doesn't make sense during recovery stage
3693                     //as we don't know what actual parameter types are
3694                     result = that.type = currentTarget;
3695                     return;
3696                 } else {
3697                     if (targetError) {
3698                         resultInfo.checkContext.report(that, diag);
3699                     } else {
3700                         log.report(diag);
3701                     }
3702                     result = that.type = types.createErrorType(currentTarget);
3703                     return;
3704                 }
3705             }
3706 
3707             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3708             that.kind = lookupHelper.referenceKind(that.sym);
3709             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3710 
3711             if (desc.getReturnType() == Type.recoveryType) {
3712                 // stop here
3713                 result = that.type = currentTarget;
3714                 return;
3715             }
3716 
3717             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3718                 checkNewInnerClass(that.pos(), env, exprType, false);
3719             }
3720 
3721             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3722 
3723                 if (that.getMode() == ReferenceMode.INVOKE &&
3724                         TreeInfo.isStaticSelector(that.expr, names) &&
3725                         that.kind.isUnbound() &&
3726                         lookupHelper.site.isRaw()) {
3727                     chk.checkRaw(that.expr, localEnv);
3728                 }
3729 
3730                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3731                         exprType.getTypeArguments().nonEmpty()) {
3732                     //static ref with class type-args
3733                     log.error(that.expr.pos(),
3734                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3735                                                  Fragments.StaticMrefWithTargs));
3736                     result = that.type = types.createErrorType(currentTarget);
3737                     return;
3738                 }
3739 
3740                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3741                     // Check that super-qualified symbols are not abstract (JLS)
3742                     rs.checkNonAbstract(that.pos(), that.sym);
3743                 }
3744 
3745                 if (isTargetSerializable) {
3746                     chk.checkAccessFromSerializableElement(that, true);
3747                 }
3748             }
3749 
3750             ResultInfo checkInfo =
3751                     resultInfo.dup(newMethodTemplate(
3752                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3753                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3754                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3755 
3756             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3757 
3758             if (that.kind.isUnbound() &&
3759                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3760                 //re-generate inference constraints for unbound receiver
3761                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3762                     //cannot happen as this has already been checked - we just need
3763                     //to regenerate the inference constraints, as that has been lost
3764                     //as a result of the call to inferenceContext.save()
3765                     Assert.error("Can't get here");
3766                 }
3767             }
3768 
3769             if (!refType.isErroneous()) {
3770                 refType = types.createMethodTypeWithReturn(refType,
3771                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3772             }
3773 
3774             //go ahead with standard method reference compatibility check - note that param check
3775             //is a no-op (as this has been taken care during method applicability)
3776             boolean isSpeculativeRound =
3777                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3778 
3779             that.type = currentTarget; //avoids recovery at this stage
3780             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3781             if (!isSpeculativeRound) {
3782                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3783             }
3784             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3785         } catch (Types.FunctionDescriptorLookupError ex) {
3786             JCDiagnostic cause = ex.getDiagnostic();
3787             resultInfo.checkContext.report(that, cause);
3788             result = that.type = types.createErrorType(pt());
3789             return;
3790         }
3791     }
3792     //where
3793         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3794             //if this is a constructor reference, the expected kind must be a type
3795             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3796                                   KindSelector.VAL_TYP : KindSelector.TYP,
3797                                   Type.noType);
3798         }
3799 
3800 
3801     @SuppressWarnings("fallthrough")
3802     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3803         InferenceContext inferenceContext = checkContext.inferenceContext();
3804         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3805 
3806         Type resType;
3807         switch (tree.getMode()) {
3808             case NEW:
3809                 if (!tree.expr.type.isRaw()) {
3810                     resType = tree.expr.type;
3811                     break;
3812                 }
3813             default:
3814                 resType = refType.getReturnType();
3815         }
3816 
3817         Type incompatibleReturnType = resType;
3818 
3819         if (returnType.hasTag(VOID)) {
3820             incompatibleReturnType = null;
3821         }
3822 
3823         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3824             if (resType.isErroneous() ||
3825                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3826                             checkContext.checkWarner(tree, resType, returnType))) {
3827                 incompatibleReturnType = null;
3828             }
3829         }
3830 
3831         if (incompatibleReturnType != null) {
3832             Fragment msg =
3833                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3834             checkContext.report(tree, diags.fragment(msg));
3835         } else {
3836             if (inferenceContext.free(refType)) {
3837                 // we need to wait for inference to finish and then replace inference vars in the referent type
3838                 inferenceContext.addFreeTypeListener(List.of(refType),
3839                         instantiatedContext -> {
3840                             tree.referentType = instantiatedContext.asInstType(refType);
3841                         });
3842             } else {
3843                 tree.referentType = refType;
3844             }
3845         }
3846 
3847         if (!speculativeAttr) {
3848             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3849                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3850             }
3851         }
3852     }
3853 
3854     boolean checkExConstraints(
3855             List<Type> thrownByFuncExpr,
3856             List<Type> thrownAtFuncType,
3857             InferenceContext inferenceContext) {
3858         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3859          *  are not proper types
3860          */
3861         List<Type> nonProperList = thrownAtFuncType.stream()
3862                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3863         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3864 
3865         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3866          *  in the throws clause of the invocation type of the method reference's compile-time
3867          *  declaration
3868          */
3869         List<Type> checkedList = thrownByFuncExpr.stream()
3870                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3871 
3872         /** If n = 0 (the function type's throws clause consists only of proper types), then
3873          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3874          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3875          *  reduces to true
3876          */
3877         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3878         for (Type checked : checkedList) {
3879             boolean isSubtype = false;
3880             for (Type proper : properList) {
3881                 if (types.isSubtype(checked, proper)) {
3882                     isSubtype = true;
3883                     break;
3884                 }
3885             }
3886             if (!isSubtype) {
3887                 uncaughtByProperTypes.add(checked);
3888             }
3889         }
3890 
3891         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3892             return false;
3893         }
3894 
3895         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3896          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3897          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3898          */
3899         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3900         uncaughtByProperTypes.forEach(checkedEx -> {
3901             nonProperAsUndet.forEach(nonProper -> {
3902                 types.isSubtype(checkedEx, nonProper);
3903             });
3904         });
3905 
3906         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3907          */
3908         nonProperAsUndet.stream()
3909                 .filter(t -> t.hasTag(UNDETVAR))
3910                 .forEach(t -> ((UndetVar)t).setThrow());
3911         return true;
3912     }
3913 
3914     /**
3915      * Set functional type info on the underlying AST. Note: as the target descriptor
3916      * might contain inference variables, we might need to register an hook in the
3917      * current inference context.
3918      */
3919     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3920             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3921         if (checkContext.inferenceContext().free(descriptorType)) {
3922             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3923                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3924                     inferenceContext.asInstType(primaryTarget), checkContext));
3925         } else {
3926             fExpr.owner = env.info.scope.owner;
3927             if (pt.hasTag(CLASS)) {
3928                 fExpr.target = primaryTarget;
3929             }
3930             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3931                     pt != Type.recoveryType) {
3932                 //check that functional interface class is well-formed
3933                 try {
3934                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3935                      * when it's executed post-inference. See the listener code
3936                      * above.
3937                      */
3938                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3939                             names.empty, fExpr.target, ABSTRACT);
3940                     if (csym != null) {
3941                         chk.checkImplementations(env.tree, csym, csym);
3942                         try {
3943                             //perform an additional functional interface check on the synthetic class,
3944                             //as there may be spurious errors for raw targets - because of existing issues
3945                             //with membership and inheritance (see JDK-8074570).
3946                             csym.flags_field |= INTERFACE;
3947                             types.findDescriptorType(csym.type);
3948                         } catch (FunctionDescriptorLookupError err) {
3949                             resultInfo.checkContext.report(fExpr,
3950                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3951                         }
3952                     }
3953                 } catch (Types.FunctionDescriptorLookupError ex) {
3954                     JCDiagnostic cause = ex.getDiagnostic();
3955                     resultInfo.checkContext.report(env.tree, cause);
3956                 }
3957             }
3958         }
3959     }
3960 
3961     public void visitParens(JCParens tree) {
3962         Type owntype = attribTree(tree.expr, env, resultInfo);
3963         result = check(tree, owntype, pkind(), resultInfo);
3964         Symbol sym = TreeInfo.symbol(tree);
3965         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
3966             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3967     }
3968 
3969     public void visitAssign(JCAssign tree) {
3970         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3971         Type capturedType = capture(owntype);
3972         attribExpr(tree.rhs, env, owntype);
3973         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3974     }
3975 
3976     public void visitAssignop(JCAssignOp tree) {
3977         // Attribute arguments.
3978         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3979         Type operand = attribExpr(tree.rhs, env);
3980         // Find operator.
3981         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3982         if (operator != operators.noOpSymbol &&
3983                 !owntype.isErroneous() &&
3984                 !operand.isErroneous()) {
3985             chk.checkDivZero(tree.rhs.pos(), operator, operand);
3986             chk.checkCastable(tree.rhs.pos(),
3987                               operator.type.getReturnType(),
3988                               owntype);
3989             chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
3990         }
3991         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3992     }
3993 
3994     public void visitUnary(JCUnary tree) {
3995         // Attribute arguments.
3996         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3997             ? attribTree(tree.arg, env, varAssignmentInfo)
3998             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3999 
4000         // Find operator.
4001         OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4002         Type owntype = types.createErrorType(tree.type);
4003         if (operator != operators.noOpSymbol &&
4004                 !argtype.isErroneous()) {
4005             owntype = (tree.getTag().isIncOrDecUnaryOp())
4006                 ? tree.arg.type
4007                 : operator.type.getReturnType();
4008             int opc = operator.opcode;
4009 
4010             // If the argument is constant, fold it.
4011             if (argtype.constValue() != null) {
4012                 Type ctype = cfolder.fold1(opc, argtype);
4013                 if (ctype != null) {
4014                     owntype = cfolder.coerce(ctype, owntype);
4015                 }
4016             }
4017         }
4018         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4019         matchBindings = matchBindingsComputer.unary(tree, matchBindings);
4020     }
4021 
4022     public void visitBinary(JCBinary tree) {
4023         // Attribute arguments.
4024         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
4025         // x && y
4026         // include x's bindings when true in y
4027 
4028         // x || y
4029         // include x's bindings when false in y
4030 
4031         MatchBindings lhsBindings = matchBindings;
4032         List<BindingSymbol> propagatedBindings;
4033         switch (tree.getTag()) {
4034             case AND:
4035                 propagatedBindings = lhsBindings.bindingsWhenTrue;
4036                 break;
4037             case OR:
4038                 propagatedBindings = lhsBindings.bindingsWhenFalse;
4039                 break;
4040             default:
4041                 propagatedBindings = List.nil();
4042                 break;
4043         }
4044         Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings);
4045         Type right;
4046         try {
4047             right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
4048         } finally {
4049             rhsEnv.info.scope.leave();
4050         }
4051 
4052         matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings);
4053 
4054         // Find operator.
4055         OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
4056         Type owntype = types.createErrorType(tree.type);
4057         if (operator != operators.noOpSymbol &&
4058                 !left.isErroneous() &&
4059                 !right.isErroneous()) {
4060             owntype = operator.type.getReturnType();
4061             int opc = operator.opcode;
4062             // If both arguments are constants, fold them.
4063             if (left.constValue() != null && right.constValue() != null) {
4064                 Type ctype = cfolder.fold2(opc, left, right);
4065                 if (ctype != null) {
4066                     owntype = cfolder.coerce(ctype, owntype);
4067                 }
4068             }
4069 
4070             // Check that argument types of a reference ==, != are
4071             // castable to each other, (JLS 15.21).  Note: unboxing
4072             // comparisons will not have an acmp* opc at this point.
4073             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4074                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4075                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4076                 }
4077             }
4078 
4079             chk.checkDivZero(tree.rhs.pos(), operator, right);
4080         }
4081         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4082     }
4083 
4084     public void visitTypeCast(final JCTypeCast tree) {
4085         Type clazztype = attribType(tree.clazz, env);
4086         chk.validate(tree.clazz, env, false);
4087         //a fresh environment is required for 292 inference to work properly ---
4088         //see Infer.instantiatePolymorphicSignatureInstance()
4089         Env<AttrContext> localEnv = env.dup(tree);
4090         //should we propagate the target type?
4091         final ResultInfo castInfo;
4092         JCExpression expr = TreeInfo.skipParens(tree.expr);
4093         boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4094         if (isPoly) {
4095             //expression is a poly - we need to propagate target type info
4096             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
4097                                       new Check.NestedCheckContext(resultInfo.checkContext) {
4098                 @Override
4099                 public boolean compatible(Type found, Type req, Warner warn) {
4100                     return types.isCastable(found, req, warn);
4101                 }
4102             });
4103         } else {
4104             //standalone cast - target-type info is not propagated
4105             castInfo = unknownExprInfo;
4106         }
4107         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
4108         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4109         if (exprtype.constValue() != null)
4110             owntype = cfolder.coerce(exprtype, owntype);
4111         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
4112         if (!isPoly)
4113             chk.checkRedundantCast(localEnv, tree);
4114     }
4115 
4116     public void visitTypeTest(JCInstanceOf tree) {
4117         Type exprtype = attribExpr(tree.expr, env);
4118         if (exprtype.isPrimitive()) {
4119             preview.checkSourceLevel(tree.expr.pos(), Feature.PRIMITIVE_PATTERNS);
4120         } else {
4121             exprtype = chk.checkNullOrRefType(
4122                     tree.expr.pos(), exprtype);
4123         }
4124         Type clazztype;
4125         JCTree typeTree;
4126         if (tree.pattern.getTag() == BINDINGPATTERN ||
4127             tree.pattern.getTag() == RECORDPATTERN) {
4128             attribExpr(tree.pattern, env, exprtype);
4129             clazztype = tree.pattern.type;
4130             if (types.isSubtype(exprtype, clazztype) &&
4131                 !exprtype.isErroneous() && !clazztype.isErroneous() &&
4132                 tree.pattern.getTag() != RECORDPATTERN) {
4133                 if (!allowUnconditionalPatternsInstanceOf) {
4134                     log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
4135                               Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName));
4136                 }
4137             }
4138             typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern);
4139         } else {
4140             clazztype = attribType(tree.pattern, env);
4141             typeTree = tree.pattern;
4142             chk.validate(typeTree, env, false);
4143         }
4144         if (clazztype.isPrimitive()) {
4145             preview.checkSourceLevel(tree.pattern.pos(), Feature.PRIMITIVE_PATTERNS);
4146         } else {
4147             if (!clazztype.hasTag(TYPEVAR)) {
4148                 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype);
4149             }
4150             if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
4151                 boolean valid = false;
4152                 if (allowReifiableTypesInInstanceof) {
4153                     valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype);
4154                 } else {
4155                     log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
4156                             Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName));
4157                     allowReifiableTypesInInstanceof = true;
4158                 }
4159                 if (!valid) {
4160                     clazztype = types.createErrorType(clazztype);
4161                 }
4162             }
4163         }
4164         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4165         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
4166     }
4167 
4168     private boolean checkCastablePattern(DiagnosticPosition pos,
4169                                          Type exprType,
4170                                          Type pattType) {
4171         Warner warner = new Warner();
4172         // if any type is erroneous, the problem is reported elsewhere
4173         if (exprType.isErroneous() || pattType.isErroneous()) {
4174             return false;
4175         }
4176         if (!types.isCastable(exprType, pattType, warner)) {
4177             chk.basicHandler.report(pos,
4178                     diags.fragment(Fragments.InconvertibleTypes(exprType, pattType)));
4179             return false;
4180         } else if ((exprType.isPrimitive() || pattType.isPrimitive()) &&
4181                 (!exprType.isPrimitive() || !pattType.isPrimitive() || !types.isSameType(exprType, pattType))) {
4182             preview.checkSourceLevel(pos, Feature.PRIMITIVE_PATTERNS);
4183             return true;
4184         } else if (warner.hasLint(LintCategory.UNCHECKED)) {
4185             log.error(pos,
4186                     Errors.InstanceofReifiableNotSafe(exprType, pattType));
4187             return false;
4188         } else {
4189             return true;
4190         }
4191     }
4192 
4193     @Override
4194     public void visitAnyPattern(JCAnyPattern tree) {
4195         result = tree.type = resultInfo.pt;
4196     }
4197 
4198     public void visitBindingPattern(JCBindingPattern tree) {
4199         Type type;
4200         if (tree.var.vartype != null) {
4201             type = attribType(tree.var.vartype, env);
4202         } else {
4203             type = resultInfo.pt;
4204         }
4205         tree.type = tree.var.type = type;
4206         BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, type, env.info.scope.owner);
4207         v.pos = tree.pos;
4208         tree.var.sym = v;
4209         if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
4210             chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
4211         }
4212         chk.validate(tree.var.vartype, env, true);
4213         if (tree.var.isImplicitlyTyped()) {
4214             setSyntheticVariableType(tree.var, type == Type.noType ? syms.errType
4215                                                                    : type);
4216         }
4217         annotate.annotateLater(tree.var.mods.annotations, env, v, tree.var);
4218         if (!tree.var.isImplicitlyTyped()) {
4219             annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v, tree.var);
4220         }
4221         annotate.flush();
4222         result = tree.type;
4223         if (v.isUnnamedVariable()) {
4224             matchBindings = MatchBindingsComputer.EMPTY;
4225         } else {
4226             matchBindings = new MatchBindings(List.of(v), List.nil());
4227         }
4228     }
4229 
4230     @Override
4231     public void visitRecordPattern(JCRecordPattern tree) {
4232         Type site;
4233 
4234         if (tree.deconstructor == null) {
4235             log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed);
4236             tree.record = syms.errSymbol;
4237             site = tree.type = types.createErrorType(tree.record.type);
4238         } else {
4239             Type type = attribType(tree.deconstructor, env);
4240             if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) {
4241                 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym);
4242                 if (inferred == null) {
4243                     log.error(tree.pos(), Errors.PatternTypeCannotInfer);
4244                 } else {
4245                     type = inferred;
4246                 }
4247             }
4248             tree.type = tree.deconstructor.type = type;
4249             site = types.capture(tree.type);
4250         }
4251 
4252         List<Type> expectedRecordTypes;
4253         if (site.tsym.kind == Kind.TYP && ((ClassSymbol) site.tsym).isRecord()) {
4254             ClassSymbol record = (ClassSymbol) site.tsym;
4255             expectedRecordTypes = record.getRecordComponents()
4256                                         .stream()
4257                                         .map(rc -> types.memberType(site, rc))
4258                                         .map(t -> types.upward(t, types.captures(t)).baseType())
4259                                         .collect(List.collector());
4260             tree.record = record;
4261         } else {
4262             log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym));
4263             expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type))
4264                                 .limit(tree.nested.size())
4265                                 .collect(List.collector());
4266             tree.record = syms.errSymbol;
4267         }
4268         ListBuffer<BindingSymbol> outBindings = new ListBuffer<>();
4269         List<Type> recordTypes = expectedRecordTypes;
4270         List<JCPattern> nestedPatterns = tree.nested;
4271         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
4272         try {
4273             while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) {
4274                 attribExpr(nestedPatterns.head, localEnv, recordTypes.head);
4275                 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type);
4276                 outBindings.addAll(matchBindings.bindingsWhenTrue);
4277                 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter);
4278                 nestedPatterns = nestedPatterns.tail;
4279                 recordTypes = recordTypes.tail;
4280             }
4281             if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) {
4282                 while (nestedPatterns.nonEmpty()) {
4283                     attribExpr(nestedPatterns.head, localEnv, Type.noType);
4284                     nestedPatterns = nestedPatterns.tail;
4285                 }
4286                 List<Type> nestedTypes =
4287                         tree.nested.stream().map(p -> p.type).collect(List.collector());
4288                 log.error(tree.pos(),
4289                           Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes,
4290                                                                  nestedTypes));
4291             }
4292         } finally {
4293             localEnv.info.scope.leave();
4294         }
4295         chk.validate(tree.deconstructor, env, true);
4296         result = tree.type;
4297         matchBindings = new MatchBindings(outBindings.toList(), List.nil());
4298     }
4299 
4300     public void visitIndexed(JCArrayAccess tree) {
4301         Type owntype = types.createErrorType(tree.type);
4302         Type atype = attribExpr(tree.indexed, env);
4303         attribExpr(tree.index, env, syms.intType);
4304         if (types.isArray(atype))
4305             owntype = types.elemtype(atype);
4306         else if (!atype.hasTag(ERROR))
4307             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
4308         if (!pkind().contains(KindSelector.VAL))
4309             owntype = capture(owntype);
4310         result = check(tree, owntype, KindSelector.VAR, resultInfo);
4311     }
4312 
4313     public void visitIdent(JCIdent tree) {
4314         Symbol sym;
4315 
4316         // Find symbol
4317         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
4318             // If we are looking for a method, the prototype `pt' will be a
4319             // method type with the type of the call's arguments as parameters.
4320             env.info.pendingResolutionPhase = null;
4321             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
4322         } else if (tree.sym != null && tree.sym.kind != VAR) {
4323             sym = tree.sym;
4324         } else {
4325             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
4326         }
4327         tree.sym = sym;
4328 
4329         // Also find the environment current for the class where
4330         // sym is defined (`symEnv').
4331         Env<AttrContext> symEnv = env;
4332         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
4333             sym.kind.matches(KindSelector.VAL_MTH) &&
4334             sym.owner.kind == TYP &&
4335             tree.name != names._this && tree.name != names._super) {
4336 
4337             // Find environment in which identifier is defined.
4338             while (symEnv.outer != null &&
4339                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
4340                 symEnv = symEnv.outer;
4341             }
4342         }
4343 
4344         // If symbol is a variable, ...
4345         if (sym.kind == VAR) {
4346             VarSymbol v = (VarSymbol)sym;
4347 
4348             // ..., evaluate its initializer, if it has one, and check for
4349             // illegal forward reference.
4350             checkInit(tree, env, v, false);
4351 
4352             // If we are expecting a variable (as opposed to a value), check
4353             // that the variable is assignable in the current environment.
4354             if (KindSelector.ASG.subset(pkind()))
4355                 checkAssignable(tree.pos(), v, null, env);
4356         }
4357 
4358         Env<AttrContext> env1 = env;
4359         if (sym.kind != ERR && sym.kind != TYP &&
4360             sym.owner != null && sym.owner != env1.enclClass.sym) {
4361             // If the found symbol is inaccessible, then it is
4362             // accessed through an enclosing instance.  Locate this
4363             // enclosing instance:
4364             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4365                 env1 = env1.outer;
4366         }
4367 
4368         if (env.info.isSerializable) {
4369             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4370         }
4371 
4372         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4373     }
4374 
4375     public void visitSelect(JCFieldAccess tree) {
4376         // Determine the expected kind of the qualifier expression.
4377         KindSelector skind = KindSelector.NIL;
4378         if (tree.name == names._this || tree.name == names._super ||
4379                 tree.name == names._class)
4380         {
4381             skind = KindSelector.TYP;
4382         } else {
4383             if (pkind().contains(KindSelector.PCK))
4384                 skind = KindSelector.of(skind, KindSelector.PCK);
4385             if (pkind().contains(KindSelector.TYP))
4386                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4387             if (pkind().contains(KindSelector.VAL_MTH))
4388                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4389         }
4390 
4391         // Attribute the qualifier expression, and determine its symbol (if any).
4392         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));

4393         if (!pkind().contains(KindSelector.TYP_PCK))
4394             site = capture(site); // Capture field access
4395 
4396         // don't allow T.class T[].class, etc
4397         if (skind == KindSelector.TYP) {
4398             Type elt = site;
4399             while (elt.hasTag(ARRAY))
4400                 elt = ((ArrayType)elt).elemtype;
4401             if (elt.hasTag(TYPEVAR)) {
4402                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4403                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4404                 tree.sym = tree.type.tsym;
4405                 return ;
4406             }
4407         }
4408 
4409         // If qualifier symbol is a type or `super', assert `selectSuper'
4410         // for the selection. This is relevant for determining whether
4411         // protected symbols are accessible.
4412         Symbol sitesym = TreeInfo.symbol(tree.selected);
4413         boolean selectSuperPrev = env.info.selectSuper;
4414         env.info.selectSuper =
4415             sitesym != null &&
4416             sitesym.name == names._super;
4417 
4418         // Determine the symbol represented by the selection.
4419         env.info.pendingResolutionPhase = null;
4420         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4421         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4422             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4423             sym = syms.errSymbol;
4424         }
4425         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4426             site = capture(site);
4427             sym = selectSym(tree, sitesym, site, env, resultInfo);
4428         }
4429         boolean varArgs = env.info.lastResolveVarargs();
4430         tree.sym = sym;
4431 
4432         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4433             site = types.skipTypeVars(site, true);
4434         }
4435 
4436         // If that symbol is a variable, ...
4437         if (sym.kind == VAR) {
4438             VarSymbol v = (VarSymbol)sym;
4439 
4440             // ..., evaluate its initializer, if it has one, and check for
4441             // illegal forward reference.
4442             checkInit(tree, env, v, true);
4443 
4444             // If we are expecting a variable (as opposed to a value), check
4445             // that the variable is assignable in the current environment.
4446             if (KindSelector.ASG.subset(pkind()))
4447                 checkAssignable(tree.pos(), v, tree.selected, env);
4448         }
4449 
4450         if (sitesym != null &&
4451                 sitesym.kind == VAR &&
4452                 ((VarSymbol)sitesym).isResourceVariable() &&
4453                 sym.kind == MTH &&
4454                 sym.name.equals(names.close) &&
4455                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
4456             env.info.lint.logIfEnabled(tree, LintWarnings.TryExplicitCloseCall);
4457         }
4458 
4459         // Disallow selecting a type from an expression
4460         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4461             tree.type = check(tree.selected, pt(),
4462                               sitesym == null ?
4463                                       KindSelector.VAL : sitesym.kind.toSelector(),
4464                               new ResultInfo(KindSelector.TYP_PCK, pt()));
4465         }
4466 
4467         if (isType(sitesym)) {
4468             if (sym.name != names._this && sym.name != names._super) {
4469                 // Check if type-qualified fields or methods are static (JLS)
4470                 if ((sym.flags() & STATIC) == 0 &&
4471                     sym.name != names._super &&
4472                     (sym.kind == VAR || sym.kind == MTH)) {
4473                     rs.accessBase(rs.new StaticError(sym),
4474                               tree.pos(), site, sym.name, true);
4475                 }
4476             }
4477         } else if (sym.kind != ERR &&
4478                    (sym.flags() & STATIC) != 0 &&
4479                    sym.name != names._class) {
4480             // If the qualified item is not a type and the selected item is static, report
4481             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4482             if (!sym.owner.isAnonymous()) {
4483                 chk.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4484             } else {
4485                 chk.lint.logIfEnabled(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4486             }
4487         }
4488 
4489         // If we are selecting an instance member via a `super', ...
4490         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4491 
4492             // Check that super-qualified symbols are not abstract (JLS)
4493             rs.checkNonAbstract(tree.pos(), sym);
4494 
4495             if (site.isRaw()) {
4496                 // Determine argument types for site.
4497                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4498                 if (site1 != null) site = site1;
4499             }
4500         }
4501 
4502         if (env.info.isSerializable) {
4503             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4504         }
4505 
4506         env.info.selectSuper = selectSuperPrev;
4507         result = checkId(tree, site, sym, env, resultInfo);
4508     }
4509     //where
4510         /** Determine symbol referenced by a Select expression,
4511          *
4512          *  @param tree   The select tree.
4513          *  @param site   The type of the selected expression,
4514          *  @param env    The current environment.
4515          *  @param resultInfo The current result.
4516          */
4517         private Symbol selectSym(JCFieldAccess tree,
4518                                  Symbol location,
4519                                  Type site,
4520                                  Env<AttrContext> env,
4521                                  ResultInfo resultInfo) {
4522             DiagnosticPosition pos = tree.pos();
4523             Name name = tree.name;
4524             switch (site.getTag()) {
4525             case PACKAGE:
4526                 return rs.accessBase(
4527                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4528                     pos, location, site, name, true);
4529             case ARRAY:
4530             case CLASS:
4531                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4532                     return rs.resolveQualifiedMethod(
4533                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4534                 } else if (name == names._this || name == names._super) {
4535                     return rs.resolveSelf(pos, env, site.tsym, name);
4536                 } else if (name == names._class) {
4537                     // In this case, we have already made sure in
4538                     // visitSelect that qualifier expression is a type.
4539                     return syms.getClassField(site, types);
4540                 } else {
4541                     // We are seeing a plain identifier as selector.
4542                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4543                         sym = rs.accessBase(sym, pos, location, site, name, true);
4544                     return sym;
4545                 }
4546             case WILDCARD:
4547                 throw new AssertionError(tree);
4548             case TYPEVAR:
4549                 // Normally, site.getUpperBound() shouldn't be null.
4550                 // It should only happen during memberEnter/attribBase
4551                 // when determining the supertype which *must* be
4552                 // done before attributing the type variables.  In
4553                 // other words, we are seeing this illegal program:
4554                 // class B<T> extends A<T.foo> {}
4555                 Symbol sym = (site.getUpperBound() != null)
4556                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4557                     : null;
4558                 if (sym == null) {
4559                     log.error(pos, Errors.TypeVarCantBeDeref);
4560                     return syms.errSymbol;
4561                 } else {
4562                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
4563                         rs.new AccessError(env, site, sym) :
4564                                 sym;
4565                     rs.accessBase(sym2, pos, location, site, name, true);
4566                     return sym;
4567                 }
4568             case ERROR:
4569                 // preserve identifier names through errors
4570                 return types.createErrorType(name, site.tsym, site).tsym;
4571             default:
4572                 // The qualifier expression is of a primitive type -- only
4573                 // .class is allowed for these.
4574                 if (name == names._class) {
4575                     // In this case, we have already made sure in Select that
4576                     // qualifier expression is a type.
4577                     return syms.getClassField(site, types);
4578                 } else {
4579                     log.error(pos, Errors.CantDeref(site));
4580                     return syms.errSymbol;
4581                 }
4582             }
4583         }
4584 
4585         /** Determine type of identifier or select expression and check that
4586          *  (1) the referenced symbol is not deprecated
4587          *  (2) the symbol's type is safe (@see checkSafe)
4588          *  (3) if symbol is a variable, check that its type and kind are
4589          *      compatible with the prototype and protokind.
4590          *  (4) if symbol is an instance field of a raw type,
4591          *      which is being assigned to, issue an unchecked warning if its
4592          *      type changes under erasure.
4593          *  (5) if symbol is an instance method of a raw type, issue an
4594          *      unchecked warning if its argument types change under erasure.
4595          *  If checks succeed:
4596          *    If symbol is a constant, return its constant type
4597          *    else if symbol is a method, return its result type
4598          *    otherwise return its type.
4599          *  Otherwise return errType.
4600          *
4601          *  @param tree       The syntax tree representing the identifier
4602          *  @param site       If this is a select, the type of the selected
4603          *                    expression, otherwise the type of the current class.
4604          *  @param sym        The symbol representing the identifier.
4605          *  @param env        The current environment.
4606          *  @param resultInfo    The expected result
4607          */
4608         Type checkId(JCTree tree,
4609                      Type site,
4610                      Symbol sym,
4611                      Env<AttrContext> env,
4612                      ResultInfo resultInfo) {
4613             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
4614                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
4615                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4616         }
4617 
4618         Type checkMethodIdInternal(JCTree tree,
4619                      Type site,
4620                      Symbol sym,
4621                      Env<AttrContext> env,
4622                      ResultInfo resultInfo) {
4623             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4624                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4625             } else {
4626                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4627             }
4628         }
4629 
4630         Type checkIdInternal(JCTree tree,
4631                      Type site,
4632                      Symbol sym,
4633                      Type pt,
4634                      Env<AttrContext> env,
4635                      ResultInfo resultInfo) {
4636             Type owntype; // The computed type of this identifier occurrence.
4637             switch (sym.kind) {
4638             case TYP:
4639                 // For types, the computed type equals the symbol's type,
4640                 // except for two situations:
4641                 owntype = sym.type;
4642                 if (owntype.hasTag(CLASS)) {
4643                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4644                     Type ownOuter = owntype.getEnclosingType();
4645 
4646                     // (a) If the symbol's type is parameterized, erase it
4647                     // because no type parameters were given.
4648                     // We recover generic outer type later in visitTypeApply.
4649                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4650                         owntype = types.erasure(owntype);
4651                     }
4652 
4653                     // (b) If the symbol's type is an inner class, then
4654                     // we have to interpret its outer type as a superclass
4655                     // of the site type. Example:
4656                     //
4657                     // class Tree<A> { class Visitor { ... } }
4658                     // class PointTree extends Tree<Point> { ... }
4659                     // ...PointTree.Visitor...
4660                     //
4661                     // Then the type of the last expression above is
4662                     // Tree<Point>.Visitor.
4663                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4664                         Type normOuter = site;
4665                         if (normOuter.hasTag(CLASS)) {
4666                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4667                         }
4668                         if (normOuter == null) // perhaps from an import
4669                             normOuter = types.erasure(ownOuter);
4670                         if (normOuter != ownOuter)
4671                             owntype = new ClassType(
4672                                 normOuter, List.nil(), owntype.tsym,
4673                                 owntype.getMetadata());
4674                     }
4675                 }
4676                 break;
4677             case VAR:
4678                 VarSymbol v = (VarSymbol)sym;
4679 
4680                 if (env.info.enclVar != null
4681                         && v.type.hasTag(NONE)) {
4682                     //self reference to implicitly typed variable declaration
4683                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4684                     return tree.type = v.type = types.createErrorType(v.type);
4685                 }
4686 
4687                 // Test (4): if symbol is an instance field of a raw type,
4688                 // which is being assigned to, issue an unchecked warning if
4689                 // its type changes under erasure.
4690                 if (KindSelector.ASG.subset(pkind()) &&
4691                     v.owner.kind == TYP &&
4692                     (v.flags() & STATIC) == 0 &&
4693                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4694                     Type s = types.asOuterSuper(site, v.owner);
4695                     if (s != null &&
4696                         s.isRaw() &&
4697                         !types.isSameType(v.type, v.erasure(types))) {
4698                         chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
4699                     }
4700                 }
4701                 // The computed type of a variable is the type of the
4702                 // variable symbol, taken as a member of the site type.
4703                 owntype = (sym.owner.kind == TYP &&
4704                            sym.name != names._this && sym.name != names._super)
4705                     ? types.memberType(site, sym)
4706                     : sym.type;
4707 
4708                 // If the variable is a constant, record constant value in
4709                 // computed type.
4710                 if (v.getConstValue() != null && isStaticReference(tree))
4711                     owntype = owntype.constType(v.getConstValue());
4712 
4713                 if (resultInfo.pkind == KindSelector.VAL) {
4714                     owntype = capture(owntype); // capture "names as expressions"
4715                 }
4716                 break;
4717             case MTH: {
4718                 owntype = checkMethod(site, sym,
4719                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4720                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4721                         resultInfo.pt.getTypeArguments());
4722                 chk.checkRestricted(tree.pos(), sym);
4723                 break;
4724             }
4725             case PCK: case ERR:
4726                 owntype = sym.type;
4727                 break;
4728             default:
4729                 throw new AssertionError("unexpected kind: " + sym.kind +
4730                                          " in tree " + tree);
4731             }
4732 
4733             // Emit a `deprecation' warning if symbol is deprecated.
4734             // (for constructors (but not for constructor references), the error
4735             // was given when the constructor was resolved)
4736 
4737             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4738                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4739                 chk.checkSunAPI(tree.pos(), sym);
4740                 chk.checkProfile(tree.pos(), sym);
4741                 chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym);
4742             }
4743 
4744             if (pt.isErroneous()) {
4745                 owntype = types.createErrorType(owntype);
4746             }
4747 
4748             // If symbol is a variable, check that its type and
4749             // kind are compatible with the prototype and protokind.
4750             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4751         }
4752 
4753         /** Check that variable is initialized and evaluate the variable's
4754          *  initializer, if not yet done. Also check that variable is not
4755          *  referenced before it is defined.
4756          *  @param tree    The tree making up the variable reference.
4757          *  @param env     The current environment.
4758          *  @param v       The variable's symbol.
4759          */
4760         private void checkInit(JCTree tree,
4761                                Env<AttrContext> env,
4762                                VarSymbol v,
4763                                boolean onlyWarning) {
4764             // A forward reference is diagnosed if the declaration position
4765             // of the variable is greater than the current tree position
4766             // and the tree and variable definition occur in the same class
4767             // definition.  Note that writes don't count as references.
4768             // This check applies only to class and instance
4769             // variables.  Local variables follow different scope rules,
4770             // and are subject to definite assignment checking.
4771             Env<AttrContext> initEnv = enclosingInitEnv(env);
4772             if (initEnv != null &&
4773                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4774                 v.owner.kind == TYP &&
4775                 v.owner == env.info.scope.owner.enclClass() &&
4776                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4777                 (!env.tree.hasTag(ASSIGN) ||
4778                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4779                 if (!onlyWarning || isStaticEnumField(v)) {
4780                     Error errkey = (initEnv.info.enclVar == v) ?
4781                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4782                     log.error(tree.pos(), errkey);
4783                 } else if (useBeforeDeclarationWarning) {
4784                     Warning warnkey = (initEnv.info.enclVar == v) ?
4785                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4786                     log.warning(tree.pos(), warnkey);
4787                 }
4788             }
4789 
4790             v.getConstValue(); // ensure initializer is evaluated
4791 
4792             checkEnumInitializer(tree, env, v);
4793         }
4794 
4795         /**
4796          * Returns the enclosing init environment associated with this env (if any). An init env
4797          * can be either a field declaration env or a static/instance initializer env.
4798          */
4799         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4800             while (true) {
4801                 switch (env.tree.getTag()) {
4802                     case VARDEF:
4803                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4804                         if (vdecl.sym.owner.kind == TYP) {
4805                             //field
4806                             return env;
4807                         }
4808                         break;
4809                     case BLOCK:
4810                         if (env.next.tree.hasTag(CLASSDEF)) {
4811                             //instance/static initializer
4812                             return env;
4813                         }
4814                         break;
4815                     case METHODDEF:
4816                     case CLASSDEF:
4817                     case TOPLEVEL:
4818                         return null;
4819                 }
4820                 Assert.checkNonNull(env.next);
4821                 env = env.next;
4822             }
4823         }
4824 
4825         /**
4826          * Check for illegal references to static members of enum.  In
4827          * an enum type, constructors and initializers may not
4828          * reference its static members unless they are constant.
4829          *
4830          * @param tree    The tree making up the variable reference.
4831          * @param env     The current environment.
4832          * @param v       The variable's symbol.
4833          * @jls 8.9 Enum Types
4834          */
4835         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4836             // JLS:
4837             //
4838             // "It is a compile-time error to reference a static field
4839             // of an enum type that is not a compile-time constant
4840             // (15.28) from constructors, instance initializer blocks,
4841             // or instance variable initializer expressions of that
4842             // type. It is a compile-time error for the constructors,
4843             // instance initializer blocks, or instance variable
4844             // initializer expressions of an enum constant e to refer
4845             // to itself or to an enum constant of the same type that
4846             // is declared to the right of e."
4847             if (isStaticEnumField(v)) {
4848                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4849 
4850                 if (enclClass == null || enclClass.owner == null)
4851                     return;
4852 
4853                 // See if the enclosing class is the enum (or a
4854                 // subclass thereof) declaring v.  If not, this
4855                 // reference is OK.
4856                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4857                     return;
4858 
4859                 // If the reference isn't from an initializer, then
4860                 // the reference is OK.
4861                 if (!Resolve.isInitializer(env))
4862                     return;
4863 
4864                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4865             }
4866         }
4867 
4868         /** Is the given symbol a static, non-constant field of an Enum?
4869          *  Note: enum literals should not be regarded as such
4870          */
4871         private boolean isStaticEnumField(VarSymbol v) {
4872             return Flags.isEnum(v.owner) &&
4873                    Flags.isStatic(v) &&
4874                    !Flags.isConstant(v) &&
4875                    v.name != names._class;
4876         }
4877 
4878     /**
4879      * Check that method arguments conform to its instantiation.
4880      **/
4881     public Type checkMethod(Type site,
4882                             final Symbol sym,
4883                             ResultInfo resultInfo,
4884                             Env<AttrContext> env,
4885                             final List<JCExpression> argtrees,
4886                             List<Type> argtypes,
4887                             List<Type> typeargtypes) {
4888         // Test (5): if symbol is an instance method of a raw type, issue
4889         // an unchecked warning if its argument types change under erasure.
4890         if ((sym.flags() & STATIC) == 0 &&
4891             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4892             Type s = types.asOuterSuper(site, sym.owner);
4893             if (s != null && s.isRaw() &&
4894                 !types.isSameTypes(sym.type.getParameterTypes(),
4895                                    sym.erasure(types).getParameterTypes())) {
4896                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
4897             }
4898         }
4899 
4900         if (env.info.defaultSuperCallSite != null) {
4901             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4902                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4903                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4904                 List<MethodSymbol> icand_sup =
4905                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4906                 if (icand_sup.nonEmpty() &&
4907                         icand_sup.head != sym &&
4908                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4909                     log.error(env.tree.pos(),
4910                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4911                     break;
4912                 }
4913             }
4914             env.info.defaultSuperCallSite = null;
4915         }
4916 
4917         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4918             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4919             if (app.meth.hasTag(SELECT) &&
4920                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4921                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4922             }
4923         }
4924 
4925         // Compute the identifier's instantiated type.
4926         // For methods, we need to compute the instance type by
4927         // Resolve.instantiate from the symbol's type as well as
4928         // any type arguments and value arguments.
4929         Warner noteWarner = new Warner();
4930         try {
4931             Type owntype = rs.checkMethod(
4932                     env,
4933                     site,
4934                     sym,
4935                     resultInfo,
4936                     argtypes,
4937                     typeargtypes,
4938                     noteWarner);
4939 
4940             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4941                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4942 
4943             argtypes = argtypes.map(checkDeferredMap);
4944 
4945             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4946                 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
4947                         sym.name,
4948                         rs.methodArguments(sym.type.getParameterTypes()),
4949                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4950                         kindName(sym.location()),
4951                         sym.location()));
4952                 if (resultInfo.pt != Infer.anyPoly ||
4953                         !owntype.hasTag(METHOD) ||
4954                         !owntype.isPartial()) {
4955                     //if this is not a partially inferred method type, erase return type. Otherwise,
4956                     //erasure is carried out in PartiallyInferredMethodType.check().
4957                     owntype = new MethodType(owntype.getParameterTypes(),
4958                             types.erasure(owntype.getReturnType()),
4959                             types.erasure(owntype.getThrownTypes()),
4960                             syms.methodClass);
4961                 }
4962             }
4963 
4964             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4965                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4966                  PolyKind.POLY : PolyKind.STANDALONE;
4967             TreeInfo.setPolyKind(env.tree, pkind);
4968 
4969             return (resultInfo.pt == Infer.anyPoly) ?
4970                     owntype :
4971                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4972                             resultInfo.checkContext.inferenceContext());
4973         } catch (Infer.InferenceException ex) {
4974             //invalid target type - propagate exception outwards or report error
4975             //depending on the current check context
4976             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4977             return types.createErrorType(site);
4978         } catch (Resolve.InapplicableMethodException ex) {
4979             final JCDiagnostic diag = ex.getDiagnostic();
4980             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4981                 @Override
4982                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4983                     return new Pair<>(sym, diag);
4984                 }
4985             };
4986             List<Type> argtypes2 = argtypes.map(
4987                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4988             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4989                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4990             log.report(errDiag);
4991             return types.createErrorType(site);
4992         }
4993     }
4994 
4995     public void visitLiteral(JCLiteral tree) {
4996         result = check(tree, litType(tree.typetag).constType(tree.value),
4997                 KindSelector.VAL, resultInfo);
4998     }
4999     //where
5000     /** Return the type of a literal with given type tag.
5001      */
5002     Type litType(TypeTag tag) {
5003         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5004     }
5005 
5006     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5007         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5008     }
5009 
5010     public void visitTypeArray(JCArrayTypeTree tree) {
5011         Type etype = attribType(tree.elemtype, env);
5012         Type type = new ArrayType(etype, syms.arrayClass);
5013         result = check(tree, type, KindSelector.TYP, resultInfo);
5014     }
5015 
5016     /** Visitor method for parameterized types.
5017      *  Bound checking is left until later, since types are attributed
5018      *  before supertype structure is completely known
5019      */
5020     public void visitTypeApply(JCTypeApply tree) {
5021         Type owntype = types.createErrorType(tree.type);
5022 
5023         // Attribute functor part of application and make sure it's a class.
5024         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5025 
5026         // Attribute type parameters
5027         List<Type> actuals = attribTypes(tree.arguments, env);
5028 
5029         if (clazztype.hasTag(CLASS)) {
5030             List<Type> formals = clazztype.tsym.type.getTypeArguments();
5031             if (actuals.isEmpty()) //diamond
5032                 actuals = formals;
5033 
5034             if (actuals.length() == formals.length()) {
5035                 List<Type> a = actuals;
5036                 List<Type> f = formals;
5037                 while (a.nonEmpty()) {
5038                     a.head = a.head.withTypeVar(f.head);
5039                     a = a.tail;
5040                     f = f.tail;
5041                 }
5042                 // Compute the proper generic outer
5043                 Type clazzOuter = clazztype.getEnclosingType();
5044                 if (clazzOuter.hasTag(CLASS)) {
5045                     Type site;
5046                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5047                     if (clazz.hasTag(IDENT)) {
5048                         site = env.enclClass.sym.type;
5049                     } else if (clazz.hasTag(SELECT)) {
5050                         site = ((JCFieldAccess) clazz).selected.type;
5051                     } else throw new AssertionError(""+tree);
5052                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5053                         if (site.hasTag(CLASS))
5054                             site = types.asOuterSuper(site, clazzOuter.tsym);
5055                         if (site == null)
5056                             site = types.erasure(clazzOuter);
5057                         clazzOuter = site;
5058                     }
5059                 }
5060                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5061                                         clazztype.getMetadata());
5062             } else {
5063                 if (formals.length() != 0) {
5064                     log.error(tree.pos(),
5065                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5066                 } else {
5067                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5068                 }
5069                 owntype = types.createErrorType(tree.type);
5070             }
5071         } else if (clazztype.hasTag(ERROR)) {
5072             ErrorType parameterizedErroneous =
5073                     new ErrorType(clazztype.getOriginalType(),
5074                                   clazztype.tsym,
5075                                   clazztype.getMetadata());
5076 
5077             parameterizedErroneous.typarams_field = actuals;
5078             owntype = parameterizedErroneous;
5079         }
5080         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5081     }
5082 
5083     public void visitTypeUnion(JCTypeUnion tree) {
5084         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5085         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5086         for (JCExpression typeTree : tree.alternatives) {
5087             Type ctype = attribType(typeTree, env);
5088             ctype = chk.checkType(typeTree.pos(),
5089                           chk.checkClassType(typeTree.pos(), ctype),
5090                           syms.throwableType);
5091             if (!ctype.isErroneous()) {
5092                 //check that alternatives of a union type are pairwise
5093                 //unrelated w.r.t. subtyping
5094                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
5095                     for (Type t : multicatchTypes) {
5096                         boolean sub = types.isSubtype(ctype, t);
5097                         boolean sup = types.isSubtype(t, ctype);
5098                         if (sub || sup) {
5099                             //assume 'a' <: 'b'
5100                             Type a = sub ? ctype : t;
5101                             Type b = sub ? t : ctype;
5102                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5103                         }
5104                     }
5105                 }
5106                 multicatchTypes.append(ctype);
5107                 if (all_multicatchTypes != null)
5108                     all_multicatchTypes.append(ctype);
5109             } else {
5110                 if (all_multicatchTypes == null) {
5111                     all_multicatchTypes = new ListBuffer<>();
5112                     all_multicatchTypes.appendList(multicatchTypes);
5113                 }
5114                 all_multicatchTypes.append(ctype);
5115             }
5116         }
5117         Type t = check(tree, types.lub(multicatchTypes.toList()),
5118                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5119         if (t.hasTag(CLASS)) {
5120             List<Type> alternatives =
5121                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5122             t = new UnionClassType((ClassType) t, alternatives);
5123         }
5124         tree.type = result = t;
5125     }
5126 
5127     public void visitTypeIntersection(JCTypeIntersection tree) {
5128         attribTypes(tree.bounds, env);
5129         tree.type = result = checkIntersection(tree, tree.bounds);
5130     }
5131 
5132     public void visitTypeParameter(JCTypeParameter tree) {
5133         TypeVar typeVar = (TypeVar) tree.type;
5134 
5135         if (tree.annotations != null && tree.annotations.nonEmpty()) {
5136             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5137         }
5138 
5139         if (!typeVar.getUpperBound().isErroneous()) {
5140             //fixup type-parameter bound computed in 'attribTypeVariables'
5141             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5142         }
5143     }
5144 
5145     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5146         Set<Symbol> boundSet = new HashSet<>();
5147         if (bounds.nonEmpty()) {
5148             // accept class or interface or typevar as first bound.
5149             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5150             boundSet.add(types.erasure(bounds.head.type).tsym);
5151             if (bounds.head.type.isErroneous()) {
5152                 return bounds.head.type;
5153             }
5154             else if (bounds.head.type.hasTag(TYPEVAR)) {
5155                 // if first bound was a typevar, do not accept further bounds.
5156                 if (bounds.tail.nonEmpty()) {
5157                     log.error(bounds.tail.head.pos(),
5158                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
5159                     return bounds.head.type;
5160                 }
5161             } else {
5162                 // if first bound was a class or interface, accept only interfaces
5163                 // as further bounds.
5164                 for (JCExpression bound : bounds.tail) {
5165                     bound.type = checkBase(bound.type, bound, env, false, true, false);
5166                     if (bound.type.isErroneous()) {
5167                         bounds = List.of(bound);
5168                     }
5169                     else if (bound.type.hasTag(CLASS)) {
5170                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5171                     }
5172                 }
5173             }
5174         }
5175 
5176         if (bounds.length() == 0) {
5177             return syms.objectType;
5178         } else if (bounds.length() == 1) {
5179             return bounds.head.type;
5180         } else {
5181             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5182             // ... the variable's bound is a class type flagged COMPOUND
5183             // (see comment for TypeVar.bound).
5184             // In this case, generate a class tree that represents the
5185             // bound class, ...
5186             JCExpression extending;
5187             List<JCExpression> implementing;
5188             if (!bounds.head.type.isInterface()) {
5189                 extending = bounds.head;
5190                 implementing = bounds.tail;
5191             } else {
5192                 extending = null;
5193                 implementing = bounds;
5194             }
5195             JCClassDecl cd = make.at(tree).ClassDef(
5196                 make.Modifiers(PUBLIC | ABSTRACT),
5197                 names.empty, List.nil(),
5198                 extending, implementing, List.nil());
5199 
5200             ClassSymbol c = (ClassSymbol)owntype.tsym;
5201             Assert.check((c.flags() & COMPOUND) != 0);
5202             cd.sym = c;
5203             c.sourcefile = env.toplevel.sourcefile;
5204 
5205             // ... and attribute the bound class
5206             c.flags_field |= UNATTRIBUTED;
5207             Env<AttrContext> cenv = enter.classEnv(cd, env);
5208             typeEnvs.put(c, cenv);
5209             attribClass(c);
5210             return owntype;
5211         }
5212     }
5213 
5214     public void visitWildcard(JCWildcard tree) {
5215         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5216         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5217             ? syms.objectType
5218             : attribType(tree.inner, env);
5219         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5220                                               tree.kind.kind,
5221                                               syms.boundClass),
5222                 KindSelector.TYP, resultInfo);
5223     }
5224 
5225     public void visitAnnotation(JCAnnotation tree) {
5226         Assert.error("should be handled in annotate");
5227     }
5228 
5229     @Override
5230     public void visitModifiers(JCModifiers tree) {
5231         //error recovery only:
5232         Assert.check(resultInfo.pkind == KindSelector.ERR);
5233 
5234         attribAnnotationTypes(tree.annotations, env);
5235     }
5236 
5237     public void visitAnnotatedType(JCAnnotatedType tree) {
5238         attribAnnotationTypes(tree.annotations, env);
5239         Type underlyingType = attribType(tree.underlyingType, env);
5240         Type annotatedType = underlyingType.preannotatedType();
5241 
5242         if (!env.info.isNewClass)
5243             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5244         result = tree.type = annotatedType;
5245     }
5246 
5247     public void visitErroneous(JCErroneous tree) {
5248         if (tree.errs != null) {
5249             WriteableScope newScope = env.info.scope;
5250 
5251             if (env.tree instanceof JCClassDecl) {
5252                 Symbol fakeOwner =
5253                     new MethodSymbol(BLOCK, names.empty, null,
5254                         env.info.scope.owner);
5255                 newScope = newScope.dupUnshared(fakeOwner);
5256             }
5257 
5258             Env<AttrContext> errEnv =
5259                     env.dup(env.tree,
5260                             env.info.dup(newScope));
5261             errEnv.info.returnResult = unknownExprInfo;
5262             for (JCTree err : tree.errs)
5263                 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5264         }
5265         result = tree.type = syms.errType;
5266     }
5267 
5268     /** Default visitor method for all other trees.
5269      */
5270     public void visitTree(JCTree tree) {
5271         throw new AssertionError();
5272     }
5273 
5274     /**
5275      * Attribute an env for either a top level tree or class or module declaration.
5276      */
5277     public void attrib(Env<AttrContext> env) {
5278         switch (env.tree.getTag()) {
5279             case MODULEDEF:
5280                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5281                 break;
5282             case PACKAGEDEF:
5283                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5284                 break;
5285             default:
5286                 attribClass(env.tree.pos(), env.enclClass.sym);
5287         }
5288 
5289         annotate.flush();
5290     }
5291 
5292     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5293         try {
5294             annotate.flush();
5295             attribPackage(p);
5296         } catch (CompletionFailure ex) {
5297             chk.completionError(pos, ex);
5298         }
5299     }
5300 
5301     void attribPackage(PackageSymbol p) {
5302         attribWithLint(p,
5303                        env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5304     }
5305 
5306     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5307         try {
5308             annotate.flush();
5309             attribModule(m);
5310         } catch (CompletionFailure ex) {
5311             chk.completionError(pos, ex);
5312         }
5313     }
5314 
5315     void attribModule(ModuleSymbol m) {
5316         attribWithLint(m, env -> attribStat(env.tree, env));
5317     }
5318 
5319     private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5320         Env<AttrContext> env = typeEnvs.get(sym);
5321 
5322         Env<AttrContext> lintEnv = env;
5323         while (lintEnv.info.lint == null)
5324             lintEnv = lintEnv.next;
5325 
5326         Lint lint = lintEnv.info.lint.augment(sym);
5327 
5328         Lint prevLint = chk.setLint(lint);
5329         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5330 
5331         try {
5332             deferredLintHandler.flush(env.tree, lint);
5333             attrib.accept(env);
5334         } finally {
5335             log.useSource(prev);
5336             chk.setLint(prevLint);
5337         }
5338     }
5339 
5340     /** Main method: attribute class definition associated with given class symbol.
5341      *  reporting completion failures at the given position.
5342      *  @param pos The source position at which completion errors are to be
5343      *             reported.
5344      *  @param c   The class symbol whose definition will be attributed.
5345      */
5346     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5347         try {
5348             annotate.flush();
5349             attribClass(c);
5350         } catch (CompletionFailure ex) {
5351             chk.completionError(pos, ex);
5352         }
5353     }
5354 
5355     /** Attribute class definition associated with given class symbol.
5356      *  @param c   The class symbol whose definition will be attributed.
5357      */
5358     void attribClass(ClassSymbol c) throws CompletionFailure {
5359         if (c.type.hasTag(ERROR)) return;
5360 
5361         // Check for cycles in the inheritance graph, which can arise from
5362         // ill-formed class files.
5363         chk.checkNonCyclic(null, c.type);
5364 
5365         Type st = types.supertype(c.type);
5366         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5367             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5368             // First, attribute superclass.
5369             if (st.hasTag(CLASS))
5370                 attribClass((ClassSymbol)st.tsym);
5371 
5372             // Next attribute owner, if it is a class.
5373             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5374                 attribClass((ClassSymbol)c.owner);
5375 
5376             c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5377         }
5378 
5379         // The previous operations might have attributed the current class
5380         // if there was a cycle. So we test first whether the class is still
5381         // UNATTRIBUTED.
5382         if ((c.flags_field & UNATTRIBUTED) != 0) {
5383             c.flags_field &= ~UNATTRIBUTED;
5384 
5385             // Get environment current at the point of class definition.
5386             Env<AttrContext> env = typeEnvs.get(c);
5387 
5388             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5389             // because the annotations were not available at the time the env was created. Therefore,
5390             // we look up the environment chain for the first enclosing environment for which the
5391             // lint value is set. Typically, this is the parent env, but might be further if there
5392             // are any envs created as a result of TypeParameter nodes.
5393             Env<AttrContext> lintEnv = env;
5394             while (lintEnv.info.lint == null)
5395                 lintEnv = lintEnv.next;
5396 
5397             // Having found the enclosing lint value, we can initialize the lint value for this class
5398             env.info.lint = lintEnv.info.lint.augment(c);
5399 
5400             Lint prevLint = chk.setLint(env.info.lint);
5401             JavaFileObject prev = log.useSource(c.sourcefile);
5402             ResultInfo prevReturnRes = env.info.returnResult;
5403 
5404             try {
5405                 if (c.isSealed() &&
5406                         !c.isEnum() &&
5407                         !c.isPermittedExplicit &&
5408                         c.getPermittedSubclasses().isEmpty()) {
5409                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5410                 }
5411 
5412                 if (c.isSealed()) {
5413                     Set<Symbol> permittedTypes = new HashSet<>();
5414                     boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5415                     for (Type subType : c.getPermittedSubclasses()) {
5416                         if (subType.isErroneous()) {
5417                             // the type already caused errors, don't produce more potentially misleading errors
5418                             continue;
5419                         }
5420                         boolean isTypeVar = false;
5421                         if (subType.getTag() == TYPEVAR) {
5422                             isTypeVar = true; //error recovery
5423                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5424                                     Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5425                         }
5426                         if (subType.tsym.isAnonymous() && !c.isEnum()) {
5427                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),  Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5428                         }
5429                         if (permittedTypes.contains(subType.tsym)) {
5430                             DiagnosticPosition pos =
5431                                     env.enclClass.permitting.stream()
5432                                             .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5433                                             .limit(2).collect(List.collector()).get(1);
5434                             log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5435                         } else {
5436                             permittedTypes.add(subType.tsym);
5437                         }
5438                         if (sealedInUnnamed) {
5439                             if (subType.tsym.packge() != c.packge()) {
5440                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5441                                         Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5442                                 );
5443                             }
5444                         } else if (subType.tsym.packge().modle != c.packge().modle) {
5445                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5446                                     Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5447                             );
5448                         }
5449                         if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5450                             log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5451                                     Errors.InvalidPermitsClause(
5452                                             subType.tsym == c.type.tsym ?
5453                                                     Fragments.MustNotBeSameClass :
5454                                                     Fragments.MustNotBeSupertype(subType)
5455                                     )
5456                             );
5457                         } else if (!isTypeVar) {
5458                             boolean thisIsASuper = types.directSupertypes(subType)
5459                                                         .stream()
5460                                                         .anyMatch(d -> d.tsym == c);
5461                             if (!thisIsASuper) {
5462                                 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5463                                         Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5464                             }
5465                         }
5466                     }
5467                 }
5468 
5469                 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5470                                                       .stream()
5471                                                       .filter(s -> s.tsym.isSealed())
5472                                                       .map(s -> (ClassSymbol) s.tsym)
5473                                                       .collect(List.collector());
5474 
5475                 if (sealedSupers.isEmpty()) {
5476                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5477                         boolean hasErrorSuper = false;
5478 
5479                         hasErrorSuper |= types.directSupertypes(c.type)
5480                                               .stream()
5481                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5482 
5483                         ClassType ct = (ClassType) c.type;
5484 
5485                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5486 
5487                         if (!hasErrorSuper) {
5488                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5489                         }
5490                     }
5491                 } else {
5492                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5493                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5494                     }
5495 
5496                     if (!c.type.isCompound()) {
5497                         for (ClassSymbol supertypeSym : sealedSupers) {
5498                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5499                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5500                             }
5501                         }
5502                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5503                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5504                                     c.isInterface() ?
5505                                             Errors.NonSealedOrSealedExpected :
5506                                             Errors.NonSealedSealedOrFinalExpected);
5507                         }
5508                     }
5509                 }
5510 
5511                 deferredLintHandler.flush(env.tree, env.info.lint);
5512                 env.info.returnResult = null;
5513                 // java.lang.Enum may not be subclassed by a non-enum
5514                 if (st.tsym == syms.enumSym &&
5515                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5516                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5517 
5518                 // Enums may not be extended by source-level classes
5519                 if (st.tsym != null &&
5520                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5521                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5522                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5523                 }
5524 
5525                 if (rs.isSerializable(c.type)) {
5526                     env.info.isSerializable = true;
5527                 }
5528 





5529                 attribClassBody(env, c);
5530 
5531                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5532                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5533                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5534                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5535 
5536                 if (c.isImplicit()) {
5537                     chk.checkHasMain(env.tree.pos(), c);
5538                 }
5539             } finally {
5540                 env.info.returnResult = prevReturnRes;
5541                 log.useSource(prev);
5542                 chk.setLint(prevLint);
5543             }
5544 
5545         }
5546     }
5547 
5548     public void visitImport(JCImport tree) {
5549         // nothing to do
5550     }
5551 
5552     public void visitModuleDef(JCModuleDecl tree) {
5553         tree.sym.completeUsesProvides();
5554         ModuleSymbol msym = tree.sym;
5555         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5556         Lint prevLint = chk.setLint(lint);
5557         chk.checkModuleName(tree);
5558         chk.checkDeprecatedAnnotation(tree, msym);
5559 
5560         try {
5561             deferredLintHandler.flush(tree, lint);
5562         } finally {
5563             chk.setLint(prevLint);
5564         }
5565     }
5566 
5567     /** Finish the attribution of a class. */
5568     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5569         JCClassDecl tree = (JCClassDecl)env.tree;
5570         Assert.check(c == tree.sym);
5571 
5572         // Validate type parameters, supertype and interfaces.
5573         attribStats(tree.typarams, env);
5574         if (!c.isAnonymous()) {
5575             //already checked if anonymous
5576             chk.validate(tree.typarams, env);
5577             chk.validate(tree.extending, env);
5578             chk.validate(tree.implementing, env);
5579         }
5580 
5581         c.markAbstractIfNeeded(types);
5582 
5583         // If this is a non-abstract class, check that it has no abstract
5584         // methods or unimplemented methods of an implemented interface.
5585         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
5586             chk.checkAllDefined(tree.pos(), c);
5587         }
5588 
5589         if ((c.flags() & ANNOTATION) != 0) {
5590             if (tree.implementing.nonEmpty())
5591                 log.error(tree.implementing.head.pos(),
5592                           Errors.CantExtendIntfAnnotation);
5593             if (tree.typarams.nonEmpty()) {
5594                 log.error(tree.typarams.head.pos(),
5595                           Errors.IntfAnnotationCantHaveTypeParams(c));
5596             }
5597 
5598             // If this annotation type has a @Repeatable, validate
5599             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
5600             // If this annotation type has a @Repeatable, validate
5601             if (repeatable != null) {
5602                 // get diagnostic position for error reporting
5603                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
5604                 Assert.checkNonNull(cbPos);
5605 
5606                 chk.validateRepeatable(c, repeatable, cbPos);
5607             }
5608         } else {
5609             // Check that all extended classes and interfaces
5610             // are compatible (i.e. no two define methods with same arguments
5611             // yet different return types).  (JLS 8.4.8.3)
5612             chk.checkCompatibleSupertypes(tree.pos(), c.type);
5613             chk.checkDefaultMethodClashes(tree.pos(), c.type);
5614             chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
5615         }
5616 
5617         // Check that class does not import the same parameterized interface
5618         // with two different argument lists.
5619         chk.checkClassBounds(tree.pos(), c.type);
5620 
5621         tree.type = c.type;
5622 
5623         for (List<JCTypeParameter> l = tree.typarams;
5624              l.nonEmpty(); l = l.tail) {
5625              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
5626         }
5627 
5628         // Check that a generic class doesn't extend Throwable
5629         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
5630             log.error(tree.extending.pos(), Errors.GenericThrowable);
5631 
5632         // Check that all methods which implement some
5633         // method conform to the method they implement.
5634         chk.checkImplementations(tree);
5635 
5636         //check that a resource implementing AutoCloseable cannot throw InterruptedException
5637         checkAutoCloseable(tree.pos(), env, c.type);
5638 
5639         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
5640             // Attribute declaration
5641             attribStat(l.head, env);
5642             // Check that declarations in inner classes are not static (JLS 8.1.2)
5643             // Make an exception for static constants.
5644             if (!allowRecords &&
5645                     c.owner.kind != PCK &&
5646                     ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
5647                     (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
5648                 VarSymbol sym = null;
5649                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
5650                 if (sym == null ||
5651                         sym.kind != VAR ||
5652                         sym.getConstValue() == null)
5653                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5654             }
5655         }
5656 
5657         // Check for proper placement of super()/this() calls.
5658         chk.checkSuperInitCalls(tree);
5659 
5660         // Check for cycles among non-initial constructors.
5661         chk.checkCyclicConstructors(tree);
5662 
5663         // Check for cycles among annotation elements.
5664         chk.checkNonCyclicElements(tree);
5665 
5666         // Check for proper use of serialVersionUID and other
5667         // serialization-related fields and methods
5668         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5669                 && rs.isSerializable(c.type)
5670                 && !c.isAnonymous()) {
5671             chk.checkSerialStructure(tree, c);
5672         }
5673         // Correctly organize the positions of the type annotations
5674         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5675 
5676         // Check type annotations applicability rules
5677         validateTypeAnnotations(tree, false);
5678     }
5679         // where
5680         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5681         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5682             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5683                 if (types.isSameType(al.head.annotationType.type, t))
5684                     return al.head.pos();
5685             }
5686 
5687             return null;
5688         }
5689 
5690     private Type capture(Type type) {
5691         return types.capture(type);
5692     }
5693 
5694     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
5695         if (type.isErroneous()) {
5696             tree.vartype = make.at(Position.NOPOS).Erroneous();
5697         } else {
5698             tree.vartype = make.at(Position.NOPOS).Type(type);
5699         }
5700     }
5701 
5702     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
5703         tree.accept(new TypeAnnotationsValidator(sigOnly));
5704     }
5705     //where
5706     private final class TypeAnnotationsValidator extends TreeScanner {
5707 
5708         private final boolean sigOnly;
5709         public TypeAnnotationsValidator(boolean sigOnly) {
5710             this.sigOnly = sigOnly;
5711         }
5712 
5713         public void visitAnnotation(JCAnnotation tree) {
5714             chk.validateTypeAnnotation(tree, null, false);
5715             super.visitAnnotation(tree);
5716         }
5717         public void visitAnnotatedType(JCAnnotatedType tree) {
5718             if (!tree.underlyingType.type.isErroneous()) {
5719                 super.visitAnnotatedType(tree);
5720             }
5721         }
5722         public void visitTypeParameter(JCTypeParameter tree) {
5723             chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
5724             scan(tree.bounds);
5725             // Don't call super.
5726             // This is needed because above we call validateTypeAnnotation with
5727             // false, which would forbid annotations on type parameters.
5728             // super.visitTypeParameter(tree);
5729         }
5730         public void visitMethodDef(JCMethodDecl tree) {
5731             if (tree.recvparam != null &&
5732                     !tree.recvparam.vartype.type.isErroneous()) {
5733                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
5734             }
5735             if (tree.restype != null && tree.restype.type != null) {
5736                 validateAnnotatedType(tree.restype, tree.restype.type);
5737             }
5738             if (sigOnly) {
5739                 scan(tree.mods);
5740                 scan(tree.restype);
5741                 scan(tree.typarams);
5742                 scan(tree.recvparam);
5743                 scan(tree.params);
5744                 scan(tree.thrown);
5745             } else {
5746                 scan(tree.defaultValue);
5747                 scan(tree.body);
5748             }
5749         }
5750         public void visitVarDef(final JCVariableDecl tree) {
5751             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
5752             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
5753                 validateAnnotatedType(tree.vartype, tree.sym.type);
5754             scan(tree.mods);
5755             scan(tree.vartype);
5756             if (!sigOnly) {
5757                 scan(tree.init);
5758             }
5759         }
5760         public void visitTypeCast(JCTypeCast tree) {
5761             if (tree.clazz != null && tree.clazz.type != null)
5762                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5763             super.visitTypeCast(tree);
5764         }
5765         public void visitTypeTest(JCInstanceOf tree) {
5766             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
5767                 validateAnnotatedType(tree.pattern, tree.pattern.type);
5768             super.visitTypeTest(tree);
5769         }
5770         public void visitNewClass(JCNewClass tree) {
5771             if (tree.clazz != null && tree.clazz.type != null) {
5772                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5773                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5774                             tree.clazz.type.tsym);
5775                 }
5776                 if (tree.def != null) {
5777                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5778                 }
5779 
5780                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5781             }
5782             super.visitNewClass(tree);
5783         }
5784         public void visitNewArray(JCNewArray tree) {
5785             if (tree.elemtype != null && tree.elemtype.type != null) {
5786                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5787                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5788                             tree.elemtype.type.tsym);
5789                 }
5790                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5791             }
5792             super.visitNewArray(tree);
5793         }
5794         public void visitClassDef(JCClassDecl tree) {
5795             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5796             if (sigOnly) {
5797                 scan(tree.mods);
5798                 scan(tree.typarams);
5799                 scan(tree.extending);
5800                 scan(tree.implementing);
5801             }
5802             for (JCTree member : tree.defs) {
5803                 if (member.hasTag(Tag.CLASSDEF)) {
5804                     continue;
5805                 }
5806                 scan(member);
5807             }
5808         }
5809         public void visitBlock(JCBlock tree) {
5810             if (!sigOnly) {
5811                 scan(tree.stats);
5812             }
5813         }
5814 
5815         /* I would want to model this after
5816          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5817          * and override visitSelect and visitTypeApply.
5818          * However, we only set the annotated type in the top-level type
5819          * of the symbol.
5820          * Therefore, we need to override each individual location where a type
5821          * can occur.
5822          */
5823         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5824             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5825 
5826             if (type.isPrimitiveOrVoid()) {
5827                 return;
5828             }
5829 
5830             JCTree enclTr = errtree;
5831             Type enclTy = type;
5832 
5833             boolean repeat = true;
5834             while (repeat) {
5835                 if (enclTr.hasTag(TYPEAPPLY)) {
5836                     List<Type> tyargs = enclTy.getTypeArguments();
5837                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5838                     if (trargs.length() > 0) {
5839                         // Nothing to do for diamonds
5840                         if (tyargs.length() == trargs.length()) {
5841                             for (int i = 0; i < tyargs.length(); ++i) {
5842                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5843                             }
5844                         }
5845                         // If the lengths don't match, it's either a diamond
5846                         // or some nested type that redundantly provides
5847                         // type arguments in the tree.
5848                     }
5849 
5850                     // Look at the clazz part of a generic type
5851                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5852                 }
5853 
5854                 if (enclTr.hasTag(SELECT)) {
5855                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5856                     if (enclTy != null &&
5857                             !enclTy.hasTag(NONE)) {
5858                         enclTy = enclTy.getEnclosingType();
5859                     }
5860                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5861                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5862                     if (enclTy == null || enclTy.hasTag(NONE)) {
5863                         ListBuffer<Attribute.TypeCompound> onlyTypeAnnotationsBuf = new ListBuffer<>();
5864                         for (JCAnnotation an : at.getAnnotations()) {
5865                             if (chk.isTypeAnnotation(an, false)) {
5866                                 onlyTypeAnnotationsBuf.add((Attribute.TypeCompound) an.attribute);
5867                             }
5868                         }
5869                         List<Attribute.TypeCompound> onlyTypeAnnotations = onlyTypeAnnotationsBuf.toList();
5870                         if (!onlyTypeAnnotations.isEmpty()) {
5871                             Fragment annotationFragment = onlyTypeAnnotations.size() == 1 ?
5872                                     Fragments.TypeAnnotation1(onlyTypeAnnotations.head) :
5873                                     Fragments.TypeAnnotation(onlyTypeAnnotations);
5874                             JCDiagnostic.AnnotatedType annotatedType = new JCDiagnostic.AnnotatedType(
5875                                     type.stripMetadata().annotatedType(onlyTypeAnnotations));
5876                             log.error(at.underlyingType.pos(), Errors.TypeAnnotationInadmissible(annotationFragment,
5877                                     type.tsym.owner, annotatedType));
5878                         }
5879                         repeat = false;
5880                     }
5881                     enclTr = at.underlyingType;
5882                     // enclTy doesn't need to be changed
5883                 } else if (enclTr.hasTag(IDENT)) {
5884                     repeat = false;
5885                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5886                     JCWildcard wc = (JCWildcard) enclTr;
5887                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5888                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5889                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5890                     } else {
5891                         // Nothing to do for UNBOUND
5892                     }
5893                     repeat = false;
5894                 } else if (enclTr.hasTag(TYPEARRAY)) {
5895                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5896                     validateAnnotatedType(art.getType(), art.elemtype.type);
5897                     repeat = false;
5898                 } else if (enclTr.hasTag(TYPEUNION)) {
5899                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5900                     for (JCTree t : ut.getTypeAlternatives()) {
5901                         validateAnnotatedType(t, t.type);
5902                     }
5903                     repeat = false;
5904                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5905                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5906                     for (JCTree t : it.getBounds()) {
5907                         validateAnnotatedType(t, t.type);
5908                     }
5909                     repeat = false;
5910                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5911                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5912                     repeat = false;
5913                 } else {
5914                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5915                             " within: "+ errtree + " with kind: " + errtree.getKind());
5916                 }
5917             }
5918         }
5919 
5920         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5921                 Symbol sym) {
5922             // Ensure that no declaration annotations are present.
5923             // Note that a tree type might be an AnnotatedType with
5924             // empty annotations, if only declaration annotations were given.
5925             // This method will raise an error for such a type.
5926             for (JCAnnotation ai : annotations) {
5927                 if (!ai.type.isErroneous() &&
5928                         typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5929                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5930                 }
5931             }
5932         }
5933     }
5934 
5935     // <editor-fold desc="post-attribution visitor">
5936 
5937     /**
5938      * Handle missing types/symbols in an AST. This routine is useful when
5939      * the compiler has encountered some errors (which might have ended up
5940      * terminating attribution abruptly); if the compiler is used in fail-over
5941      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5942      * prevents NPE to be propagated during subsequent compilation steps.
5943      */
5944     public void postAttr(JCTree tree) {
5945         new PostAttrAnalyzer().scan(tree);
5946     }
5947 
5948     class PostAttrAnalyzer extends TreeScanner {
5949 
5950         private void initTypeIfNeeded(JCTree that) {
5951             if (that.type == null) {
5952                 if (that.hasTag(METHODDEF)) {
5953                     that.type = dummyMethodType((JCMethodDecl)that);
5954                 } else {
5955                     that.type = syms.unknownType;
5956                 }
5957             }
5958         }
5959 
5960         /* Construct a dummy method type. If we have a method declaration,
5961          * and the declared return type is void, then use that return type
5962          * instead of UNKNOWN to avoid spurious error messages in lambda
5963          * bodies (see:JDK-8041704).
5964          */
5965         private Type dummyMethodType(JCMethodDecl md) {
5966             Type restype = syms.unknownType;
5967             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5968                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5969                 if (prim.typetag == VOID)
5970                     restype = syms.voidType;
5971             }
5972             return new MethodType(List.nil(), restype,
5973                                   List.nil(), syms.methodClass);
5974         }
5975         private Type dummyMethodType() {
5976             return dummyMethodType(null);
5977         }
5978 
5979         @Override
5980         public void scan(JCTree tree) {
5981             if (tree == null) return;
5982             if (tree instanceof JCExpression) {
5983                 initTypeIfNeeded(tree);
5984             }
5985             super.scan(tree);
5986         }
5987 
5988         @Override
5989         public void visitIdent(JCIdent that) {
5990             if (that.sym == null) {
5991                 that.sym = syms.unknownSymbol;
5992             }
5993         }
5994 
5995         @Override
5996         public void visitSelect(JCFieldAccess that) {
5997             if (that.sym == null) {
5998                 that.sym = syms.unknownSymbol;
5999             }
6000             super.visitSelect(that);
6001         }
6002 
6003         @Override
6004         public void visitClassDef(JCClassDecl that) {
6005             initTypeIfNeeded(that);
6006             if (that.sym == null) {
6007                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6008             }
6009             super.visitClassDef(that);
6010         }
6011 
6012         @Override
6013         public void visitMethodDef(JCMethodDecl that) {
6014             initTypeIfNeeded(that);
6015             if (that.sym == null) {
6016                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6017             }
6018             super.visitMethodDef(that);
6019         }
6020 
6021         @Override
6022         public void visitVarDef(JCVariableDecl that) {
6023             initTypeIfNeeded(that);
6024             if (that.sym == null) {
6025                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6026                 that.sym.adr = 0;
6027             }
6028             if (that.vartype == null) {
6029                 that.vartype = make.at(Position.NOPOS).Erroneous();
6030             }
6031             super.visitVarDef(that);
6032         }
6033 
6034         @Override
6035         public void visitBindingPattern(JCBindingPattern that) {
6036             initTypeIfNeeded(that);
6037             initTypeIfNeeded(that.var);
6038             if (that.var.sym == null) {
6039                 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6040                 that.var.sym.adr = 0;
6041             }
6042             super.visitBindingPattern(that);
6043         }
6044 
6045         @Override
6046         public void visitRecordPattern(JCRecordPattern that) {
6047             initTypeIfNeeded(that);
6048             if (that.record == null) {
6049                 that.record = new ClassSymbol(0, TreeInfo.name(that.deconstructor),
6050                                               that.type, syms.noSymbol);
6051             }
6052             if (that.fullComponentTypes == null) {
6053                 that.fullComponentTypes = List.nil();
6054             }
6055             super.visitRecordPattern(that);
6056         }
6057 
6058         @Override
6059         public void visitNewClass(JCNewClass that) {
6060             if (that.constructor == null) {
6061                 that.constructor = new MethodSymbol(0, names.init,
6062                         dummyMethodType(), syms.noSymbol);
6063             }
6064             if (that.constructorType == null) {
6065                 that.constructorType = syms.unknownType;
6066             }
6067             super.visitNewClass(that);
6068         }
6069 
6070         @Override
6071         public void visitAssignop(JCAssignOp that) {
6072             if (that.operator == null) {
6073                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6074                         -1, syms.noSymbol);
6075             }
6076             super.visitAssignop(that);
6077         }
6078 
6079         @Override
6080         public void visitBinary(JCBinary that) {
6081             if (that.operator == null) {
6082                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6083                         -1, syms.noSymbol);
6084             }
6085             super.visitBinary(that);
6086         }
6087 
6088         @Override
6089         public void visitUnary(JCUnary that) {
6090             if (that.operator == null) {
6091                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6092                         -1, syms.noSymbol);
6093             }
6094             super.visitUnary(that);
6095         }
6096 
6097         @Override
6098         public void visitReference(JCMemberReference that) {
6099             super.visitReference(that);
6100             if (that.sym == null) {
6101                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6102                         syms.noSymbol);
6103             }
6104         }
6105     }
6106     // </editor-fold>
6107 
6108     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6109         new TreeScanner() {
6110             Symbol packge = pkg;
6111             @Override
6112             public void visitIdent(JCIdent that) {
6113                 that.sym = packge;
6114             }
6115 
6116             @Override
6117             public void visitSelect(JCFieldAccess that) {
6118                 that.sym = packge;
6119                 packge = packge.owner;
6120                 super.visitSelect(that);
6121             }
6122         }.scan(pid);
6123     }
6124 
6125 }
--- EOF ---