src/share/classes/com/sun/tools/javac/comp/Attr.java

Fri, 30 Nov 2012 15:14:12 +0000

author
mcimadamore
date
Fri, 30 Nov 2012 15:14:12 +0000
changeset 1433
4f9853659bf1
parent 1415
01c9d4161882
child 1434
34d1ebaf4645
permissions
-rw-r--r--

8004105: Expression statement lambdas should be void-compatible
Summary: Fix lambda compatibility rules as per latest EDR
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, 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  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    31 import javax.lang.model.element.ElementKind;
    32 import javax.tools.JavaFileObject;
    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.InferenceContext.FreeTypeListener;
    47 import com.sun.tools.javac.jvm.*;
    48 import com.sun.tools.javac.jvm.Target;
    49 import com.sun.tools.javac.tree.*;
    50 import com.sun.tools.javac.tree.JCTree.*;
    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.*;
    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>();
    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;
    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     }
   105     protected Attr(Context context) {
   106         context.put(attrKey, this);
   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);
   126         Options options = Options.instance(context);
   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);
   147         statInfo = new ResultInfo(NIL, Type.noType);
   148         varInfo = new ResultInfo(VAR, Type.noType);
   149         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   150         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   151         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   152     }
   154     /** Switch: relax some constraints for retrofit mode.
   155      */
   156     boolean relax;
   158     /** Switch: support target-typing inference
   159      */
   160     boolean allowPoly;
   162     /** Switch: support generics?
   163      */
   164     boolean allowGenerics;
   166     /** Switch: allow variable-arity methods.
   167      */
   168     boolean allowVarargs;
   170     /** Switch: support enums?
   171      */
   172     boolean allowEnums;
   174     /** Switch: support boxing and unboxing?
   175      */
   176     boolean allowBoxing;
   178     /** Switch: support covariant result types?
   179      */
   180     boolean allowCovariantReturns;
   182     /** Switch: support lambda expressions ?
   183      */
   184     boolean allowLambda;
   186     /** Switch: support default methods ?
   187      */
   188     boolean allowDefaultMethods;
   190     /** Switch: allow references to surrounding object from anonymous
   191      * objects during constructor call?
   192      */
   193     boolean allowAnonOuterThis;
   195     /** Switch: generates a warning if diamond can be safely applied
   196      *  to a given new expression
   197      */
   198     boolean findDiamonds;
   200     /**
   201      * Internally enables/disables diamond finder feature
   202      */
   203     static final boolean allowDiamondFinder = true;
   205     /**
   206      * Switch: warn about use of variable before declaration?
   207      * RFE: 6425594
   208      */
   209     boolean useBeforeDeclarationWarning;
   211     /**
   212      * Switch: generate warnings whenever an anonymous inner class that is convertible
   213      * to a lambda expression is found
   214      */
   215     boolean identifyLambdaCandidate;
   217     /**
   218      * Switch: allow strings in switch?
   219      */
   220     boolean allowStringsInSwitch;
   222     /**
   223      * Switch: name of source level; used for error reporting.
   224      */
   225     String sourceName;
   227     /** Check kind and type of given tree against protokind and prototype.
   228      *  If check succeeds, store type in tree and return it.
   229      *  If check fails, store errType in tree and return it.
   230      *  No checks are performed if the prototype is a method type.
   231      *  It is not necessary in this case since we know that kind and type
   232      *  are correct.
   233      *
   234      *  @param tree     The tree whose kind and type is checked
   235      *  @param ownkind  The computed kind of the tree
   236      *  @param resultInfo  The expected result of the tree
   237      */
   238     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   239         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   240         Type owntype = found;
   241         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   242             if (inferenceContext.free(found)) {
   243                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   244                     @Override
   245                     public void typesInferred(InferenceContext inferenceContext) {
   246                         ResultInfo pendingResult =
   247                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt, types));
   248                         check(tree, inferenceContext.asInstType(found, types), ownkind, pendingResult);
   249                     }
   250                 });
   251                 return tree.type = resultInfo.pt;
   252             } else {
   253                 if ((ownkind & ~resultInfo.pkind) == 0) {
   254                     owntype = resultInfo.check(tree, owntype);
   255                 } else {
   256                     log.error(tree.pos(), "unexpected.type",
   257                             kindNames(resultInfo.pkind),
   258                             kindName(ownkind));
   259                     owntype = types.createErrorType(owntype);
   260                 }
   261             }
   262         }
   263         tree.type = owntype;
   264         return owntype;
   265     }
   267     /** Is given blank final variable assignable, i.e. in a scope where it
   268      *  may be assigned to even though it is final?
   269      *  @param v      The blank final variable.
   270      *  @param env    The current environment.
   271      */
   272     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   273         Symbol owner = owner(env);
   274            // owner refers to the innermost variable, method or
   275            // initializer block declaration at this point.
   276         return
   277             v.owner == owner
   278             ||
   279             ((owner.name == names.init ||    // i.e. we are in a constructor
   280               owner.kind == VAR ||           // i.e. we are in a variable initializer
   281               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   282              &&
   283              v.owner == owner.owner
   284              &&
   285              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   286     }
   288     /**
   289      * Return the innermost enclosing owner symbol in a given attribution context
   290      */
   291     Symbol owner(Env<AttrContext> env) {
   292         while (true) {
   293             switch (env.tree.getTag()) {
   294                 case VARDEF:
   295                     //a field can be owner
   296                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   297                     if (vsym.owner.kind == TYP) {
   298                         return vsym;
   299                     }
   300                     break;
   301                 case METHODDEF:
   302                     //method def is always an owner
   303                     return ((JCMethodDecl)env.tree).sym;
   304                 case CLASSDEF:
   305                     //class def is always an owner
   306                     return ((JCClassDecl)env.tree).sym;
   307                 case LAMBDA:
   308                     //a lambda is an owner - return a fresh synthetic method symbol
   309                     return new MethodSymbol(0, names.empty, null, syms.methodClass);
   310                 case BLOCK:
   311                     //static/instance init blocks are owner
   312                     Symbol blockSym = env.info.scope.owner;
   313                     if ((blockSym.flags() & BLOCK) != 0) {
   314                         return blockSym;
   315                     }
   316                     break;
   317                 case TOPLEVEL:
   318                     //toplevel is always an owner (for pkge decls)
   319                     return env.info.scope.owner;
   320             }
   321             Assert.checkNonNull(env.next);
   322             env = env.next;
   323         }
   324     }
   326     /** Check that variable can be assigned to.
   327      *  @param pos    The current source code position.
   328      *  @param v      The assigned varaible
   329      *  @param base   If the variable is referred to in a Select, the part
   330      *                to the left of the `.', null otherwise.
   331      *  @param env    The current environment.
   332      */
   333     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   334         if ((v.flags() & FINAL) != 0 &&
   335             ((v.flags() & HASINIT) != 0
   336              ||
   337              !((base == null ||
   338                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   339                isAssignableAsBlankFinal(v, env)))) {
   340             if (v.isResourceVariable()) { //TWR resource
   341                 log.error(pos, "try.resource.may.not.be.assigned", v);
   342             } else {
   343                 log.error(pos, "cant.assign.val.to.final.var", v);
   344             }
   345         }
   346     }
   348     /** Does tree represent a static reference to an identifier?
   349      *  It is assumed that tree is either a SELECT or an IDENT.
   350      *  We have to weed out selects from non-type names here.
   351      *  @param tree    The candidate tree.
   352      */
   353     boolean isStaticReference(JCTree tree) {
   354         if (tree.hasTag(SELECT)) {
   355             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   356             if (lsym == null || lsym.kind != TYP) {
   357                 return false;
   358             }
   359         }
   360         return true;
   361     }
   363     /** Is this symbol a type?
   364      */
   365     static boolean isType(Symbol sym) {
   366         return sym != null && sym.kind == TYP;
   367     }
   369     /** The current `this' symbol.
   370      *  @param env    The current environment.
   371      */
   372     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   373         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   374     }
   376     /** Attribute a parsed identifier.
   377      * @param tree Parsed identifier name
   378      * @param topLevel The toplevel to use
   379      */
   380     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   381         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   382         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   383                                            syms.errSymbol.name,
   384                                            null, null, null, null);
   385         localEnv.enclClass.sym = syms.errSymbol;
   386         return tree.accept(identAttributer, localEnv);
   387     }
   388     // where
   389         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   390         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   391             @Override
   392             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   393                 Symbol site = visit(node.getExpression(), env);
   394                 if (site.kind == ERR)
   395                     return site;
   396                 Name name = (Name)node.getIdentifier();
   397                 if (site.kind == PCK) {
   398                     env.toplevel.packge = (PackageSymbol)site;
   399                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   400                 } else {
   401                     env.enclClass.sym = (ClassSymbol)site;
   402                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   403                 }
   404             }
   406             @Override
   407             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   408                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   409             }
   410         }
   412     public Type coerce(Type etype, Type ttype) {
   413         return cfolder.coerce(etype, ttype);
   414     }
   416     public Type attribType(JCTree node, TypeSymbol sym) {
   417         Env<AttrContext> env = enter.typeEnvs.get(sym);
   418         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   419         return attribTree(node, localEnv, unknownTypeInfo);
   420     }
   422     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   423         // Attribute qualifying package or class.
   424         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   425         return attribTree(s.selected,
   426                        env,
   427                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   428                        Type.noType));
   429     }
   431     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   432         breakTree = tree;
   433         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   434         try {
   435             attribExpr(expr, env);
   436         } catch (BreakAttr b) {
   437             return b.env;
   438         } catch (AssertionError ae) {
   439             if (ae.getCause() instanceof BreakAttr) {
   440                 return ((BreakAttr)(ae.getCause())).env;
   441             } else {
   442                 throw ae;
   443             }
   444         } finally {
   445             breakTree = null;
   446             log.useSource(prev);
   447         }
   448         return env;
   449     }
   451     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   452         breakTree = tree;
   453         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   454         try {
   455             attribStat(stmt, env);
   456         } catch (BreakAttr b) {
   457             return b.env;
   458         } catch (AssertionError ae) {
   459             if (ae.getCause() instanceof BreakAttr) {
   460                 return ((BreakAttr)(ae.getCause())).env;
   461             } else {
   462                 throw ae;
   463             }
   464         } finally {
   465             breakTree = null;
   466             log.useSource(prev);
   467         }
   468         return env;
   469     }
   471     private JCTree breakTree = null;
   473     private static class BreakAttr extends RuntimeException {
   474         static final long serialVersionUID = -6924771130405446405L;
   475         private Env<AttrContext> env;
   476         private BreakAttr(Env<AttrContext> env) {
   477             this.env = copyEnv(env);
   478         }
   480         private Env<AttrContext> copyEnv(Env<AttrContext> env) {
   481             Env<AttrContext> newEnv =
   482                     env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   483             if (newEnv.outer != null) {
   484                 newEnv.outer = copyEnv(newEnv.outer);
   485             }
   486             return newEnv;
   487         }
   489         private Scope copyScope(Scope sc) {
   490             Scope newScope = new Scope(sc.owner);
   491             List<Symbol> elemsList = List.nil();
   492             while (sc != null) {
   493                 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   494                     elemsList = elemsList.prepend(e.sym);
   495                 }
   496                 sc = sc.next;
   497             }
   498             for (Symbol s : elemsList) {
   499                 newScope.enter(s);
   500             }
   501             return newScope;
   502         }
   503     }
   505     class ResultInfo {
   506         final int pkind;
   507         final Type pt;
   508         final CheckContext checkContext;
   510         ResultInfo(int pkind, Type pt) {
   511             this(pkind, pt, chk.basicHandler);
   512         }
   514         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   515             this.pkind = pkind;
   516             this.pt = pt;
   517             this.checkContext = checkContext;
   518         }
   520         protected Type check(final DiagnosticPosition pos, final Type found) {
   521             return chk.checkType(pos, found, pt, checkContext);
   522         }
   524         protected ResultInfo dup(Type newPt) {
   525             return new ResultInfo(pkind, newPt, checkContext);
   526         }
   528         protected ResultInfo dup(CheckContext newContext) {
   529             return new ResultInfo(pkind, pt, newContext);
   530         }
   531     }
   533     class RecoveryInfo extends ResultInfo {
   535         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   536             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   537                 @Override
   538                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   539                     return deferredAttrContext;
   540                 }
   541                 @Override
   542                 public boolean compatible(Type found, Type req, Warner warn) {
   543                     return true;
   544                 }
   545                 @Override
   546                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   547                     chk.basicHandler.report(pos, details);
   548                 }
   549             });
   550         }
   552         @Override
   553         protected Type check(DiagnosticPosition pos, Type found) {
   554             return chk.checkNonVoid(pos, super.check(pos, found));
   555         }
   556     }
   558     final ResultInfo statInfo;
   559     final ResultInfo varInfo;
   560     final ResultInfo unknownExprInfo;
   561     final ResultInfo unknownTypeInfo;
   562     final ResultInfo recoveryInfo;
   564     Type pt() {
   565         return resultInfo.pt;
   566     }
   568     int pkind() {
   569         return resultInfo.pkind;
   570     }
   572 /* ************************************************************************
   573  * Visitor methods
   574  *************************************************************************/
   576     /** Visitor argument: the current environment.
   577      */
   578     Env<AttrContext> env;
   580     /** Visitor argument: the currently expected attribution result.
   581      */
   582     ResultInfo resultInfo;
   584     /** Visitor result: the computed type.
   585      */
   586     Type result;
   588     /** Visitor method: attribute a tree, catching any completion failure
   589      *  exceptions. Return the tree's type.
   590      *
   591      *  @param tree    The tree to be visited.
   592      *  @param env     The environment visitor argument.
   593      *  @param resultInfo   The result info visitor argument.
   594      */
   595     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   596         Env<AttrContext> prevEnv = this.env;
   597         ResultInfo prevResult = this.resultInfo;
   598         try {
   599             this.env = env;
   600             this.resultInfo = resultInfo;
   601             tree.accept(this);
   602             if (tree == breakTree &&
   603                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   604                 throw new BreakAttr(env);
   605             }
   606             return result;
   607         } catch (CompletionFailure ex) {
   608             tree.type = syms.errType;
   609             return chk.completionError(tree.pos(), ex);
   610         } finally {
   611             this.env = prevEnv;
   612             this.resultInfo = prevResult;
   613         }
   614     }
   616     /** Derived visitor method: attribute an expression tree.
   617      */
   618     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   619         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   620     }
   622     /** Derived visitor method: attribute an expression tree with
   623      *  no constraints on the computed type.
   624      */
   625     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   626         return attribTree(tree, env, unknownExprInfo);
   627     }
   629     /** Derived visitor method: attribute a type tree.
   630      */
   631     public Type attribType(JCTree tree, Env<AttrContext> env) {
   632         Type result = attribType(tree, env, Type.noType);
   633         return result;
   634     }
   636     /** Derived visitor method: attribute a type tree.
   637      */
   638     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   639         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   640         return result;
   641     }
   643     /** Derived visitor method: attribute a statement or definition tree.
   644      */
   645     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   646         return attribTree(tree, env, statInfo);
   647     }
   649     /** Attribute a list of expressions, returning a list of types.
   650      */
   651     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   652         ListBuffer<Type> ts = new ListBuffer<Type>();
   653         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   654             ts.append(attribExpr(l.head, env, pt));
   655         return ts.toList();
   656     }
   658     /** Attribute a list of statements, returning nothing.
   659      */
   660     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   661         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   662             attribStat(l.head, env);
   663     }
   665     /** Attribute the arguments in a method call, returning a list of types.
   666      */
   667     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   668         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   669         for (JCExpression arg : trees) {
   670             Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ?
   671                     deferredAttr.new DeferredType(arg, env) :
   672                     chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
   673             argtypes.append(argtype);
   674         }
   675         return argtypes.toList();
   676     }
   678     /** Attribute a type argument list, returning a list of types.
   679      *  Caller is responsible for calling checkRefTypes.
   680      */
   681     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   682         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   683         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   684             argtypes.append(attribType(l.head, env));
   685         return argtypes.toList();
   686     }
   688     /** Attribute a type argument list, returning a list of types.
   689      *  Check that all the types are references.
   690      */
   691     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   692         List<Type> types = attribAnyTypes(trees, env);
   693         return chk.checkRefTypes(trees, types);
   694     }
   696     /**
   697      * Attribute type variables (of generic classes or methods).
   698      * Compound types are attributed later in attribBounds.
   699      * @param typarams the type variables to enter
   700      * @param env      the current environment
   701      */
   702     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   703         for (JCTypeParameter tvar : typarams) {
   704             TypeVar a = (TypeVar)tvar.type;
   705             a.tsym.flags_field |= UNATTRIBUTED;
   706             a.bound = Type.noType;
   707             if (!tvar.bounds.isEmpty()) {
   708                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   709                 for (JCExpression bound : tvar.bounds.tail)
   710                     bounds = bounds.prepend(attribType(bound, env));
   711                 types.setBounds(a, bounds.reverse());
   712             } else {
   713                 // if no bounds are given, assume a single bound of
   714                 // java.lang.Object.
   715                 types.setBounds(a, List.of(syms.objectType));
   716             }
   717             a.tsym.flags_field &= ~UNATTRIBUTED;
   718         }
   719         for (JCTypeParameter tvar : typarams)
   720             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   721         attribStats(typarams, env);
   722     }
   724     void attribBounds(List<JCTypeParameter> typarams) {
   725         for (JCTypeParameter typaram : typarams) {
   726             Type bound = typaram.type.getUpperBound();
   727             if (bound != null && bound.tsym instanceof ClassSymbol) {
   728                 ClassSymbol c = (ClassSymbol)bound.tsym;
   729                 if ((c.flags_field & COMPOUND) != 0) {
   730                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   731                     attribClass(typaram.pos(), c);
   732                 }
   733             }
   734         }
   735     }
   737     /**
   738      * Attribute the type references in a list of annotations.
   739      */
   740     void attribAnnotationTypes(List<JCAnnotation> annotations,
   741                                Env<AttrContext> env) {
   742         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   743             JCAnnotation a = al.head;
   744             attribType(a.annotationType, env);
   745         }
   746     }
   748     /**
   749      * Attribute a "lazy constant value".
   750      *  @param env         The env for the const value
   751      *  @param initializer The initializer for the const value
   752      *  @param type        The expected type, or null
   753      *  @see VarSymbol#setLazyConstValue
   754      */
   755     public Object attribLazyConstantValue(Env<AttrContext> env,
   756                                       JCTree.JCExpression initializer,
   757                                       Type type) {
   759         // in case no lint value has been set up for this env, scan up
   760         // env stack looking for smallest enclosing env for which it is set.
   761         Env<AttrContext> lintEnv = env;
   762         while (lintEnv.info.lint == null)
   763             lintEnv = lintEnv.next;
   765         // Having found the enclosing lint value, we can initialize the lint value for this class
   766         // ... but ...
   767         // There's a problem with evaluating annotations in the right order, such that
   768         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   769         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   770         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   771         if (env.info.enclVar.annotations.pendingCompletion()) {
   772             env.info.lint = lintEnv.info.lint;
   773         } else {
   774             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
   775                                                       env.info.enclVar.flags());
   776         }
   778         Lint prevLint = chk.setLint(env.info.lint);
   779         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   781         try {
   782             Type itype = attribExpr(initializer, env, type);
   783             if (itype.constValue() != null)
   784                 return coerce(itype, type).constValue();
   785             else
   786                 return null;
   787         } finally {
   788             env.info.lint = prevLint;
   789             log.useSource(prevSource);
   790         }
   791     }
   793     /** Attribute type reference in an `extends' or `implements' clause.
   794      *  Supertypes of anonymous inner classes are usually already attributed.
   795      *
   796      *  @param tree              The tree making up the type reference.
   797      *  @param env               The environment current at the reference.
   798      *  @param classExpected     true if only a class is expected here.
   799      *  @param interfaceExpected true if only an interface is expected here.
   800      */
   801     Type attribBase(JCTree tree,
   802                     Env<AttrContext> env,
   803                     boolean classExpected,
   804                     boolean interfaceExpected,
   805                     boolean checkExtensible) {
   806         Type t = tree.type != null ?
   807             tree.type :
   808             attribType(tree, env);
   809         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   810     }
   811     Type checkBase(Type t,
   812                    JCTree tree,
   813                    Env<AttrContext> env,
   814                    boolean classExpected,
   815                    boolean interfaceExpected,
   816                    boolean checkExtensible) {
   817         if (t.isErroneous())
   818             return t;
   819         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   820             // check that type variable is already visible
   821             if (t.getUpperBound() == null) {
   822                 log.error(tree.pos(), "illegal.forward.ref");
   823                 return types.createErrorType(t);
   824             }
   825         } else {
   826             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   827         }
   828         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   829             log.error(tree.pos(), "intf.expected.here");
   830             // return errType is necessary since otherwise there might
   831             // be undetected cycles which cause attribution to loop
   832             return types.createErrorType(t);
   833         } else if (checkExtensible &&
   834                    classExpected &&
   835                    (t.tsym.flags() & INTERFACE) != 0) {
   836                 log.error(tree.pos(), "no.intf.expected.here");
   837             return types.createErrorType(t);
   838         }
   839         if (checkExtensible &&
   840             ((t.tsym.flags() & FINAL) != 0)) {
   841             log.error(tree.pos(),
   842                       "cant.inherit.from.final", t.tsym);
   843         }
   844         chk.checkNonCyclic(tree.pos(), t);
   845         return t;
   846     }
   848     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   849         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   850         id.type = env.info.scope.owner.type;
   851         id.sym = env.info.scope.owner;
   852         return id.type;
   853     }
   855     public void visitClassDef(JCClassDecl tree) {
   856         // Local classes have not been entered yet, so we need to do it now:
   857         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   858             enter.classEnter(tree, env);
   860         ClassSymbol c = tree.sym;
   861         if (c == null) {
   862             // exit in case something drastic went wrong during enter.
   863             result = null;
   864         } else {
   865             // make sure class has been completed:
   866             c.complete();
   868             // If this class appears as an anonymous class
   869             // in a superclass constructor call where
   870             // no explicit outer instance is given,
   871             // disable implicit outer instance from being passed.
   872             // (This would be an illegal access to "this before super").
   873             if (env.info.isSelfCall &&
   874                 env.tree.hasTag(NEWCLASS) &&
   875                 ((JCNewClass) env.tree).encl == null)
   876             {
   877                 c.flags_field |= NOOUTERTHIS;
   878             }
   879             attribClass(tree.pos(), c);
   880             result = tree.type = c.type;
   881         }
   882     }
   884     public void visitMethodDef(JCMethodDecl tree) {
   885         MethodSymbol m = tree.sym;
   886         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   888         Lint lint = env.info.lint.augment(m.annotations, m.flags());
   889         Lint prevLint = chk.setLint(lint);
   890         MethodSymbol prevMethod = chk.setMethod(m);
   891         try {
   892             deferredLintHandler.flush(tree.pos());
   893             chk.checkDeprecatedAnnotation(tree.pos(), m);
   895             attribBounds(tree.typarams);
   897             // If we override any other methods, check that we do so properly.
   898             // JLS ???
   899             if (m.isStatic()) {
   900                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   901             } else {
   902                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   903             }
   904             chk.checkOverride(tree, m);
   906             // Create a new environment with local scope
   907             // for attributing the method.
   908             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   910             localEnv.info.lint = lint;
   912             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   913                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   914             }
   916             // Enter all type parameters into the local method scope.
   917             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   918                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   920             ClassSymbol owner = env.enclClass.sym;
   921             if ((owner.flags() & ANNOTATION) != 0 &&
   922                 tree.params.nonEmpty())
   923                 log.error(tree.params.head.pos(),
   924                           "intf.annotation.members.cant.have.params");
   926             // Attribute all value parameters.
   927             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   928                 attribStat(l.head, localEnv);
   929             }
   931             chk.checkVarargsMethodDecl(localEnv, tree);
   933             // Check that type parameters are well-formed.
   934             chk.validate(tree.typarams, localEnv);
   936             // Check that result type is well-formed.
   937             chk.validate(tree.restype, localEnv);
   939             // annotation method checks
   940             if ((owner.flags() & ANNOTATION) != 0) {
   941                 // annotation method cannot have throws clause
   942                 if (tree.thrown.nonEmpty()) {
   943                     log.error(tree.thrown.head.pos(),
   944                             "throws.not.allowed.in.intf.annotation");
   945                 }
   946                 // annotation method cannot declare type-parameters
   947                 if (tree.typarams.nonEmpty()) {
   948                     log.error(tree.typarams.head.pos(),
   949                             "intf.annotation.members.cant.have.type.params");
   950                 }
   951                 // validate annotation method's return type (could be an annotation type)
   952                 chk.validateAnnotationType(tree.restype);
   953                 // ensure that annotation method does not clash with members of Object/Annotation
   954                 chk.validateAnnotationMethod(tree.pos(), m);
   956                 if (tree.defaultValue != null) {
   957                     // if default value is an annotation, check it is a well-formed
   958                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   959                     chk.validateAnnotationTree(tree.defaultValue);
   960                 }
   961             }
   963             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   964                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   966             if (tree.body == null) {
   967                 // Empty bodies are only allowed for
   968                 // abstract, native, or interface methods, or for methods
   969                 // in a retrofit signature class.
   970                 if (isDefaultMethod || ((owner.flags() & INTERFACE) == 0 &&
   971                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0) &&
   972                     !relax)
   973                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   974                 if (tree.defaultValue != null) {
   975                     if ((owner.flags() & ANNOTATION) == 0)
   976                         log.error(tree.pos(),
   977                                   "default.allowed.in.intf.annotation.member");
   978                 }
   979             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   980                 if ((owner.flags() & INTERFACE) != 0) {
   981                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   982                 } else {
   983                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   984                 }
   985             } else if ((tree.mods.flags & NATIVE) != 0) {
   986                 log.error(tree.pos(), "native.meth.cant.have.body");
   987             } else {
   988                 // Add an implicit super() call unless an explicit call to
   989                 // super(...) or this(...) is given
   990                 // or we are compiling class java.lang.Object.
   991                 if (tree.name == names.init && owner.type != syms.objectType) {
   992                     JCBlock body = tree.body;
   993                     if (body.stats.isEmpty() ||
   994                         !TreeInfo.isSelfCall(body.stats.head)) {
   995                         body.stats = body.stats.
   996                             prepend(memberEnter.SuperCall(make.at(body.pos),
   997                                                           List.<Type>nil(),
   998                                                           List.<JCVariableDecl>nil(),
   999                                                           false));
  1000                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1001                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1002                                TreeInfo.isSuperCall(body.stats.head)) {
  1003                         // enum constructors are not allowed to call super
  1004                         // directly, so make sure there aren't any super calls
  1005                         // in enum constructors, except in the compiler
  1006                         // generated one.
  1007                         log.error(tree.body.stats.head.pos(),
  1008                                   "call.to.super.not.allowed.in.enum.ctor",
  1009                                   env.enclClass.sym);
  1013                 // Attribute method body.
  1014                 attribStat(tree.body, localEnv);
  1016             localEnv.info.scope.leave();
  1017             result = tree.type = m.type;
  1018             chk.validateAnnotations(tree.mods.annotations, m);
  1020         finally {
  1021             chk.setLint(prevLint);
  1022             chk.setMethod(prevMethod);
  1026     public void visitVarDef(JCVariableDecl tree) {
  1027         // Local variables have not been entered yet, so we need to do it now:
  1028         if (env.info.scope.owner.kind == MTH) {
  1029             if (tree.sym != null) {
  1030                 // parameters have already been entered
  1031                 env.info.scope.enter(tree.sym);
  1032             } else {
  1033                 memberEnter.memberEnter(tree, env);
  1034                 annotate.flush();
  1038         VarSymbol v = tree.sym;
  1039         Lint lint = env.info.lint.augment(v.annotations, v.flags());
  1040         Lint prevLint = chk.setLint(lint);
  1042         // Check that the variable's declared type is well-formed.
  1043         chk.validate(tree.vartype, env);
  1044         deferredLintHandler.flush(tree.pos());
  1046         try {
  1047             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1049             if (tree.init != null) {
  1050                 if ((v.flags_field & FINAL) != 0 &&
  1051                         !tree.init.hasTag(NEWCLASS) &&
  1052                         !tree.init.hasTag(LAMBDA) &&
  1053                         !tree.init.hasTag(REFERENCE)) {
  1054                     // In this case, `v' is final.  Ensure that it's initializer is
  1055                     // evaluated.
  1056                     v.getConstValue(); // ensure initializer is evaluated
  1057                 } else {
  1058                     // Attribute initializer in a new environment
  1059                     // with the declared variable as owner.
  1060                     // Check that initializer conforms to variable's declared type.
  1061                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1062                     initEnv.info.lint = lint;
  1063                     // In order to catch self-references, we set the variable's
  1064                     // declaration position to maximal possible value, effectively
  1065                     // marking the variable as undefined.
  1066                     initEnv.info.enclVar = v;
  1067                     attribExpr(tree.init, initEnv, v.type);
  1070             result = tree.type = v.type;
  1071             chk.validateAnnotations(tree.mods.annotations, v);
  1073         finally {
  1074             chk.setLint(prevLint);
  1078     public void visitSkip(JCSkip tree) {
  1079         result = null;
  1082     public void visitBlock(JCBlock tree) {
  1083         if (env.info.scope.owner.kind == TYP) {
  1084             // Block is a static or instance initializer;
  1085             // let the owner of the environment be a freshly
  1086             // created BLOCK-method.
  1087             Env<AttrContext> localEnv =
  1088                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1089             localEnv.info.scope.owner =
  1090                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
  1091                                  env.info.scope.owner);
  1092             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1093             attribStats(tree.stats, localEnv);
  1094         } else {
  1095             // Create a new local environment with a local scope.
  1096             Env<AttrContext> localEnv =
  1097                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1098             try {
  1099                 attribStats(tree.stats, localEnv);
  1100             } finally {
  1101                 localEnv.info.scope.leave();
  1104         result = null;
  1107     public void visitDoLoop(JCDoWhileLoop tree) {
  1108         attribStat(tree.body, env.dup(tree));
  1109         attribExpr(tree.cond, env, syms.booleanType);
  1110         result = null;
  1113     public void visitWhileLoop(JCWhileLoop tree) {
  1114         attribExpr(tree.cond, env, syms.booleanType);
  1115         attribStat(tree.body, env.dup(tree));
  1116         result = null;
  1119     public void visitForLoop(JCForLoop tree) {
  1120         Env<AttrContext> loopEnv =
  1121             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1122         try {
  1123             attribStats(tree.init, loopEnv);
  1124             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1125             loopEnv.tree = tree; // before, we were not in loop!
  1126             attribStats(tree.step, loopEnv);
  1127             attribStat(tree.body, loopEnv);
  1128             result = null;
  1130         finally {
  1131             loopEnv.info.scope.leave();
  1135     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1136         Env<AttrContext> loopEnv =
  1137             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1138         try {
  1139             attribStat(tree.var, loopEnv);
  1140             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1141             chk.checkNonVoid(tree.pos(), exprType);
  1142             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1143             if (elemtype == null) {
  1144                 // or perhaps expr implements Iterable<T>?
  1145                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1146                 if (base == null) {
  1147                     log.error(tree.expr.pos(),
  1148                             "foreach.not.applicable.to.type",
  1149                             exprType,
  1150                             diags.fragment("type.req.array.or.iterable"));
  1151                     elemtype = types.createErrorType(exprType);
  1152                 } else {
  1153                     List<Type> iterableParams = base.allparams();
  1154                     elemtype = iterableParams.isEmpty()
  1155                         ? syms.objectType
  1156                         : types.upperBound(iterableParams.head);
  1159             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1160             loopEnv.tree = tree; // before, we were not in loop!
  1161             attribStat(tree.body, loopEnv);
  1162             result = null;
  1164         finally {
  1165             loopEnv.info.scope.leave();
  1169     public void visitLabelled(JCLabeledStatement tree) {
  1170         // Check that label is not used in an enclosing statement
  1171         Env<AttrContext> env1 = env;
  1172         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1173             if (env1.tree.hasTag(LABELLED) &&
  1174                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1175                 log.error(tree.pos(), "label.already.in.use",
  1176                           tree.label);
  1177                 break;
  1179             env1 = env1.next;
  1182         attribStat(tree.body, env.dup(tree));
  1183         result = null;
  1186     public void visitSwitch(JCSwitch tree) {
  1187         Type seltype = attribExpr(tree.selector, env);
  1189         Env<AttrContext> switchEnv =
  1190             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1192         try {
  1194             boolean enumSwitch =
  1195                 allowEnums &&
  1196                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1197             boolean stringSwitch = false;
  1198             if (types.isSameType(seltype, syms.stringType)) {
  1199                 if (allowStringsInSwitch) {
  1200                     stringSwitch = true;
  1201                 } else {
  1202                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1205             if (!enumSwitch && !stringSwitch)
  1206                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1208             // Attribute all cases and
  1209             // check that there are no duplicate case labels or default clauses.
  1210             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1211             boolean hasDefault = false;      // Is there a default label?
  1212             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1213                 JCCase c = l.head;
  1214                 Env<AttrContext> caseEnv =
  1215                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1216                 try {
  1217                     if (c.pat != null) {
  1218                         if (enumSwitch) {
  1219                             Symbol sym = enumConstant(c.pat, seltype);
  1220                             if (sym == null) {
  1221                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1222                             } else if (!labels.add(sym)) {
  1223                                 log.error(c.pos(), "duplicate.case.label");
  1225                         } else {
  1226                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1227                             if (!pattype.hasTag(ERROR)) {
  1228                                 if (pattype.constValue() == null) {
  1229                                     log.error(c.pat.pos(),
  1230                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1231                                 } else if (labels.contains(pattype.constValue())) {
  1232                                     log.error(c.pos(), "duplicate.case.label");
  1233                                 } else {
  1234                                     labels.add(pattype.constValue());
  1238                     } else if (hasDefault) {
  1239                         log.error(c.pos(), "duplicate.default.label");
  1240                     } else {
  1241                         hasDefault = true;
  1243                     attribStats(c.stats, caseEnv);
  1244                 } finally {
  1245                     caseEnv.info.scope.leave();
  1246                     addVars(c.stats, switchEnv.info.scope);
  1250             result = null;
  1252         finally {
  1253             switchEnv.info.scope.leave();
  1256     // where
  1257         /** Add any variables defined in stats to the switch scope. */
  1258         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1259             for (;stats.nonEmpty(); stats = stats.tail) {
  1260                 JCTree stat = stats.head;
  1261                 if (stat.hasTag(VARDEF))
  1262                     switchScope.enter(((JCVariableDecl) stat).sym);
  1265     // where
  1266     /** Return the selected enumeration constant symbol, or null. */
  1267     private Symbol enumConstant(JCTree tree, Type enumType) {
  1268         if (!tree.hasTag(IDENT)) {
  1269             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1270             return syms.errSymbol;
  1272         JCIdent ident = (JCIdent)tree;
  1273         Name name = ident.name;
  1274         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1275              e.scope != null; e = e.next()) {
  1276             if (e.sym.kind == VAR) {
  1277                 Symbol s = ident.sym = e.sym;
  1278                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1279                 ident.type = s.type;
  1280                 return ((s.flags_field & Flags.ENUM) == 0)
  1281                     ? null : s;
  1284         return null;
  1287     public void visitSynchronized(JCSynchronized tree) {
  1288         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1289         attribStat(tree.body, env);
  1290         result = null;
  1293     public void visitTry(JCTry tree) {
  1294         // Create a new local environment with a local
  1295         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1296         try {
  1297             boolean isTryWithResource = tree.resources.nonEmpty();
  1298             // Create a nested environment for attributing the try block if needed
  1299             Env<AttrContext> tryEnv = isTryWithResource ?
  1300                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1301                 localEnv;
  1302             try {
  1303                 // Attribute resource declarations
  1304                 for (JCTree resource : tree.resources) {
  1305                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1306                         @Override
  1307                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1308                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1310                     };
  1311                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1312                     if (resource.hasTag(VARDEF)) {
  1313                         attribStat(resource, tryEnv);
  1314                         twrResult.check(resource, resource.type);
  1316                         //check that resource type cannot throw InterruptedException
  1317                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1319                         VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1320                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1321                     } else {
  1322                         attribTree(resource, tryEnv, twrResult);
  1325                 // Attribute body
  1326                 attribStat(tree.body, tryEnv);
  1327             } finally {
  1328                 if (isTryWithResource)
  1329                     tryEnv.info.scope.leave();
  1332             // Attribute catch clauses
  1333             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1334                 JCCatch c = l.head;
  1335                 Env<AttrContext> catchEnv =
  1336                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1337                 try {
  1338                     Type ctype = attribStat(c.param, catchEnv);
  1339                     if (TreeInfo.isMultiCatch(c)) {
  1340                         //multi-catch parameter is implicitly marked as final
  1341                         c.param.sym.flags_field |= FINAL | UNION;
  1343                     if (c.param.sym.kind == Kinds.VAR) {
  1344                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1346                     chk.checkType(c.param.vartype.pos(),
  1347                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1348                                   syms.throwableType);
  1349                     attribStat(c.body, catchEnv);
  1350                 } finally {
  1351                     catchEnv.info.scope.leave();
  1355             // Attribute finalizer
  1356             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1357             result = null;
  1359         finally {
  1360             localEnv.info.scope.leave();
  1364     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1365         if (!resource.isErroneous() &&
  1366             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1367             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1368             Symbol close = syms.noSymbol;
  1369             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1370             try {
  1371                 close = rs.resolveQualifiedMethod(pos,
  1372                         env,
  1373                         resource,
  1374                         names.close,
  1375                         List.<Type>nil(),
  1376                         List.<Type>nil());
  1378             finally {
  1379                 log.popDiagnosticHandler(discardHandler);
  1381             if (close.kind == MTH &&
  1382                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1383                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1384                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1385                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1390     public void visitConditional(JCConditional tree) {
  1391         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1393         boolean standaloneConditional = !allowPoly ||
  1394                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1395                 isBooleanOrNumeric(env, tree);
  1397         if (!standaloneConditional && resultInfo.pt.hasTag(VOID)) {
  1398             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1399             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1400             result = tree.type = types.createErrorType(resultInfo.pt);
  1401             return;
  1404         ResultInfo condInfo = standaloneConditional ?
  1405                 unknownExprInfo :
  1406                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1407                     //this will use enclosing check context to check compatibility of
  1408                     //subexpression against target type; if we are in a method check context,
  1409                     //depending on whether boxing is allowed, we could have incompatibilities
  1410                     @Override
  1411                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1412                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1414                 });
  1416         Type truetype = attribTree(tree.truepart, env, condInfo);
  1417         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1419         Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt();
  1420         if (condtype.constValue() != null &&
  1421                 truetype.constValue() != null &&
  1422                 falsetype.constValue() != null) {
  1423             //constant folding
  1424             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1426         result = check(tree, owntype, VAL, resultInfo);
  1428     //where
  1429         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1430             switch (tree.getTag()) {
  1431                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1432                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1433                               ((JCLiteral)tree).typetag == BOT;
  1434                 case LAMBDA: case REFERENCE: return false;
  1435                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1436                 case CONDEXPR:
  1437                     JCConditional condTree = (JCConditional)tree;
  1438                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1439                             isBooleanOrNumeric(env, condTree.falsepart);
  1440                 default:
  1441                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1442                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1443                     return speculativeType.isPrimitive();
  1447         /** Compute the type of a conditional expression, after
  1448          *  checking that it exists.  See JLS 15.25. Does not take into
  1449          *  account the special case where condition and both arms
  1450          *  are constants.
  1452          *  @param pos      The source position to be used for error
  1453          *                  diagnostics.
  1454          *  @param thentype The type of the expression's then-part.
  1455          *  @param elsetype The type of the expression's else-part.
  1456          */
  1457         private Type condType(DiagnosticPosition pos,
  1458                                Type thentype, Type elsetype) {
  1459             // If same type, that is the result
  1460             if (types.isSameType(thentype, elsetype))
  1461                 return thentype.baseType();
  1463             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1464                 ? thentype : types.unboxedType(thentype);
  1465             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1466                 ? elsetype : types.unboxedType(elsetype);
  1468             // Otherwise, if both arms can be converted to a numeric
  1469             // type, return the least numeric type that fits both arms
  1470             // (i.e. return larger of the two, or return int if one
  1471             // arm is short, the other is char).
  1472             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1473                 // If one arm has an integer subrange type (i.e., byte,
  1474                 // short, or char), and the other is an integer constant
  1475                 // that fits into the subrange, return the subrange type.
  1476                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
  1477                     types.isAssignable(elseUnboxed, thenUnboxed))
  1478                     return thenUnboxed.baseType();
  1479                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
  1480                     types.isAssignable(thenUnboxed, elseUnboxed))
  1481                     return elseUnboxed.baseType();
  1483                 for (TypeTag tag : TypeTag.values()) {
  1484                     if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
  1485                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1486                     if (candidate != null &&
  1487                         candidate.isPrimitive() &&
  1488                         types.isSubtype(thenUnboxed, candidate) &&
  1489                         types.isSubtype(elseUnboxed, candidate))
  1490                         return candidate;
  1494             // Those were all the cases that could result in a primitive
  1495             if (allowBoxing) {
  1496                 if (thentype.isPrimitive())
  1497                     thentype = types.boxedClass(thentype).type;
  1498                 if (elsetype.isPrimitive())
  1499                     elsetype = types.boxedClass(elsetype).type;
  1502             if (types.isSubtype(thentype, elsetype))
  1503                 return elsetype.baseType();
  1504             if (types.isSubtype(elsetype, thentype))
  1505                 return thentype.baseType();
  1507             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1508                 log.error(pos, "neither.conditional.subtype",
  1509                           thentype, elsetype);
  1510                 return thentype.baseType();
  1513             // both are known to be reference types.  The result is
  1514             // lub(thentype,elsetype). This cannot fail, as it will
  1515             // always be possible to infer "Object" if nothing better.
  1516             return types.lub(thentype.baseType(), elsetype.baseType());
  1519     public void visitIf(JCIf tree) {
  1520         attribExpr(tree.cond, env, syms.booleanType);
  1521         attribStat(tree.thenpart, env);
  1522         if (tree.elsepart != null)
  1523             attribStat(tree.elsepart, env);
  1524         chk.checkEmptyIf(tree);
  1525         result = null;
  1528     public void visitExec(JCExpressionStatement tree) {
  1529         //a fresh environment is required for 292 inference to work properly ---
  1530         //see Infer.instantiatePolymorphicSignatureInstance()
  1531         Env<AttrContext> localEnv = env.dup(tree);
  1532         attribExpr(tree.expr, localEnv);
  1533         result = null;
  1536     public void visitBreak(JCBreak tree) {
  1537         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1538         result = null;
  1541     public void visitContinue(JCContinue tree) {
  1542         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1543         result = null;
  1545     //where
  1546         /** Return the target of a break or continue statement, if it exists,
  1547          *  report an error if not.
  1548          *  Note: The target of a labelled break or continue is the
  1549          *  (non-labelled) statement tree referred to by the label,
  1550          *  not the tree representing the labelled statement itself.
  1552          *  @param pos     The position to be used for error diagnostics
  1553          *  @param tag     The tag of the jump statement. This is either
  1554          *                 Tree.BREAK or Tree.CONTINUE.
  1555          *  @param label   The label of the jump statement, or null if no
  1556          *                 label is given.
  1557          *  @param env     The environment current at the jump statement.
  1558          */
  1559         private JCTree findJumpTarget(DiagnosticPosition pos,
  1560                                     JCTree.Tag tag,
  1561                                     Name label,
  1562                                     Env<AttrContext> env) {
  1563             // Search environments outwards from the point of jump.
  1564             Env<AttrContext> env1 = env;
  1565             LOOP:
  1566             while (env1 != null) {
  1567                 switch (env1.tree.getTag()) {
  1568                     case LABELLED:
  1569                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1570                         if (label == labelled.label) {
  1571                             // If jump is a continue, check that target is a loop.
  1572                             if (tag == CONTINUE) {
  1573                                 if (!labelled.body.hasTag(DOLOOP) &&
  1574                                         !labelled.body.hasTag(WHILELOOP) &&
  1575                                         !labelled.body.hasTag(FORLOOP) &&
  1576                                         !labelled.body.hasTag(FOREACHLOOP))
  1577                                     log.error(pos, "not.loop.label", label);
  1578                                 // Found labelled statement target, now go inwards
  1579                                 // to next non-labelled tree.
  1580                                 return TreeInfo.referencedStatement(labelled);
  1581                             } else {
  1582                                 return labelled;
  1585                         break;
  1586                     case DOLOOP:
  1587                     case WHILELOOP:
  1588                     case FORLOOP:
  1589                     case FOREACHLOOP:
  1590                         if (label == null) return env1.tree;
  1591                         break;
  1592                     case SWITCH:
  1593                         if (label == null && tag == BREAK) return env1.tree;
  1594                         break;
  1595                     case LAMBDA:
  1596                     case METHODDEF:
  1597                     case CLASSDEF:
  1598                         break LOOP;
  1599                     default:
  1601                 env1 = env1.next;
  1603             if (label != null)
  1604                 log.error(pos, "undef.label", label);
  1605             else if (tag == CONTINUE)
  1606                 log.error(pos, "cont.outside.loop");
  1607             else
  1608                 log.error(pos, "break.outside.switch.loop");
  1609             return null;
  1612     public void visitReturn(JCReturn tree) {
  1613         // Check that there is an enclosing method which is
  1614         // nested within than the enclosing class.
  1615         if (env.info.returnResult == null) {
  1616             log.error(tree.pos(), "ret.outside.meth");
  1617         } else {
  1618             // Attribute return expression, if it exists, and check that
  1619             // it conforms to result type of enclosing method.
  1620             if (tree.expr != null) {
  1621                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1622                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1623                               diags.fragment("unexpected.ret.val"));
  1625                 attribTree(tree.expr, env, env.info.returnResult);
  1626             } else if (!env.info.returnResult.pt.hasTag(VOID)) {
  1627                 env.info.returnResult.checkContext.report(tree.pos(),
  1628                               diags.fragment("missing.ret.val"));
  1631         result = null;
  1634     public void visitThrow(JCThrow tree) {
  1635         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1636         if (allowPoly) {
  1637             chk.checkType(tree, owntype, syms.throwableType);
  1639         result = null;
  1642     public void visitAssert(JCAssert tree) {
  1643         attribExpr(tree.cond, env, syms.booleanType);
  1644         if (tree.detail != null) {
  1645             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1647         result = null;
  1650      /** Visitor method for method invocations.
  1651      *  NOTE: The method part of an application will have in its type field
  1652      *        the return type of the method, not the method's type itself!
  1653      */
  1654     public void visitApply(JCMethodInvocation tree) {
  1655         // The local environment of a method application is
  1656         // a new environment nested in the current one.
  1657         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1659         // The types of the actual method arguments.
  1660         List<Type> argtypes;
  1662         // The types of the actual method type arguments.
  1663         List<Type> typeargtypes = null;
  1665         Name methName = TreeInfo.name(tree.meth);
  1667         boolean isConstructorCall =
  1668             methName == names._this || methName == names._super;
  1670         if (isConstructorCall) {
  1671             // We are seeing a ...this(...) or ...super(...) call.
  1672             // Check that this is the first statement in a constructor.
  1673             if (checkFirstConstructorStat(tree, env)) {
  1675                 // Record the fact
  1676                 // that this is a constructor call (using isSelfCall).
  1677                 localEnv.info.isSelfCall = true;
  1679                 // Attribute arguments, yielding list of argument types.
  1680                 argtypes = attribArgs(tree.args, localEnv);
  1681                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1683                 // Variable `site' points to the class in which the called
  1684                 // constructor is defined.
  1685                 Type site = env.enclClass.sym.type;
  1686                 if (methName == names._super) {
  1687                     if (site == syms.objectType) {
  1688                         log.error(tree.meth.pos(), "no.superclass", site);
  1689                         site = types.createErrorType(syms.objectType);
  1690                     } else {
  1691                         site = types.supertype(site);
  1695                 if (site.hasTag(CLASS)) {
  1696                     Type encl = site.getEnclosingType();
  1697                     while (encl != null && encl.hasTag(TYPEVAR))
  1698                         encl = encl.getUpperBound();
  1699                     if (encl.hasTag(CLASS)) {
  1700                         // we are calling a nested class
  1702                         if (tree.meth.hasTag(SELECT)) {
  1703                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1705                             // We are seeing a prefixed call, of the form
  1706                             //     <expr>.super(...).
  1707                             // Check that the prefix expression conforms
  1708                             // to the outer instance type of the class.
  1709                             chk.checkRefType(qualifier.pos(),
  1710                                              attribExpr(qualifier, localEnv,
  1711                                                         encl));
  1712                         } else if (methName == names._super) {
  1713                             // qualifier omitted; check for existence
  1714                             // of an appropriate implicit qualifier.
  1715                             rs.resolveImplicitThis(tree.meth.pos(),
  1716                                                    localEnv, site, true);
  1718                     } else if (tree.meth.hasTag(SELECT)) {
  1719                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1720                                   site.tsym);
  1723                     // if we're calling a java.lang.Enum constructor,
  1724                     // prefix the implicit String and int parameters
  1725                     if (site.tsym == syms.enumSym && allowEnums)
  1726                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1728                     // Resolve the called constructor under the assumption
  1729                     // that we are referring to a superclass instance of the
  1730                     // current instance (JLS ???).
  1731                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1732                     localEnv.info.selectSuper = true;
  1733                     localEnv.info.pendingResolutionPhase = null;
  1734                     Symbol sym = rs.resolveConstructor(
  1735                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1736                     localEnv.info.selectSuper = selectSuperPrev;
  1738                     // Set method symbol to resolved constructor...
  1739                     TreeInfo.setSymbol(tree.meth, sym);
  1741                     // ...and check that it is legal in the current context.
  1742                     // (this will also set the tree's type)
  1743                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1744                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1746                 // Otherwise, `site' is an error type and we do nothing
  1748             result = tree.type = syms.voidType;
  1749         } else {
  1750             // Otherwise, we are seeing a regular method call.
  1751             // Attribute the arguments, yielding list of argument types, ...
  1752             argtypes = attribArgs(tree.args, localEnv);
  1753             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1755             // ... and attribute the method using as a prototype a methodtype
  1756             // whose formal argument types is exactly the list of actual
  1757             // arguments (this will also set the method symbol).
  1758             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1759             localEnv.info.pendingResolutionPhase = null;
  1760             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
  1762             // Compute the result type.
  1763             Type restype = mtype.getReturnType();
  1764             if (restype.hasTag(WILDCARD))
  1765                 throw new AssertionError(mtype);
  1767             Type qualifier = (tree.meth.hasTag(SELECT))
  1768                     ? ((JCFieldAccess) tree.meth).selected.type
  1769                     : env.enclClass.sym.type;
  1770             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1772             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1774             // Check that value of resulting type is admissible in the
  1775             // current context.  Also, capture the return type
  1776             result = check(tree, capture(restype), VAL, resultInfo);
  1778             if (localEnv.info.lastResolveVarargs())
  1779                 Assert.check(result.isErroneous() || tree.varargsElement != null);
  1781         chk.validate(tree.typeargs, localEnv);
  1783     //where
  1784         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1785             if (allowCovariantReturns &&
  1786                     methodName == names.clone &&
  1787                 types.isArray(qualifierType)) {
  1788                 // as a special case, array.clone() has a result that is
  1789                 // the same as static type of the array being cloned
  1790                 return qualifierType;
  1791             } else if (allowGenerics &&
  1792                     methodName == names.getClass &&
  1793                     argtypes.isEmpty()) {
  1794                 // as a special case, x.getClass() has type Class<? extends |X|>
  1795                 return new ClassType(restype.getEnclosingType(),
  1796                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1797                                                                BoundKind.EXTENDS,
  1798                                                                syms.boundClass)),
  1799                               restype.tsym);
  1800             } else {
  1801                 return restype;
  1805         /** Check that given application node appears as first statement
  1806          *  in a constructor call.
  1807          *  @param tree   The application node
  1808          *  @param env    The environment current at the application.
  1809          */
  1810         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1811             JCMethodDecl enclMethod = env.enclMethod;
  1812             if (enclMethod != null && enclMethod.name == names.init) {
  1813                 JCBlock body = enclMethod.body;
  1814                 if (body.stats.head.hasTag(EXEC) &&
  1815                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1816                     return true;
  1818             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1819                       TreeInfo.name(tree.meth));
  1820             return false;
  1823         /** Obtain a method type with given argument types.
  1824          */
  1825         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1826             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1827             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1830     public void visitNewClass(final JCNewClass tree) {
  1831         Type owntype = types.createErrorType(tree.type);
  1833         // The local environment of a class creation is
  1834         // a new environment nested in the current one.
  1835         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1837         // The anonymous inner class definition of the new expression,
  1838         // if one is defined by it.
  1839         JCClassDecl cdef = tree.def;
  1841         // If enclosing class is given, attribute it, and
  1842         // complete class name to be fully qualified
  1843         JCExpression clazz = tree.clazz; // Class field following new
  1844         JCExpression clazzid =          // Identifier in class field
  1845             (clazz.hasTag(TYPEAPPLY))
  1846             ? ((JCTypeApply) clazz).clazz
  1847             : clazz;
  1849         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1851         if (tree.encl != null) {
  1852             // We are seeing a qualified new, of the form
  1853             //    <expr>.new C <...> (...) ...
  1854             // In this case, we let clazz stand for the name of the
  1855             // allocated class C prefixed with the type of the qualifier
  1856             // expression, so that we can
  1857             // resolve it with standard techniques later. I.e., if
  1858             // <expr> has type T, then <expr>.new C <...> (...)
  1859             // yields a clazz T.C.
  1860             Type encltype = chk.checkRefType(tree.encl.pos(),
  1861                                              attribExpr(tree.encl, env));
  1862             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1863                                                  ((JCIdent) clazzid).name);
  1864             if (clazz.hasTag(TYPEAPPLY))
  1865                 clazz = make.at(tree.pos).
  1866                     TypeApply(clazzid1,
  1867                               ((JCTypeApply) clazz).arguments);
  1868             else
  1869                 clazz = clazzid1;
  1872         // Attribute clazz expression and store
  1873         // symbol + type back into the attributed tree.
  1874         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1875             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1876             attribType(clazz, env);
  1878         clazztype = chk.checkDiamond(tree, clazztype);
  1879         chk.validate(clazz, localEnv);
  1880         if (tree.encl != null) {
  1881             // We have to work in this case to store
  1882             // symbol + type back into the attributed tree.
  1883             tree.clazz.type = clazztype;
  1884             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1885             clazzid.type = ((JCIdent) clazzid).sym.type;
  1886             if (!clazztype.isErroneous()) {
  1887                 if (cdef != null && clazztype.tsym.isInterface()) {
  1888                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1889                 } else if (clazztype.tsym.isStatic()) {
  1890                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1893         } else if (!clazztype.tsym.isInterface() &&
  1894                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1895             // Check for the existence of an apropos outer instance
  1896             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1899         // Attribute constructor arguments.
  1900         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1901         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1903         // If we have made no mistakes in the class type...
  1904         if (clazztype.hasTag(CLASS)) {
  1905             // Enums may not be instantiated except implicitly
  1906             if (allowEnums &&
  1907                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1908                 (!env.tree.hasTag(VARDEF) ||
  1909                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1910                  ((JCVariableDecl) env.tree).init != tree))
  1911                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1912             // Check that class is not abstract
  1913             if (cdef == null &&
  1914                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1915                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1916                           clazztype.tsym);
  1917             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1918                 // Check that no constructor arguments are given to
  1919                 // anonymous classes implementing an interface
  1920                 if (!argtypes.isEmpty())
  1921                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1923                 if (!typeargtypes.isEmpty())
  1924                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1926                 // Error recovery: pretend no arguments were supplied.
  1927                 argtypes = List.nil();
  1928                 typeargtypes = List.nil();
  1929             } else if (TreeInfo.isDiamond(tree)) {
  1930                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  1931                             clazztype.tsym.type.getTypeArguments(),
  1932                             clazztype.tsym);
  1934                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  1935                 diamondEnv.info.selectSuper = cdef != null;
  1936                 diamondEnv.info.pendingResolutionPhase = null;
  1938                 //if the type of the instance creation expression is a class type
  1939                 //apply method resolution inference (JLS 15.12.2.7). The return type
  1940                 //of the resolved constructor will be a partially instantiated type
  1941                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  1942                             diamondEnv,
  1943                             site,
  1944                             argtypes,
  1945                             typeargtypes);
  1946                 tree.constructor = constructor.baseSymbol();
  1948                 final TypeSymbol csym = clazztype.tsym;
  1949                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  1950                     @Override
  1951                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  1952                         enclosingContext.report(tree.clazz,
  1953                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  1955                 });
  1956                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  1957                 constructorType = checkId(tree, site,
  1958                         constructor,
  1959                         diamondEnv,
  1960                         diamondResult);
  1962                 tree.clazz.type = types.createErrorType(clazztype);
  1963                 if (!constructorType.isErroneous()) {
  1964                     tree.clazz.type = clazztype = constructorType.getReturnType();
  1965                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  1967                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  1970             // Resolve the called constructor under the assumption
  1971             // that we are referring to a superclass instance of the
  1972             // current instance (JLS ???).
  1973             else {
  1974                 //the following code alters some of the fields in the current
  1975                 //AttrContext - hence, the current context must be dup'ed in
  1976                 //order to avoid downstream failures
  1977                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  1978                 rsEnv.info.selectSuper = cdef != null;
  1979                 rsEnv.info.pendingResolutionPhase = null;
  1980                 tree.constructor = rs.resolveConstructor(
  1981                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  1982                 if (cdef == null) { //do not check twice!
  1983                     tree.constructorType = checkId(tree,
  1984                             clazztype,
  1985                             tree.constructor,
  1986                             rsEnv,
  1987                             new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  1988                     if (rsEnv.info.lastResolveVarargs())
  1989                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1991                 findDiamondIfNeeded(localEnv, tree, clazztype);
  1994             if (cdef != null) {
  1995                 // We are seeing an anonymous class instance creation.
  1996                 // In this case, the class instance creation
  1997                 // expression
  1998                 //
  1999                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2000                 //
  2001                 // is represented internally as
  2002                 //
  2003                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2004                 //
  2005                 // This expression is then *transformed* as follows:
  2006                 //
  2007                 // (1) add a STATIC flag to the class definition
  2008                 //     if the current environment is static
  2009                 // (2) add an extends or implements clause
  2010                 // (3) add a constructor.
  2011                 //
  2012                 // For instance, if C is a class, and ET is the type of E,
  2013                 // the expression
  2014                 //
  2015                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2016                 //
  2017                 // is translated to (where X is a fresh name and typarams is the
  2018                 // parameter list of the super constructor):
  2019                 //
  2020                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2021                 //     X extends C<typargs2> {
  2022                 //       <typarams> X(ET e, args) {
  2023                 //         e.<typeargs1>super(args)
  2024                 //       }
  2025                 //       ...
  2026                 //     }
  2027                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2029                 if (clazztype.tsym.isInterface()) {
  2030                     cdef.implementing = List.of(clazz);
  2031                 } else {
  2032                     cdef.extending = clazz;
  2035                 attribStat(cdef, localEnv);
  2037                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2039                 // If an outer instance is given,
  2040                 // prefix it to the constructor arguments
  2041                 // and delete it from the new expression
  2042                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2043                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2044                     argtypes = argtypes.prepend(tree.encl.type);
  2045                     tree.encl = null;
  2048                 // Reassign clazztype and recompute constructor.
  2049                 clazztype = cdef.sym.type;
  2050                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2051                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2052                 Assert.check(sym.kind < AMBIGUOUS);
  2053                 tree.constructor = sym;
  2054                 tree.constructorType = checkId(tree,
  2055                     clazztype,
  2056                     tree.constructor,
  2057                     localEnv,
  2058                     new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2061             if (tree.constructor != null && tree.constructor.kind == MTH)
  2062                 owntype = clazztype;
  2064         result = check(tree, owntype, VAL, resultInfo);
  2065         chk.validate(tree.typeargs, localEnv);
  2067     //where
  2068         void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2069             if (tree.def == null &&
  2070                     !clazztype.isErroneous() &&
  2071                     clazztype.getTypeArguments().nonEmpty() &&
  2072                     findDiamonds) {
  2073                 JCTypeApply ta = (JCTypeApply)tree.clazz;
  2074                 List<JCExpression> prevTypeargs = ta.arguments;
  2075                 try {
  2076                     //create a 'fake' diamond AST node by removing type-argument trees
  2077                     ta.arguments = List.nil();
  2078                     ResultInfo findDiamondResult = new ResultInfo(VAL,
  2079                             resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2080                     Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2081                     if (!inferred.isErroneous() &&
  2082                         types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) {
  2083                         String key = types.isSameType(clazztype, inferred) ?
  2084                             "diamond.redundant.args" :
  2085                             "diamond.redundant.args.1";
  2086                         log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2088                 } finally {
  2089                     ta.arguments = prevTypeargs;
  2094             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2095                 if (allowLambda &&
  2096                         identifyLambdaCandidate &&
  2097                         clazztype.hasTag(CLASS) &&
  2098                         !pt().hasTag(NONE) &&
  2099                         types.isFunctionalInterface(clazztype.tsym)) {
  2100                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2101                     int count = 0;
  2102                     boolean found = false;
  2103                     for (Symbol sym : csym.members().getElements()) {
  2104                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2105                                 sym.isConstructor()) continue;
  2106                         count++;
  2107                         if (sym.kind != MTH ||
  2108                                 !sym.name.equals(descriptor.name)) continue;
  2109                         Type mtype = types.memberType(clazztype, sym);
  2110                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2111                             found = true;
  2114                     if (found && count == 1) {
  2115                         log.note(tree.def, "potential.lambda.found");
  2120     /** Make an attributed null check tree.
  2121      */
  2122     public JCExpression makeNullCheck(JCExpression arg) {
  2123         // optimization: X.this is never null; skip null check
  2124         Name name = TreeInfo.name(arg);
  2125         if (name == names._this || name == names._super) return arg;
  2127         JCTree.Tag optag = NULLCHK;
  2128         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2129         tree.operator = syms.nullcheck;
  2130         tree.type = arg.type;
  2131         return tree;
  2134     public void visitNewArray(JCNewArray tree) {
  2135         Type owntype = types.createErrorType(tree.type);
  2136         Env<AttrContext> localEnv = env.dup(tree);
  2137         Type elemtype;
  2138         if (tree.elemtype != null) {
  2139             elemtype = attribType(tree.elemtype, localEnv);
  2140             chk.validate(tree.elemtype, localEnv);
  2141             owntype = elemtype;
  2142             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2143                 attribExpr(l.head, localEnv, syms.intType);
  2144                 owntype = new ArrayType(owntype, syms.arrayClass);
  2146         } else {
  2147             // we are seeing an untyped aggregate { ... }
  2148             // this is allowed only if the prototype is an array
  2149             if (pt().hasTag(ARRAY)) {
  2150                 elemtype = types.elemtype(pt());
  2151             } else {
  2152                 if (!pt().hasTag(ERROR)) {
  2153                     log.error(tree.pos(), "illegal.initializer.for.type",
  2154                               pt());
  2156                 elemtype = types.createErrorType(pt());
  2159         if (tree.elems != null) {
  2160             attribExprs(tree.elems, localEnv, elemtype);
  2161             owntype = new ArrayType(elemtype, syms.arrayClass);
  2163         if (!types.isReifiable(elemtype))
  2164             log.error(tree.pos(), "generic.array.creation");
  2165         result = check(tree, owntype, VAL, resultInfo);
  2168     /*
  2169      * A lambda expression can only be attributed when a target-type is available.
  2170      * In addition, if the target-type is that of a functional interface whose
  2171      * descriptor contains inference variables in argument position the lambda expression
  2172      * is 'stuck' (see DeferredAttr).
  2173      */
  2174     @Override
  2175     public void visitLambda(final JCLambda that) {
  2176         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2177             if (pt().hasTag(NONE)) {
  2178                 //lambda only allowed in assignment or method invocation/cast context
  2179                 log.error(that.pos(), "unexpected.lambda");
  2181             result = that.type = types.createErrorType(pt());
  2182             return;
  2184         //create an environment for attribution of the lambda expression
  2185         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2186         boolean needsRecovery =
  2187                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2188         try {
  2189             List<Type> explicitParamTypes = null;
  2190             if (TreeInfo.isExplicitLambda(that)) {
  2191                 //attribute lambda parameters
  2192                 attribStats(that.params, localEnv);
  2193                 explicitParamTypes = TreeInfo.types(that.params);
  2196             Type target;
  2197             Type lambdaType;
  2198             if (pt() != Type.recoveryType) {
  2199                 target = infer.instantiateFunctionalInterface(that, pt(), explicitParamTypes, resultInfo.checkContext);
  2200                 lambdaType = types.findDescriptorType(target);
  2201                 chk.checkFunctionalInterface(that, target);
  2202             } else {
  2203                 target = Type.recoveryType;
  2204                 lambdaType = fallbackDescriptorType(that);
  2207             if (!TreeInfo.isExplicitLambda(that)) {
  2208                 //add param type info in the AST
  2209                 List<Type> actuals = lambdaType.getParameterTypes();
  2210                 List<JCVariableDecl> params = that.params;
  2212                 boolean arityMismatch = false;
  2214                 while (params.nonEmpty()) {
  2215                     if (actuals.isEmpty()) {
  2216                         //not enough actuals to perform lambda parameter inference
  2217                         arityMismatch = true;
  2219                     //reset previously set info
  2220                     Type argType = arityMismatch ?
  2221                             syms.errType :
  2222                             actuals.head;
  2223                     params.head.vartype = make.Type(argType);
  2224                     params.head.sym = null;
  2225                     actuals = actuals.isEmpty() ?
  2226                             actuals :
  2227                             actuals.tail;
  2228                     params = params.tail;
  2231                 //attribute lambda parameters
  2232                 attribStats(that.params, localEnv);
  2234                 if (arityMismatch) {
  2235                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2236                         result = that.type = types.createErrorType(target);
  2237                         return;
  2241             //from this point on, no recovery is needed; if we are in assignment context
  2242             //we will be able to attribute the whole lambda body, regardless of errors;
  2243             //if we are in a 'check' method context, and the lambda is not compatible
  2244             //with the target-type, it will be recovered anyway in Attr.checkId
  2245             needsRecovery = false;
  2247             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2248                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2249                     new FunctionalReturnContext(resultInfo.checkContext);
  2251             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2252                 recoveryInfo :
  2253                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2254             localEnv.info.returnResult = bodyResultInfo;
  2256             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2257                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2258             } else {
  2259                 JCBlock body = (JCBlock)that.body;
  2260                 attribStats(body.stats, localEnv);
  2263             result = check(that, target, VAL, resultInfo);
  2265             boolean isSpeculativeRound =
  2266                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2268             postAttr(that);
  2269             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2271             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
  2273             if (!isSpeculativeRound) {
  2274                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
  2276             result = check(that, target, VAL, resultInfo);
  2277         } catch (Types.FunctionDescriptorLookupError ex) {
  2278             JCDiagnostic cause = ex.getDiagnostic();
  2279             resultInfo.checkContext.report(that, cause);
  2280             result = that.type = types.createErrorType(pt());
  2281             return;
  2282         } finally {
  2283             localEnv.info.scope.leave();
  2284             if (needsRecovery) {
  2285                 attribTree(that, env, recoveryInfo);
  2289     //where
  2290         private Type fallbackDescriptorType(JCExpression tree) {
  2291             switch (tree.getTag()) {
  2292                 case LAMBDA:
  2293                     JCLambda lambda = (JCLambda)tree;
  2294                     List<Type> argtypes = List.nil();
  2295                     for (JCVariableDecl param : lambda.params) {
  2296                         argtypes = param.vartype != null ?
  2297                                 argtypes.append(param.vartype.type) :
  2298                                 argtypes.append(syms.errType);
  2300                     return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
  2301                 case REFERENCE:
  2302                     return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
  2303                 default:
  2304                     Assert.error("Cannot get here!");
  2306             return null;
  2309         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) {
  2310             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2313         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) {
  2314             if (inferenceContext.free(ts)) {
  2315                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2316                     @Override
  2317                     public void typesInferred(InferenceContext inferenceContext) {
  2318                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts, types));
  2320                 });
  2321             } else {
  2322                 for (Type t : ts) {
  2323                     rs.checkAccessibleType(env, t);
  2328         /**
  2329          * Lambda/method reference have a special check context that ensures
  2330          * that i.e. a lambda return type is compatible with the expected
  2331          * type according to both the inherited context and the assignment
  2332          * context.
  2333          */
  2334         class FunctionalReturnContext extends Check.NestedCheckContext {
  2336             FunctionalReturnContext(CheckContext enclosingContext) {
  2337                 super(enclosingContext);
  2340             @Override
  2341             public boolean compatible(Type found, Type req, Warner warn) {
  2342                 //return type must be compatible in both current context and assignment context
  2343                 return types.isAssignable(found, inferenceContext().asFree(req, types), warn) &&
  2344                         super.compatible(found, req, warn);
  2346             @Override
  2347             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2348                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2352         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2354             JCExpression expr;
  2356             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2357                 super(enclosingContext);
  2358                 this.expr = expr;
  2361             @Override
  2362             public boolean compatible(Type found, Type req, Warner warn) {
  2363                 //a void return is compatible with an expression statement lambda
  2364                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2365                         super.compatible(found, req, warn);
  2369         /**
  2370         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2371         * are compatible with the expected functional interface descriptor. This means that:
  2372         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2373         * types must be compatible with the return type of the expected descriptor;
  2374         * (iii) thrown types must be 'included' in the thrown types list of the expected
  2375         * descriptor.
  2376         */
  2377         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
  2378             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
  2380             //return values have already been checked - but if lambda has no return
  2381             //values, we must ensure that void/value compatibility is correct;
  2382             //this amounts at checking that, if a lambda body can complete normally,
  2383             //the descriptor's return type must be void
  2384             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2385                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2386                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2387                         diags.fragment("missing.ret.val", returnType)));
  2390             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
  2391             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2392                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2395             if (!speculativeAttr) {
  2396                 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
  2397                 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
  2398                     log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
  2403         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2404             Env<AttrContext> lambdaEnv;
  2405             Symbol owner = env.info.scope.owner;
  2406             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2407                 //field initializer
  2408                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2409                 lambdaEnv.info.scope.owner =
  2410                     new MethodSymbol(0, names.empty, null,
  2411                                      env.info.scope.owner);
  2412             } else {
  2413                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2415             return lambdaEnv;
  2418     @Override
  2419     public void visitReference(final JCMemberReference that) {
  2420         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2421             if (pt().hasTag(NONE)) {
  2422                 //method reference only allowed in assignment or method invocation/cast context
  2423                 log.error(that.pos(), "unexpected.mref");
  2425             result = that.type = types.createErrorType(pt());
  2426             return;
  2428         final Env<AttrContext> localEnv = env.dup(that);
  2429         try {
  2430             //attribute member reference qualifier - if this is a constructor
  2431             //reference, the expected kind must be a type
  2432             Type exprType = attribTree(that.expr,
  2433                     env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
  2435             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2436                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2439             if (exprType.isErroneous()) {
  2440                 //if the qualifier expression contains problems,
  2441                 //give up atttribution of method reference
  2442                 result = that.type = exprType;
  2443                 return;
  2446             if (TreeInfo.isStaticSelector(that.expr, names) &&
  2447                     (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
  2448                 //if the qualifier is a type, validate it
  2449                 chk.validate(that.expr, env);
  2452             //attrib type-arguments
  2453             List<Type> typeargtypes = null;
  2454             if (that.typeargs != null) {
  2455                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2458             Type target;
  2459             Type desc;
  2460             if (pt() != Type.recoveryType) {
  2461                 target = infer.instantiateFunctionalInterface(that, pt(), null, resultInfo.checkContext);
  2462                 desc = types.findDescriptorType(target);
  2463                 chk.checkFunctionalInterface(that, target);
  2464             } else {
  2465                 target = Type.recoveryType;
  2466                 desc = fallbackDescriptorType(that);
  2469             List<Type> argtypes = desc.getParameterTypes();
  2471             boolean allowBoxing =
  2472                     resultInfo.checkContext.deferredAttrContext().phase.isBoxingRequired();
  2473             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
  2474                     that.expr.type, that.name, argtypes, typeargtypes, allowBoxing);
  2476             Symbol refSym = refResult.fst;
  2477             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2479             if (refSym.kind != MTH) {
  2480                 boolean targetError;
  2481                 switch (refSym.kind) {
  2482                     case ABSENT_MTH:
  2483                         targetError = false;
  2484                         break;
  2485                     case WRONG_MTH:
  2486                     case WRONG_MTHS:
  2487                     case AMBIGUOUS:
  2488                     case HIDDEN:
  2489                     case STATICERR:
  2490                     case MISSING_ENCL:
  2491                         targetError = true;
  2492                         break;
  2493                     default:
  2494                         Assert.error("unexpected result kind " + refSym.kind);
  2495                         targetError = false;
  2498                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2499                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2501                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2502                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2504                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2505                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2507                 if (targetError && target == Type.recoveryType) {
  2508                     //a target error doesn't make sense during recovery stage
  2509                     //as we don't know what actual parameter types are
  2510                     result = that.type = target;
  2511                     return;
  2512                 } else {
  2513                     if (targetError) {
  2514                         resultInfo.checkContext.report(that, diag);
  2515                     } else {
  2516                         log.report(diag);
  2518                     result = that.type = types.createErrorType(target);
  2519                     return;
  2523             if (desc.getReturnType() == Type.recoveryType) {
  2524                 // stop here
  2525                 result = that.type = target;
  2526                 return;
  2529             that.sym = refSym.baseSymbol();
  2530             that.kind = lookupHelper.referenceKind(that.sym);
  2532             ResultInfo checkInfo =
  2533                     resultInfo.dup(newMethodTemplate(
  2534                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2535                         lookupHelper.argtypes,
  2536                         typeargtypes));
  2538             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2540             if (!refType.isErroneous()) {
  2541                 refType = types.createMethodTypeWithReturn(refType,
  2542                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2545             //go ahead with standard method reference compatibility check - note that param check
  2546             //is a no-op (as this has been taken care during method applicability)
  2547             boolean isSpeculativeRound =
  2548                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2549             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2550             if (!isSpeculativeRound) {
  2551                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2553             result = check(that, target, VAL, resultInfo);
  2554         } catch (Types.FunctionDescriptorLookupError ex) {
  2555             JCDiagnostic cause = ex.getDiagnostic();
  2556             resultInfo.checkContext.report(that, cause);
  2557             result = that.type = types.createErrorType(pt());
  2558             return;
  2562     @SuppressWarnings("fallthrough")
  2563     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2564         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
  2566         Type resType;
  2567         switch (tree.getMode()) {
  2568             case NEW:
  2569                 if (!tree.expr.type.isRaw()) {
  2570                     resType = tree.expr.type;
  2571                     break;
  2573             default:
  2574                 resType = refType.getReturnType();
  2577         Type incompatibleReturnType = resType;
  2579         if (returnType.hasTag(VOID)) {
  2580             incompatibleReturnType = null;
  2583         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2584             if (resType.isErroneous() ||
  2585                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2586                 incompatibleReturnType = null;
  2590         if (incompatibleReturnType != null) {
  2591             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2592                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2595         if (!speculativeAttr) {
  2596             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
  2597             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2598                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2603     public void visitParens(JCParens tree) {
  2604         Type owntype = attribTree(tree.expr, env, resultInfo);
  2605         result = check(tree, owntype, pkind(), resultInfo);
  2606         Symbol sym = TreeInfo.symbol(tree);
  2607         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2608             log.error(tree.pos(), "illegal.start.of.type");
  2611     public void visitAssign(JCAssign tree) {
  2612         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2613         Type capturedType = capture(owntype);
  2614         attribExpr(tree.rhs, env, owntype);
  2615         result = check(tree, capturedType, VAL, resultInfo);
  2618     public void visitAssignop(JCAssignOp tree) {
  2619         // Attribute arguments.
  2620         Type owntype = attribTree(tree.lhs, env, varInfo);
  2621         Type operand = attribExpr(tree.rhs, env);
  2622         // Find operator.
  2623         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2624             tree.pos(), tree.getTag().noAssignOp(), env,
  2625             owntype, operand);
  2627         if (operator.kind == MTH &&
  2628                 !owntype.isErroneous() &&
  2629                 !operand.isErroneous()) {
  2630             chk.checkOperator(tree.pos(),
  2631                               (OperatorSymbol)operator,
  2632                               tree.getTag().noAssignOp(),
  2633                               owntype,
  2634                               operand);
  2635             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2636             chk.checkCastable(tree.rhs.pos(),
  2637                               operator.type.getReturnType(),
  2638                               owntype);
  2640         result = check(tree, owntype, VAL, resultInfo);
  2643     public void visitUnary(JCUnary tree) {
  2644         // Attribute arguments.
  2645         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2646             ? attribTree(tree.arg, env, varInfo)
  2647             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2649         // Find operator.
  2650         Symbol operator = tree.operator =
  2651             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2653         Type owntype = types.createErrorType(tree.type);
  2654         if (operator.kind == MTH &&
  2655                 !argtype.isErroneous()) {
  2656             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2657                 ? tree.arg.type
  2658                 : operator.type.getReturnType();
  2659             int opc = ((OperatorSymbol)operator).opcode;
  2661             // If the argument is constant, fold it.
  2662             if (argtype.constValue() != null) {
  2663                 Type ctype = cfolder.fold1(opc, argtype);
  2664                 if (ctype != null) {
  2665                     owntype = cfolder.coerce(ctype, owntype);
  2667                     // Remove constant types from arguments to
  2668                     // conserve space. The parser will fold concatenations
  2669                     // of string literals; the code here also
  2670                     // gets rid of intermediate results when some of the
  2671                     // operands are constant identifiers.
  2672                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2673                         tree.arg.type = syms.stringType;
  2678         result = check(tree, owntype, VAL, resultInfo);
  2681     public void visitBinary(JCBinary tree) {
  2682         // Attribute arguments.
  2683         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2684         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2686         // Find operator.
  2687         Symbol operator = tree.operator =
  2688             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2690         Type owntype = types.createErrorType(tree.type);
  2691         if (operator.kind == MTH &&
  2692                 !left.isErroneous() &&
  2693                 !right.isErroneous()) {
  2694             owntype = operator.type.getReturnType();
  2695             int opc = chk.checkOperator(tree.lhs.pos(),
  2696                                         (OperatorSymbol)operator,
  2697                                         tree.getTag(),
  2698                                         left,
  2699                                         right);
  2701             // If both arguments are constants, fold them.
  2702             if (left.constValue() != null && right.constValue() != null) {
  2703                 Type ctype = cfolder.fold2(opc, left, right);
  2704                 if (ctype != null) {
  2705                     owntype = cfolder.coerce(ctype, owntype);
  2707                     // Remove constant types from arguments to
  2708                     // conserve space. The parser will fold concatenations
  2709                     // of string literals; the code here also
  2710                     // gets rid of intermediate results when some of the
  2711                     // operands are constant identifiers.
  2712                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2713                         tree.lhs.type = syms.stringType;
  2715                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2716                         tree.rhs.type = syms.stringType;
  2721             // Check that argument types of a reference ==, != are
  2722             // castable to each other, (JLS???).
  2723             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2724                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2725                     log.error(tree.pos(), "incomparable.types", left, right);
  2729             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2731         result = check(tree, owntype, VAL, resultInfo);
  2734     public void visitTypeCast(final JCTypeCast tree) {
  2735         Type clazztype = attribType(tree.clazz, env);
  2736         chk.validate(tree.clazz, env, false);
  2737         //a fresh environment is required for 292 inference to work properly ---
  2738         //see Infer.instantiatePolymorphicSignatureInstance()
  2739         Env<AttrContext> localEnv = env.dup(tree);
  2740         //should we propagate the target type?
  2741         final ResultInfo castInfo;
  2742         final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
  2743         if (isPoly) {
  2744             //expression is a poly - we need to propagate target type info
  2745             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  2746                 @Override
  2747                 public boolean compatible(Type found, Type req, Warner warn) {
  2748                     return types.isCastable(found, req, warn);
  2750             });
  2751         } else {
  2752             //standalone cast - target-type info is not propagated
  2753             castInfo = unknownExprInfo;
  2755         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  2756         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2757         if (exprtype.constValue() != null)
  2758             owntype = cfolder.coerce(exprtype, owntype);
  2759         result = check(tree, capture(owntype), VAL, resultInfo);
  2760         if (!isPoly)
  2761             chk.checkRedundantCast(localEnv, tree);
  2764     public void visitTypeTest(JCInstanceOf tree) {
  2765         Type exprtype = chk.checkNullOrRefType(
  2766             tree.expr.pos(), attribExpr(tree.expr, env));
  2767         Type clazztype = chk.checkReifiableReferenceType(
  2768             tree.clazz.pos(), attribType(tree.clazz, env));
  2769         chk.validate(tree.clazz, env, false);
  2770         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2771         result = check(tree, syms.booleanType, VAL, resultInfo);
  2774     public void visitIndexed(JCArrayAccess tree) {
  2775         Type owntype = types.createErrorType(tree.type);
  2776         Type atype = attribExpr(tree.indexed, env);
  2777         attribExpr(tree.index, env, syms.intType);
  2778         if (types.isArray(atype))
  2779             owntype = types.elemtype(atype);
  2780         else if (!atype.hasTag(ERROR))
  2781             log.error(tree.pos(), "array.req.but.found", atype);
  2782         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  2783         result = check(tree, owntype, VAR, resultInfo);
  2786     public void visitIdent(JCIdent tree) {
  2787         Symbol sym;
  2789         // Find symbol
  2790         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  2791             // If we are looking for a method, the prototype `pt' will be a
  2792             // method type with the type of the call's arguments as parameters.
  2793             env.info.pendingResolutionPhase = null;
  2794             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  2795         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2796             sym = tree.sym;
  2797         } else {
  2798             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  2800         tree.sym = sym;
  2802         // (1) Also find the environment current for the class where
  2803         //     sym is defined (`symEnv').
  2804         // Only for pre-tiger versions (1.4 and earlier):
  2805         // (2) Also determine whether we access symbol out of an anonymous
  2806         //     class in a this or super call.  This is illegal for instance
  2807         //     members since such classes don't carry a this$n link.
  2808         //     (`noOuterThisPath').
  2809         Env<AttrContext> symEnv = env;
  2810         boolean noOuterThisPath = false;
  2811         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2812             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2813             sym.owner.kind == TYP &&
  2814             tree.name != names._this && tree.name != names._super) {
  2816             // Find environment in which identifier is defined.
  2817             while (symEnv.outer != null &&
  2818                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2819                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2820                     noOuterThisPath = !allowAnonOuterThis;
  2821                 symEnv = symEnv.outer;
  2825         // If symbol is a variable, ...
  2826         if (sym.kind == VAR) {
  2827             VarSymbol v = (VarSymbol)sym;
  2829             // ..., evaluate its initializer, if it has one, and check for
  2830             // illegal forward reference.
  2831             checkInit(tree, env, v, false);
  2833             // If we are expecting a variable (as opposed to a value), check
  2834             // that the variable is assignable in the current environment.
  2835             if (pkind() == VAR)
  2836                 checkAssignable(tree.pos(), v, null, env);
  2839         // In a constructor body,
  2840         // if symbol is a field or instance method, check that it is
  2841         // not accessed before the supertype constructor is called.
  2842         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2843             (sym.kind & (VAR | MTH)) != 0 &&
  2844             sym.owner.kind == TYP &&
  2845             (sym.flags() & STATIC) == 0) {
  2846             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2848         Env<AttrContext> env1 = env;
  2849         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2850             // If the found symbol is inaccessible, then it is
  2851             // accessed through an enclosing instance.  Locate this
  2852             // enclosing instance:
  2853             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2854                 env1 = env1.outer;
  2856         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  2859     public void visitSelect(JCFieldAccess tree) {
  2860         // Determine the expected kind of the qualifier expression.
  2861         int skind = 0;
  2862         if (tree.name == names._this || tree.name == names._super ||
  2863             tree.name == names._class)
  2865             skind = TYP;
  2866         } else {
  2867             if ((pkind() & PCK) != 0) skind = skind | PCK;
  2868             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  2869             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2872         // Attribute the qualifier expression, and determine its symbol (if any).
  2873         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  2874         if ((pkind() & (PCK | TYP)) == 0)
  2875             site = capture(site); // Capture field access
  2877         // don't allow T.class T[].class, etc
  2878         if (skind == TYP) {
  2879             Type elt = site;
  2880             while (elt.hasTag(ARRAY))
  2881                 elt = ((ArrayType)elt).elemtype;
  2882             if (elt.hasTag(TYPEVAR)) {
  2883                 log.error(tree.pos(), "type.var.cant.be.deref");
  2884                 result = types.createErrorType(tree.type);
  2885                 return;
  2889         // If qualifier symbol is a type or `super', assert `selectSuper'
  2890         // for the selection. This is relevant for determining whether
  2891         // protected symbols are accessible.
  2892         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2893         boolean selectSuperPrev = env.info.selectSuper;
  2894         env.info.selectSuper =
  2895             sitesym != null &&
  2896             sitesym.name == names._super;
  2898         // Determine the symbol represented by the selection.
  2899         env.info.pendingResolutionPhase = null;
  2900         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  2901         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  2902             site = capture(site);
  2903             sym = selectSym(tree, sitesym, site, env, resultInfo);
  2905         boolean varArgs = env.info.lastResolveVarargs();
  2906         tree.sym = sym;
  2908         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  2909             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  2910             site = capture(site);
  2913         // If that symbol is a variable, ...
  2914         if (sym.kind == VAR) {
  2915             VarSymbol v = (VarSymbol)sym;
  2917             // ..., evaluate its initializer, if it has one, and check for
  2918             // illegal forward reference.
  2919             checkInit(tree, env, v, true);
  2921             // If we are expecting a variable (as opposed to a value), check
  2922             // that the variable is assignable in the current environment.
  2923             if (pkind() == VAR)
  2924                 checkAssignable(tree.pos(), v, tree.selected, env);
  2927         if (sitesym != null &&
  2928                 sitesym.kind == VAR &&
  2929                 ((VarSymbol)sitesym).isResourceVariable() &&
  2930                 sym.kind == MTH &&
  2931                 sym.name.equals(names.close) &&
  2932                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2933                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2934             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2937         // Disallow selecting a type from an expression
  2938         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2939             tree.type = check(tree.selected, pt(),
  2940                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  2943         if (isType(sitesym)) {
  2944             if (sym.name == names._this) {
  2945                 // If `C' is the currently compiled class, check that
  2946                 // C.this' does not appear in a call to a super(...)
  2947                 if (env.info.isSelfCall &&
  2948                     site.tsym == env.enclClass.sym) {
  2949                     chk.earlyRefError(tree.pos(), sym);
  2951             } else {
  2952                 // Check if type-qualified fields or methods are static (JLS)
  2953                 if ((sym.flags() & STATIC) == 0 &&
  2954                     !env.next.tree.hasTag(REFERENCE) &&
  2955                     sym.name != names._super &&
  2956                     (sym.kind == VAR || sym.kind == MTH)) {
  2957                     rs.accessBase(rs.new StaticError(sym),
  2958                               tree.pos(), site, sym.name, true);
  2961         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2962             // If the qualified item is not a type and the selected item is static, report
  2963             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2964             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2967         // If we are selecting an instance member via a `super', ...
  2968         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2970             // Check that super-qualified symbols are not abstract (JLS)
  2971             rs.checkNonAbstract(tree.pos(), sym);
  2973             if (site.isRaw()) {
  2974                 // Determine argument types for site.
  2975                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2976                 if (site1 != null) site = site1;
  2980         env.info.selectSuper = selectSuperPrev;
  2981         result = checkId(tree, site, sym, env, resultInfo);
  2983     //where
  2984         /** Determine symbol referenced by a Select expression,
  2986          *  @param tree   The select tree.
  2987          *  @param site   The type of the selected expression,
  2988          *  @param env    The current environment.
  2989          *  @param resultInfo The current result.
  2990          */
  2991         private Symbol selectSym(JCFieldAccess tree,
  2992                                  Symbol location,
  2993                                  Type site,
  2994                                  Env<AttrContext> env,
  2995                                  ResultInfo resultInfo) {
  2996             DiagnosticPosition pos = tree.pos();
  2997             Name name = tree.name;
  2998             switch (site.getTag()) {
  2999             case PACKAGE:
  3000                 return rs.accessBase(
  3001                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3002                     pos, location, site, name, true);
  3003             case ARRAY:
  3004             case CLASS:
  3005                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3006                     return rs.resolveQualifiedMethod(
  3007                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3008                 } else if (name == names._this || name == names._super) {
  3009                     return rs.resolveSelf(pos, env, site.tsym, name);
  3010                 } else if (name == names._class) {
  3011                     // In this case, we have already made sure in
  3012                     // visitSelect that qualifier expression is a type.
  3013                     Type t = syms.classType;
  3014                     List<Type> typeargs = allowGenerics
  3015                         ? List.of(types.erasure(site))
  3016                         : List.<Type>nil();
  3017                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3018                     return new VarSymbol(
  3019                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3020                 } else {
  3021                     // We are seeing a plain identifier as selector.
  3022                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3023                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3024                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3025                     return sym;
  3027             case WILDCARD:
  3028                 throw new AssertionError(tree);
  3029             case TYPEVAR:
  3030                 // Normally, site.getUpperBound() shouldn't be null.
  3031                 // It should only happen during memberEnter/attribBase
  3032                 // when determining the super type which *must* beac
  3033                 // done before attributing the type variables.  In
  3034                 // other words, we are seeing this illegal program:
  3035                 // class B<T> extends A<T.foo> {}
  3036                 Symbol sym = (site.getUpperBound() != null)
  3037                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3038                     : null;
  3039                 if (sym == null) {
  3040                     log.error(pos, "type.var.cant.be.deref");
  3041                     return syms.errSymbol;
  3042                 } else {
  3043                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3044                         rs.new AccessError(env, site, sym) :
  3045                                 sym;
  3046                     rs.accessBase(sym2, pos, location, site, name, true);
  3047                     return sym;
  3049             case ERROR:
  3050                 // preserve identifier names through errors
  3051                 return types.createErrorType(name, site.tsym, site).tsym;
  3052             default:
  3053                 // The qualifier expression is of a primitive type -- only
  3054                 // .class is allowed for these.
  3055                 if (name == names._class) {
  3056                     // In this case, we have already made sure in Select that
  3057                     // qualifier expression is a type.
  3058                     Type t = syms.classType;
  3059                     Type arg = types.boxedClass(site).type;
  3060                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3061                     return new VarSymbol(
  3062                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3063                 } else {
  3064                     log.error(pos, "cant.deref", site);
  3065                     return syms.errSymbol;
  3070         /** Determine type of identifier or select expression and check that
  3071          *  (1) the referenced symbol is not deprecated
  3072          *  (2) the symbol's type is safe (@see checkSafe)
  3073          *  (3) if symbol is a variable, check that its type and kind are
  3074          *      compatible with the prototype and protokind.
  3075          *  (4) if symbol is an instance field of a raw type,
  3076          *      which is being assigned to, issue an unchecked warning if its
  3077          *      type changes under erasure.
  3078          *  (5) if symbol is an instance method of a raw type, issue an
  3079          *      unchecked warning if its argument types change under erasure.
  3080          *  If checks succeed:
  3081          *    If symbol is a constant, return its constant type
  3082          *    else if symbol is a method, return its result type
  3083          *    otherwise return its type.
  3084          *  Otherwise return errType.
  3086          *  @param tree       The syntax tree representing the identifier
  3087          *  @param site       If this is a select, the type of the selected
  3088          *                    expression, otherwise the type of the current class.
  3089          *  @param sym        The symbol representing the identifier.
  3090          *  @param env        The current environment.
  3091          *  @param resultInfo    The expected result
  3092          */
  3093         Type checkId(JCTree tree,
  3094                      Type site,
  3095                      Symbol sym,
  3096                      Env<AttrContext> env,
  3097                      ResultInfo resultInfo) {
  3098             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3099                     checkMethodId(tree, site, sym, env, resultInfo) :
  3100                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3103         Type checkMethodId(JCTree tree,
  3104                      Type site,
  3105                      Symbol sym,
  3106                      Env<AttrContext> env,
  3107                      ResultInfo resultInfo) {
  3108             boolean isPolymorhicSignature =
  3109                 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
  3110             return isPolymorhicSignature ?
  3111                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3112                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3115         Type checkSigPolyMethodId(JCTree tree,
  3116                      Type site,
  3117                      Symbol sym,
  3118                      Env<AttrContext> env,
  3119                      ResultInfo resultInfo) {
  3120             //recover original symbol for signature polymorphic methods
  3121             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3122             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3123             return sym.type;
  3126         Type checkMethodIdInternal(JCTree tree,
  3127                      Type site,
  3128                      Symbol sym,
  3129                      Env<AttrContext> env,
  3130                      ResultInfo resultInfo) {
  3131             Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3132             Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3133             resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3134             return owntype;
  3137         Type checkIdInternal(JCTree tree,
  3138                      Type site,
  3139                      Symbol sym,
  3140                      Type pt,
  3141                      Env<AttrContext> env,
  3142                      ResultInfo resultInfo) {
  3143             if (pt.isErroneous()) {
  3144                 return types.createErrorType(site);
  3146             Type owntype; // The computed type of this identifier occurrence.
  3147             switch (sym.kind) {
  3148             case TYP:
  3149                 // For types, the computed type equals the symbol's type,
  3150                 // except for two situations:
  3151                 owntype = sym.type;
  3152                 if (owntype.hasTag(CLASS)) {
  3153                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3154                     Type ownOuter = owntype.getEnclosingType();
  3156                     // (a) If the symbol's type is parameterized, erase it
  3157                     // because no type parameters were given.
  3158                     // We recover generic outer type later in visitTypeApply.
  3159                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3160                         owntype = types.erasure(owntype);
  3163                     // (b) If the symbol's type is an inner class, then
  3164                     // we have to interpret its outer type as a superclass
  3165                     // of the site type. Example:
  3166                     //
  3167                     // class Tree<A> { class Visitor { ... } }
  3168                     // class PointTree extends Tree<Point> { ... }
  3169                     // ...PointTree.Visitor...
  3170                     //
  3171                     // Then the type of the last expression above is
  3172                     // Tree<Point>.Visitor.
  3173                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3174                         Type normOuter = site;
  3175                         if (normOuter.hasTag(CLASS))
  3176                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3177                         if (normOuter == null) // perhaps from an import
  3178                             normOuter = types.erasure(ownOuter);
  3179                         if (normOuter != ownOuter)
  3180                             owntype = new ClassType(
  3181                                 normOuter, List.<Type>nil(), owntype.tsym);
  3184                 break;
  3185             case VAR:
  3186                 VarSymbol v = (VarSymbol)sym;
  3187                 // Test (4): if symbol is an instance field of a raw type,
  3188                 // which is being assigned to, issue an unchecked warning if
  3189                 // its type changes under erasure.
  3190                 if (allowGenerics &&
  3191                     resultInfo.pkind == VAR &&
  3192                     v.owner.kind == TYP &&
  3193                     (v.flags() & STATIC) == 0 &&
  3194                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3195                     Type s = types.asOuterSuper(site, v.owner);
  3196                     if (s != null &&
  3197                         s.isRaw() &&
  3198                         !types.isSameType(v.type, v.erasure(types))) {
  3199                         chk.warnUnchecked(tree.pos(),
  3200                                           "unchecked.assign.to.var",
  3201                                           v, s);
  3204                 // The computed type of a variable is the type of the
  3205                 // variable symbol, taken as a member of the site type.
  3206                 owntype = (sym.owner.kind == TYP &&
  3207                            sym.name != names._this && sym.name != names._super)
  3208                     ? types.memberType(site, sym)
  3209                     : sym.type;
  3211                 // If the variable is a constant, record constant value in
  3212                 // computed type.
  3213                 if (v.getConstValue() != null && isStaticReference(tree))
  3214                     owntype = owntype.constType(v.getConstValue());
  3216                 if (resultInfo.pkind == VAL) {
  3217                     owntype = capture(owntype); // capture "names as expressions"
  3219                 break;
  3220             case MTH: {
  3221                 owntype = checkMethod(site, sym,
  3222                         new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3223                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3224                         resultInfo.pt.getTypeArguments());
  3225                 break;
  3227             case PCK: case ERR:
  3228                 owntype = sym.type;
  3229                 break;
  3230             default:
  3231                 throw new AssertionError("unexpected kind: " + sym.kind +
  3232                                          " in tree " + tree);
  3235             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3236             // (for constructors, the error was given when the constructor was
  3237             // resolved)
  3239             if (sym.name != names.init) {
  3240                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3241                 chk.checkSunAPI(tree.pos(), sym);
  3244             // Test (3): if symbol is a variable, check that its type and
  3245             // kind are compatible with the prototype and protokind.
  3246             return check(tree, owntype, sym.kind, resultInfo);
  3249         /** Check that variable is initialized and evaluate the variable's
  3250          *  initializer, if not yet done. Also check that variable is not
  3251          *  referenced before it is defined.
  3252          *  @param tree    The tree making up the variable reference.
  3253          *  @param env     The current environment.
  3254          *  @param v       The variable's symbol.
  3255          */
  3256         private void checkInit(JCTree tree,
  3257                                Env<AttrContext> env,
  3258                                VarSymbol v,
  3259                                boolean onlyWarning) {
  3260 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3261 //                             tree.pos + " " + v.pos + " " +
  3262 //                             Resolve.isStatic(env));//DEBUG
  3264             // A forward reference is diagnosed if the declaration position
  3265             // of the variable is greater than the current tree position
  3266             // and the tree and variable definition occur in the same class
  3267             // definition.  Note that writes don't count as references.
  3268             // This check applies only to class and instance
  3269             // variables.  Local variables follow different scope rules,
  3270             // and are subject to definite assignment checking.
  3271             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3272                 v.owner.kind == TYP &&
  3273                 canOwnInitializer(owner(env)) &&
  3274                 v.owner == env.info.scope.owner.enclClass() &&
  3275                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3276                 (!env.tree.hasTag(ASSIGN) ||
  3277                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3278                 String suffix = (env.info.enclVar == v) ?
  3279                                 "self.ref" : "forward.ref";
  3280                 if (!onlyWarning || isStaticEnumField(v)) {
  3281                     log.error(tree.pos(), "illegal." + suffix);
  3282                 } else if (useBeforeDeclarationWarning) {
  3283                     log.warning(tree.pos(), suffix, v);
  3287             v.getConstValue(); // ensure initializer is evaluated
  3289             checkEnumInitializer(tree, env, v);
  3292         /**
  3293          * Check for illegal references to static members of enum.  In
  3294          * an enum type, constructors and initializers may not
  3295          * reference its static members unless they are constant.
  3297          * @param tree    The tree making up the variable reference.
  3298          * @param env     The current environment.
  3299          * @param v       The variable's symbol.
  3300          * @jls  section 8.9 Enums
  3301          */
  3302         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3303             // JLS:
  3304             //
  3305             // "It is a compile-time error to reference a static field
  3306             // of an enum type that is not a compile-time constant
  3307             // (15.28) from constructors, instance initializer blocks,
  3308             // or instance variable initializer expressions of that
  3309             // type. It is a compile-time error for the constructors,
  3310             // instance initializer blocks, or instance variable
  3311             // initializer expressions of an enum constant e to refer
  3312             // to itself or to an enum constant of the same type that
  3313             // is declared to the right of e."
  3314             if (isStaticEnumField(v)) {
  3315                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3317                 if (enclClass == null || enclClass.owner == null)
  3318                     return;
  3320                 // See if the enclosing class is the enum (or a
  3321                 // subclass thereof) declaring v.  If not, this
  3322                 // reference is OK.
  3323                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3324                     return;
  3326                 // If the reference isn't from an initializer, then
  3327                 // the reference is OK.
  3328                 if (!Resolve.isInitializer(env))
  3329                     return;
  3331                 log.error(tree.pos(), "illegal.enum.static.ref");
  3335         /** Is the given symbol a static, non-constant field of an Enum?
  3336          *  Note: enum literals should not be regarded as such
  3337          */
  3338         private boolean isStaticEnumField(VarSymbol v) {
  3339             return Flags.isEnum(v.owner) &&
  3340                    Flags.isStatic(v) &&
  3341                    !Flags.isConstant(v) &&
  3342                    v.name != names._class;
  3345         /** Can the given symbol be the owner of code which forms part
  3346          *  if class initialization? This is the case if the symbol is
  3347          *  a type or field, or if the symbol is the synthetic method.
  3348          *  owning a block.
  3349          */
  3350         private boolean canOwnInitializer(Symbol sym) {
  3351             return
  3352                 (sym.kind & (VAR | TYP)) != 0 ||
  3353                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3356     Warner noteWarner = new Warner();
  3358     /**
  3359      * Check that method arguments conform to its instantiation.
  3360      **/
  3361     public Type checkMethod(Type site,
  3362                             Symbol sym,
  3363                             ResultInfo resultInfo,
  3364                             Env<AttrContext> env,
  3365                             final List<JCExpression> argtrees,
  3366                             List<Type> argtypes,
  3367                             List<Type> typeargtypes) {
  3368         // Test (5): if symbol is an instance method of a raw type, issue
  3369         // an unchecked warning if its argument types change under erasure.
  3370         if (allowGenerics &&
  3371             (sym.flags() & STATIC) == 0 &&
  3372             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3373             Type s = types.asOuterSuper(site, sym.owner);
  3374             if (s != null && s.isRaw() &&
  3375                 !types.isSameTypes(sym.type.getParameterTypes(),
  3376                                    sym.erasure(types).getParameterTypes())) {
  3377                 chk.warnUnchecked(env.tree.pos(),
  3378                                   "unchecked.call.mbr.of.raw.type",
  3379                                   sym, s);
  3383         if (env.info.defaultSuperCallSite != null) {
  3384             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3385                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3386                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3387                 List<MethodSymbol> icand_sup =
  3388                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3389                 if (icand_sup.nonEmpty() &&
  3390                         icand_sup.head != sym &&
  3391                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3392                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3393                         diags.fragment("overridden.default", sym, sup));
  3394                     break;
  3397             env.info.defaultSuperCallSite = null;
  3400         // Compute the identifier's instantiated type.
  3401         // For methods, we need to compute the instance type by
  3402         // Resolve.instantiate from the symbol's type as well as
  3403         // any type arguments and value arguments.
  3404         noteWarner.clear();
  3405         try {
  3406             Type owntype = rs.checkMethod(
  3407                     env,
  3408                     site,
  3409                     sym,
  3410                     resultInfo,
  3411                     argtypes,
  3412                     typeargtypes,
  3413                     noteWarner);
  3415             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3416                     noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
  3417         } catch (Infer.InferenceException ex) {
  3418             //invalid target type - propagate exception outwards or report error
  3419             //depending on the current check context
  3420             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3421             return types.createErrorType(site);
  3422         } catch (Resolve.InapplicableMethodException ex) {
  3423             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
  3424             return null;
  3428     public void visitLiteral(JCLiteral tree) {
  3429         result = check(
  3430             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3432     //where
  3433     /** Return the type of a literal with given type tag.
  3434      */
  3435     Type litType(TypeTag tag) {
  3436         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3439     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3440         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3443     public void visitTypeArray(JCArrayTypeTree tree) {
  3444         Type etype = attribType(tree.elemtype, env);
  3445         Type type = new ArrayType(etype, syms.arrayClass);
  3446         result = check(tree, type, TYP, resultInfo);
  3449     /** Visitor method for parameterized types.
  3450      *  Bound checking is left until later, since types are attributed
  3451      *  before supertype structure is completely known
  3452      */
  3453     public void visitTypeApply(JCTypeApply tree) {
  3454         Type owntype = types.createErrorType(tree.type);
  3456         // Attribute functor part of application and make sure it's a class.
  3457         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3459         // Attribute type parameters
  3460         List<Type> actuals = attribTypes(tree.arguments, env);
  3462         if (clazztype.hasTag(CLASS)) {
  3463             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3464             if (actuals.isEmpty()) //diamond
  3465                 actuals = formals;
  3467             if (actuals.length() == formals.length()) {
  3468                 List<Type> a = actuals;
  3469                 List<Type> f = formals;
  3470                 while (a.nonEmpty()) {
  3471                     a.head = a.head.withTypeVar(f.head);
  3472                     a = a.tail;
  3473                     f = f.tail;
  3475                 // Compute the proper generic outer
  3476                 Type clazzOuter = clazztype.getEnclosingType();
  3477                 if (clazzOuter.hasTag(CLASS)) {
  3478                     Type site;
  3479                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3480                     if (clazz.hasTag(IDENT)) {
  3481                         site = env.enclClass.sym.type;
  3482                     } else if (clazz.hasTag(SELECT)) {
  3483                         site = ((JCFieldAccess) clazz).selected.type;
  3484                     } else throw new AssertionError(""+tree);
  3485                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3486                         if (site.hasTag(CLASS))
  3487                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3488                         if (site == null)
  3489                             site = types.erasure(clazzOuter);
  3490                         clazzOuter = site;
  3493                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3494             } else {
  3495                 if (formals.length() != 0) {
  3496                     log.error(tree.pos(), "wrong.number.type.args",
  3497                               Integer.toString(formals.length()));
  3498                 } else {
  3499                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3501                 owntype = types.createErrorType(tree.type);
  3504         result = check(tree, owntype, TYP, resultInfo);
  3507     public void visitTypeUnion(JCTypeUnion tree) {
  3508         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  3509         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3510         for (JCExpression typeTree : tree.alternatives) {
  3511             Type ctype = attribType(typeTree, env);
  3512             ctype = chk.checkType(typeTree.pos(),
  3513                           chk.checkClassType(typeTree.pos(), ctype),
  3514                           syms.throwableType);
  3515             if (!ctype.isErroneous()) {
  3516                 //check that alternatives of a union type are pairwise
  3517                 //unrelated w.r.t. subtyping
  3518                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3519                     for (Type t : multicatchTypes) {
  3520                         boolean sub = types.isSubtype(ctype, t);
  3521                         boolean sup = types.isSubtype(t, ctype);
  3522                         if (sub || sup) {
  3523                             //assume 'a' <: 'b'
  3524                             Type a = sub ? ctype : t;
  3525                             Type b = sub ? t : ctype;
  3526                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3530                 multicatchTypes.append(ctype);
  3531                 if (all_multicatchTypes != null)
  3532                     all_multicatchTypes.append(ctype);
  3533             } else {
  3534                 if (all_multicatchTypes == null) {
  3535                     all_multicatchTypes = ListBuffer.lb();
  3536                     all_multicatchTypes.appendList(multicatchTypes);
  3538                 all_multicatchTypes.append(ctype);
  3541         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3542         if (t.hasTag(CLASS)) {
  3543             List<Type> alternatives =
  3544                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3545             t = new UnionClassType((ClassType) t, alternatives);
  3547         tree.type = result = t;
  3550     public void visitTypeParameter(JCTypeParameter tree) {
  3551         TypeVar a = (TypeVar)tree.type;
  3552         Set<Type> boundSet = new HashSet<Type>();
  3553         if (a.bound.isErroneous())
  3554             return;
  3555         List<Type> bs = types.getBounds(a);
  3556         if (tree.bounds.nonEmpty()) {
  3557             // accept class or interface or typevar as first bound.
  3558             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  3559             boundSet.add(types.erasure(b));
  3560             if (b.isErroneous()) {
  3561                 a.bound = b;
  3563             else if (b.hasTag(TYPEVAR)) {
  3564                 // if first bound was a typevar, do not accept further bounds.
  3565                 if (tree.bounds.tail.nonEmpty()) {
  3566                     log.error(tree.bounds.tail.head.pos(),
  3567                               "type.var.may.not.be.followed.by.other.bounds");
  3568                     tree.bounds = List.of(tree.bounds.head);
  3569                     a.bound = bs.head;
  3571             } else {
  3572                 // if first bound was a class or interface, accept only interfaces
  3573                 // as further bounds.
  3574                 for (JCExpression bound : tree.bounds.tail) {
  3575                     bs = bs.tail;
  3576                     Type i = checkBase(bs.head, bound, env, false, true, false);
  3577                     if (i.isErroneous())
  3578                         a.bound = i;
  3579                     else if (i.hasTag(CLASS))
  3580                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  3584         bs = types.getBounds(a);
  3586         // in case of multiple bounds ...
  3587         if (bs.length() > 1) {
  3588             // ... the variable's bound is a class type flagged COMPOUND
  3589             // (see comment for TypeVar.bound).
  3590             // In this case, generate a class tree that represents the
  3591             // bound class, ...
  3592             JCExpression extending;
  3593             List<JCExpression> implementing;
  3594             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  3595                 extending = tree.bounds.head;
  3596                 implementing = tree.bounds.tail;
  3597             } else {
  3598                 extending = null;
  3599                 implementing = tree.bounds;
  3601             JCClassDecl cd = make.at(tree.pos).ClassDef(
  3602                 make.Modifiers(PUBLIC | ABSTRACT),
  3603                 tree.name, List.<JCTypeParameter>nil(),
  3604                 extending, implementing, List.<JCTree>nil());
  3606             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  3607             Assert.check((c.flags() & COMPOUND) != 0);
  3608             cd.sym = c;
  3609             c.sourcefile = env.toplevel.sourcefile;
  3611             // ... and attribute the bound class
  3612             c.flags_field |= UNATTRIBUTED;
  3613             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3614             enter.typeEnvs.put(c, cenv);
  3619     public void visitWildcard(JCWildcard tree) {
  3620         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3621         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3622             ? syms.objectType
  3623             : attribType(tree.inner, env);
  3624         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3625                                               tree.kind.kind,
  3626                                               syms.boundClass),
  3627                        TYP, resultInfo);
  3630     public void visitAnnotation(JCAnnotation tree) {
  3631         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  3632         result = tree.type = syms.errType;
  3635     public void visitErroneous(JCErroneous tree) {
  3636         if (tree.errs != null)
  3637             for (JCTree err : tree.errs)
  3638                 attribTree(err, env, new ResultInfo(ERR, pt()));
  3639         result = tree.type = syms.errType;
  3642     /** Default visitor method for all other trees.
  3643      */
  3644     public void visitTree(JCTree tree) {
  3645         throw new AssertionError();
  3648     /**
  3649      * Attribute an env for either a top level tree or class declaration.
  3650      */
  3651     public void attrib(Env<AttrContext> env) {
  3652         if (env.tree.hasTag(TOPLEVEL))
  3653             attribTopLevel(env);
  3654         else
  3655             attribClass(env.tree.pos(), env.enclClass.sym);
  3658     /**
  3659      * Attribute a top level tree. These trees are encountered when the
  3660      * package declaration has annotations.
  3661      */
  3662     public void attribTopLevel(Env<AttrContext> env) {
  3663         JCCompilationUnit toplevel = env.toplevel;
  3664         try {
  3665             annotate.flush();
  3666             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  3667         } catch (CompletionFailure ex) {
  3668             chk.completionError(toplevel.pos(), ex);
  3672     /** Main method: attribute class definition associated with given class symbol.
  3673      *  reporting completion failures at the given position.
  3674      *  @param pos The source position at which completion errors are to be
  3675      *             reported.
  3676      *  @param c   The class symbol whose definition will be attributed.
  3677      */
  3678     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3679         try {
  3680             annotate.flush();
  3681             attribClass(c);
  3682         } catch (CompletionFailure ex) {
  3683             chk.completionError(pos, ex);
  3687     /** Attribute class definition associated with given class symbol.
  3688      *  @param c   The class symbol whose definition will be attributed.
  3689      */
  3690     void attribClass(ClassSymbol c) throws CompletionFailure {
  3691         if (c.type.hasTag(ERROR)) return;
  3693         // Check for cycles in the inheritance graph, which can arise from
  3694         // ill-formed class files.
  3695         chk.checkNonCyclic(null, c.type);
  3697         Type st = types.supertype(c.type);
  3698         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3699             // First, attribute superclass.
  3700             if (st.hasTag(CLASS))
  3701                 attribClass((ClassSymbol)st.tsym);
  3703             // Next attribute owner, if it is a class.
  3704             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  3705                 attribClass((ClassSymbol)c.owner);
  3708         // The previous operations might have attributed the current class
  3709         // if there was a cycle. So we test first whether the class is still
  3710         // UNATTRIBUTED.
  3711         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3712             c.flags_field &= ~UNATTRIBUTED;
  3714             // Get environment current at the point of class definition.
  3715             Env<AttrContext> env = enter.typeEnvs.get(c);
  3717             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3718             // because the annotations were not available at the time the env was created. Therefore,
  3719             // we look up the environment chain for the first enclosing environment for which the
  3720             // lint value is set. Typically, this is the parent env, but might be further if there
  3721             // are any envs created as a result of TypeParameter nodes.
  3722             Env<AttrContext> lintEnv = env;
  3723             while (lintEnv.info.lint == null)
  3724                 lintEnv = lintEnv.next;
  3726             // Having found the enclosing lint value, we can initialize the lint value for this class
  3727             env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
  3729             Lint prevLint = chk.setLint(env.info.lint);
  3730             JavaFileObject prev = log.useSource(c.sourcefile);
  3731             ResultInfo prevReturnRes = env.info.returnResult;
  3733             try {
  3734                 env.info.returnResult = null;
  3735                 // java.lang.Enum may not be subclassed by a non-enum
  3736                 if (st.tsym == syms.enumSym &&
  3737                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3738                     log.error(env.tree.pos(), "enum.no.subclassing");
  3740                 // Enums may not be extended by source-level classes
  3741                 if (st.tsym != null &&
  3742                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3743                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3744                     !target.compilerBootstrap(c)) {
  3745                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3747                 attribClassBody(env, c);
  3749                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3750             } finally {
  3751                 env.info.returnResult = prevReturnRes;
  3752                 log.useSource(prev);
  3753                 chk.setLint(prevLint);
  3759     public void visitImport(JCImport tree) {
  3760         // nothing to do
  3763     /** Finish the attribution of a class. */
  3764     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3765         JCClassDecl tree = (JCClassDecl)env.tree;
  3766         Assert.check(c == tree.sym);
  3768         // Validate annotations
  3769         chk.validateAnnotations(tree.mods.annotations, c);
  3771         // Validate type parameters, supertype and interfaces.
  3772         attribBounds(tree.typarams);
  3773         if (!c.isAnonymous()) {
  3774             //already checked if anonymous
  3775             chk.validate(tree.typarams, env);
  3776             chk.validate(tree.extending, env);
  3777             chk.validate(tree.implementing, env);
  3780         // If this is a non-abstract class, check that it has no abstract
  3781         // methods or unimplemented methods of an implemented interface.
  3782         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3783             if (!relax)
  3784                 chk.checkAllDefined(tree.pos(), c);
  3787         if ((c.flags() & ANNOTATION) != 0) {
  3788             if (tree.implementing.nonEmpty())
  3789                 log.error(tree.implementing.head.pos(),
  3790                           "cant.extend.intf.annotation");
  3791             if (tree.typarams.nonEmpty())
  3792                 log.error(tree.typarams.head.pos(),
  3793                           "intf.annotation.cant.have.type.params");
  3795             // If this annotation has a @ContainedBy, validate
  3796             Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym);
  3797             if (containedBy != null) {
  3798                 // get diagnositc position for error reporting
  3799                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type);
  3800                 Assert.checkNonNull(cbPos);
  3802                 chk.validateContainedBy(c, containedBy, cbPos);
  3805             // If this annotation has a @ContainerFor, validate
  3806             Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym);
  3807             if (containerFor != null) {
  3808                 // get diagnositc position for error reporting
  3809                 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type);
  3810                 Assert.checkNonNull(cfPos);
  3812                 chk.validateContainerFor(c, containerFor, cfPos);
  3814         } else {
  3815             // Check that all extended classes and interfaces
  3816             // are compatible (i.e. no two define methods with same arguments
  3817             // yet different return types).  (JLS 8.4.6.3)
  3818             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3819             if (allowDefaultMethods) {
  3820                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  3824         // Check that class does not import the same parameterized interface
  3825         // with two different argument lists.
  3826         chk.checkClassBounds(tree.pos(), c.type);
  3828         tree.type = c.type;
  3830         for (List<JCTypeParameter> l = tree.typarams;
  3831              l.nonEmpty(); l = l.tail) {
  3832              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3835         // Check that a generic class doesn't extend Throwable
  3836         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3837             log.error(tree.extending.pos(), "generic.throwable");
  3839         // Check that all methods which implement some
  3840         // method conform to the method they implement.
  3841         chk.checkImplementations(tree);
  3843         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  3844         checkAutoCloseable(tree.pos(), env, c.type);
  3846         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3847             // Attribute declaration
  3848             attribStat(l.head, env);
  3849             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3850             // Make an exception for static constants.
  3851             if (c.owner.kind != PCK &&
  3852                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3853                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3854                 Symbol sym = null;
  3855                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  3856                 if (sym == null ||
  3857                     sym.kind != VAR ||
  3858                     ((VarSymbol) sym).getConstValue() == null)
  3859                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3863         // Check for cycles among non-initial constructors.
  3864         chk.checkCyclicConstructors(tree);
  3866         // Check for cycles among annotation elements.
  3867         chk.checkNonCyclicElements(tree);
  3869         // Check for proper use of serialVersionUID
  3870         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3871             isSerializable(c) &&
  3872             (c.flags() & Flags.ENUM) == 0 &&
  3873             (c.flags() & ABSTRACT) == 0) {
  3874             checkSerialVersionUID(tree, c);
  3877         // where
  3878         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  3879         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  3880             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  3881                 if (types.isSameType(al.head.annotationType.type, t))
  3882                     return al.head.pos();
  3885             return null;
  3888         /** check if a class is a subtype of Serializable, if that is available. */
  3889         private boolean isSerializable(ClassSymbol c) {
  3890             try {
  3891                 syms.serializableType.complete();
  3893             catch (CompletionFailure e) {
  3894                 return false;
  3896             return types.isSubtype(c.type, syms.serializableType);
  3899         /** Check that an appropriate serialVersionUID member is defined. */
  3900         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3902             // check for presence of serialVersionUID
  3903             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3904             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3905             if (e.scope == null) {
  3906                 log.warning(LintCategory.SERIAL,
  3907                         tree.pos(), "missing.SVUID", c);
  3908                 return;
  3911             // check that it is static final
  3912             VarSymbol svuid = (VarSymbol)e.sym;
  3913             if ((svuid.flags() & (STATIC | FINAL)) !=
  3914                 (STATIC | FINAL))
  3915                 log.warning(LintCategory.SERIAL,
  3916                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3918             // check that it is long
  3919             else if (!svuid.type.hasTag(LONG))
  3920                 log.warning(LintCategory.SERIAL,
  3921                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3923             // check constant
  3924             else if (svuid.getConstValue() == null)
  3925                 log.warning(LintCategory.SERIAL,
  3926                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3929     private Type capture(Type type) {
  3930         return types.capture(type);
  3933     // <editor-fold desc="post-attribution visitor">
  3935     /**
  3936      * Handle missing types/symbols in an AST. This routine is useful when
  3937      * the compiler has encountered some errors (which might have ended up
  3938      * terminating attribution abruptly); if the compiler is used in fail-over
  3939      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3940      * prevents NPE to be progagated during subsequent compilation steps.
  3941      */
  3942     public void postAttr(JCTree tree) {
  3943         new PostAttrAnalyzer().scan(tree);
  3946     class PostAttrAnalyzer extends TreeScanner {
  3948         private void initTypeIfNeeded(JCTree that) {
  3949             if (that.type == null) {
  3950                 that.type = syms.unknownType;
  3954         @Override
  3955         public void scan(JCTree tree) {
  3956             if (tree == null) return;
  3957             if (tree instanceof JCExpression) {
  3958                 initTypeIfNeeded(tree);
  3960             super.scan(tree);
  3963         @Override
  3964         public void visitIdent(JCIdent that) {
  3965             if (that.sym == null) {
  3966                 that.sym = syms.unknownSymbol;
  3970         @Override
  3971         public void visitSelect(JCFieldAccess that) {
  3972             if (that.sym == null) {
  3973                 that.sym = syms.unknownSymbol;
  3975             super.visitSelect(that);
  3978         @Override
  3979         public void visitClassDef(JCClassDecl that) {
  3980             initTypeIfNeeded(that);
  3981             if (that.sym == null) {
  3982                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3984             super.visitClassDef(that);
  3987         @Override
  3988         public void visitMethodDef(JCMethodDecl that) {
  3989             initTypeIfNeeded(that);
  3990             if (that.sym == null) {
  3991                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3993             super.visitMethodDef(that);
  3996         @Override
  3997         public void visitVarDef(JCVariableDecl that) {
  3998             initTypeIfNeeded(that);
  3999             if (that.sym == null) {
  4000                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4001                 that.sym.adr = 0;
  4003             super.visitVarDef(that);
  4006         @Override
  4007         public void visitNewClass(JCNewClass that) {
  4008             if (that.constructor == null) {
  4009                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  4011             if (that.constructorType == null) {
  4012                 that.constructorType = syms.unknownType;
  4014             super.visitNewClass(that);
  4017         @Override
  4018         public void visitAssignop(JCAssignOp that) {
  4019             if (that.operator == null)
  4020                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4021             super.visitAssignop(that);
  4024         @Override
  4025         public void visitBinary(JCBinary that) {
  4026             if (that.operator == null)
  4027                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4028             super.visitBinary(that);
  4031         @Override
  4032         public void visitUnary(JCUnary that) {
  4033             if (that.operator == null)
  4034                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4035             super.visitUnary(that);
  4038         @Override
  4039         public void visitReference(JCMemberReference that) {
  4040             super.visitReference(that);
  4041             if (that.sym == null) {
  4042                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  4046     // </editor-fold>

mercurial