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