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             // This will figure out when unboxing can happen and
2995             // choose the right comparison operator.
2996             int opc = chk.checkOperator(tree.lhs.pos(),
2997                                         (OperatorSymbol)operator,
2998                                         tree.getTag(),
2999                                         left,
3000                                         right);
3001 
3002             // If both arguments are constants, fold them.
3003             if (left.constValue() != null && right.constValue() != null) {
3004                 Type ctype = cfolder.fold2(opc, left, right);
3005                 if (ctype != null) {
3006                     owntype = cfolder.coerce(ctype, owntype);
3007 
3008                     // Remove constant types from arguments to
3009                     // conserve space. The parser will fold concatenations
3010                     // of string literals; the code here also
3011                     // gets rid of intermediate results when some of the
3012                     // operands are constant identifiers.
3013                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
3014                         tree.lhs.type = syms.stringType;
3015                     }
3016                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
3017                         tree.rhs.type = syms.stringType;
3018                     }
3019                 }
3020             }
3021 
3022             // Check that argument types of a reference ==, != are
3023             // castable to each other, (JLS 15.21).  Note: unboxing
3024             // comparisons will not have an acmp* opc at this point.
3025             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3026                 if (!types.isEqualityComparable(left, right,
3027                                                 new Warner(tree.pos()))) {
3028                     log.error(tree.pos(), "incomparable.types", left, right);
3029                 }
3030             }
3031 
3032             chk.checkDivZero(tree.rhs.pos(), operator, right);
3033         }
3034         result = check(tree, owntype, VAL, resultInfo);
3035     }
3036 
3037     public void visitTypeCast(final JCTypeCast tree) {
3038         Type clazztype = attribType(tree.clazz, env);
3039         chk.validate(tree.clazz, env, false);
3040         //a fresh environment is required for 292 inference to work properly ---
3041         //see Infer.instantiatePolymorphicSignatureInstance()
3042         Env<AttrContext> localEnv = env.dup(tree);
3043         //should we propagate the target type?
3044         final ResultInfo castInfo;
3045         JCExpression expr = TreeInfo.skipParens(tree.expr);
3046         boolean isPoly = expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE);
3047         if (isPoly) {
3048             //expression is a poly - we need to propagate target type info
3049             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
3050                 @Override
3051                 public boolean compatible(Type found, Type req, Warner warn) {
3052                     return types.isCastable(found, req, warn);
3053                 }
3054             });
3055         } else {
3056             //standalone cast - target-type info is not propagated
3057             castInfo = unknownExprInfo;
3058         }
3059         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3060         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3061         if (exprtype.constValue() != null)
3062             owntype = cfolder.coerce(exprtype, owntype);
3063         result = check(tree, capture(owntype), VAL, resultInfo);
3064         if (!isPoly)
3065             chk.checkRedundantCast(localEnv, tree);
3066     }
3067 
3068     public void visitTypeTest(JCInstanceOf tree) {
3069         Type exprtype = chk.checkNullOrRefType(
3070             tree.expr.pos(), attribExpr(tree.expr, env));
3071         Type clazztype = chk.checkReifiableReferenceType(
3072             tree.clazz.pos(), attribType(tree.clazz, env));
3073         chk.validate(tree.clazz, env, false);
3074         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3075         result = check(tree, syms.booleanType, VAL, resultInfo);
3076     }
3077 
3078     public void visitIndexed(JCArrayAccess tree) {
3079         Type owntype = types.createErrorType(tree.type);
3080         Type atype = attribExpr(tree.indexed, env);
3081         attribExpr(tree.index, env, syms.intType);
3082         if (types.isArray(atype))
3083             owntype = types.elemtype(atype);
3084         else if (!atype.hasTag(ERROR))
3085             log.error(tree.pos(), "array.req.but.found", atype);
3086         if ((pkind() & VAR) == 0) owntype = capture(owntype);
3087         result = check(tree, owntype, VAR, resultInfo);
3088     }
3089 
3090     public void visitIdent(JCIdent tree) {
3091         Symbol sym;
3092 
3093         // Find symbol
3094         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3095             // If we are looking for a method, the prototype `pt' will be a
3096             // method type with the type of the call's arguments as parameters.
3097             env.info.pendingResolutionPhase = null;
3098             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3099         } else if (tree.sym != null && tree.sym.kind != VAR) {
3100             sym = tree.sym;
3101         } else {
3102             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3103         }
3104         tree.sym = sym;
3105 
3106         // (1) Also find the environment current for the class where
3107         //     sym is defined (`symEnv').
3108         // Only for pre-tiger versions (1.4 and earlier):
3109         // (2) Also determine whether we access symbol out of an anonymous
3110         //     class in a this or super call.  This is illegal for instance
3111         //     members since such classes don't carry a this$n link.
3112         //     (`noOuterThisPath').
3113         Env<AttrContext> symEnv = env;
3114         boolean noOuterThisPath = false;
3115         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3116             (sym.kind & (VAR | MTH | TYP)) != 0 &&
3117             sym.owner.kind == TYP &&
3118             tree.name != names._this && tree.name != names._super) {
3119 
3120             // Find environment in which identifier is defined.
3121             while (symEnv.outer != null &&
3122                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3123                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3124                     noOuterThisPath = !allowAnonOuterThis;
3125                 symEnv = symEnv.outer;
3126             }
3127         }
3128 
3129         // If symbol is a variable, ...
3130         if (sym.kind == VAR) {
3131             VarSymbol v = (VarSymbol)sym;
3132 
3133             // ..., evaluate its initializer, if it has one, and check for
3134             // illegal forward reference.
3135             checkInit(tree, env, v, false);
3136 
3137             // If we are expecting a variable (as opposed to a value), check
3138             // that the variable is assignable in the current environment.
3139             if (pkind() == VAR)
3140                 checkAssignable(tree.pos(), v, null, env);
3141         }
3142 
3143         // In a constructor body,
3144         // if symbol is a field or instance method, check that it is
3145         // not accessed before the supertype constructor is called.
3146         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3147             (sym.kind & (VAR | MTH)) != 0 &&
3148             sym.owner.kind == TYP &&
3149             (sym.flags() & STATIC) == 0) {
3150             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
3151         }
3152         Env<AttrContext> env1 = env;
3153         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
3154             // If the found symbol is inaccessible, then it is
3155             // accessed through an enclosing instance.  Locate this
3156             // enclosing instance:
3157             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3158                 env1 = env1.outer;
3159         }
3160         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3161     }
3162 
3163     public void visitSelect(JCFieldAccess tree) {
3164         // Determine the expected kind of the qualifier expression.
3165         int skind = 0;
3166         if (tree.name == names._this || tree.name == names._super ||
3167             tree.name == names._class)
3168         {
3169             skind = TYP;
3170         } else {
3171             if ((pkind() & PCK) != 0) skind = skind | PCK;
3172             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
3173             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
3174         }
3175 
3176         // Attribute the qualifier expression, and determine its symbol (if any).
3177         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3178         if ((pkind() & (PCK | TYP)) == 0)
3179             site = capture(site); // Capture field access
3180 
3181         // don't allow T.class T[].class, etc
3182         if (skind == TYP) {
3183             Type elt = site;
3184             while (elt.hasTag(ARRAY))
3185                 elt = ((ArrayType)elt).elemtype;
3186             if (elt.hasTag(TYPEVAR)) {
3187                 log.error(tree.pos(), "type.var.cant.be.deref");
3188                 result = types.createErrorType(tree.type);
3189                 return;
3190             }
3191         }
3192 
3193         // If qualifier symbol is a type or `super', assert `selectSuper'
3194         // for the selection. This is relevant for determining whether
3195         // protected symbols are accessible.
3196         Symbol sitesym = TreeInfo.symbol(tree.selected);
3197         boolean selectSuperPrev = env.info.selectSuper;
3198         env.info.selectSuper =
3199             sitesym != null &&
3200             sitesym.name == names._super;
3201 
3202         // Determine the symbol represented by the selection.
3203         env.info.pendingResolutionPhase = null;
3204         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3205         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
3206             site = capture(site);
3207             sym = selectSym(tree, sitesym, site, env, resultInfo);
3208         }
3209         boolean varArgs = env.info.lastResolveVarargs();
3210         tree.sym = sym;
3211 
3212         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3213             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3214             site = capture(site);
3215         }
3216 
3217         // If that symbol is a variable, ...
3218         if (sym.kind == VAR) {
3219             VarSymbol v = (VarSymbol)sym;
3220 
3221             // ..., evaluate its initializer, if it has one, and check for
3222             // illegal forward reference.
3223             checkInit(tree, env, v, true);
3224 
3225             // If we are expecting a variable (as opposed to a value), check
3226             // that the variable is assignable in the current environment.
3227             if (pkind() == VAR)
3228                 checkAssignable(tree.pos(), v, tree.selected, env);
3229         }
3230 
3231         if (sitesym != null &&
3232                 sitesym.kind == VAR &&
3233                 ((VarSymbol)sitesym).isResourceVariable() &&
3234                 sym.kind == MTH &&
3235                 sym.name.equals(names.close) &&
3236                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3237                 env.info.lint.isEnabled(LintCategory.TRY)) {
3238             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3239         }
3240 
3241         // Disallow selecting a type from an expression
3242         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3243             tree.type = check(tree.selected, pt(),
3244                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3245         }
3246 
3247         if (isType(sitesym)) {
3248             if (sym.name == names._this) {
3249                 // If `C' is the currently compiled class, check that
3250                 // C.this' does not appear in a call to a super(...)
3251                 if (env.info.isSelfCall &&
3252                     site.tsym == env.enclClass.sym) {
3253                     chk.earlyRefError(tree.pos(), sym);
3254                 }
3255             } else {
3256                 // Check if type-qualified fields or methods are static (JLS)
3257                 if ((sym.flags() & STATIC) == 0 &&
3258                     !env.next.tree.hasTag(REFERENCE) &&
3259                     sym.name != names._super &&
3260                     (sym.kind == VAR || sym.kind == MTH)) {
3261                     rs.accessBase(rs.new StaticError(sym),
3262                               tree.pos(), site, sym.name, true);
3263                 }
3264             }
3265         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3266             // If the qualified item is not a type and the selected item is static, report
3267             // a warning. Make allowance for the class of an array type e.g. Object[].class)
3268             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3269         }
3270 
3271         // If we are selecting an instance member via a `super', ...
3272         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3273 
3274             // Check that super-qualified symbols are not abstract (JLS)
3275             rs.checkNonAbstract(tree.pos(), sym);
3276 
3277             if (site.isRaw()) {
3278                 // Determine argument types for site.
3279                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3280                 if (site1 != null) site = site1;
3281             }
3282         }
3283 
3284         env.info.selectSuper = selectSuperPrev;
3285         result = checkId(tree, site, sym, env, resultInfo);
3286     }
3287     //where
3288         /** Determine symbol referenced by a Select expression,
3289          *
3290          *  @param tree   The select tree.
3291          *  @param site   The type of the selected expression,
3292          *  @param env    The current environment.
3293          *  @param resultInfo The current result.
3294          */
3295         private Symbol selectSym(JCFieldAccess tree,
3296                                  Symbol location,
3297                                  Type site,
3298                                  Env<AttrContext> env,
3299                                  ResultInfo resultInfo) {
3300             DiagnosticPosition pos = tree.pos();
3301             Name name = tree.name;
3302             switch (site.getTag()) {
3303             case PACKAGE:
3304                 return rs.accessBase(
3305                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3306                     pos, location, site, name, true);
3307             case ARRAY:
3308             case CLASS:
3309                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3310                     return rs.resolveQualifiedMethod(
3311                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3312                 } else if (name == names._this || name == names._super) {
3313                     return rs.resolveSelf(pos, env, site.tsym, name);
3314                 } else if (name == names._class) {
3315                     // In this case, we have already made sure in
3316                     // visitSelect that qualifier expression is a type.
3317                     Type t = syms.classType;
3318                     List<Type> typeargs = allowGenerics
3319                         ? List.of(types.erasure(site))
3320                         : List.<Type>nil();
3321                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3322                     return new VarSymbol(
3323                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3324                 } else {
3325                     // We are seeing a plain identifier as selector.
3326                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3327                     if ((resultInfo.pkind & ERRONEOUS) == 0)
3328                         sym = rs.accessBase(sym, pos, location, site, name, true);
3329                     return sym;
3330                 }
3331             case WILDCARD:
3332                 throw new AssertionError(tree);
3333             case TYPEVAR:
3334                 // Normally, site.getUpperBound() shouldn't be null.
3335                 // It should only happen during memberEnter/attribBase
3336                 // when determining the super type which *must* beac
3337                 // done before attributing the type variables.  In
3338                 // other words, we are seeing this illegal program:
3339                 // class B<T> extends A<T.foo> {}
3340                 Symbol sym = (site.getUpperBound() != null)
3341                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3342                     : null;
3343                 if (sym == null) {
3344                     log.error(pos, "type.var.cant.be.deref");
3345                     return syms.errSymbol;
3346                 } else {
3347                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3348                         rs.new AccessError(env, site, sym) :
3349                                 sym;
3350                     rs.accessBase(sym2, pos, location, site, name, true);
3351                     return sym;
3352                 }
3353             case ERROR:
3354                 // preserve identifier names through errors
3355                 return types.createErrorType(name, site.tsym, site).tsym;
3356             default:
3357                 // The qualifier expression is of a primitive type -- only
3358                 // .class is allowed for these.
3359                 if (name == names._class) {
3360                     // In this case, we have already made sure in Select that
3361                     // qualifier expression is a type.
3362                     Type t = syms.classType;
3363                     Type arg = types.boxedClass(site).type;
3364                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3365                     return new VarSymbol(
3366                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3367                 } else {
3368                     log.error(pos, "cant.deref", site);
3369                     return syms.errSymbol;
3370                 }
3371             }
3372         }
3373 
3374         /** Determine type of identifier or select expression and check that
3375          *  (1) the referenced symbol is not deprecated
3376          *  (2) the symbol's type is safe (@see checkSafe)
3377          *  (3) if symbol is a variable, check that its type and kind are
3378          *      compatible with the prototype and protokind.
3379          *  (4) if symbol is an instance field of a raw type,
3380          *      which is being assigned to, issue an unchecked warning if its
3381          *      type changes under erasure.
3382          *  (5) if symbol is an instance method of a raw type, issue an
3383          *      unchecked warning if its argument types change under erasure.
3384          *  If checks succeed:
3385          *    If symbol is a constant, return its constant type
3386          *    else if symbol is a method, return its result type
3387          *    otherwise return its type.
3388          *  Otherwise return errType.
3389          *
3390          *  @param tree       The syntax tree representing the identifier
3391          *  @param site       If this is a select, the type of the selected
3392          *                    expression, otherwise the type of the current class.
3393          *  @param sym        The symbol representing the identifier.
3394          *  @param env        The current environment.
3395          *  @param resultInfo    The expected result
3396          */
3397         Type checkId(JCTree tree,
3398                      Type site,
3399                      Symbol sym,
3400                      Env<AttrContext> env,
3401                      ResultInfo resultInfo) {
3402             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3403                     checkMethodId(tree, site, sym, env, resultInfo) :
3404                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3405         }
3406 
3407         Type checkMethodId(JCTree tree,
3408                      Type site,
3409                      Symbol sym,
3410                      Env<AttrContext> env,
3411                      ResultInfo resultInfo) {
3412             boolean isPolymorhicSignature =
3413                 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
3414             return isPolymorhicSignature ?
3415                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3416                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
3417         }
3418 
3419         Type checkSigPolyMethodId(JCTree tree,
3420                      Type site,
3421                      Symbol sym,
3422                      Env<AttrContext> env,
3423                      ResultInfo resultInfo) {
3424             //recover original symbol for signature polymorphic methods
3425             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3426             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3427             return sym.type;
3428         }
3429 
3430         Type checkMethodIdInternal(JCTree tree,
3431                      Type site,
3432                      Symbol sym,
3433                      Env<AttrContext> env,
3434                      ResultInfo resultInfo) {
3435             Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3436             Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3437             resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3438             return owntype;
3439         }
3440 
3441         Type checkIdInternal(JCTree tree,
3442                      Type site,
3443                      Symbol sym,
3444                      Type pt,
3445                      Env<AttrContext> env,
3446                      ResultInfo resultInfo) {
3447             if (pt.isErroneous()) {
3448                 return types.createErrorType(site);
3449             }
3450             Type owntype; // The computed type of this identifier occurrence.
3451             switch (sym.kind) {
3452             case TYP:
3453                 // For types, the computed type equals the symbol's type,
3454                 // except for two situations:
3455                 owntype = sym.type;
3456                 if (owntype.hasTag(CLASS)) {
3457                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3458                     Type ownOuter = owntype.getEnclosingType();
3459 
3460                     // (a) If the symbol's type is parameterized, erase it
3461                     // because no type parameters were given.
3462                     // We recover generic outer type later in visitTypeApply.
3463                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3464                         owntype = types.erasure(owntype);
3465                     }
3466 
3467                     // (b) If the symbol's type is an inner class, then
3468                     // we have to interpret its outer type as a superclass
3469                     // of the site type. Example:
3470                     //
3471                     // class Tree<A> { class Visitor { ... } }
3472                     // class PointTree extends Tree<Point> { ... }
3473                     // ...PointTree.Visitor...
3474                     //
3475                     // Then the type of the last expression above is
3476                     // Tree<Point>.Visitor.
3477                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3478                         Type normOuter = site;
3479                         if (normOuter.hasTag(CLASS)) {
3480                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3481                             if (site.isAnnotated()) {
3482                                 // Propagate any type annotations.
3483                                 // TODO: should asEnclosingSuper do this?
3484                                 // Note that the type annotations in site will be updated
3485                                 // by annotateType. Therefore, modify site instead
3486                                 // of creating a new AnnotatedType.
3487                                 ((AnnotatedType)site).underlyingType = normOuter;
3488                                 normOuter = site;
3489                             }
3490                         }
3491                         if (normOuter == null) // perhaps from an import
3492                             normOuter = types.erasure(ownOuter);
3493                         if (normOuter != ownOuter)
3494                             owntype = new ClassType(
3495                                 normOuter, List.<Type>nil(), owntype.tsym);
3496                     }
3497                 }
3498                 break;
3499             case VAR:
3500                 VarSymbol v = (VarSymbol)sym;
3501                 // Test (4): if symbol is an instance field of a raw type,
3502                 // which is being assigned to, issue an unchecked warning if
3503                 // its type changes under erasure.
3504                 if (allowGenerics &&
3505                     resultInfo.pkind == VAR &&
3506                     v.owner.kind == TYP &&
3507                     (v.flags() & STATIC) == 0 &&
3508                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3509                     Type s = types.asOuterSuper(site, v.owner);
3510                     if (s != null &&
3511                         s.isRaw() &&
3512                         !types.isSameType(v.type, v.erasure(types))) {
3513                         chk.warnUnchecked(tree.pos(),
3514                                           "unchecked.assign.to.var",
3515                                           v, s);
3516                     }
3517                 }
3518                 // The computed type of a variable is the type of the
3519                 // variable symbol, taken as a member of the site type.
3520                 owntype = (sym.owner.kind == TYP &&
3521                            sym.name != names._this && sym.name != names._super)
3522                     ? types.memberType(site, sym)
3523                     : sym.type;
3524 
3525                 // If the variable is a constant, record constant value in
3526                 // computed type.
3527                 if (v.getConstValue() != null && isStaticReference(tree))
3528                     owntype = owntype.constType(v.getConstValue());
3529 
3530                 if (resultInfo.pkind == VAL) {
3531                     owntype = capture(owntype); // capture "names as expressions"
3532                 }
3533                 break;
3534             case MTH: {
3535                 owntype = checkMethod(site, sym,
3536                         new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3537                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3538                         resultInfo.pt.getTypeArguments());
3539                 break;
3540             }
3541             case PCK: case ERR:
3542                 owntype = sym.type;
3543                 break;
3544             default:
3545                 throw new AssertionError("unexpected kind: " + sym.kind +
3546                                          " in tree " + tree);
3547             }
3548 
3549             // Test (1): emit a `deprecation' warning if symbol is deprecated.
3550             // (for constructors, the error was given when the constructor was
3551             // resolved)
3552 
3553             if (sym.name != names.init) {
3554                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3555                 chk.checkSunAPI(tree.pos(), sym);
3556                 chk.checkProfile(tree.pos(), sym);
3557             }
3558 
3559             // Test (3): if symbol is a variable, check that its type and
3560             // kind are compatible with the prototype and protokind.
3561             return check(tree, owntype, sym.kind, resultInfo);
3562         }
3563 
3564         /** Check that variable is initialized and evaluate the variable's
3565          *  initializer, if not yet done. Also check that variable is not
3566          *  referenced before it is defined.
3567          *  @param tree    The tree making up the variable reference.
3568          *  @param env     The current environment.
3569          *  @param v       The variable's symbol.
3570          */
3571         private void checkInit(JCTree tree,
3572                                Env<AttrContext> env,
3573                                VarSymbol v,
3574                                boolean onlyWarning) {
3575 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3576 //                             tree.pos + " " + v.pos + " " +
3577 //                             Resolve.isStatic(env));//DEBUG
3578 
3579             // A forward reference is diagnosed if the declaration position
3580             // of the variable is greater than the current tree position
3581             // and the tree and variable definition occur in the same class
3582             // definition.  Note that writes don't count as references.
3583             // This check applies only to class and instance
3584             // variables.  Local variables follow different scope rules,
3585             // and are subject to definite assignment checking.
3586             if ((env.info.enclVar == v || v.pos > tree.pos) &&
3587                 v.owner.kind == TYP &&
3588                 canOwnInitializer(owner(env)) &&
3589                 v.owner == env.info.scope.owner.enclClass() &&
3590                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3591                 (!env.tree.hasTag(ASSIGN) ||
3592                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3593                 String suffix = (env.info.enclVar == v) ?
3594                                 "self.ref" : "forward.ref";
3595                 if (!onlyWarning || isStaticEnumField(v)) {
3596                     log.error(tree.pos(), "illegal." + suffix);
3597                 } else if (useBeforeDeclarationWarning) {
3598                     log.warning(tree.pos(), suffix, v);
3599                 }
3600             }
3601 
3602             v.getConstValue(); // ensure initializer is evaluated
3603 
3604             checkEnumInitializer(tree, env, v);
3605         }
3606 
3607         /**
3608          * Check for illegal references to static members of enum.  In
3609          * an enum type, constructors and initializers may not
3610          * reference its static members unless they are constant.
3611          *
3612          * @param tree    The tree making up the variable reference.
3613          * @param env     The current environment.
3614          * @param v       The variable's symbol.
3615          * @jls  section 8.9 Enums
3616          */
3617         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3618             // JLS:
3619             //
3620             // "It is a compile-time error to reference a static field
3621             // of an enum type that is not a compile-time constant
3622             // (15.28) from constructors, instance initializer blocks,
3623             // or instance variable initializer expressions of that
3624             // type. It is a compile-time error for the constructors,
3625             // instance initializer blocks, or instance variable
3626             // initializer expressions of an enum constant e to refer
3627             // to itself or to an enum constant of the same type that
3628             // is declared to the right of e."
3629             if (isStaticEnumField(v)) {
3630                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3631 
3632                 if (enclClass == null || enclClass.owner == null)
3633                     return;
3634 
3635                 // See if the enclosing class is the enum (or a
3636                 // subclass thereof) declaring v.  If not, this
3637                 // reference is OK.
3638                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3639                     return;
3640 
3641                 // If the reference isn't from an initializer, then
3642                 // the reference is OK.
3643                 if (!Resolve.isInitializer(env))
3644                     return;
3645 
3646                 log.error(tree.pos(), "illegal.enum.static.ref");
3647             }
3648         }
3649 
3650         /** Is the given symbol a static, non-constant field of an Enum?
3651          *  Note: enum literals should not be regarded as such
3652          */
3653         private boolean isStaticEnumField(VarSymbol v) {
3654             return Flags.isEnum(v.owner) &&
3655                    Flags.isStatic(v) &&
3656                    !Flags.isConstant(v) &&
3657                    v.name != names._class;
3658         }
3659 
3660         /** Can the given symbol be the owner of code which forms part
3661          *  if class initialization? This is the case if the symbol is
3662          *  a type or field, or if the symbol is the synthetic method.
3663          *  owning a block.
3664          */
3665         private boolean canOwnInitializer(Symbol sym) {
3666             return
3667                 (sym.kind & (VAR | TYP)) != 0 ||
3668                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3669         }
3670 
3671     Warner noteWarner = new Warner();
3672 
3673     /**
3674      * Check that method arguments conform to its instantiation.
3675      **/
3676     public Type checkMethod(Type site,
3677                             Symbol sym,
3678                             ResultInfo resultInfo,
3679                             Env<AttrContext> env,
3680                             final List<JCExpression> argtrees,
3681                             List<Type> argtypes,
3682                             List<Type> typeargtypes) {
3683         // Test (5): if symbol is an instance method of a raw type, issue
3684         // an unchecked warning if its argument types change under erasure.
3685         if (allowGenerics &&
3686             (sym.flags() & STATIC) == 0 &&
3687             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3688             Type s = types.asOuterSuper(site, sym.owner);
3689             if (s != null && s.isRaw() &&
3690                 !types.isSameTypes(sym.type.getParameterTypes(),
3691                                    sym.erasure(types).getParameterTypes())) {
3692                 chk.warnUnchecked(env.tree.pos(),
3693                                   "unchecked.call.mbr.of.raw.type",
3694                                   sym, s);
3695             }
3696         }
3697 
3698         if (env.info.defaultSuperCallSite != null) {
3699             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3700                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3701                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3702                 List<MethodSymbol> icand_sup =
3703                         types.interfaceCandidates(sup, (MethodSymbol)sym);
3704                 if (icand_sup.nonEmpty() &&
3705                         icand_sup.head != sym &&
3706                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3707                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3708                         diags.fragment("overridden.default", sym, sup));
3709                     break;
3710                 }
3711             }
3712             env.info.defaultSuperCallSite = null;
3713         }
3714 
3715         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3716             JCMethodInvocation app = (JCMethodInvocation)env.tree;
3717             if (app.meth.hasTag(SELECT) &&
3718                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3719                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3720             }
3721         }
3722 
3723         // Compute the identifier's instantiated type.
3724         // For methods, we need to compute the instance type by
3725         // Resolve.instantiate from the symbol's type as well as
3726         // any type arguments and value arguments.
3727         noteWarner.clear();
3728         try {
3729             Type owntype = rs.checkMethod(
3730                     env,
3731                     site,
3732                     sym,
3733                     resultInfo,
3734                     argtypes,
3735                     typeargtypes,
3736                     noteWarner);
3737 
3738             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3739                     noteWarner.hasNonSilentLint(LintCategory.UNCHECKED), resultInfo.checkContext.inferenceContext());
3740         } catch (Infer.InferenceException ex) {
3741             //invalid target type - propagate exception outwards or report error
3742             //depending on the current check context
3743             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3744             return types.createErrorType(site);
3745         } catch (Resolve.InapplicableMethodException ex) {
3746             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3747             return null;
3748         }
3749     }
3750 
3751     public void visitLiteral(JCLiteral tree) {
3752         result = check(
3753             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3754     }
3755     //where
3756     /** Return the type of a literal with given type tag.
3757      */
3758     Type litType(TypeTag tag) {
3759         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3760     }
3761 
3762     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3763         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3764     }
3765 
3766     public void visitTypeArray(JCArrayTypeTree tree) {
3767         Type etype = attribType(tree.elemtype, env);
3768         Type type = new ArrayType(etype, syms.arrayClass);
3769         result = check(tree, type, TYP, resultInfo);
3770     }
3771 
3772     /** Visitor method for parameterized types.
3773      *  Bound checking is left until later, since types are attributed
3774      *  before supertype structure is completely known
3775      */
3776     public void visitTypeApply(JCTypeApply tree) {
3777         Type owntype = types.createErrorType(tree.type);
3778 
3779         // Attribute functor part of application and make sure it's a class.
3780         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3781 
3782         // Attribute type parameters
3783         List<Type> actuals = attribTypes(tree.arguments, env);
3784 
3785         if (clazztype.hasTag(CLASS)) {
3786             List<Type> formals = clazztype.tsym.type.getTypeArguments();
3787             if (actuals.isEmpty()) //diamond
3788                 actuals = formals;
3789 
3790             if (actuals.length() == formals.length()) {
3791                 List<Type> a = actuals;
3792                 List<Type> f = formals;
3793                 while (a.nonEmpty()) {
3794                     a.head = a.head.withTypeVar(f.head);
3795                     a = a.tail;
3796                     f = f.tail;
3797                 }
3798                 // Compute the proper generic outer
3799                 Type clazzOuter = clazztype.getEnclosingType();
3800                 if (clazzOuter.hasTag(CLASS)) {
3801                     Type site;
3802                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3803                     if (clazz.hasTag(IDENT)) {
3804                         site = env.enclClass.sym.type;
3805                     } else if (clazz.hasTag(SELECT)) {
3806                         site = ((JCFieldAccess) clazz).selected.type;
3807                     } else throw new AssertionError(""+tree);
3808                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3809                         if (site.hasTag(CLASS))
3810                             site = types.asOuterSuper(site, clazzOuter.tsym);
3811                         if (site == null)
3812                             site = types.erasure(clazzOuter);
3813                         clazzOuter = site;
3814                     }
3815                 }
3816                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3817                 if (clazztype.isAnnotated()) {
3818                     // Use the same AnnotatedType, because it will have
3819                     // its annotations set later.
3820                     ((AnnotatedType)clazztype).underlyingType = owntype;
3821                     owntype = clazztype;
3822                 }
3823             } else {
3824                 if (formals.length() != 0) {
3825                     log.error(tree.pos(), "wrong.number.type.args",
3826                               Integer.toString(formals.length()));
3827                 } else {
3828                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3829                 }
3830                 owntype = types.createErrorType(tree.type);
3831             }
3832         }
3833         result = check(tree, owntype, TYP, resultInfo);
3834     }
3835 
3836     public void visitTypeUnion(JCTypeUnion tree) {
3837         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3838         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3839         for (JCExpression typeTree : tree.alternatives) {
3840             Type ctype = attribType(typeTree, env);
3841             ctype = chk.checkType(typeTree.pos(),
3842                           chk.checkClassType(typeTree.pos(), ctype),
3843                           syms.throwableType);
3844             if (!ctype.isErroneous()) {
3845                 //check that alternatives of a union type are pairwise
3846                 //unrelated w.r.t. subtyping
3847                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
3848                     for (Type t : multicatchTypes) {
3849                         boolean sub = types.isSubtype(ctype, t);
3850                         boolean sup = types.isSubtype(t, ctype);
3851                         if (sub || sup) {
3852                             //assume 'a' <: 'b'
3853                             Type a = sub ? ctype : t;
3854                             Type b = sub ? t : ctype;
3855                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3856                         }
3857                     }
3858                 }
3859                 multicatchTypes.append(ctype);
3860                 if (all_multicatchTypes != null)
3861                     all_multicatchTypes.append(ctype);
3862             } else {
3863                 if (all_multicatchTypes == null) {
3864                     all_multicatchTypes = ListBuffer.lb();
3865                     all_multicatchTypes.appendList(multicatchTypes);
3866                 }
3867                 all_multicatchTypes.append(ctype);
3868             }
3869         }
3870         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3871         if (t.hasTag(CLASS)) {
3872             List<Type> alternatives =
3873                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3874             t = new UnionClassType((ClassType) t, alternatives);
3875         }
3876         tree.type = result = t;
3877     }
3878 
3879     public void visitTypeIntersection(JCTypeIntersection tree) {
3880         attribTypes(tree.bounds, env);
3881         tree.type = result = checkIntersection(tree, tree.bounds);
3882     }
3883 
3884     public void visitTypeParameter(JCTypeParameter tree) {
3885         TypeVar typeVar = (TypeVar) tree.type;
3886 
3887         if (tree.annotations != null && tree.annotations.nonEmpty()) {
3888             AnnotatedType antype = new AnnotatedType(typeVar);
3889             annotateType(antype, tree.annotations);
3890             tree.type = antype;
3891         }
3892 
3893         if (!typeVar.bound.isErroneous()) {
3894             //fixup type-parameter bound computed in 'attribTypeVariables'
3895             typeVar.bound = checkIntersection(tree, tree.bounds);
3896         }
3897     }
3898 
3899     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3900         Set<Type> boundSet = new HashSet<Type>();
3901         if (bounds.nonEmpty()) {
3902             // accept class or interface or typevar as first bound.
3903             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3904             boundSet.add(types.erasure(bounds.head.type));
3905             if (bounds.head.type.isErroneous()) {
3906                 return bounds.head.type;
3907             }
3908             else if (bounds.head.type.hasTag(TYPEVAR)) {
3909                 // if first bound was a typevar, do not accept further bounds.
3910                 if (bounds.tail.nonEmpty()) {
3911                     log.error(bounds.tail.head.pos(),
3912                               "type.var.may.not.be.followed.by.other.bounds");
3913                     return bounds.head.type;
3914                 }
3915             } else {
3916                 // if first bound was a class or interface, accept only interfaces
3917                 // as further bounds.
3918                 for (JCExpression bound : bounds.tail) {
3919                     bound.type = checkBase(bound.type, bound, env, false, true, false);
3920                     if (bound.type.isErroneous()) {
3921                         bounds = List.of(bound);
3922                     }
3923                     else if (bound.type.hasTag(CLASS)) {
3924                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3925                     }
3926                 }
3927             }
3928         }
3929 
3930         if (bounds.length() == 0) {
3931             return syms.objectType;
3932         } else if (bounds.length() == 1) {
3933             return bounds.head.type;
3934         } else {
3935             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3936             if (tree.hasTag(TYPEINTERSECTION)) {
3937                 ((IntersectionClassType)owntype).intersectionKind =
3938                         IntersectionClassType.IntersectionKind.EXPLICIT;
3939             }
3940             // ... the variable's bound is a class type flagged COMPOUND
3941             // (see comment for TypeVar.bound).
3942             // In this case, generate a class tree that represents the
3943             // bound class, ...
3944             JCExpression extending;
3945             List<JCExpression> implementing;
3946             if (!bounds.head.type.isInterface()) {
3947                 extending = bounds.head;
3948                 implementing = bounds.tail;
3949             } else {
3950                 extending = null;
3951                 implementing = bounds;
3952             }
3953             JCClassDecl cd = make.at(tree).ClassDef(
3954                 make.Modifiers(PUBLIC | ABSTRACT),
3955                 names.empty, List.<JCTypeParameter>nil(),
3956                 extending, implementing, List.<JCTree>nil());
3957 
3958             ClassSymbol c = (ClassSymbol)owntype.tsym;
3959             Assert.check((c.flags() & COMPOUND) != 0);
3960             cd.sym = c;
3961             c.sourcefile = env.toplevel.sourcefile;
3962 
3963             // ... and attribute the bound class
3964             c.flags_field |= UNATTRIBUTED;
3965             Env<AttrContext> cenv = enter.classEnv(cd, env);
3966             enter.typeEnvs.put(c, cenv);
3967             attribClass(c);
3968             return owntype;
3969         }
3970     }
3971 
3972     public void visitWildcard(JCWildcard tree) {
3973         //- System.err.println("visitWildcard("+tree+");");//DEBUG
3974         Type type = (tree.kind.kind == BoundKind.UNBOUND)
3975             ? syms.objectType
3976             : attribType(tree.inner, env);
3977         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3978                                               tree.kind.kind,
3979                                               syms.boundClass),
3980                        TYP, resultInfo);
3981     }
3982 
3983     public void visitAnnotation(JCAnnotation tree) {
3984         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3985         result = tree.type = syms.errType;
3986     }
3987 
3988     public void visitAnnotatedType(JCAnnotatedType tree) {
3989         Type underlyingType = attribType(tree.getUnderlyingType(), env);
3990         this.attribAnnotationTypes(tree.annotations, env);
3991         AnnotatedType antype = new AnnotatedType(underlyingType);
3992         annotateType(antype, tree.annotations);
3993         result = tree.type = antype;
3994     }
3995 
3996     /**
3997      * Apply the annotations to the particular type.
3998      */
3999     public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
4000         if (annotations.isEmpty())
4001             return;
4002         annotate.typeAnnotation(new Annotate.Annotator() {
4003             @Override
4004             public String toString() {
4005                 return "annotate " + annotations + " onto " + type;
4006             }
4007             @Override
4008             public void enterAnnotation() {
4009                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4010                 type.typeAnnotations = compounds;
4011             }
4012         });
4013     }
4014 
4015     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4016         if (annotations.isEmpty())
4017             return List.nil();
4018 
4019         ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
4020         for (JCAnnotation anno : annotations) {
4021             if (anno.attribute != null) {
4022                 // TODO: this null-check is only needed for an obscure
4023                 // ordering issue, where annotate.flush is called when
4024                 // the attribute is not set yet. For an example failure
4025                 // try the referenceinfos/NestedTypes.java test.
4026                 // Any better solutions?
4027                 buf.append((Attribute.TypeCompound) anno.attribute);
4028             }
4029         }
4030         return buf.toList();
4031     }
4032 
4033     public void visitErroneous(JCErroneous tree) {
4034         if (tree.errs != null)
4035             for (JCTree err : tree.errs)
4036                 attribTree(err, env, new ResultInfo(ERR, pt()));
4037         result = tree.type = syms.errType;
4038     }
4039 
4040     /** Default visitor method for all other trees.
4041      */
4042     public void visitTree(JCTree tree) {
4043         throw new AssertionError();
4044     }
4045 
4046     /**
4047      * Attribute an env for either a top level tree or class declaration.
4048      */
4049     public void attrib(Env<AttrContext> env) {
4050         if (env.tree.hasTag(TOPLEVEL))
4051             attribTopLevel(env);
4052         else
4053             attribClass(env.tree.pos(), env.enclClass.sym);
4054     }
4055 
4056     /**
4057      * Attribute a top level tree. These trees are encountered when the
4058      * package declaration has annotations.
4059      */
4060     public void attribTopLevel(Env<AttrContext> env) {
4061         JCCompilationUnit toplevel = env.toplevel;
4062         try {
4063             annotate.flush();
4064             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
4065         } catch (CompletionFailure ex) {
4066             chk.completionError(toplevel.pos(), ex);
4067         }
4068     }
4069 
4070     /** Main method: attribute class definition associated with given class symbol.
4071      *  reporting completion failures at the given position.
4072      *  @param pos The source position at which completion errors are to be
4073      *             reported.
4074      *  @param c   The class symbol whose definition will be attributed.
4075      */
4076     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4077         try {
4078             annotate.flush();
4079             attribClass(c);
4080         } catch (CompletionFailure ex) {
4081             chk.completionError(pos, ex);
4082         }
4083     }
4084 
4085     /** Attribute class definition associated with given class symbol.
4086      *  @param c   The class symbol whose definition will be attributed.
4087      */
4088     void attribClass(ClassSymbol c) throws CompletionFailure {
4089         if (c.type.hasTag(ERROR)) return;
4090 
4091         // Check for cycles in the inheritance graph, which can arise from
4092         // ill-formed class files.
4093         chk.checkNonCyclic(null, c.type);
4094 
4095         Type st = types.supertype(c.type);
4096         if ((c.flags_field & Flags.COMPOUND) == 0) {
4097             // First, attribute superclass.
4098             if (st.hasTag(CLASS))
4099                 attribClass((ClassSymbol)st.tsym);
4100 
4101             // Next attribute owner, if it is a class.
4102             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4103                 attribClass((ClassSymbol)c.owner);
4104         }
4105 
4106         // The previous operations might have attributed the current class
4107         // if there was a cycle. So we test first whether the class is still
4108         // UNATTRIBUTED.
4109         if ((c.flags_field & UNATTRIBUTED) != 0) {
4110             c.flags_field &= ~UNATTRIBUTED;
4111 
4112             // Get environment current at the point of class definition.
4113             Env<AttrContext> env = enter.typeEnvs.get(c);
4114 
4115             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
4116             // because the annotations were not available at the time the env was created. Therefore,
4117             // we look up the environment chain for the first enclosing environment for which the
4118             // lint value is set. Typically, this is the parent env, but might be further if there
4119             // are any envs created as a result of TypeParameter nodes.
4120             Env<AttrContext> lintEnv = env;
4121             while (lintEnv.info.lint == null)
4122                 lintEnv = lintEnv.next;
4123 
4124             // Having found the enclosing lint value, we can initialize the lint value for this class
4125             env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
4126 
4127             Lint prevLint = chk.setLint(env.info.lint);
4128             JavaFileObject prev = log.useSource(c.sourcefile);
4129             ResultInfo prevReturnRes = env.info.returnResult;
4130 
4131             try {
4132                 env.info.returnResult = null;
4133                 // java.lang.Enum may not be subclassed by a non-enum
4134                 if (st.tsym == syms.enumSym &&
4135                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4136                     log.error(env.tree.pos(), "enum.no.subclassing");
4137 
4138                 // Enums may not be extended by source-level classes
4139                 if (st.tsym != null &&
4140                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4141                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4142                     log.error(env.tree.pos(), "enum.types.not.extensible");
4143                 }
4144                 attribClassBody(env, c);
4145 
4146                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4147                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4148             } finally {
4149                 env.info.returnResult = prevReturnRes;
4150                 log.useSource(prev);
4151                 chk.setLint(prevLint);
4152             }
4153 
4154         }
4155     }
4156 
4157     public void visitImport(JCImport tree) {
4158         // nothing to do
4159     }
4160 
4161     /** Finish the attribution of a class. */
4162     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4163         JCClassDecl tree = (JCClassDecl)env.tree;
4164         Assert.check(c == tree.sym);
4165 
4166         // Validate annotations
4167         chk.validateAnnotations(tree.mods.annotations, c);
4168 
4169         // Validate type parameters, supertype and interfaces.
4170         attribStats(tree.typarams, env);
4171         if (!c.isAnonymous()) {
4172             //already checked if anonymous
4173             chk.validate(tree.typarams, env);
4174             chk.validate(tree.extending, env);
4175             chk.validate(tree.implementing, env);
4176         }
4177 
4178         // If this is a non-abstract class, check that it has no abstract
4179         // methods or unimplemented methods of an implemented interface.
4180         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4181             if (!relax)
4182                 chk.checkAllDefined(tree.pos(), c);
4183         }
4184 
4185         if ((c.flags() & ANNOTATION) != 0) {
4186             if (tree.implementing.nonEmpty())
4187                 log.error(tree.implementing.head.pos(),
4188                           "cant.extend.intf.annotation");
4189             if (tree.typarams.nonEmpty())
4190                 log.error(tree.typarams.head.pos(),
4191                           "intf.annotation.cant.have.type.params");
4192 
4193             // If this annotation has a @Repeatable, validate
4194             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4195             if (repeatable != null) {
4196                 // get diagnostic position for error reporting
4197                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4198                 Assert.checkNonNull(cbPos);
4199 
4200                 chk.validateRepeatable(c, repeatable, cbPos);
4201             }
4202         } else {
4203             // Check that all extended classes and interfaces
4204             // are compatible (i.e. no two define methods with same arguments
4205             // yet different return types).  (JLS 8.4.6.3)
4206             chk.checkCompatibleSupertypes(tree.pos(), c.type);
4207             if (allowDefaultMethods) {
4208                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4209             }
4210         }
4211 
4212         // Check that class does not import the same parameterized interface
4213         // with two different argument lists.
4214         chk.checkClassBounds(tree.pos(), c.type);
4215 
4216         tree.type = c.type;
4217 
4218         for (List<JCTypeParameter> l = tree.typarams;
4219              l.nonEmpty(); l = l.tail) {
4220              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
4221         }
4222 
4223         // Check that a generic class doesn't extend Throwable
4224         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4225             log.error(tree.extending.pos(), "generic.throwable");
4226 
4227         // Check that all methods which implement some
4228         // method conform to the method they implement.
4229         chk.checkImplementations(tree);
4230 
4231         //check that a resource implementing AutoCloseable cannot throw InterruptedException
4232         checkAutoCloseable(tree.pos(), env, c.type);
4233 
4234         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4235             // Attribute declaration
4236             attribStat(l.head, env);
4237             // Check that declarations in inner classes are not static (JLS 8.1.2)
4238             // Make an exception for static constants.
4239             if (c.owner.kind != PCK &&
4240                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4241                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4242                 Symbol sym = null;
4243                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4244                 if (sym == null ||
4245                     sym.kind != VAR ||
4246                     ((VarSymbol) sym).getConstValue() == null)
4247                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4248             }
4249         }
4250 
4251         // Check for cycles among non-initial constructors.
4252         chk.checkCyclicConstructors(tree);
4253 
4254         // Check for cycles among annotation elements.
4255         chk.checkNonCyclicElements(tree);
4256 
4257         // Check for proper use of serialVersionUID
4258         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4259             isSerializable(c) &&
4260             (c.flags() & Flags.ENUM) == 0 &&
4261             (c.flags() & ABSTRACT) == 0) {
4262             checkSerialVersionUID(tree, c);
4263         }
4264 
4265         // Correctly organize the postions of the type annotations
4266         TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
4267 
4268         // Check type annotations applicability rules
4269         validateTypeAnnotations(tree);
4270     }
4271         // where
4272         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4273         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4274             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4275                 if (types.isSameType(al.head.annotationType.type, t))
4276                     return al.head.pos();
4277             }
4278 
4279             return null;
4280         }
4281 
4282         /** check if a class is a subtype of Serializable, if that is available. */
4283         private boolean isSerializable(ClassSymbol c) {
4284             try {
4285                 syms.serializableType.complete();
4286             }
4287             catch (CompletionFailure e) {
4288                 return false;
4289             }
4290             return types.isSubtype(c.type, syms.serializableType);
4291         }
4292 
4293         /** Check that an appropriate serialVersionUID member is defined. */
4294         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4295 
4296             // check for presence of serialVersionUID
4297             Scope.Entry e = c.members().lookup(names.serialVersionUID);
4298             while (e.scope != null && e.sym.kind != VAR) e = e.next();
4299             if (e.scope == null) {
4300                 log.warning(LintCategory.SERIAL,
4301                         tree.pos(), "missing.SVUID", c);
4302                 return;
4303             }
4304 
4305             // check that it is static final
4306             VarSymbol svuid = (VarSymbol)e.sym;
4307             if ((svuid.flags() & (STATIC | FINAL)) !=
4308                 (STATIC | FINAL))
4309                 log.warning(LintCategory.SERIAL,
4310                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4311 
4312             // check that it is long
4313             else if (!svuid.type.hasTag(LONG))
4314                 log.warning(LintCategory.SERIAL,
4315                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4316 
4317             // check constant
4318             else if (svuid.getConstValue() == null)
4319                 log.warning(LintCategory.SERIAL,
4320                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4321         }
4322 
4323     private Type capture(Type type) {
4324         //do not capture free types
4325         return resultInfo.checkContext.inferenceContext().free(type) ?
4326                 type : types.capture(type);
4327     }
4328 
4329     private void validateTypeAnnotations(JCTree tree) {
4330         tree.accept(typeAnnotationsValidator);
4331     }
4332     //where
4333     private final JCTree.Visitor typeAnnotationsValidator = new TreeScanner() {
4334 
4335         private boolean checkAllAnnotations = false;
4336 
4337         public void visitAnnotation(JCAnnotation tree) {
4338             if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
4339                 chk.validateTypeAnnotation(tree, false);
4340             }
4341             super.visitAnnotation(tree);
4342         }
4343         public void visitTypeParameter(JCTypeParameter tree) {
4344             chk.validateTypeAnnotations(tree.annotations, true);
4345             scan(tree.bounds);
4346             // Don't call super.
4347             // This is needed because above we call validateTypeAnnotation with
4348             // false, which would forbid annotations on type parameters.
4349             // super.visitTypeParameter(tree);
4350         }
4351         public void visitMethodDef(JCMethodDecl tree) {
4352             if (tree.recvparam != null &&
4353                     tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
4354                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4355                         tree.recvparam.vartype.type.tsym);
4356             }
4357             if (tree.restype != null && tree.restype.type != null) {
4358                 validateAnnotatedType(tree.restype, tree.restype.type);
4359             }
4360             super.visitMethodDef(tree);
4361         }
4362         public void visitVarDef(final JCVariableDecl tree) {
4363             if (tree.sym != null && tree.sym.type != null)
4364                 validateAnnotatedType(tree, tree.sym.type);
4365             super.visitVarDef(tree);
4366         }
4367         public void visitTypeCast(JCTypeCast tree) {
4368             if (tree.clazz != null && tree.clazz.type != null)
4369                 validateAnnotatedType(tree.clazz, tree.clazz.type);
4370             super.visitTypeCast(tree);
4371         }
4372         public void visitTypeTest(JCInstanceOf tree) {
4373             if (tree.clazz != null && tree.clazz.type != null)
4374                 validateAnnotatedType(tree.clazz, tree.clazz.type);
4375             super.visitTypeTest(tree);
4376         }
4377         public void visitNewClass(JCNewClass tree) {
4378             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4379                 boolean prevCheck = this.checkAllAnnotations;
4380                 try {
4381                     this.checkAllAnnotations = true;
4382                     scan(((JCAnnotatedType)tree.clazz).annotations);
4383                 } finally {
4384                     this.checkAllAnnotations = prevCheck;
4385                 }
4386             }
4387             super.visitNewClass(tree);
4388         }
4389         public void visitNewArray(JCNewArray tree) {
4390             if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4391                 boolean prevCheck = this.checkAllAnnotations;
4392                 try {
4393                     this.checkAllAnnotations = true;
4394                     scan(((JCAnnotatedType)tree.elemtype).annotations);
4395                 } finally {
4396                     this.checkAllAnnotations = prevCheck;
4397                 }
4398             }
4399             super.visitNewArray(tree);
4400         }
4401 
4402         /* I would want to model this after
4403          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4404          * and override visitSelect and visitTypeApply.
4405          * However, we only set the annotated type in the top-level type
4406          * of the symbol.
4407          * Therefore, we need to override each individual location where a type
4408          * can occur.
4409          */
4410         private void validateAnnotatedType(final JCTree errtree, final Type type) {
4411             if (type.getEnclosingType() != null &&
4412                     type != type.getEnclosingType()) {
4413                 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
4414             }
4415             for (Type targ : type.getTypeArguments()) {
4416                 validateAnnotatedType(errtree, targ);
4417             }
4418         }
4419         private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
4420             validateAnnotatedType(errtree, type);
4421             if (type.tsym != null &&
4422                     type.tsym.isStatic() &&
4423                     type.getAnnotationMirrors().nonEmpty()) {
4424                     // Enclosing static classes cannot have type annotations.
4425                 log.error(errtree.pos(), "cant.annotate.static.class");
4426             }
4427         }
4428     };
4429 
4430     // <editor-fold desc="post-attribution visitor">
4431 
4432     /**
4433      * Handle missing types/symbols in an AST. This routine is useful when
4434      * the compiler has encountered some errors (which might have ended up
4435      * terminating attribution abruptly); if the compiler is used in fail-over
4436      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4437      * prevents NPE to be progagated during subsequent compilation steps.
4438      */
4439     public void postAttr(JCTree tree) {
4440         new PostAttrAnalyzer().scan(tree);
4441     }
4442 
4443     class PostAttrAnalyzer extends TreeScanner {
4444 
4445         private void initTypeIfNeeded(JCTree that) {
4446             if (that.type == null) {
4447                 that.type = syms.unknownType;
4448             }
4449         }
4450 
4451         @Override
4452         public void scan(JCTree tree) {
4453             if (tree == null) return;
4454             if (tree instanceof JCExpression) {
4455                 initTypeIfNeeded(tree);
4456             }
4457             super.scan(tree);
4458         }
4459 
4460         @Override
4461         public void visitIdent(JCIdent that) {
4462             if (that.sym == null) {
4463                 that.sym = syms.unknownSymbol;
4464             }
4465         }
4466 
4467         @Override
4468         public void visitSelect(JCFieldAccess that) {
4469             if (that.sym == null) {
4470                 that.sym = syms.unknownSymbol;
4471             }
4472             super.visitSelect(that);
4473         }
4474 
4475         @Override
4476         public void visitClassDef(JCClassDecl that) {
4477             initTypeIfNeeded(that);
4478             if (that.sym == null) {
4479                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4480             }
4481             super.visitClassDef(that);
4482         }
4483 
4484         @Override
4485         public void visitMethodDef(JCMethodDecl that) {
4486             initTypeIfNeeded(that);
4487             if (that.sym == null) {
4488                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4489             }
4490             super.visitMethodDef(that);
4491         }
4492 
4493         @Override
4494         public void visitVarDef(JCVariableDecl that) {
4495             initTypeIfNeeded(that);
4496             if (that.sym == null) {
4497                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4498                 that.sym.adr = 0;
4499             }
4500             super.visitVarDef(that);
4501         }
4502 
4503         @Override
4504         public void visitNewClass(JCNewClass that) {
4505             if (that.constructor == null) {
4506                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4507             }
4508             if (that.constructorType == null) {
4509                 that.constructorType = syms.unknownType;
4510             }
4511             super.visitNewClass(that);
4512         }
4513 
4514         @Override
4515         public void visitAssignop(JCAssignOp that) {
4516             if (that.operator == null)
4517                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4518             super.visitAssignop(that);
4519         }
4520 
4521         @Override
4522         public void visitBinary(JCBinary that) {
4523             if (that.operator == null)
4524                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4525             super.visitBinary(that);
4526         }
4527 
4528         @Override
4529         public void visitUnary(JCUnary that) {
4530             if (that.operator == null)
4531                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4532             super.visitUnary(that);
4533         }
4534 
4535         @Override
4536         public void visitLambda(JCLambda that) {
4537             super.visitLambda(that);
4538             if (that.descriptorType == null) {
4539                 that.descriptorType = syms.unknownType;
4540             }
4541             if (that.targets == null) {
4542                 that.targets = List.nil();
4543             }
4544         }
4545 
4546         @Override
4547         public void visitReference(JCMemberReference that) {
4548             super.visitReference(that);
4549             if (that.sym == null) {
4550                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4551             }
4552             if (that.descriptorType == null) {
4553                 that.descriptorType = syms.unknownType;
4554             }
4555             if (that.targets == null) {
4556                 that.targets = List.nil();
4557             }
4558         }
4559     }
4560     // </editor-fold>
4561 }