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