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