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