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