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