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