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

Tue, 30 Oct 2012 10:15:19 -0700

author
jjg
date
Tue, 30 Oct 2012 10:15:19 -0700
changeset 1381
23fe1a96bc0f
parent 1374
c002fdee76fd
child 1384
bf54daa9dcd8
permissions
-rw-r--r--

8001929: fix doclint errors in langtools doc comments
Reviewed-by: darcy

     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() && options.isSet("allowPoly");
   137         allowLambda = source.allowLambda();
   138         sourceName = source.name;
   139         relax = (options.isSet("-retrofit") ||
   140                  options.isSet("-relax"));
   141         findDiamonds = options.get("findDiamond") != null &&
   142                  source.allowDiamond();
   143         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   144         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   146         statInfo = new ResultInfo(NIL, Type.noType);
   147         varInfo = new ResultInfo(VAR, Type.noType);
   148         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   149         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   150         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   151     }
   153     /** Switch: relax some constraints for retrofit mode.
   154      */
   155     boolean relax;
   157     /** Switch: support target-typing inference
   158      */
   159     boolean allowPoly;
   161     /** Switch: support generics?
   162      */
   163     boolean allowGenerics;
   165     /** Switch: allow variable-arity methods.
   166      */
   167     boolean allowVarargs;
   169     /** Switch: support enums?
   170      */
   171     boolean allowEnums;
   173     /** Switch: support boxing and unboxing?
   174      */
   175     boolean allowBoxing;
   177     /** Switch: support covariant result types?
   178      */
   179     boolean allowCovariantReturns;
   181     /** Switch: support lambda expressions ?
   182      */
   183     boolean allowLambda;
   185     /** Switch: allow references to surrounding object from anonymous
   186      * objects during constructor call?
   187      */
   188     boolean allowAnonOuterThis;
   190     /** Switch: generates a warning if diamond can be safely applied
   191      *  to a given new expression
   192      */
   193     boolean findDiamonds;
   195     /**
   196      * Internally enables/disables diamond finder feature
   197      */
   198     static final boolean allowDiamondFinder = true;
   200     /**
   201      * Switch: warn about use of variable before declaration?
   202      * RFE: 6425594
   203      */
   204     boolean useBeforeDeclarationWarning;
   206     /**
   207      * Switch: generate warnings whenever an anonymous inner class that is convertible
   208      * to a lambda expression is found
   209      */
   210     boolean identifyLambdaCandidate;
   212     /**
   213      * Switch: allow strings in switch?
   214      */
   215     boolean allowStringsInSwitch;
   217     /**
   218      * Switch: name of source level; used for error reporting.
   219      */
   220     String sourceName;
   222     /** Check kind and type of given tree against protokind and prototype.
   223      *  If check succeeds, store type in tree and return it.
   224      *  If check fails, store errType in tree and return it.
   225      *  No checks are performed if the prototype is a method type.
   226      *  It is not necessary in this case since we know that kind and type
   227      *  are correct.
   228      *
   229      *  @param tree     The tree whose kind and type is checked
   230      *  @param ownkind  The computed kind of the tree
   231      *  @param resultInfo  The expected result of the tree
   232      */
   233     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   234         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   235         Type owntype = found;
   236         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   237             if (inferenceContext.free(found)) {
   238                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   239                     @Override
   240                     public void typesInferred(InferenceContext inferenceContext) {
   241                         ResultInfo pendingResult =
   242                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt, types));
   243                         check(tree, inferenceContext.asInstType(found, types), ownkind, pendingResult);
   244                     }
   245                 });
   246                 return tree.type = resultInfo.pt;
   247             } else {
   248                 if ((ownkind & ~resultInfo.pkind) == 0) {
   249                     owntype = resultInfo.check(tree, owntype);
   250                 } else {
   251                     log.error(tree.pos(), "unexpected.type",
   252                             kindNames(resultInfo.pkind),
   253                             kindName(ownkind));
   254                     owntype = types.createErrorType(owntype);
   255                 }
   256             }
   257         }
   258         tree.type = owntype;
   259         return owntype;
   260     }
   262     /** Is given blank final variable assignable, i.e. in a scope where it
   263      *  may be assigned to even though it is final?
   264      *  @param v      The blank final variable.
   265      *  @param env    The current environment.
   266      */
   267     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   268         Symbol owner = owner(env);
   269            // owner refers to the innermost variable, method or
   270            // initializer block declaration at this point.
   271         return
   272             v.owner == owner
   273             ||
   274             ((owner.name == names.init ||    // i.e. we are in a constructor
   275               owner.kind == VAR ||           // i.e. we are in a variable initializer
   276               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   277              &&
   278              v.owner == owner.owner
   279              &&
   280              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   281     }
   283     /**
   284      * Return the innermost enclosing owner symbol in a given attribution context
   285      */
   286     Symbol owner(Env<AttrContext> env) {
   287         while (true) {
   288             switch (env.tree.getTag()) {
   289                 case VARDEF:
   290                     //a field can be owner
   291                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   292                     if (vsym.owner.kind == TYP) {
   293                         return vsym;
   294                     }
   295                     break;
   296                 case METHODDEF:
   297                     //method def is always an owner
   298                     return ((JCMethodDecl)env.tree).sym;
   299                 case CLASSDEF:
   300                     //class def is always an owner
   301                     return ((JCClassDecl)env.tree).sym;
   302                 case LAMBDA:
   303                     //a lambda is an owner - return a fresh synthetic method symbol
   304                     return new MethodSymbol(0, names.empty, null, syms.methodClass);
   305                 case BLOCK:
   306                     //static/instance init blocks are owner
   307                     Symbol blockSym = env.info.scope.owner;
   308                     if ((blockSym.flags() & BLOCK) != 0) {
   309                         return blockSym;
   310                     }
   311                     break;
   312                 case TOPLEVEL:
   313                     //toplevel is always an owner (for pkge decls)
   314                     return env.info.scope.owner;
   315             }
   316             Assert.checkNonNull(env.next);
   317             env = env.next;
   318         }
   319     }
   321     /** Check that variable can be assigned to.
   322      *  @param pos    The current source code position.
   323      *  @param v      The assigned varaible
   324      *  @param base   If the variable is referred to in a Select, the part
   325      *                to the left of the `.', null otherwise.
   326      *  @param env    The current environment.
   327      */
   328     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   329         if ((v.flags() & FINAL) != 0 &&
   330             ((v.flags() & HASINIT) != 0
   331              ||
   332              !((base == null ||
   333                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   334                isAssignableAsBlankFinal(v, env)))) {
   335             if (v.isResourceVariable()) { //TWR resource
   336                 log.error(pos, "try.resource.may.not.be.assigned", v);
   337             } else {
   338                 log.error(pos, "cant.assign.val.to.final.var", v);
   339             }
   340         }
   341     }
   343     /** Does tree represent a static reference to an identifier?
   344      *  It is assumed that tree is either a SELECT or an IDENT.
   345      *  We have to weed out selects from non-type names here.
   346      *  @param tree    The candidate tree.
   347      */
   348     boolean isStaticReference(JCTree tree) {
   349         if (tree.hasTag(SELECT)) {
   350             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   351             if (lsym == null || lsym.kind != TYP) {
   352                 return false;
   353             }
   354         }
   355         return true;
   356     }
   358     /** Is this symbol a type?
   359      */
   360     static boolean isType(Symbol sym) {
   361         return sym != null && sym.kind == TYP;
   362     }
   364     /** The current `this' symbol.
   365      *  @param env    The current environment.
   366      */
   367     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   368         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   369     }
   371     /** Attribute a parsed identifier.
   372      * @param tree Parsed identifier name
   373      * @param topLevel The toplevel to use
   374      */
   375     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   376         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   377         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   378                                            syms.errSymbol.name,
   379                                            null, null, null, null);
   380         localEnv.enclClass.sym = syms.errSymbol;
   381         return tree.accept(identAttributer, localEnv);
   382     }
   383     // where
   384         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   385         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   386             @Override
   387             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   388                 Symbol site = visit(node.getExpression(), env);
   389                 if (site.kind == ERR)
   390                     return site;
   391                 Name name = (Name)node.getIdentifier();
   392                 if (site.kind == PCK) {
   393                     env.toplevel.packge = (PackageSymbol)site;
   394                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   395                 } else {
   396                     env.enclClass.sym = (ClassSymbol)site;
   397                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   398                 }
   399             }
   401             @Override
   402             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   403                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   404             }
   405         }
   407     public Type coerce(Type etype, Type ttype) {
   408         return cfolder.coerce(etype, ttype);
   409     }
   411     public Type attribType(JCTree node, TypeSymbol sym) {
   412         Env<AttrContext> env = enter.typeEnvs.get(sym);
   413         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   414         return attribTree(node, localEnv, unknownTypeInfo);
   415     }
   417     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   418         // Attribute qualifying package or class.
   419         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   420         return attribTree(s.selected,
   421                        env,
   422                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   423                        Type.noType));
   424     }
   426     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   427         breakTree = tree;
   428         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   429         try {
   430             attribExpr(expr, env);
   431         } catch (BreakAttr b) {
   432             return b.env;
   433         } catch (AssertionError ae) {
   434             if (ae.getCause() instanceof BreakAttr) {
   435                 return ((BreakAttr)(ae.getCause())).env;
   436             } else {
   437                 throw ae;
   438             }
   439         } finally {
   440             breakTree = null;
   441             log.useSource(prev);
   442         }
   443         return env;
   444     }
   446     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   447         breakTree = tree;
   448         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   449         try {
   450             attribStat(stmt, env);
   451         } catch (BreakAttr b) {
   452             return b.env;
   453         } catch (AssertionError ae) {
   454             if (ae.getCause() instanceof BreakAttr) {
   455                 return ((BreakAttr)(ae.getCause())).env;
   456             } else {
   457                 throw ae;
   458             }
   459         } finally {
   460             breakTree = null;
   461             log.useSource(prev);
   462         }
   463         return env;
   464     }
   466     private JCTree breakTree = null;
   468     private static class BreakAttr extends RuntimeException {
   469         static final long serialVersionUID = -6924771130405446405L;
   470         private Env<AttrContext> env;
   471         private BreakAttr(Env<AttrContext> env) {
   472             this.env = copyEnv(env);
   473         }
   475         private Env<AttrContext> copyEnv(Env<AttrContext> env) {
   476             Env<AttrContext> newEnv =
   477                     env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   478             if (newEnv.outer != null) {
   479                 newEnv.outer = copyEnv(newEnv.outer);
   480             }
   481             return newEnv;
   482         }
   484         private Scope copyScope(Scope sc) {
   485             Scope newScope = new Scope(sc.owner);
   486             List<Symbol> elemsList = List.nil();
   487             while (sc != null) {
   488                 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   489                     elemsList = elemsList.prepend(e.sym);
   490                 }
   491                 sc = sc.next;
   492             }
   493             for (Symbol s : elemsList) {
   494                 newScope.enter(s);
   495             }
   496             return newScope;
   497         }
   498     }
   500     class ResultInfo {
   501         final int pkind;
   502         final Type pt;
   503         final CheckContext checkContext;
   505         ResultInfo(int pkind, Type pt) {
   506             this(pkind, pt, chk.basicHandler);
   507         }
   509         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   510             this.pkind = pkind;
   511             this.pt = pt;
   512             this.checkContext = checkContext;
   513         }
   515         protected Type check(final DiagnosticPosition pos, final Type found) {
   516             return chk.checkType(pos, found, pt, checkContext);
   517         }
   519         protected ResultInfo dup(Type newPt) {
   520             return new ResultInfo(pkind, newPt, checkContext);
   521         }
   522     }
   524     class RecoveryInfo extends ResultInfo {
   526         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   527             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   528                 @Override
   529                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   530                     return deferredAttrContext;
   531                 }
   532                 @Override
   533                 public boolean compatible(Type found, Type req, Warner warn) {
   534                     return true;
   535                 }
   536                 @Override
   537                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   538                     //do nothing
   539                 }
   540             });
   541         }
   543         @Override
   544         protected Type check(DiagnosticPosition pos, Type found) {
   545             return chk.checkNonVoid(pos, super.check(pos, found));
   546         }
   547     }
   549     final ResultInfo statInfo;
   550     final ResultInfo varInfo;
   551     final ResultInfo unknownExprInfo;
   552     final ResultInfo unknownTypeInfo;
   553     final ResultInfo recoveryInfo;
   555     Type pt() {
   556         return resultInfo.pt;
   557     }
   559     int pkind() {
   560         return resultInfo.pkind;
   561     }
   563 /* ************************************************************************
   564  * Visitor methods
   565  *************************************************************************/
   567     /** Visitor argument: the current environment.
   568      */
   569     Env<AttrContext> env;
   571     /** Visitor argument: the currently expected attribution result.
   572      */
   573     ResultInfo resultInfo;
   575     /** Visitor result: the computed type.
   576      */
   577     Type result;
   579     /** Visitor method: attribute a tree, catching any completion failure
   580      *  exceptions. Return the tree's type.
   581      *
   582      *  @param tree    The tree to be visited.
   583      *  @param env     The environment visitor argument.
   584      *  @param resultInfo   The result info visitor argument.
   585      */
   586     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   587         Env<AttrContext> prevEnv = this.env;
   588         ResultInfo prevResult = this.resultInfo;
   589         try {
   590             this.env = env;
   591             this.resultInfo = resultInfo;
   592             tree.accept(this);
   593             if (tree == breakTree)
   594                 throw new BreakAttr(env);
   595             return result;
   596         } catch (CompletionFailure ex) {
   597             tree.type = syms.errType;
   598             return chk.completionError(tree.pos(), ex);
   599         } finally {
   600             this.env = prevEnv;
   601             this.resultInfo = prevResult;
   602         }
   603     }
   605     /** Derived visitor method: attribute an expression tree.
   606      */
   607     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   608         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   609     }
   611     /** Derived visitor method: attribute an expression tree with
   612      *  no constraints on the computed type.
   613      */
   614     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   615         return attribTree(tree, env, unknownExprInfo);
   616     }
   618     /** Derived visitor method: attribute a type tree.
   619      */
   620     Type attribType(JCTree tree, Env<AttrContext> env) {
   621         Type result = attribType(tree, env, Type.noType);
   622         return result;
   623     }
   625     /** Derived visitor method: attribute a type tree.
   626      */
   627     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   628         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   629         return result;
   630     }
   632     /** Derived visitor method: attribute a statement or definition tree.
   633      */
   634     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   635         return attribTree(tree, env, statInfo);
   636     }
   638     /** Attribute a list of expressions, returning a list of types.
   639      */
   640     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   641         ListBuffer<Type> ts = new ListBuffer<Type>();
   642         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   643             ts.append(attribExpr(l.head, env, pt));
   644         return ts.toList();
   645     }
   647     /** Attribute a list of statements, returning nothing.
   648      */
   649     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   650         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   651             attribStat(l.head, env);
   652     }
   654     /** Attribute the arguments in a method call, returning a list of types.
   655      */
   656     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   657         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   658         for (JCExpression arg : trees) {
   659             Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ?
   660                     deferredAttr.new DeferredType(arg, env) :
   661                     chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
   662             argtypes.append(argtype);
   663         }
   664         return argtypes.toList();
   665     }
   667     /** Attribute a type argument list, returning a list of types.
   668      *  Caller is responsible for calling checkRefTypes.
   669      */
   670     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   671         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   672         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   673             argtypes.append(attribType(l.head, env));
   674         return argtypes.toList();
   675     }
   677     /** Attribute a type argument list, returning a list of types.
   678      *  Check that all the types are references.
   679      */
   680     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   681         List<Type> types = attribAnyTypes(trees, env);
   682         return chk.checkRefTypes(trees, types);
   683     }
   685     /**
   686      * Attribute type variables (of generic classes or methods).
   687      * Compound types are attributed later in attribBounds.
   688      * @param typarams the type variables to enter
   689      * @param env      the current environment
   690      */
   691     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   692         for (JCTypeParameter tvar : typarams) {
   693             TypeVar a = (TypeVar)tvar.type;
   694             a.tsym.flags_field |= UNATTRIBUTED;
   695             a.bound = Type.noType;
   696             if (!tvar.bounds.isEmpty()) {
   697                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   698                 for (JCExpression bound : tvar.bounds.tail)
   699                     bounds = bounds.prepend(attribType(bound, env));
   700                 types.setBounds(a, bounds.reverse());
   701             } else {
   702                 // if no bounds are given, assume a single bound of
   703                 // java.lang.Object.
   704                 types.setBounds(a, List.of(syms.objectType));
   705             }
   706             a.tsym.flags_field &= ~UNATTRIBUTED;
   707         }
   708         for (JCTypeParameter tvar : typarams)
   709             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   710         attribStats(typarams, env);
   711     }
   713     void attribBounds(List<JCTypeParameter> typarams) {
   714         for (JCTypeParameter typaram : typarams) {
   715             Type bound = typaram.type.getUpperBound();
   716             if (bound != null && bound.tsym instanceof ClassSymbol) {
   717                 ClassSymbol c = (ClassSymbol)bound.tsym;
   718                 if ((c.flags_field & COMPOUND) != 0) {
   719                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   720                     attribClass(typaram.pos(), c);
   721                 }
   722             }
   723         }
   724     }
   726     /**
   727      * Attribute the type references in a list of annotations.
   728      */
   729     void attribAnnotationTypes(List<JCAnnotation> annotations,
   730                                Env<AttrContext> env) {
   731         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   732             JCAnnotation a = al.head;
   733             attribType(a.annotationType, env);
   734         }
   735     }
   737     /**
   738      * Attribute a "lazy constant value".
   739      *  @param env         The env for the const value
   740      *  @param initializer The initializer for the const value
   741      *  @param type        The expected type, or null
   742      *  @see VarSymbol#setLazyConstValue
   743      */
   744     public Object attribLazyConstantValue(Env<AttrContext> env,
   745                                       JCTree.JCExpression initializer,
   746                                       Type type) {
   748         // in case no lint value has been set up for this env, scan up
   749         // env stack looking for smallest enclosing env for which it is set.
   750         Env<AttrContext> lintEnv = env;
   751         while (lintEnv.info.lint == null)
   752             lintEnv = lintEnv.next;
   754         // Having found the enclosing lint value, we can initialize the lint value for this class
   755         // ... but ...
   756         // There's a problem with evaluating annotations in the right order, such that
   757         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   758         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   759         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   760         if (env.info.enclVar.annotations.pendingCompletion()) {
   761             env.info.lint = lintEnv.info.lint;
   762         } else {
   763             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
   764                                                       env.info.enclVar.flags());
   765         }
   767         Lint prevLint = chk.setLint(env.info.lint);
   768         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   770         try {
   771             Type itype = attribExpr(initializer, env, type);
   772             if (itype.constValue() != null)
   773                 return coerce(itype, type).constValue();
   774             else
   775                 return null;
   776         } finally {
   777             env.info.lint = prevLint;
   778             log.useSource(prevSource);
   779         }
   780     }
   782     /** Attribute type reference in an `extends' or `implements' clause.
   783      *  Supertypes of anonymous inner classes are usually already attributed.
   784      *
   785      *  @param tree              The tree making up the type reference.
   786      *  @param env               The environment current at the reference.
   787      *  @param classExpected     true if only a class is expected here.
   788      *  @param interfaceExpected true if only an interface is expected here.
   789      */
   790     Type attribBase(JCTree tree,
   791                     Env<AttrContext> env,
   792                     boolean classExpected,
   793                     boolean interfaceExpected,
   794                     boolean checkExtensible) {
   795         Type t = tree.type != null ?
   796             tree.type :
   797             attribType(tree, env);
   798         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   799     }
   800     Type checkBase(Type t,
   801                    JCTree tree,
   802                    Env<AttrContext> env,
   803                    boolean classExpected,
   804                    boolean interfaceExpected,
   805                    boolean checkExtensible) {
   806         if (t.isErroneous())
   807             return t;
   808         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   809             // check that type variable is already visible
   810             if (t.getUpperBound() == null) {
   811                 log.error(tree.pos(), "illegal.forward.ref");
   812                 return types.createErrorType(t);
   813             }
   814         } else {
   815             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   816         }
   817         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   818             log.error(tree.pos(), "intf.expected.here");
   819             // return errType is necessary since otherwise there might
   820             // be undetected cycles which cause attribution to loop
   821             return types.createErrorType(t);
   822         } else if (checkExtensible &&
   823                    classExpected &&
   824                    (t.tsym.flags() & INTERFACE) != 0) {
   825                 log.error(tree.pos(), "no.intf.expected.here");
   826             return types.createErrorType(t);
   827         }
   828         if (checkExtensible &&
   829             ((t.tsym.flags() & FINAL) != 0)) {
   830             log.error(tree.pos(),
   831                       "cant.inherit.from.final", t.tsym);
   832         }
   833         chk.checkNonCyclic(tree.pos(), t);
   834         return t;
   835     }
   837     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   838         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   839         id.type = env.info.scope.owner.type;
   840         id.sym = env.info.scope.owner;
   841         return id.type;
   842     }
   844     public void visitClassDef(JCClassDecl tree) {
   845         // Local classes have not been entered yet, so we need to do it now:
   846         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   847             enter.classEnter(tree, env);
   849         ClassSymbol c = tree.sym;
   850         if (c == null) {
   851             // exit in case something drastic went wrong during enter.
   852             result = null;
   853         } else {
   854             // make sure class has been completed:
   855             c.complete();
   857             // If this class appears as an anonymous class
   858             // in a superclass constructor call where
   859             // no explicit outer instance is given,
   860             // disable implicit outer instance from being passed.
   861             // (This would be an illegal access to "this before super").
   862             if (env.info.isSelfCall &&
   863                 env.tree.hasTag(NEWCLASS) &&
   864                 ((JCNewClass) env.tree).encl == null)
   865             {
   866                 c.flags_field |= NOOUTERTHIS;
   867             }
   868             attribClass(tree.pos(), c);
   869             result = tree.type = c.type;
   870         }
   871     }
   873     public void visitMethodDef(JCMethodDecl tree) {
   874         MethodSymbol m = tree.sym;
   875         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   877         Lint lint = env.info.lint.augment(m.annotations, m.flags());
   878         Lint prevLint = chk.setLint(lint);
   879         MethodSymbol prevMethod = chk.setMethod(m);
   880         try {
   881             deferredLintHandler.flush(tree.pos());
   882             chk.checkDeprecatedAnnotation(tree.pos(), m);
   884             attribBounds(tree.typarams);
   886             // If we override any other methods, check that we do so properly.
   887             // JLS ???
   888             if (m.isStatic()) {
   889                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   890             } else {
   891                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   892             }
   893             chk.checkOverride(tree, m);
   895             // Create a new environment with local scope
   896             // for attributing the method.
   897             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   899             localEnv.info.lint = lint;
   901             // Enter all type parameters into the local method scope.
   902             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   903                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   905             ClassSymbol owner = env.enclClass.sym;
   906             if ((owner.flags() & ANNOTATION) != 0 &&
   907                 tree.params.nonEmpty())
   908                 log.error(tree.params.head.pos(),
   909                           "intf.annotation.members.cant.have.params");
   911             // Attribute all value parameters.
   912             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   913                 attribStat(l.head, localEnv);
   914             }
   916             chk.checkVarargsMethodDecl(localEnv, tree);
   918             // Check that type parameters are well-formed.
   919             chk.validate(tree.typarams, localEnv);
   921             // Check that result type is well-formed.
   922             chk.validate(tree.restype, localEnv);
   924             // annotation method checks
   925             if ((owner.flags() & ANNOTATION) != 0) {
   926                 // annotation method cannot have throws clause
   927                 if (tree.thrown.nonEmpty()) {
   928                     log.error(tree.thrown.head.pos(),
   929                             "throws.not.allowed.in.intf.annotation");
   930                 }
   931                 // annotation method cannot declare type-parameters
   932                 if (tree.typarams.nonEmpty()) {
   933                     log.error(tree.typarams.head.pos(),
   934                             "intf.annotation.members.cant.have.type.params");
   935                 }
   936                 // validate annotation method's return type (could be an annotation type)
   937                 chk.validateAnnotationType(tree.restype);
   938                 // ensure that annotation method does not clash with members of Object/Annotation
   939                 chk.validateAnnotationMethod(tree.pos(), m);
   941                 if (tree.defaultValue != null) {
   942                     // if default value is an annotation, check it is a well-formed
   943                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   944                     chk.validateAnnotationTree(tree.defaultValue);
   945                 }
   946             }
   948             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   949                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   951             if (tree.body == null) {
   952                 // Empty bodies are only allowed for
   953                 // abstract, native, or interface methods, or for methods
   954                 // in a retrofit signature class.
   955                 if (isDefaultMethod || ((owner.flags() & INTERFACE) == 0 &&
   956                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0) &&
   957                     !relax)
   958                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   959                 if (tree.defaultValue != null) {
   960                     if ((owner.flags() & ANNOTATION) == 0)
   961                         log.error(tree.pos(),
   962                                   "default.allowed.in.intf.annotation.member");
   963                 }
   964             } else if ((owner.flags() & INTERFACE) != 0 && !isDefaultMethod) {
   965                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   966             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   967                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   968             } else if ((tree.mods.flags & NATIVE) != 0) {
   969                 log.error(tree.pos(), "native.meth.cant.have.body");
   970             } else {
   971                 // Add an implicit super() call unless an explicit call to
   972                 // super(...) or this(...) is given
   973                 // or we are compiling class java.lang.Object.
   974                 if (tree.name == names.init && owner.type != syms.objectType) {
   975                     JCBlock body = tree.body;
   976                     if (body.stats.isEmpty() ||
   977                         !TreeInfo.isSelfCall(body.stats.head)) {
   978                         body.stats = body.stats.
   979                             prepend(memberEnter.SuperCall(make.at(body.pos),
   980                                                           List.<Type>nil(),
   981                                                           List.<JCVariableDecl>nil(),
   982                                                           false));
   983                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   984                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   985                                TreeInfo.isSuperCall(body.stats.head)) {
   986                         // enum constructors are not allowed to call super
   987                         // directly, so make sure there aren't any super calls
   988                         // in enum constructors, except in the compiler
   989                         // generated one.
   990                         log.error(tree.body.stats.head.pos(),
   991                                   "call.to.super.not.allowed.in.enum.ctor",
   992                                   env.enclClass.sym);
   993                     }
   994                 }
   996                 // Attribute method body.
   997                 attribStat(tree.body, localEnv);
   998             }
   999             localEnv.info.scope.leave();
  1000             result = tree.type = m.type;
  1001             chk.validateAnnotations(tree.mods.annotations, m);
  1003         finally {
  1004             chk.setLint(prevLint);
  1005             chk.setMethod(prevMethod);
  1009     public void visitVarDef(JCVariableDecl tree) {
  1010         // Local variables have not been entered yet, so we need to do it now:
  1011         if (env.info.scope.owner.kind == MTH) {
  1012             if (tree.sym != null) {
  1013                 // parameters have already been entered
  1014                 env.info.scope.enter(tree.sym);
  1015             } else {
  1016                 memberEnter.memberEnter(tree, env);
  1017                 annotate.flush();
  1021         VarSymbol v = tree.sym;
  1022         Lint lint = env.info.lint.augment(v.annotations, v.flags());
  1023         Lint prevLint = chk.setLint(lint);
  1025         // Check that the variable's declared type is well-formed.
  1026         chk.validate(tree.vartype, env);
  1027         deferredLintHandler.flush(tree.pos());
  1029         try {
  1030             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1032             if (tree.init != null) {
  1033                 if ((v.flags_field & FINAL) != 0 &&
  1034                         !tree.init.hasTag(NEWCLASS) &&
  1035                         !tree.init.hasTag(LAMBDA) &&
  1036                         !tree.init.hasTag(REFERENCE)) {
  1037                     // In this case, `v' is final.  Ensure that it's initializer is
  1038                     // evaluated.
  1039                     v.getConstValue(); // ensure initializer is evaluated
  1040                 } else {
  1041                     // Attribute initializer in a new environment
  1042                     // with the declared variable as owner.
  1043                     // Check that initializer conforms to variable's declared type.
  1044                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1045                     initEnv.info.lint = lint;
  1046                     // In order to catch self-references, we set the variable's
  1047                     // declaration position to maximal possible value, effectively
  1048                     // marking the variable as undefined.
  1049                     initEnv.info.enclVar = v;
  1050                     attribExpr(tree.init, initEnv, v.type);
  1053             result = tree.type = v.type;
  1054             chk.validateAnnotations(tree.mods.annotations, v);
  1056         finally {
  1057             chk.setLint(prevLint);
  1061     public void visitSkip(JCSkip tree) {
  1062         result = null;
  1065     public void visitBlock(JCBlock tree) {
  1066         if (env.info.scope.owner.kind == TYP) {
  1067             // Block is a static or instance initializer;
  1068             // let the owner of the environment be a freshly
  1069             // created BLOCK-method.
  1070             Env<AttrContext> localEnv =
  1071                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1072             localEnv.info.scope.owner =
  1073                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
  1074                                  env.info.scope.owner);
  1075             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1076             attribStats(tree.stats, localEnv);
  1077         } else {
  1078             // Create a new local environment with a local scope.
  1079             Env<AttrContext> localEnv =
  1080                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1081             try {
  1082                 attribStats(tree.stats, localEnv);
  1083             } finally {
  1084                 localEnv.info.scope.leave();
  1087         result = null;
  1090     public void visitDoLoop(JCDoWhileLoop tree) {
  1091         attribStat(tree.body, env.dup(tree));
  1092         attribExpr(tree.cond, env, syms.booleanType);
  1093         result = null;
  1096     public void visitWhileLoop(JCWhileLoop tree) {
  1097         attribExpr(tree.cond, env, syms.booleanType);
  1098         attribStat(tree.body, env.dup(tree));
  1099         result = null;
  1102     public void visitForLoop(JCForLoop tree) {
  1103         Env<AttrContext> loopEnv =
  1104             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1105         try {
  1106             attribStats(tree.init, loopEnv);
  1107             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1108             loopEnv.tree = tree; // before, we were not in loop!
  1109             attribStats(tree.step, loopEnv);
  1110             attribStat(tree.body, loopEnv);
  1111             result = null;
  1113         finally {
  1114             loopEnv.info.scope.leave();
  1118     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1119         Env<AttrContext> loopEnv =
  1120             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1121         try {
  1122             attribStat(tree.var, loopEnv);
  1123             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1124             chk.checkNonVoid(tree.pos(), exprType);
  1125             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1126             if (elemtype == null) {
  1127                 // or perhaps expr implements Iterable<T>?
  1128                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1129                 if (base == null) {
  1130                     log.error(tree.expr.pos(),
  1131                             "foreach.not.applicable.to.type",
  1132                             exprType,
  1133                             diags.fragment("type.req.array.or.iterable"));
  1134                     elemtype = types.createErrorType(exprType);
  1135                 } else {
  1136                     List<Type> iterableParams = base.allparams();
  1137                     elemtype = iterableParams.isEmpty()
  1138                         ? syms.objectType
  1139                         : types.upperBound(iterableParams.head);
  1142             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1143             loopEnv.tree = tree; // before, we were not in loop!
  1144             attribStat(tree.body, loopEnv);
  1145             result = null;
  1147         finally {
  1148             loopEnv.info.scope.leave();
  1152     public void visitLabelled(JCLabeledStatement tree) {
  1153         // Check that label is not used in an enclosing statement
  1154         Env<AttrContext> env1 = env;
  1155         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1156             if (env1.tree.hasTag(LABELLED) &&
  1157                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1158                 log.error(tree.pos(), "label.already.in.use",
  1159                           tree.label);
  1160                 break;
  1162             env1 = env1.next;
  1165         attribStat(tree.body, env.dup(tree));
  1166         result = null;
  1169     public void visitSwitch(JCSwitch tree) {
  1170         Type seltype = attribExpr(tree.selector, env);
  1172         Env<AttrContext> switchEnv =
  1173             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1175         try {
  1177             boolean enumSwitch =
  1178                 allowEnums &&
  1179                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1180             boolean stringSwitch = false;
  1181             if (types.isSameType(seltype, syms.stringType)) {
  1182                 if (allowStringsInSwitch) {
  1183                     stringSwitch = true;
  1184                 } else {
  1185                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1188             if (!enumSwitch && !stringSwitch)
  1189                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1191             // Attribute all cases and
  1192             // check that there are no duplicate case labels or default clauses.
  1193             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1194             boolean hasDefault = false;      // Is there a default label?
  1195             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1196                 JCCase c = l.head;
  1197                 Env<AttrContext> caseEnv =
  1198                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1199                 try {
  1200                     if (c.pat != null) {
  1201                         if (enumSwitch) {
  1202                             Symbol sym = enumConstant(c.pat, seltype);
  1203                             if (sym == null) {
  1204                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1205                             } else if (!labels.add(sym)) {
  1206                                 log.error(c.pos(), "duplicate.case.label");
  1208                         } else {
  1209                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1210                             if (!pattype.hasTag(ERROR)) {
  1211                                 if (pattype.constValue() == null) {
  1212                                     log.error(c.pat.pos(),
  1213                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1214                                 } else if (labels.contains(pattype.constValue())) {
  1215                                     log.error(c.pos(), "duplicate.case.label");
  1216                                 } else {
  1217                                     labels.add(pattype.constValue());
  1221                     } else if (hasDefault) {
  1222                         log.error(c.pos(), "duplicate.default.label");
  1223                     } else {
  1224                         hasDefault = true;
  1226                     attribStats(c.stats, caseEnv);
  1227                 } finally {
  1228                     caseEnv.info.scope.leave();
  1229                     addVars(c.stats, switchEnv.info.scope);
  1233             result = null;
  1235         finally {
  1236             switchEnv.info.scope.leave();
  1239     // where
  1240         /** Add any variables defined in stats to the switch scope. */
  1241         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1242             for (;stats.nonEmpty(); stats = stats.tail) {
  1243                 JCTree stat = stats.head;
  1244                 if (stat.hasTag(VARDEF))
  1245                     switchScope.enter(((JCVariableDecl) stat).sym);
  1248     // where
  1249     /** Return the selected enumeration constant symbol, or null. */
  1250     private Symbol enumConstant(JCTree tree, Type enumType) {
  1251         if (!tree.hasTag(IDENT)) {
  1252             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1253             return syms.errSymbol;
  1255         JCIdent ident = (JCIdent)tree;
  1256         Name name = ident.name;
  1257         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1258              e.scope != null; e = e.next()) {
  1259             if (e.sym.kind == VAR) {
  1260                 Symbol s = ident.sym = e.sym;
  1261                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1262                 ident.type = s.type;
  1263                 return ((s.flags_field & Flags.ENUM) == 0)
  1264                     ? null : s;
  1267         return null;
  1270     public void visitSynchronized(JCSynchronized tree) {
  1271         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1272         attribStat(tree.body, env);
  1273         result = null;
  1276     public void visitTry(JCTry tree) {
  1277         // Create a new local environment with a local
  1278         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1279         try {
  1280             boolean isTryWithResource = tree.resources.nonEmpty();
  1281             // Create a nested environment for attributing the try block if needed
  1282             Env<AttrContext> tryEnv = isTryWithResource ?
  1283                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1284                 localEnv;
  1285             try {
  1286                 // Attribute resource declarations
  1287                 for (JCTree resource : tree.resources) {
  1288                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1289                         @Override
  1290                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1291                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1293                     };
  1294                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1295                     if (resource.hasTag(VARDEF)) {
  1296                         attribStat(resource, tryEnv);
  1297                         twrResult.check(resource, resource.type);
  1299                         //check that resource type cannot throw InterruptedException
  1300                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1302                         VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1303                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1304                     } else {
  1305                         attribTree(resource, tryEnv, twrResult);
  1308                 // Attribute body
  1309                 attribStat(tree.body, tryEnv);
  1310             } finally {
  1311                 if (isTryWithResource)
  1312                     tryEnv.info.scope.leave();
  1315             // Attribute catch clauses
  1316             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1317                 JCCatch c = l.head;
  1318                 Env<AttrContext> catchEnv =
  1319                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1320                 try {
  1321                     Type ctype = attribStat(c.param, catchEnv);
  1322                     if (TreeInfo.isMultiCatch(c)) {
  1323                         //multi-catch parameter is implicitly marked as final
  1324                         c.param.sym.flags_field |= FINAL | UNION;
  1326                     if (c.param.sym.kind == Kinds.VAR) {
  1327                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1329                     chk.checkType(c.param.vartype.pos(),
  1330                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1331                                   syms.throwableType);
  1332                     attribStat(c.body, catchEnv);
  1333                 } finally {
  1334                     catchEnv.info.scope.leave();
  1338             // Attribute finalizer
  1339             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1340             result = null;
  1342         finally {
  1343             localEnv.info.scope.leave();
  1347     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1348         if (!resource.isErroneous() &&
  1349             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1350             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1351             Symbol close = syms.noSymbol;
  1352             Filter<JCDiagnostic> prevDeferDiagsFilter = log.deferredDiagFilter;
  1353             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1354             try {
  1355                 log.deferAll();
  1356                 log.deferredDiagnostics = ListBuffer.lb();
  1357                 close = rs.resolveQualifiedMethod(pos,
  1358                         env,
  1359                         resource,
  1360                         names.close,
  1361                         List.<Type>nil(),
  1362                         List.<Type>nil());
  1364             finally {
  1365                 log.deferredDiagFilter = prevDeferDiagsFilter;
  1366                 log.deferredDiagnostics = prevDeferredDiags;
  1368             if (close.kind == MTH &&
  1369                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1370                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1371                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1372                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1377     public void visitConditional(JCConditional tree) {
  1378         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1380         boolean standaloneConditional = !allowPoly ||
  1381                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1382                 isBooleanOrNumeric(env, tree);
  1384         if (!standaloneConditional && resultInfo.pt.hasTag(VOID)) {
  1385             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1386             result = tree.type = types.createErrorType(resultInfo.pt);
  1387             return;
  1390         ResultInfo condInfo = standaloneConditional ?
  1391                 unknownExprInfo :
  1392                 new ResultInfo(VAL, pt(), new Check.NestedCheckContext(resultInfo.checkContext) {
  1393                     //this will use enclosing check context to check compatibility of
  1394                     //subexpression against target type; if we are in a method check context,
  1395                     //depending on whether boxing is allowed, we could have incompatibilities
  1396                     @Override
  1397                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1398                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1400                 });
  1402         Type truetype = attribTree(tree.truepart, env, condInfo);
  1403         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1405         Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt();
  1406         if (condtype.constValue() != null &&
  1407                 truetype.constValue() != null &&
  1408                 falsetype.constValue() != null) {
  1409             //constant folding
  1410             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1412         result = check(tree, owntype, VAL, resultInfo);
  1414     //where
  1415         @SuppressWarnings("fallthrough")
  1416         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1417             switch (tree.getTag()) {
  1418                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1419                               ((JCLiteral)tree).typetag == BOOLEAN;
  1420                 case LAMBDA: case REFERENCE: return false;
  1421                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1422                 case CONDEXPR:
  1423                     JCConditional condTree = (JCConditional)tree;
  1424                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1425                             isBooleanOrNumeric(env, condTree.falsepart);
  1426                 default:
  1427                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1428                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1429                     return speculativeType.isPrimitive();
  1433         /** Compute the type of a conditional expression, after
  1434          *  checking that it exists.  See JLS 15.25. Does not take into
  1435          *  account the special case where condition and both arms
  1436          *  are constants.
  1438          *  @param pos      The source position to be used for error
  1439          *                  diagnostics.
  1440          *  @param thentype The type of the expression's then-part.
  1441          *  @param elsetype The type of the expression's else-part.
  1442          */
  1443         private Type condType(DiagnosticPosition pos,
  1444                                Type thentype, Type elsetype) {
  1445             // If same type, that is the result
  1446             if (types.isSameType(thentype, elsetype))
  1447                 return thentype.baseType();
  1449             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1450                 ? thentype : types.unboxedType(thentype);
  1451             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1452                 ? elsetype : types.unboxedType(elsetype);
  1454             // Otherwise, if both arms can be converted to a numeric
  1455             // type, return the least numeric type that fits both arms
  1456             // (i.e. return larger of the two, or return int if one
  1457             // arm is short, the other is char).
  1458             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1459                 // If one arm has an integer subrange type (i.e., byte,
  1460                 // short, or char), and the other is an integer constant
  1461                 // that fits into the subrange, return the subrange type.
  1462                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
  1463                     types.isAssignable(elseUnboxed, thenUnboxed))
  1464                     return thenUnboxed.baseType();
  1465                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
  1466                     types.isAssignable(thenUnboxed, elseUnboxed))
  1467                     return elseUnboxed.baseType();
  1469                 for (TypeTag tag : TypeTag.values()) {
  1470                     if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
  1471                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1472                     if (candidate != null &&
  1473                         candidate.isPrimitive() &&
  1474                         types.isSubtype(thenUnboxed, candidate) &&
  1475                         types.isSubtype(elseUnboxed, candidate))
  1476                         return candidate;
  1480             // Those were all the cases that could result in a primitive
  1481             if (allowBoxing) {
  1482                 if (thentype.isPrimitive())
  1483                     thentype = types.boxedClass(thentype).type;
  1484                 if (elsetype.isPrimitive())
  1485                     elsetype = types.boxedClass(elsetype).type;
  1488             if (types.isSubtype(thentype, elsetype))
  1489                 return elsetype.baseType();
  1490             if (types.isSubtype(elsetype, thentype))
  1491                 return thentype.baseType();
  1493             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1494                 log.error(pos, "neither.conditional.subtype",
  1495                           thentype, elsetype);
  1496                 return thentype.baseType();
  1499             // both are known to be reference types.  The result is
  1500             // lub(thentype,elsetype). This cannot fail, as it will
  1501             // always be possible to infer "Object" if nothing better.
  1502             return types.lub(thentype.baseType(), elsetype.baseType());
  1505     public void visitIf(JCIf tree) {
  1506         attribExpr(tree.cond, env, syms.booleanType);
  1507         attribStat(tree.thenpart, env);
  1508         if (tree.elsepart != null)
  1509             attribStat(tree.elsepart, env);
  1510         chk.checkEmptyIf(tree);
  1511         result = null;
  1514     public void visitExec(JCExpressionStatement tree) {
  1515         //a fresh environment is required for 292 inference to work properly ---
  1516         //see Infer.instantiatePolymorphicSignatureInstance()
  1517         Env<AttrContext> localEnv = env.dup(tree);
  1518         attribExpr(tree.expr, localEnv);
  1519         result = null;
  1522     public void visitBreak(JCBreak tree) {
  1523         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1524         result = null;
  1527     public void visitContinue(JCContinue tree) {
  1528         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1529         result = null;
  1531     //where
  1532         /** Return the target of a break or continue statement, if it exists,
  1533          *  report an error if not.
  1534          *  Note: The target of a labelled break or continue is the
  1535          *  (non-labelled) statement tree referred to by the label,
  1536          *  not the tree representing the labelled statement itself.
  1538          *  @param pos     The position to be used for error diagnostics
  1539          *  @param tag     The tag of the jump statement. This is either
  1540          *                 Tree.BREAK or Tree.CONTINUE.
  1541          *  @param label   The label of the jump statement, or null if no
  1542          *                 label is given.
  1543          *  @param env     The environment current at the jump statement.
  1544          */
  1545         private JCTree findJumpTarget(DiagnosticPosition pos,
  1546                                     JCTree.Tag tag,
  1547                                     Name label,
  1548                                     Env<AttrContext> env) {
  1549             // Search environments outwards from the point of jump.
  1550             Env<AttrContext> env1 = env;
  1551             LOOP:
  1552             while (env1 != null) {
  1553                 switch (env1.tree.getTag()) {
  1554                     case LABELLED:
  1555                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1556                         if (label == labelled.label) {
  1557                             // If jump is a continue, check that target is a loop.
  1558                             if (tag == CONTINUE) {
  1559                                 if (!labelled.body.hasTag(DOLOOP) &&
  1560                                         !labelled.body.hasTag(WHILELOOP) &&
  1561                                         !labelled.body.hasTag(FORLOOP) &&
  1562                                         !labelled.body.hasTag(FOREACHLOOP))
  1563                                     log.error(pos, "not.loop.label", label);
  1564                                 // Found labelled statement target, now go inwards
  1565                                 // to next non-labelled tree.
  1566                                 return TreeInfo.referencedStatement(labelled);
  1567                             } else {
  1568                                 return labelled;
  1571                         break;
  1572                     case DOLOOP:
  1573                     case WHILELOOP:
  1574                     case FORLOOP:
  1575                     case FOREACHLOOP:
  1576                         if (label == null) return env1.tree;
  1577                         break;
  1578                     case SWITCH:
  1579                         if (label == null && tag == BREAK) return env1.tree;
  1580                         break;
  1581                     case LAMBDA:
  1582                     case METHODDEF:
  1583                     case CLASSDEF:
  1584                         break LOOP;
  1585                     default:
  1587                 env1 = env1.next;
  1589             if (label != null)
  1590                 log.error(pos, "undef.label", label);
  1591             else if (tag == CONTINUE)
  1592                 log.error(pos, "cont.outside.loop");
  1593             else
  1594                 log.error(pos, "break.outside.switch.loop");
  1595             return null;
  1598     public void visitReturn(JCReturn tree) {
  1599         // Check that there is an enclosing method which is
  1600         // nested within than the enclosing class.
  1601         if (env.info.returnResult == null) {
  1602             log.error(tree.pos(), "ret.outside.meth");
  1603         } else {
  1604             // Attribute return expression, if it exists, and check that
  1605             // it conforms to result type of enclosing method.
  1606             if (tree.expr != null) {
  1607                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1608                     log.error(tree.expr.pos(),
  1609                               "cant.ret.val.from.meth.decl.void");
  1611                 attribTree(tree.expr, env, env.info.returnResult);
  1612             } else if (!env.info.returnResult.pt.hasTag(VOID)) {
  1613                 log.error(tree.pos(), "missing.ret.val");
  1616         result = null;
  1619     public void visitThrow(JCThrow tree) {
  1620         attribExpr(tree.expr, env, syms.throwableType);
  1621         result = null;
  1624     public void visitAssert(JCAssert tree) {
  1625         attribExpr(tree.cond, env, syms.booleanType);
  1626         if (tree.detail != null) {
  1627             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1629         result = null;
  1632      /** Visitor method for method invocations.
  1633      *  NOTE: The method part of an application will have in its type field
  1634      *        the return type of the method, not the method's type itself!
  1635      */
  1636     public void visitApply(JCMethodInvocation tree) {
  1637         // The local environment of a method application is
  1638         // a new environment nested in the current one.
  1639         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1641         // The types of the actual method arguments.
  1642         List<Type> argtypes;
  1644         // The types of the actual method type arguments.
  1645         List<Type> typeargtypes = null;
  1647         Name methName = TreeInfo.name(tree.meth);
  1649         boolean isConstructorCall =
  1650             methName == names._this || methName == names._super;
  1652         if (isConstructorCall) {
  1653             // We are seeing a ...this(...) or ...super(...) call.
  1654             // Check that this is the first statement in a constructor.
  1655             if (checkFirstConstructorStat(tree, env)) {
  1657                 // Record the fact
  1658                 // that this is a constructor call (using isSelfCall).
  1659                 localEnv.info.isSelfCall = true;
  1661                 // Attribute arguments, yielding list of argument types.
  1662                 argtypes = attribArgs(tree.args, localEnv);
  1663                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1665                 // Variable `site' points to the class in which the called
  1666                 // constructor is defined.
  1667                 Type site = env.enclClass.sym.type;
  1668                 if (methName == names._super) {
  1669                     if (site == syms.objectType) {
  1670                         log.error(tree.meth.pos(), "no.superclass", site);
  1671                         site = types.createErrorType(syms.objectType);
  1672                     } else {
  1673                         site = types.supertype(site);
  1677                 if (site.hasTag(CLASS)) {
  1678                     Type encl = site.getEnclosingType();
  1679                     while (encl != null && encl.hasTag(TYPEVAR))
  1680                         encl = encl.getUpperBound();
  1681                     if (encl.hasTag(CLASS)) {
  1682                         // we are calling a nested class
  1684                         if (tree.meth.hasTag(SELECT)) {
  1685                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1687                             // We are seeing a prefixed call, of the form
  1688                             //     <expr>.super(...).
  1689                             // Check that the prefix expression conforms
  1690                             // to the outer instance type of the class.
  1691                             chk.checkRefType(qualifier.pos(),
  1692                                              attribExpr(qualifier, localEnv,
  1693                                                         encl));
  1694                         } else if (methName == names._super) {
  1695                             // qualifier omitted; check for existence
  1696                             // of an appropriate implicit qualifier.
  1697                             rs.resolveImplicitThis(tree.meth.pos(),
  1698                                                    localEnv, site, true);
  1700                     } else if (tree.meth.hasTag(SELECT)) {
  1701                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1702                                   site.tsym);
  1705                     // if we're calling a java.lang.Enum constructor,
  1706                     // prefix the implicit String and int parameters
  1707                     if (site.tsym == syms.enumSym && allowEnums)
  1708                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1710                     // Resolve the called constructor under the assumption
  1711                     // that we are referring to a superclass instance of the
  1712                     // current instance (JLS ???).
  1713                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1714                     localEnv.info.selectSuper = true;
  1715                     localEnv.info.pendingResolutionPhase = null;
  1716                     Symbol sym = rs.resolveConstructor(
  1717                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1718                     localEnv.info.selectSuper = selectSuperPrev;
  1720                     // Set method symbol to resolved constructor...
  1721                     TreeInfo.setSymbol(tree.meth, sym);
  1723                     // ...and check that it is legal in the current context.
  1724                     // (this will also set the tree's type)
  1725                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1726                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1728                 // Otherwise, `site' is an error type and we do nothing
  1730             result = tree.type = syms.voidType;
  1731         } else {
  1732             // Otherwise, we are seeing a regular method call.
  1733             // Attribute the arguments, yielding list of argument types, ...
  1734             argtypes = attribArgs(tree.args, localEnv);
  1735             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1737             // ... and attribute the method using as a prototype a methodtype
  1738             // whose formal argument types is exactly the list of actual
  1739             // arguments (this will also set the method symbol).
  1740             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1741             localEnv.info.pendingResolutionPhase = null;
  1742             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
  1744             // Compute the result type.
  1745             Type restype = mtype.getReturnType();
  1746             if (restype.hasTag(WILDCARD))
  1747                 throw new AssertionError(mtype);
  1749             Type qualifier = (tree.meth.hasTag(SELECT))
  1750                     ? ((JCFieldAccess) tree.meth).selected.type
  1751                     : env.enclClass.sym.type;
  1752             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1754             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1756             // Check that value of resulting type is admissible in the
  1757             // current context.  Also, capture the return type
  1758             result = check(tree, capture(restype), VAL, resultInfo);
  1760             if (localEnv.info.lastResolveVarargs())
  1761                 Assert.check(result.isErroneous() || tree.varargsElement != null);
  1763         chk.validate(tree.typeargs, localEnv);
  1765     //where
  1766         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1767             if (allowCovariantReturns &&
  1768                     methodName == names.clone &&
  1769                 types.isArray(qualifierType)) {
  1770                 // as a special case, array.clone() has a result that is
  1771                 // the same as static type of the array being cloned
  1772                 return qualifierType;
  1773             } else if (allowGenerics &&
  1774                     methodName == names.getClass &&
  1775                     argtypes.isEmpty()) {
  1776                 // as a special case, x.getClass() has type Class<? extends |X|>
  1777                 return new ClassType(restype.getEnclosingType(),
  1778                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1779                                                                BoundKind.EXTENDS,
  1780                                                                syms.boundClass)),
  1781                               restype.tsym);
  1782             } else {
  1783                 return restype;
  1787         /** Check that given application node appears as first statement
  1788          *  in a constructor call.
  1789          *  @param tree   The application node
  1790          *  @param env    The environment current at the application.
  1791          */
  1792         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1793             JCMethodDecl enclMethod = env.enclMethod;
  1794             if (enclMethod != null && enclMethod.name == names.init) {
  1795                 JCBlock body = enclMethod.body;
  1796                 if (body.stats.head.hasTag(EXEC) &&
  1797                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1798                     return true;
  1800             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1801                       TreeInfo.name(tree.meth));
  1802             return false;
  1805         /** Obtain a method type with given argument types.
  1806          */
  1807         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1808             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1809             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1812     public void visitNewClass(final JCNewClass tree) {
  1813         Type owntype = types.createErrorType(tree.type);
  1815         // The local environment of a class creation is
  1816         // a new environment nested in the current one.
  1817         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1819         // The anonymous inner class definition of the new expression,
  1820         // if one is defined by it.
  1821         JCClassDecl cdef = tree.def;
  1823         // If enclosing class is given, attribute it, and
  1824         // complete class name to be fully qualified
  1825         JCExpression clazz = tree.clazz; // Class field following new
  1826         JCExpression clazzid =          // Identifier in class field
  1827             (clazz.hasTag(TYPEAPPLY))
  1828             ? ((JCTypeApply) clazz).clazz
  1829             : clazz;
  1831         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1833         if (tree.encl != null) {
  1834             // We are seeing a qualified new, of the form
  1835             //    <expr>.new C <...> (...) ...
  1836             // In this case, we let clazz stand for the name of the
  1837             // allocated class C prefixed with the type of the qualifier
  1838             // expression, so that we can
  1839             // resolve it with standard techniques later. I.e., if
  1840             // <expr> has type T, then <expr>.new C <...> (...)
  1841             // yields a clazz T.C.
  1842             Type encltype = chk.checkRefType(tree.encl.pos(),
  1843                                              attribExpr(tree.encl, env));
  1844             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1845                                                  ((JCIdent) clazzid).name);
  1846             if (clazz.hasTag(TYPEAPPLY))
  1847                 clazz = make.at(tree.pos).
  1848                     TypeApply(clazzid1,
  1849                               ((JCTypeApply) clazz).arguments);
  1850             else
  1851                 clazz = clazzid1;
  1854         // Attribute clazz expression and store
  1855         // symbol + type back into the attributed tree.
  1856         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1857             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1858             attribType(clazz, env);
  1860         clazztype = chk.checkDiamond(tree, clazztype);
  1861         chk.validate(clazz, localEnv);
  1862         if (tree.encl != null) {
  1863             // We have to work in this case to store
  1864             // symbol + type back into the attributed tree.
  1865             tree.clazz.type = clazztype;
  1866             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1867             clazzid.type = ((JCIdent) clazzid).sym.type;
  1868             if (!clazztype.isErroneous()) {
  1869                 if (cdef != null && clazztype.tsym.isInterface()) {
  1870                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1871                 } else if (clazztype.tsym.isStatic()) {
  1872                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1875         } else if (!clazztype.tsym.isInterface() &&
  1876                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1877             // Check for the existence of an apropos outer instance
  1878             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1881         // Attribute constructor arguments.
  1882         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1883         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1885         // If we have made no mistakes in the class type...
  1886         if (clazztype.hasTag(CLASS)) {
  1887             // Enums may not be instantiated except implicitly
  1888             if (allowEnums &&
  1889                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1890                 (!env.tree.hasTag(VARDEF) ||
  1891                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1892                  ((JCVariableDecl) env.tree).init != tree))
  1893                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1894             // Check that class is not abstract
  1895             if (cdef == null &&
  1896                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1897                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1898                           clazztype.tsym);
  1899             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1900                 // Check that no constructor arguments are given to
  1901                 // anonymous classes implementing an interface
  1902                 if (!argtypes.isEmpty())
  1903                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1905                 if (!typeargtypes.isEmpty())
  1906                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1908                 // Error recovery: pretend no arguments were supplied.
  1909                 argtypes = List.nil();
  1910                 typeargtypes = List.nil();
  1911             } else if (TreeInfo.isDiamond(tree)) {
  1912                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  1913                             clazztype.tsym.type.getTypeArguments(),
  1914                             clazztype.tsym);
  1916                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  1917                 diamondEnv.info.selectSuper = cdef != null;
  1918                 diamondEnv.info.pendingResolutionPhase = null;
  1920                 //if the type of the instance creation expression is a class type
  1921                 //apply method resolution inference (JLS 15.12.2.7). The return type
  1922                 //of the resolved constructor will be a partially instantiated type
  1923                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  1924                             diamondEnv,
  1925                             site,
  1926                             argtypes,
  1927                             typeargtypes);
  1928                 tree.constructor = constructor.baseSymbol();
  1930                 final TypeSymbol csym = clazztype.tsym;
  1931                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  1932                     @Override
  1933                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  1934                         enclosingContext.report(tree.clazz,
  1935                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  1937                 });
  1938                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  1939                 constructorType = checkId(tree, site,
  1940                         constructor,
  1941                         diamondEnv,
  1942                         diamondResult);
  1944                 tree.clazz.type = types.createErrorType(clazztype);
  1945                 if (!constructorType.isErroneous()) {
  1946                     tree.clazz.type = clazztype = constructorType.getReturnType();
  1947                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  1949                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  1952             // Resolve the called constructor under the assumption
  1953             // that we are referring to a superclass instance of the
  1954             // current instance (JLS ???).
  1955             else {
  1956                 //the following code alters some of the fields in the current
  1957                 //AttrContext - hence, the current context must be dup'ed in
  1958                 //order to avoid downstream failures
  1959                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  1960                 rsEnv.info.selectSuper = cdef != null;
  1961                 rsEnv.info.pendingResolutionPhase = null;
  1962                 tree.constructor = rs.resolveConstructor(
  1963                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  1964                 if (cdef == null) { //do not check twice!
  1965                     tree.constructorType = checkId(tree,
  1966                             clazztype,
  1967                             tree.constructor,
  1968                             rsEnv,
  1969                             new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  1970                     if (rsEnv.info.lastResolveVarargs())
  1971                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1973                 findDiamondIfNeeded(localEnv, tree, clazztype);
  1976             if (cdef != null) {
  1977                 // We are seeing an anonymous class instance creation.
  1978                 // In this case, the class instance creation
  1979                 // expression
  1980                 //
  1981                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1982                 //
  1983                 // is represented internally as
  1984                 //
  1985                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1986                 //
  1987                 // This expression is then *transformed* as follows:
  1988                 //
  1989                 // (1) add a STATIC flag to the class definition
  1990                 //     if the current environment is static
  1991                 // (2) add an extends or implements clause
  1992                 // (3) add a constructor.
  1993                 //
  1994                 // For instance, if C is a class, and ET is the type of E,
  1995                 // the expression
  1996                 //
  1997                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1998                 //
  1999                 // is translated to (where X is a fresh name and typarams is the
  2000                 // parameter list of the super constructor):
  2001                 //
  2002                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2003                 //     X extends C<typargs2> {
  2004                 //       <typarams> X(ET e, args) {
  2005                 //         e.<typeargs1>super(args)
  2006                 //       }
  2007                 //       ...
  2008                 //     }
  2009                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2011                 if (clazztype.tsym.isInterface()) {
  2012                     cdef.implementing = List.of(clazz);
  2013                 } else {
  2014                     cdef.extending = clazz;
  2017                 attribStat(cdef, localEnv);
  2019                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2021                 // If an outer instance is given,
  2022                 // prefix it to the constructor arguments
  2023                 // and delete it from the new expression
  2024                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2025                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2026                     argtypes = argtypes.prepend(tree.encl.type);
  2027                     tree.encl = null;
  2030                 // Reassign clazztype and recompute constructor.
  2031                 clazztype = cdef.sym.type;
  2032                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2033                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2034                 Assert.check(sym.kind < AMBIGUOUS);
  2035                 tree.constructor = sym;
  2036                 tree.constructorType = checkId(tree,
  2037                     clazztype,
  2038                     tree.constructor,
  2039                     localEnv,
  2040                     new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2043             if (tree.constructor != null && tree.constructor.kind == MTH)
  2044                 owntype = clazztype;
  2046         result = check(tree, owntype, VAL, resultInfo);
  2047         chk.validate(tree.typeargs, localEnv);
  2049     //where
  2050         void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2051             if (tree.def == null &&
  2052                     !clazztype.isErroneous() &&
  2053                     clazztype.getTypeArguments().nonEmpty() &&
  2054                     findDiamonds) {
  2055                 JCTypeApply ta = (JCTypeApply)tree.clazz;
  2056                 List<JCExpression> prevTypeargs = ta.arguments;
  2057                 try {
  2058                     //create a 'fake' diamond AST node by removing type-argument trees
  2059                     ta.arguments = List.nil();
  2060                     ResultInfo findDiamondResult = new ResultInfo(VAL,
  2061                             resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2062                     Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2063                     if (!inferred.isErroneous() &&
  2064                         types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), Warner.noWarnings)) {
  2065                         String key = types.isSameType(clazztype, inferred) ?
  2066                             "diamond.redundant.args" :
  2067                             "diamond.redundant.args.1";
  2068                         log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2070                 } finally {
  2071                     ta.arguments = prevTypeargs;
  2076             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2077                 if (allowLambda &&
  2078                         identifyLambdaCandidate &&
  2079                         clazztype.hasTag(CLASS) &&
  2080                         !pt().hasTag(NONE) &&
  2081                         types.isFunctionalInterface(clazztype.tsym)) {
  2082                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2083                     int count = 0;
  2084                     boolean found = false;
  2085                     for (Symbol sym : csym.members().getElements()) {
  2086                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2087                                 sym.isConstructor()) continue;
  2088                         count++;
  2089                         if (sym.kind != MTH ||
  2090                                 !sym.name.equals(descriptor.name)) continue;
  2091                         Type mtype = types.memberType(clazztype, sym);
  2092                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2093                             found = true;
  2096                     if (found && count == 1) {
  2097                         log.note(tree.def, "potential.lambda.found");
  2102     /** Make an attributed null check tree.
  2103      */
  2104     public JCExpression makeNullCheck(JCExpression arg) {
  2105         // optimization: X.this is never null; skip null check
  2106         Name name = TreeInfo.name(arg);
  2107         if (name == names._this || name == names._super) return arg;
  2109         JCTree.Tag optag = NULLCHK;
  2110         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2111         tree.operator = syms.nullcheck;
  2112         tree.type = arg.type;
  2113         return tree;
  2116     public void visitNewArray(JCNewArray tree) {
  2117         Type owntype = types.createErrorType(tree.type);
  2118         Env<AttrContext> localEnv = env.dup(tree);
  2119         Type elemtype;
  2120         if (tree.elemtype != null) {
  2121             elemtype = attribType(tree.elemtype, localEnv);
  2122             chk.validate(tree.elemtype, localEnv);
  2123             owntype = elemtype;
  2124             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2125                 attribExpr(l.head, localEnv, syms.intType);
  2126                 owntype = new ArrayType(owntype, syms.arrayClass);
  2128         } else {
  2129             // we are seeing an untyped aggregate { ... }
  2130             // this is allowed only if the prototype is an array
  2131             if (pt().hasTag(ARRAY)) {
  2132                 elemtype = types.elemtype(pt());
  2133             } else {
  2134                 if (!pt().hasTag(ERROR)) {
  2135                     log.error(tree.pos(), "illegal.initializer.for.type",
  2136                               pt());
  2138                 elemtype = types.createErrorType(pt());
  2141         if (tree.elems != null) {
  2142             attribExprs(tree.elems, localEnv, elemtype);
  2143             owntype = new ArrayType(elemtype, syms.arrayClass);
  2145         if (!types.isReifiable(elemtype))
  2146             log.error(tree.pos(), "generic.array.creation");
  2147         result = check(tree, owntype, VAL, resultInfo);
  2150     /*
  2151      * A lambda expression can only be attributed when a target-type is available.
  2152      * In addition, if the target-type is that of a functional interface whose
  2153      * descriptor contains inference variables in argument position the lambda expression
  2154      * is 'stuck' (see DeferredAttr).
  2155      */
  2156     @Override
  2157     public void visitLambda(final JCLambda that) {
  2158         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2159             if (pt().hasTag(NONE)) {
  2160                 //lambda only allowed in assignment or method invocation/cast context
  2161                 log.error(that.pos(), "unexpected.lambda");
  2163             result = that.type = types.createErrorType(pt());
  2164             return;
  2166         //create an environment for attribution of the lambda expression
  2167         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2168         boolean needsRecovery = resultInfo.checkContext.deferredAttrContext() == deferredAttr.emptyDeferredAttrContext ||
  2169                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2170         try {
  2171             List<Type> explicitParamTypes = null;
  2172             if (TreeInfo.isExplicitLambda(that)) {
  2173                 //attribute lambda parameters
  2174                 attribStats(that.params, localEnv);
  2175                 explicitParamTypes = TreeInfo.types(that.params);
  2178             Type target = infer.instantiateFunctionalInterface(that, pt(), explicitParamTypes, resultInfo.checkContext);
  2179             Type lambdaType = (target == Type.recoveryType) ?
  2180                     fallbackDescriptorType(that) :
  2181                     types.findDescriptorType(target);
  2183             if (!TreeInfo.isExplicitLambda(that)) {
  2184                 //add param type info in the AST
  2185                 List<Type> actuals = lambdaType.getParameterTypes();
  2186                 List<JCVariableDecl> params = that.params;
  2188                 boolean arityMismatch = false;
  2190                 while (params.nonEmpty()) {
  2191                     if (actuals.isEmpty()) {
  2192                         //not enough actuals to perform lambda parameter inference
  2193                         arityMismatch = true;
  2195                     //reset previously set info
  2196                     Type argType = arityMismatch ?
  2197                             syms.errType :
  2198                             actuals.head;
  2199                     params.head.vartype = make.Type(argType);
  2200                     params.head.sym = null;
  2201                     actuals = actuals.isEmpty() ?
  2202                             actuals :
  2203                             actuals.tail;
  2204                     params = params.tail;
  2207                 //attribute lambda parameters
  2208                 attribStats(that.params, localEnv);
  2210                 if (arityMismatch) {
  2211                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2212                         result = that.type = types.createErrorType(target);
  2213                         return;
  2217             //from this point on, no recovery is needed; if we are in assignment context
  2218             //we will be able to attribute the whole lambda body, regardless of errors;
  2219             //if we are in a 'check' method context, and the lambda is not compatible
  2220             //with the target-type, it will be recovered anyway in Attr.checkId
  2221             needsRecovery = false;
  2223             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2224                 recoveryInfo :
  2225                 new ResultInfo(VAL, lambdaType.getReturnType(), new LambdaReturnContext(resultInfo.checkContext));
  2226             localEnv.info.returnResult = bodyResultInfo;
  2228             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2229                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2230             } else {
  2231                 JCBlock body = (JCBlock)that.body;
  2232                 attribStats(body.stats, localEnv);
  2235             result = check(that, target, VAL, resultInfo);
  2237             boolean isSpeculativeRound =
  2238                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2240             postAttr(that);
  2241             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2243             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
  2245             if (!isSpeculativeRound) {
  2246                 checkAccessibleFunctionalDescriptor(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType);
  2248             result = check(that, target, VAL, resultInfo);
  2249         } catch (Types.FunctionDescriptorLookupError ex) {
  2250             JCDiagnostic cause = ex.getDiagnostic();
  2251             resultInfo.checkContext.report(that, cause);
  2252             result = that.type = types.createErrorType(pt());
  2253             return;
  2254         } finally {
  2255             localEnv.info.scope.leave();
  2256             if (needsRecovery) {
  2257                 attribTree(that, env, recoveryInfo);
  2261     //where
  2262         private Type fallbackDescriptorType(JCExpression tree) {
  2263             switch (tree.getTag()) {
  2264                 case LAMBDA:
  2265                     JCLambda lambda = (JCLambda)tree;
  2266                     List<Type> argtypes = List.nil();
  2267                     for (JCVariableDecl param : lambda.params) {
  2268                         argtypes = param.vartype != null ?
  2269                                 argtypes.append(param.vartype.type) :
  2270                                 argtypes.append(syms.errType);
  2272                     return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
  2273                 case REFERENCE:
  2274                     return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
  2275                 default:
  2276                     Assert.error("Cannot get here!");
  2278             return null;
  2281         private void checkAccessibleFunctionalDescriptor(final DiagnosticPosition pos,
  2282                 final Env<AttrContext> env, final InferenceContext inferenceContext, final Type desc) {
  2283             if (inferenceContext.free(desc)) {
  2284                 inferenceContext.addFreeTypeListener(List.of(desc), new FreeTypeListener() {
  2285                     @Override
  2286                     public void typesInferred(InferenceContext inferenceContext) {
  2287                         checkAccessibleFunctionalDescriptor(pos, env, inferenceContext, inferenceContext.asInstType(desc, types));
  2289                 });
  2290             } else {
  2291                 chk.checkAccessibleFunctionalDescriptor(pos, env, desc);
  2295         /**
  2296          * Lambda/method reference have a special check context that ensures
  2297          * that i.e. a lambda return type is compatible with the expected
  2298          * type according to both the inherited context and the assignment
  2299          * context.
  2300          */
  2301         class LambdaReturnContext extends Check.NestedCheckContext {
  2302             public LambdaReturnContext(CheckContext enclosingContext) {
  2303                 super(enclosingContext);
  2306             @Override
  2307             public boolean compatible(Type found, Type req, Warner warn) {
  2308                 //return type must be compatible in both current context and assignment context
  2309                 return types.isAssignable(found, inferenceContext().asFree(req, types), warn) &&
  2310                         super.compatible(found, req, warn);
  2312             @Override
  2313             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2314                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2318         /**
  2319         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2320         * are compatible with the expected functional interface descriptor. This means that:
  2321         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2322         * types must be compatible with the return type of the expected descriptor;
  2323         * (iii) thrown types must be 'included' in the thrown types list of the expected
  2324         * descriptor.
  2325         */
  2326         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
  2327             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
  2329             //return values have already been checked - but if lambda has no return
  2330             //values, we must ensure that void/value compatibility is correct;
  2331             //this amounts at checking that, if a lambda body can complete normally,
  2332             //the descriptor's return type must be void
  2333             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2334                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2335                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2336                         diags.fragment("missing.ret.val", returnType)));
  2339             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
  2340             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2341                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2344             if (!speculativeAttr) {
  2345                 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
  2346                 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
  2347                     log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
  2352         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2353             Env<AttrContext> lambdaEnv;
  2354             Symbol owner = env.info.scope.owner;
  2355             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2356                 //field initializer
  2357                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2358                 lambdaEnv.info.scope.owner =
  2359                     new MethodSymbol(0, names.empty, null,
  2360                                      env.info.scope.owner);
  2361             } else {
  2362                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2364             return lambdaEnv;
  2367     @Override
  2368     public void visitReference(final JCMemberReference that) {
  2369         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2370             if (pt().hasTag(NONE)) {
  2371                 //method reference only allowed in assignment or method invocation/cast context
  2372                 log.error(that.pos(), "unexpected.mref");
  2374             result = that.type = types.createErrorType(pt());
  2375             return;
  2377         final Env<AttrContext> localEnv = env.dup(that);
  2378         try {
  2379             //attribute member reference qualifier - if this is a constructor
  2380             //reference, the expected kind must be a type
  2381             Type exprType = attribTree(that.expr,
  2382                     env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
  2384             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2385                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2388             if (exprType.isErroneous()) {
  2389                 //if the qualifier expression contains problems,
  2390                 //give up atttribution of method reference
  2391                 result = that.type = exprType;
  2392                 return;
  2395             if (TreeInfo.isStaticSelector(that.expr, names) &&
  2396                     (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
  2397                 //if the qualifier is a type, validate it
  2398                 chk.validate(that.expr, env);
  2401             //attrib type-arguments
  2402             List<Type> typeargtypes = null;
  2403             if (that.typeargs != null) {
  2404                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2407             Type target = infer.instantiateFunctionalInterface(that, pt(), null, resultInfo.checkContext);
  2408             Type desc = (target == Type.recoveryType) ?
  2409                     fallbackDescriptorType(that) :
  2410                     types.findDescriptorType(target);
  2412             List<Type> argtypes = desc.getParameterTypes();
  2414             boolean allowBoxing =
  2415                     resultInfo.checkContext.deferredAttrContext() == deferredAttr.emptyDeferredAttrContext ||
  2416                     resultInfo.checkContext.deferredAttrContext().phase.isBoxingRequired();
  2417             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
  2418                     that.expr.type, that.name, argtypes, typeargtypes, allowBoxing);
  2420             Symbol refSym = refResult.fst;
  2421             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2423             if (refSym.kind != MTH) {
  2424                 boolean targetError;
  2425                 switch (refSym.kind) {
  2426                     case ABSENT_MTH:
  2427                         targetError = false;
  2428                         break;
  2429                     case WRONG_MTH:
  2430                     case WRONG_MTHS:
  2431                     case AMBIGUOUS:
  2432                     case HIDDEN:
  2433                     case STATICERR:
  2434                     case MISSING_ENCL:
  2435                         targetError = true;
  2436                         break;
  2437                     default:
  2438                         Assert.error("unexpected result kind " + refSym.kind);
  2439                         targetError = false;
  2442                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2443                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2445                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2446                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2448                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2449                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2451                 if (targetError) {
  2452                     resultInfo.checkContext.report(that, diag);
  2453                 } else {
  2454                     log.report(diag);
  2456                 result = that.type = types.createErrorType(target);
  2457                 return;
  2460             if (desc.getReturnType() == Type.recoveryType) {
  2461                 // stop here
  2462                 result = that.type = types.createErrorType(target);
  2463                 return;
  2466             that.sym = refSym.baseSymbol();
  2467             that.kind = lookupHelper.referenceKind(that.sym);
  2469             ResultInfo checkInfo =
  2470                     resultInfo.dup(newMethodTemplate(
  2471                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2472                         lookupHelper.argtypes,
  2473                         typeargtypes));
  2475             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2477             if (!refType.isErroneous()) {
  2478                 refType = types.createMethodTypeWithReturn(refType,
  2479                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2482             //go ahead with standard method reference compatibility check - note that param check
  2483             //is a no-op (as this has been taken care during method applicability)
  2484             boolean isSpeculativeRound =
  2485                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2486             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2487             if (!isSpeculativeRound) {
  2488                 checkAccessibleFunctionalDescriptor(that, localEnv, resultInfo.checkContext.inferenceContext(), desc);
  2490             result = check(that, target, VAL, resultInfo);
  2491         } catch (Types.FunctionDescriptorLookupError ex) {
  2492             JCDiagnostic cause = ex.getDiagnostic();
  2493             resultInfo.checkContext.report(that, cause);
  2494             result = that.type = types.createErrorType(pt());
  2495             return;
  2499     @SuppressWarnings("fallthrough")
  2500     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2501         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
  2503         Type resType;
  2504         switch (tree.getMode()) {
  2505             case NEW:
  2506                 if (!tree.expr.type.isRaw()) {
  2507                     resType = tree.expr.type;
  2508                     break;
  2510             default:
  2511                 resType = refType.getReturnType();
  2514         Type incompatibleReturnType = resType;
  2516         if (returnType.hasTag(VOID)) {
  2517             incompatibleReturnType = null;
  2520         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2521             if (resType.isErroneous() ||
  2522                     new LambdaReturnContext(checkContext).compatible(resType, returnType, Warner.noWarnings)) {
  2523                 incompatibleReturnType = null;
  2527         if (incompatibleReturnType != null) {
  2528             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2529                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2532         if (!speculativeAttr) {
  2533             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
  2534             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2535                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2540     public void visitParens(JCParens tree) {
  2541         Type owntype = attribTree(tree.expr, env, resultInfo);
  2542         result = check(tree, owntype, pkind(), resultInfo);
  2543         Symbol sym = TreeInfo.symbol(tree);
  2544         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2545             log.error(tree.pos(), "illegal.start.of.type");
  2548     public void visitAssign(JCAssign tree) {
  2549         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2550         Type capturedType = capture(owntype);
  2551         attribExpr(tree.rhs, env, owntype);
  2552         result = check(tree, capturedType, VAL, resultInfo);
  2555     public void visitAssignop(JCAssignOp tree) {
  2556         // Attribute arguments.
  2557         Type owntype = attribTree(tree.lhs, env, varInfo);
  2558         Type operand = attribExpr(tree.rhs, env);
  2559         // Find operator.
  2560         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2561             tree.pos(), tree.getTag().noAssignOp(), env,
  2562             owntype, operand);
  2564         if (operator.kind == MTH &&
  2565                 !owntype.isErroneous() &&
  2566                 !operand.isErroneous()) {
  2567             chk.checkOperator(tree.pos(),
  2568                               (OperatorSymbol)operator,
  2569                               tree.getTag().noAssignOp(),
  2570                               owntype,
  2571                               operand);
  2572             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2573             chk.checkCastable(tree.rhs.pos(),
  2574                               operator.type.getReturnType(),
  2575                               owntype);
  2577         result = check(tree, owntype, VAL, resultInfo);
  2580     public void visitUnary(JCUnary tree) {
  2581         // Attribute arguments.
  2582         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2583             ? attribTree(tree.arg, env, varInfo)
  2584             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2586         // Find operator.
  2587         Symbol operator = tree.operator =
  2588             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2590         Type owntype = types.createErrorType(tree.type);
  2591         if (operator.kind == MTH &&
  2592                 !argtype.isErroneous()) {
  2593             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2594                 ? tree.arg.type
  2595                 : operator.type.getReturnType();
  2596             int opc = ((OperatorSymbol)operator).opcode;
  2598             // If the argument is constant, fold it.
  2599             if (argtype.constValue() != null) {
  2600                 Type ctype = cfolder.fold1(opc, argtype);
  2601                 if (ctype != null) {
  2602                     owntype = cfolder.coerce(ctype, owntype);
  2604                     // Remove constant types from arguments to
  2605                     // conserve space. The parser will fold concatenations
  2606                     // of string literals; the code here also
  2607                     // gets rid of intermediate results when some of the
  2608                     // operands are constant identifiers.
  2609                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2610                         tree.arg.type = syms.stringType;
  2615         result = check(tree, owntype, VAL, resultInfo);
  2618     public void visitBinary(JCBinary tree) {
  2619         // Attribute arguments.
  2620         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2621         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2623         // Find operator.
  2624         Symbol operator = tree.operator =
  2625             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2627         Type owntype = types.createErrorType(tree.type);
  2628         if (operator.kind == MTH &&
  2629                 !left.isErroneous() &&
  2630                 !right.isErroneous()) {
  2631             owntype = operator.type.getReturnType();
  2632             int opc = chk.checkOperator(tree.lhs.pos(),
  2633                                         (OperatorSymbol)operator,
  2634                                         tree.getTag(),
  2635                                         left,
  2636                                         right);
  2638             // If both arguments are constants, fold them.
  2639             if (left.constValue() != null && right.constValue() != null) {
  2640                 Type ctype = cfolder.fold2(opc, left, right);
  2641                 if (ctype != null) {
  2642                     owntype = cfolder.coerce(ctype, owntype);
  2644                     // Remove constant types from arguments to
  2645                     // conserve space. The parser will fold concatenations
  2646                     // of string literals; the code here also
  2647                     // gets rid of intermediate results when some of the
  2648                     // operands are constant identifiers.
  2649                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2650                         tree.lhs.type = syms.stringType;
  2652                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2653                         tree.rhs.type = syms.stringType;
  2658             // Check that argument types of a reference ==, != are
  2659             // castable to each other, (JLS???).
  2660             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2661                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2662                     log.error(tree.pos(), "incomparable.types", left, right);
  2666             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2668         result = check(tree, owntype, VAL, resultInfo);
  2671     public void visitTypeCast(final JCTypeCast tree) {
  2672         Type clazztype = attribType(tree.clazz, env);
  2673         chk.validate(tree.clazz, env, false);
  2674         //a fresh environment is required for 292 inference to work properly ---
  2675         //see Infer.instantiatePolymorphicSignatureInstance()
  2676         Env<AttrContext> localEnv = env.dup(tree);
  2677         //should we propagate the target type?
  2678         final ResultInfo castInfo;
  2679         final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
  2680         if (isPoly) {
  2681             //expression is a poly - we need to propagate target type info
  2682             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  2683                 @Override
  2684                 public boolean compatible(Type found, Type req, Warner warn) {
  2685                     return types.isCastable(found, req, warn);
  2687             });
  2688         } else {
  2689             //standalone cast - target-type info is not propagated
  2690             castInfo = unknownExprInfo;
  2692         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  2693         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2694         if (exprtype.constValue() != null)
  2695             owntype = cfolder.coerce(exprtype, owntype);
  2696         result = check(tree, capture(owntype), VAL, resultInfo);
  2697         if (!isPoly)
  2698             chk.checkRedundantCast(localEnv, tree);
  2701     public void visitTypeTest(JCInstanceOf tree) {
  2702         Type exprtype = chk.checkNullOrRefType(
  2703             tree.expr.pos(), attribExpr(tree.expr, env));
  2704         Type clazztype = chk.checkReifiableReferenceType(
  2705             tree.clazz.pos(), attribType(tree.clazz, env));
  2706         chk.validate(tree.clazz, env, false);
  2707         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2708         result = check(tree, syms.booleanType, VAL, resultInfo);
  2711     public void visitIndexed(JCArrayAccess tree) {
  2712         Type owntype = types.createErrorType(tree.type);
  2713         Type atype = attribExpr(tree.indexed, env);
  2714         attribExpr(tree.index, env, syms.intType);
  2715         if (types.isArray(atype))
  2716             owntype = types.elemtype(atype);
  2717         else if (!atype.hasTag(ERROR))
  2718             log.error(tree.pos(), "array.req.but.found", atype);
  2719         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  2720         result = check(tree, owntype, VAR, resultInfo);
  2723     public void visitIdent(JCIdent tree) {
  2724         Symbol sym;
  2726         // Find symbol
  2727         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  2728             // If we are looking for a method, the prototype `pt' will be a
  2729             // method type with the type of the call's arguments as parameters.
  2730             env.info.pendingResolutionPhase = null;
  2731             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  2732         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2733             sym = tree.sym;
  2734         } else {
  2735             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  2737         tree.sym = sym;
  2739         // (1) Also find the environment current for the class where
  2740         //     sym is defined (`symEnv').
  2741         // Only for pre-tiger versions (1.4 and earlier):
  2742         // (2) Also determine whether we access symbol out of an anonymous
  2743         //     class in a this or super call.  This is illegal for instance
  2744         //     members since such classes don't carry a this$n link.
  2745         //     (`noOuterThisPath').
  2746         Env<AttrContext> symEnv = env;
  2747         boolean noOuterThisPath = false;
  2748         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2749             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2750             sym.owner.kind == TYP &&
  2751             tree.name != names._this && tree.name != names._super) {
  2753             // Find environment in which identifier is defined.
  2754             while (symEnv.outer != null &&
  2755                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2756                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2757                     noOuterThisPath = !allowAnonOuterThis;
  2758                 symEnv = symEnv.outer;
  2762         // If symbol is a variable, ...
  2763         if (sym.kind == VAR) {
  2764             VarSymbol v = (VarSymbol)sym;
  2766             // ..., evaluate its initializer, if it has one, and check for
  2767             // illegal forward reference.
  2768             checkInit(tree, env, v, false);
  2770             // If we are expecting a variable (as opposed to a value), check
  2771             // that the variable is assignable in the current environment.
  2772             if (pkind() == VAR)
  2773                 checkAssignable(tree.pos(), v, null, env);
  2776         // In a constructor body,
  2777         // if symbol is a field or instance method, check that it is
  2778         // not accessed before the supertype constructor is called.
  2779         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2780             (sym.kind & (VAR | MTH)) != 0 &&
  2781             sym.owner.kind == TYP &&
  2782             (sym.flags() & STATIC) == 0) {
  2783             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2785         Env<AttrContext> env1 = env;
  2786         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2787             // If the found symbol is inaccessible, then it is
  2788             // accessed through an enclosing instance.  Locate this
  2789             // enclosing instance:
  2790             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2791                 env1 = env1.outer;
  2793         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  2796     public void visitSelect(JCFieldAccess tree) {
  2797         // Determine the expected kind of the qualifier expression.
  2798         int skind = 0;
  2799         if (tree.name == names._this || tree.name == names._super ||
  2800             tree.name == names._class)
  2802             skind = TYP;
  2803         } else {
  2804             if ((pkind() & PCK) != 0) skind = skind | PCK;
  2805             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  2806             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2809         // Attribute the qualifier expression, and determine its symbol (if any).
  2810         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  2811         if ((pkind() & (PCK | TYP)) == 0)
  2812             site = capture(site); // Capture field access
  2814         // don't allow T.class T[].class, etc
  2815         if (skind == TYP) {
  2816             Type elt = site;
  2817             while (elt.hasTag(ARRAY))
  2818                 elt = ((ArrayType)elt).elemtype;
  2819             if (elt.hasTag(TYPEVAR)) {
  2820                 log.error(tree.pos(), "type.var.cant.be.deref");
  2821                 result = types.createErrorType(tree.type);
  2822                 return;
  2826         // If qualifier symbol is a type or `super', assert `selectSuper'
  2827         // for the selection. This is relevant for determining whether
  2828         // protected symbols are accessible.
  2829         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2830         boolean selectSuperPrev = env.info.selectSuper;
  2831         env.info.selectSuper =
  2832             sitesym != null &&
  2833             sitesym.name == names._super;
  2835         // Determine the symbol represented by the selection.
  2836         env.info.pendingResolutionPhase = null;
  2837         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  2838         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  2839             site = capture(site);
  2840             sym = selectSym(tree, sitesym, site, env, resultInfo);
  2842         boolean varArgs = env.info.lastResolveVarargs();
  2843         tree.sym = sym;
  2845         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  2846             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  2847             site = capture(site);
  2850         // If that symbol is a variable, ...
  2851         if (sym.kind == VAR) {
  2852             VarSymbol v = (VarSymbol)sym;
  2854             // ..., evaluate its initializer, if it has one, and check for
  2855             // illegal forward reference.
  2856             checkInit(tree, env, v, true);
  2858             // If we are expecting a variable (as opposed to a value), check
  2859             // that the variable is assignable in the current environment.
  2860             if (pkind() == VAR)
  2861                 checkAssignable(tree.pos(), v, tree.selected, env);
  2864         if (sitesym != null &&
  2865                 sitesym.kind == VAR &&
  2866                 ((VarSymbol)sitesym).isResourceVariable() &&
  2867                 sym.kind == MTH &&
  2868                 sym.name.equals(names.close) &&
  2869                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2870                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2871             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2874         // Disallow selecting a type from an expression
  2875         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2876             tree.type = check(tree.selected, pt(),
  2877                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  2880         if (isType(sitesym)) {
  2881             if (sym.name == names._this) {
  2882                 // If `C' is the currently compiled class, check that
  2883                 // C.this' does not appear in a call to a super(...)
  2884                 if (env.info.isSelfCall &&
  2885                     site.tsym == env.enclClass.sym) {
  2886                     chk.earlyRefError(tree.pos(), sym);
  2888             } else {
  2889                 // Check if type-qualified fields or methods are static (JLS)
  2890                 if ((sym.flags() & STATIC) == 0 &&
  2891                     !env.next.tree.hasTag(REFERENCE) &&
  2892                     sym.name != names._super &&
  2893                     (sym.kind == VAR || sym.kind == MTH)) {
  2894                     rs.accessBase(rs.new StaticError(sym),
  2895                               tree.pos(), site, sym.name, true);
  2898         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2899             // If the qualified item is not a type and the selected item is static, report
  2900             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2901             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2904         // If we are selecting an instance member via a `super', ...
  2905         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2907             // Check that super-qualified symbols are not abstract (JLS)
  2908             rs.checkNonAbstract(tree.pos(), sym);
  2910             if (site.isRaw()) {
  2911                 // Determine argument types for site.
  2912                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2913                 if (site1 != null) site = site1;
  2917         env.info.selectSuper = selectSuperPrev;
  2918         result = checkId(tree, site, sym, env, resultInfo);
  2920     //where
  2921         /** Determine symbol referenced by a Select expression,
  2923          *  @param tree   The select tree.
  2924          *  @param site   The type of the selected expression,
  2925          *  @param env    The current environment.
  2926          *  @param resultInfo The current result.
  2927          */
  2928         private Symbol selectSym(JCFieldAccess tree,
  2929                                  Symbol location,
  2930                                  Type site,
  2931                                  Env<AttrContext> env,
  2932                                  ResultInfo resultInfo) {
  2933             DiagnosticPosition pos = tree.pos();
  2934             Name name = tree.name;
  2935             switch (site.getTag()) {
  2936             case PACKAGE:
  2937                 return rs.accessBase(
  2938                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  2939                     pos, location, site, name, true);
  2940             case ARRAY:
  2941             case CLASS:
  2942                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  2943                     return rs.resolveQualifiedMethod(
  2944                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  2945                 } else if (name == names._this || name == names._super) {
  2946                     return rs.resolveSelf(pos, env, site.tsym, name);
  2947                 } else if (name == names._class) {
  2948                     // In this case, we have already made sure in
  2949                     // visitSelect that qualifier expression is a type.
  2950                     Type t = syms.classType;
  2951                     List<Type> typeargs = allowGenerics
  2952                         ? List.of(types.erasure(site))
  2953                         : List.<Type>nil();
  2954                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2955                     return new VarSymbol(
  2956                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2957                 } else {
  2958                     // We are seeing a plain identifier as selector.
  2959                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  2960                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  2961                         sym = rs.accessBase(sym, pos, location, site, name, true);
  2962                     return sym;
  2964             case WILDCARD:
  2965                 throw new AssertionError(tree);
  2966             case TYPEVAR:
  2967                 // Normally, site.getUpperBound() shouldn't be null.
  2968                 // It should only happen during memberEnter/attribBase
  2969                 // when determining the super type which *must* beac
  2970                 // done before attributing the type variables.  In
  2971                 // other words, we are seeing this illegal program:
  2972                 // class B<T> extends A<T.foo> {}
  2973                 Symbol sym = (site.getUpperBound() != null)
  2974                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  2975                     : null;
  2976                 if (sym == null) {
  2977                     log.error(pos, "type.var.cant.be.deref");
  2978                     return syms.errSymbol;
  2979                 } else {
  2980                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2981                         rs.new AccessError(env, site, sym) :
  2982                                 sym;
  2983                     rs.accessBase(sym2, pos, location, site, name, true);
  2984                     return sym;
  2986             case ERROR:
  2987                 // preserve identifier names through errors
  2988                 return types.createErrorType(name, site.tsym, site).tsym;
  2989             default:
  2990                 // The qualifier expression is of a primitive type -- only
  2991                 // .class is allowed for these.
  2992                 if (name == names._class) {
  2993                     // In this case, we have already made sure in Select that
  2994                     // qualifier expression is a type.
  2995                     Type t = syms.classType;
  2996                     Type arg = types.boxedClass(site).type;
  2997                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2998                     return new VarSymbol(
  2999                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3000                 } else {
  3001                     log.error(pos, "cant.deref", site);
  3002                     return syms.errSymbol;
  3007         /** Determine type of identifier or select expression and check that
  3008          *  (1) the referenced symbol is not deprecated
  3009          *  (2) the symbol's type is safe (@see checkSafe)
  3010          *  (3) if symbol is a variable, check that its type and kind are
  3011          *      compatible with the prototype and protokind.
  3012          *  (4) if symbol is an instance field of a raw type,
  3013          *      which is being assigned to, issue an unchecked warning if its
  3014          *      type changes under erasure.
  3015          *  (5) if symbol is an instance method of a raw type, issue an
  3016          *      unchecked warning if its argument types change under erasure.
  3017          *  If checks succeed:
  3018          *    If symbol is a constant, return its constant type
  3019          *    else if symbol is a method, return its result type
  3020          *    otherwise return its type.
  3021          *  Otherwise return errType.
  3023          *  @param tree       The syntax tree representing the identifier
  3024          *  @param site       If this is a select, the type of the selected
  3025          *                    expression, otherwise the type of the current class.
  3026          *  @param sym        The symbol representing the identifier.
  3027          *  @param env        The current environment.
  3028          *  @param resultInfo    The expected result
  3029          */
  3030         Type checkId(JCTree tree,
  3031                      Type site,
  3032                      Symbol sym,
  3033                      Env<AttrContext> env,
  3034                      ResultInfo resultInfo) {
  3035             Type pt = resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD) ?
  3036                     resultInfo.pt.map(deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)) :
  3037                     resultInfo.pt;
  3039             DeferredAttr.DeferredTypeMap recoveryMap =
  3040                     deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3042             if (pt.isErroneous()) {
  3043                 Type.map(resultInfo.pt.getParameterTypes(), recoveryMap);
  3044                 return types.createErrorType(site);
  3046             Type owntype; // The computed type of this identifier occurrence.
  3047             switch (sym.kind) {
  3048             case TYP:
  3049                 // For types, the computed type equals the symbol's type,
  3050                 // except for two situations:
  3051                 owntype = sym.type;
  3052                 if (owntype.hasTag(CLASS)) {
  3053                     Type ownOuter = owntype.getEnclosingType();
  3055                     // (a) If the symbol's type is parameterized, erase it
  3056                     // because no type parameters were given.
  3057                     // We recover generic outer type later in visitTypeApply.
  3058                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3059                         owntype = types.erasure(owntype);
  3062                     // (b) If the symbol's type is an inner class, then
  3063                     // we have to interpret its outer type as a superclass
  3064                     // of the site type. Example:
  3065                     //
  3066                     // class Tree<A> { class Visitor { ... } }
  3067                     // class PointTree extends Tree<Point> { ... }
  3068                     // ...PointTree.Visitor...
  3069                     //
  3070                     // Then the type of the last expression above is
  3071                     // Tree<Point>.Visitor.
  3072                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3073                         Type normOuter = site;
  3074                         if (normOuter.hasTag(CLASS))
  3075                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3076                         if (normOuter == null) // perhaps from an import
  3077                             normOuter = types.erasure(ownOuter);
  3078                         if (normOuter != ownOuter)
  3079                             owntype = new ClassType(
  3080                                 normOuter, List.<Type>nil(), owntype.tsym);
  3083                 break;
  3084             case VAR:
  3085                 VarSymbol v = (VarSymbol)sym;
  3086                 // Test (4): if symbol is an instance field of a raw type,
  3087                 // which is being assigned to, issue an unchecked warning if
  3088                 // its type changes under erasure.
  3089                 if (allowGenerics &&
  3090                     resultInfo.pkind == VAR &&
  3091                     v.owner.kind == TYP &&
  3092                     (v.flags() & STATIC) == 0 &&
  3093                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3094                     Type s = types.asOuterSuper(site, v.owner);
  3095                     if (s != null &&
  3096                         s.isRaw() &&
  3097                         !types.isSameType(v.type, v.erasure(types))) {
  3098                         chk.warnUnchecked(tree.pos(),
  3099                                           "unchecked.assign.to.var",
  3100                                           v, s);
  3103                 // The computed type of a variable is the type of the
  3104                 // variable symbol, taken as a member of the site type.
  3105                 owntype = (sym.owner.kind == TYP &&
  3106                            sym.name != names._this && sym.name != names._super)
  3107                     ? types.memberType(site, sym)
  3108                     : sym.type;
  3110                 // If the variable is a constant, record constant value in
  3111                 // computed type.
  3112                 if (v.getConstValue() != null && isStaticReference(tree))
  3113                     owntype = owntype.constType(v.getConstValue());
  3115                 if (resultInfo.pkind == VAL) {
  3116                     owntype = capture(owntype); // capture "names as expressions"
  3118                 break;
  3119             case MTH: {
  3120                 owntype = checkMethod(site, sym,
  3121                         new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3122                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3123                         resultInfo.pt.getTypeArguments());
  3124                 break;
  3126             case PCK: case ERR:
  3127                 Type.map(resultInfo.pt.getParameterTypes(), recoveryMap);
  3128                 owntype = sym.type;
  3129                 break;
  3130             default:
  3131                 throw new AssertionError("unexpected kind: " + sym.kind +
  3132                                          " in tree " + tree);
  3135             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3136             // (for constructors, the error was given when the constructor was
  3137             // resolved)
  3139             if (sym.name != names.init) {
  3140                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3141                 chk.checkSunAPI(tree.pos(), sym);
  3144             // Test (3): if symbol is a variable, check that its type and
  3145             // kind are compatible with the prototype and protokind.
  3146             return check(tree, owntype, sym.kind, resultInfo);
  3149         /** Check that variable is initialized and evaluate the variable's
  3150          *  initializer, if not yet done. Also check that variable is not
  3151          *  referenced before it is defined.
  3152          *  @param tree    The tree making up the variable reference.
  3153          *  @param env     The current environment.
  3154          *  @param v       The variable's symbol.
  3155          */
  3156         private void checkInit(JCTree tree,
  3157                                Env<AttrContext> env,
  3158                                VarSymbol v,
  3159                                boolean onlyWarning) {
  3160 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3161 //                             tree.pos + " " + v.pos + " " +
  3162 //                             Resolve.isStatic(env));//DEBUG
  3164             // A forward reference is diagnosed if the declaration position
  3165             // of the variable is greater than the current tree position
  3166             // and the tree and variable definition occur in the same class
  3167             // definition.  Note that writes don't count as references.
  3168             // This check applies only to class and instance
  3169             // variables.  Local variables follow different scope rules,
  3170             // and are subject to definite assignment checking.
  3171             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3172                 v.owner.kind == TYP &&
  3173                 canOwnInitializer(owner(env)) &&
  3174                 v.owner == env.info.scope.owner.enclClass() &&
  3175                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3176                 (!env.tree.hasTag(ASSIGN) ||
  3177                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3178                 String suffix = (env.info.enclVar == v) ?
  3179                                 "self.ref" : "forward.ref";
  3180                 if (!onlyWarning || isStaticEnumField(v)) {
  3181                     log.error(tree.pos(), "illegal." + suffix);
  3182                 } else if (useBeforeDeclarationWarning) {
  3183                     log.warning(tree.pos(), suffix, v);
  3187             v.getConstValue(); // ensure initializer is evaluated
  3189             checkEnumInitializer(tree, env, v);
  3192         /**
  3193          * Check for illegal references to static members of enum.  In
  3194          * an enum type, constructors and initializers may not
  3195          * reference its static members unless they are constant.
  3197          * @param tree    The tree making up the variable reference.
  3198          * @param env     The current environment.
  3199          * @param v       The variable's symbol.
  3200          * @jls  section 8.9 Enums
  3201          */
  3202         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3203             // JLS:
  3204             //
  3205             // "It is a compile-time error to reference a static field
  3206             // of an enum type that is not a compile-time constant
  3207             // (15.28) from constructors, instance initializer blocks,
  3208             // or instance variable initializer expressions of that
  3209             // type. It is a compile-time error for the constructors,
  3210             // instance initializer blocks, or instance variable
  3211             // initializer expressions of an enum constant e to refer
  3212             // to itself or to an enum constant of the same type that
  3213             // is declared to the right of e."
  3214             if (isStaticEnumField(v)) {
  3215                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3217                 if (enclClass == null || enclClass.owner == null)
  3218                     return;
  3220                 // See if the enclosing class is the enum (or a
  3221                 // subclass thereof) declaring v.  If not, this
  3222                 // reference is OK.
  3223                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3224                     return;
  3226                 // If the reference isn't from an initializer, then
  3227                 // the reference is OK.
  3228                 if (!Resolve.isInitializer(env))
  3229                     return;
  3231                 log.error(tree.pos(), "illegal.enum.static.ref");
  3235         /** Is the given symbol a static, non-constant field of an Enum?
  3236          *  Note: enum literals should not be regarded as such
  3237          */
  3238         private boolean isStaticEnumField(VarSymbol v) {
  3239             return Flags.isEnum(v.owner) &&
  3240                    Flags.isStatic(v) &&
  3241                    !Flags.isConstant(v) &&
  3242                    v.name != names._class;
  3245         /** Can the given symbol be the owner of code which forms part
  3246          *  if class initialization? This is the case if the symbol is
  3247          *  a type or field, or if the symbol is the synthetic method.
  3248          *  owning a block.
  3249          */
  3250         private boolean canOwnInitializer(Symbol sym) {
  3251             return
  3252                 (sym.kind & (VAR | TYP)) != 0 ||
  3253                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3256     Warner noteWarner = new Warner();
  3258     /**
  3259      * Check that method arguments conform to its instantiation.
  3260      **/
  3261     public Type checkMethod(Type site,
  3262                             Symbol sym,
  3263                             ResultInfo resultInfo,
  3264                             Env<AttrContext> env,
  3265                             final List<JCExpression> argtrees,
  3266                             List<Type> argtypes,
  3267                             List<Type> typeargtypes) {
  3268         // Test (5): if symbol is an instance method of a raw type, issue
  3269         // an unchecked warning if its argument types change under erasure.
  3270         if (allowGenerics &&
  3271             (sym.flags() & STATIC) == 0 &&
  3272             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3273             Type s = types.asOuterSuper(site, sym.owner);
  3274             if (s != null && s.isRaw() &&
  3275                 !types.isSameTypes(sym.type.getParameterTypes(),
  3276                                    sym.erasure(types).getParameterTypes())) {
  3277                 chk.warnUnchecked(env.tree.pos(),
  3278                                   "unchecked.call.mbr.of.raw.type",
  3279                                   sym, s);
  3283         // Compute the identifier's instantiated type.
  3284         // For methods, we need to compute the instance type by
  3285         // Resolve.instantiate from the symbol's type as well as
  3286         // any type arguments and value arguments.
  3287         noteWarner.clear();
  3288         try {
  3289             Type owntype = rs.checkMethod(
  3290                     env,
  3291                     site,
  3292                     sym,
  3293                     resultInfo,
  3294                     argtypes,
  3295                     typeargtypes,
  3296                     noteWarner);
  3298             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3299                     noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
  3300         } catch (Infer.InferenceException ex) {
  3301             //invalid target type - propagate exception outwards or report error
  3302             //depending on the current check context
  3303             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3304             return types.createErrorType(site);
  3305         } catch (Resolve.InapplicableMethodException ex) {
  3306             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
  3307             return null;
  3311     public void visitLiteral(JCLiteral tree) {
  3312         result = check(
  3313             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3315     //where
  3316     /** Return the type of a literal with given type tag.
  3317      */
  3318     Type litType(TypeTag tag) {
  3319         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3322     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3323         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3326     public void visitTypeArray(JCArrayTypeTree tree) {
  3327         Type etype = attribType(tree.elemtype, env);
  3328         Type type = new ArrayType(etype, syms.arrayClass);
  3329         result = check(tree, type, TYP, resultInfo);
  3332     /** Visitor method for parameterized types.
  3333      *  Bound checking is left until later, since types are attributed
  3334      *  before supertype structure is completely known
  3335      */
  3336     public void visitTypeApply(JCTypeApply tree) {
  3337         Type owntype = types.createErrorType(tree.type);
  3339         // Attribute functor part of application and make sure it's a class.
  3340         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3342         // Attribute type parameters
  3343         List<Type> actuals = attribTypes(tree.arguments, env);
  3345         if (clazztype.hasTag(CLASS)) {
  3346             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3347             if (actuals.isEmpty()) //diamond
  3348                 actuals = formals;
  3350             if (actuals.length() == formals.length()) {
  3351                 List<Type> a = actuals;
  3352                 List<Type> f = formals;
  3353                 while (a.nonEmpty()) {
  3354                     a.head = a.head.withTypeVar(f.head);
  3355                     a = a.tail;
  3356                     f = f.tail;
  3358                 // Compute the proper generic outer
  3359                 Type clazzOuter = clazztype.getEnclosingType();
  3360                 if (clazzOuter.hasTag(CLASS)) {
  3361                     Type site;
  3362                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3363                     if (clazz.hasTag(IDENT)) {
  3364                         site = env.enclClass.sym.type;
  3365                     } else if (clazz.hasTag(SELECT)) {
  3366                         site = ((JCFieldAccess) clazz).selected.type;
  3367                     } else throw new AssertionError(""+tree);
  3368                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3369                         if (site.hasTag(CLASS))
  3370                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3371                         if (site == null)
  3372                             site = types.erasure(clazzOuter);
  3373                         clazzOuter = site;
  3376                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3377             } else {
  3378                 if (formals.length() != 0) {
  3379                     log.error(tree.pos(), "wrong.number.type.args",
  3380                               Integer.toString(formals.length()));
  3381                 } else {
  3382                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3384                 owntype = types.createErrorType(tree.type);
  3387         result = check(tree, owntype, TYP, resultInfo);
  3390     public void visitTypeUnion(JCTypeUnion tree) {
  3391         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  3392         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3393         for (JCExpression typeTree : tree.alternatives) {
  3394             Type ctype = attribType(typeTree, env);
  3395             ctype = chk.checkType(typeTree.pos(),
  3396                           chk.checkClassType(typeTree.pos(), ctype),
  3397                           syms.throwableType);
  3398             if (!ctype.isErroneous()) {
  3399                 //check that alternatives of a union type are pairwise
  3400                 //unrelated w.r.t. subtyping
  3401                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3402                     for (Type t : multicatchTypes) {
  3403                         boolean sub = types.isSubtype(ctype, t);
  3404                         boolean sup = types.isSubtype(t, ctype);
  3405                         if (sub || sup) {
  3406                             //assume 'a' <: 'b'
  3407                             Type a = sub ? ctype : t;
  3408                             Type b = sub ? t : ctype;
  3409                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3413                 multicatchTypes.append(ctype);
  3414                 if (all_multicatchTypes != null)
  3415                     all_multicatchTypes.append(ctype);
  3416             } else {
  3417                 if (all_multicatchTypes == null) {
  3418                     all_multicatchTypes = ListBuffer.lb();
  3419                     all_multicatchTypes.appendList(multicatchTypes);
  3421                 all_multicatchTypes.append(ctype);
  3424         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3425         if (t.hasTag(CLASS)) {
  3426             List<Type> alternatives =
  3427                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3428             t = new UnionClassType((ClassType) t, alternatives);
  3430         tree.type = result = t;
  3433     public void visitTypeParameter(JCTypeParameter tree) {
  3434         TypeVar a = (TypeVar)tree.type;
  3435         Set<Type> boundSet = new HashSet<Type>();
  3436         if (a.bound.isErroneous())
  3437             return;
  3438         List<Type> bs = types.getBounds(a);
  3439         if (tree.bounds.nonEmpty()) {
  3440             // accept class or interface or typevar as first bound.
  3441             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  3442             boundSet.add(types.erasure(b));
  3443             if (b.isErroneous()) {
  3444                 a.bound = b;
  3446             else if (b.hasTag(TYPEVAR)) {
  3447                 // if first bound was a typevar, do not accept further bounds.
  3448                 if (tree.bounds.tail.nonEmpty()) {
  3449                     log.error(tree.bounds.tail.head.pos(),
  3450                               "type.var.may.not.be.followed.by.other.bounds");
  3451                     tree.bounds = List.of(tree.bounds.head);
  3452                     a.bound = bs.head;
  3454             } else {
  3455                 // if first bound was a class or interface, accept only interfaces
  3456                 // as further bounds.
  3457                 for (JCExpression bound : tree.bounds.tail) {
  3458                     bs = bs.tail;
  3459                     Type i = checkBase(bs.head, bound, env, false, true, false);
  3460                     if (i.isErroneous())
  3461                         a.bound = i;
  3462                     else if (i.hasTag(CLASS))
  3463                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  3467         bs = types.getBounds(a);
  3469         // in case of multiple bounds ...
  3470         if (bs.length() > 1) {
  3471             // ... the variable's bound is a class type flagged COMPOUND
  3472             // (see comment for TypeVar.bound).
  3473             // In this case, generate a class tree that represents the
  3474             // bound class, ...
  3475             JCExpression extending;
  3476             List<JCExpression> implementing;
  3477             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  3478                 extending = tree.bounds.head;
  3479                 implementing = tree.bounds.tail;
  3480             } else {
  3481                 extending = null;
  3482                 implementing = tree.bounds;
  3484             JCClassDecl cd = make.at(tree.pos).ClassDef(
  3485                 make.Modifiers(PUBLIC | ABSTRACT),
  3486                 tree.name, List.<JCTypeParameter>nil(),
  3487                 extending, implementing, List.<JCTree>nil());
  3489             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  3490             Assert.check((c.flags() & COMPOUND) != 0);
  3491             cd.sym = c;
  3492             c.sourcefile = env.toplevel.sourcefile;
  3494             // ... and attribute the bound class
  3495             c.flags_field |= UNATTRIBUTED;
  3496             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3497             enter.typeEnvs.put(c, cenv);
  3502     public void visitWildcard(JCWildcard tree) {
  3503         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3504         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3505             ? syms.objectType
  3506             : attribType(tree.inner, env);
  3507         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3508                                               tree.kind.kind,
  3509                                               syms.boundClass),
  3510                        TYP, resultInfo);
  3513     public void visitAnnotation(JCAnnotation tree) {
  3514         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  3515         result = tree.type = syms.errType;
  3518     public void visitErroneous(JCErroneous tree) {
  3519         if (tree.errs != null)
  3520             for (JCTree err : tree.errs)
  3521                 attribTree(err, env, new ResultInfo(ERR, pt()));
  3522         result = tree.type = syms.errType;
  3525     /** Default visitor method for all other trees.
  3526      */
  3527     public void visitTree(JCTree tree) {
  3528         throw new AssertionError();
  3531     /**
  3532      * Attribute an env for either a top level tree or class declaration.
  3533      */
  3534     public void attrib(Env<AttrContext> env) {
  3535         if (env.tree.hasTag(TOPLEVEL))
  3536             attribTopLevel(env);
  3537         else
  3538             attribClass(env.tree.pos(), env.enclClass.sym);
  3541     /**
  3542      * Attribute a top level tree. These trees are encountered when the
  3543      * package declaration has annotations.
  3544      */
  3545     public void attribTopLevel(Env<AttrContext> env) {
  3546         JCCompilationUnit toplevel = env.toplevel;
  3547         try {
  3548             annotate.flush();
  3549             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  3550         } catch (CompletionFailure ex) {
  3551             chk.completionError(toplevel.pos(), ex);
  3555     /** Main method: attribute class definition associated with given class symbol.
  3556      *  reporting completion failures at the given position.
  3557      *  @param pos The source position at which completion errors are to be
  3558      *             reported.
  3559      *  @param c   The class symbol whose definition will be attributed.
  3560      */
  3561     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3562         try {
  3563             annotate.flush();
  3564             attribClass(c);
  3565         } catch (CompletionFailure ex) {
  3566             chk.completionError(pos, ex);
  3570     /** Attribute class definition associated with given class symbol.
  3571      *  @param c   The class symbol whose definition will be attributed.
  3572      */
  3573     void attribClass(ClassSymbol c) throws CompletionFailure {
  3574         if (c.type.hasTag(ERROR)) return;
  3576         // Check for cycles in the inheritance graph, which can arise from
  3577         // ill-formed class files.
  3578         chk.checkNonCyclic(null, c.type);
  3580         Type st = types.supertype(c.type);
  3581         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3582             // First, attribute superclass.
  3583             if (st.hasTag(CLASS))
  3584                 attribClass((ClassSymbol)st.tsym);
  3586             // Next attribute owner, if it is a class.
  3587             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  3588                 attribClass((ClassSymbol)c.owner);
  3591         // The previous operations might have attributed the current class
  3592         // if there was a cycle. So we test first whether the class is still
  3593         // UNATTRIBUTED.
  3594         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3595             c.flags_field &= ~UNATTRIBUTED;
  3597             // Get environment current at the point of class definition.
  3598             Env<AttrContext> env = enter.typeEnvs.get(c);
  3600             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3601             // because the annotations were not available at the time the env was created. Therefore,
  3602             // we look up the environment chain for the first enclosing environment for which the
  3603             // lint value is set. Typically, this is the parent env, but might be further if there
  3604             // are any envs created as a result of TypeParameter nodes.
  3605             Env<AttrContext> lintEnv = env;
  3606             while (lintEnv.info.lint == null)
  3607                 lintEnv = lintEnv.next;
  3609             // Having found the enclosing lint value, we can initialize the lint value for this class
  3610             env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
  3612             Lint prevLint = chk.setLint(env.info.lint);
  3613             JavaFileObject prev = log.useSource(c.sourcefile);
  3614             ResultInfo prevReturnRes = env.info.returnResult;
  3616             try {
  3617                 env.info.returnResult = null;
  3618                 // java.lang.Enum may not be subclassed by a non-enum
  3619                 if (st.tsym == syms.enumSym &&
  3620                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3621                     log.error(env.tree.pos(), "enum.no.subclassing");
  3623                 // Enums may not be extended by source-level classes
  3624                 if (st.tsym != null &&
  3625                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3626                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3627                     !target.compilerBootstrap(c)) {
  3628                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3630                 attribClassBody(env, c);
  3632                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3633             } finally {
  3634                 env.info.returnResult = prevReturnRes;
  3635                 log.useSource(prev);
  3636                 chk.setLint(prevLint);
  3642     public void visitImport(JCImport tree) {
  3643         // nothing to do
  3646     /** Finish the attribution of a class. */
  3647     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3648         JCClassDecl tree = (JCClassDecl)env.tree;
  3649         Assert.check(c == tree.sym);
  3651         // Validate annotations
  3652         chk.validateAnnotations(tree.mods.annotations, c);
  3654         // Validate type parameters, supertype and interfaces.
  3655         attribBounds(tree.typarams);
  3656         if (!c.isAnonymous()) {
  3657             //already checked if anonymous
  3658             chk.validate(tree.typarams, env);
  3659             chk.validate(tree.extending, env);
  3660             chk.validate(tree.implementing, env);
  3663         // If this is a non-abstract class, check that it has no abstract
  3664         // methods or unimplemented methods of an implemented interface.
  3665         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3666             if (!relax)
  3667                 chk.checkAllDefined(tree.pos(), c);
  3670         if ((c.flags() & ANNOTATION) != 0) {
  3671             if (tree.implementing.nonEmpty())
  3672                 log.error(tree.implementing.head.pos(),
  3673                           "cant.extend.intf.annotation");
  3674             if (tree.typarams.nonEmpty())
  3675                 log.error(tree.typarams.head.pos(),
  3676                           "intf.annotation.cant.have.type.params");
  3678             // If this annotation has a @ContainedBy, validate
  3679             Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym);
  3680             if (containedBy != null) {
  3681                 // get diagnositc position for error reporting
  3682                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type);
  3683                 Assert.checkNonNull(cbPos);
  3685                 chk.validateContainedBy(c, containedBy, cbPos);
  3688             // If this annotation has a @ContainerFor, validate
  3689             Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym);
  3690             if (containerFor != null) {
  3691                 // get diagnositc position for error reporting
  3692                 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type);
  3693                 Assert.checkNonNull(cfPos);
  3695                 chk.validateContainerFor(c, containerFor, cfPos);
  3697         } else {
  3698             // Check that all extended classes and interfaces
  3699             // are compatible (i.e. no two define methods with same arguments
  3700             // yet different return types).  (JLS 8.4.6.3)
  3701             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3704         // Check that class does not import the same parameterized interface
  3705         // with two different argument lists.
  3706         chk.checkClassBounds(tree.pos(), c.type);
  3708         tree.type = c.type;
  3710         for (List<JCTypeParameter> l = tree.typarams;
  3711              l.nonEmpty(); l = l.tail) {
  3712              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3715         // Check that a generic class doesn't extend Throwable
  3716         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3717             log.error(tree.extending.pos(), "generic.throwable");
  3719         // Check that all methods which implement some
  3720         // method conform to the method they implement.
  3721         chk.checkImplementations(tree);
  3723         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  3724         checkAutoCloseable(tree.pos(), env, c.type);
  3726         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3727             // Attribute declaration
  3728             attribStat(l.head, env);
  3729             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3730             // Make an exception for static constants.
  3731             if (c.owner.kind != PCK &&
  3732                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3733                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3734                 Symbol sym = null;
  3735                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  3736                 if (sym == null ||
  3737                     sym.kind != VAR ||
  3738                     ((VarSymbol) sym).getConstValue() == null)
  3739                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3743         // Check for cycles among non-initial constructors.
  3744         chk.checkCyclicConstructors(tree);
  3746         // Check for cycles among annotation elements.
  3747         chk.checkNonCyclicElements(tree);
  3749         // Check for proper use of serialVersionUID
  3750         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3751             isSerializable(c) &&
  3752             (c.flags() & Flags.ENUM) == 0 &&
  3753             (c.flags() & ABSTRACT) == 0) {
  3754             checkSerialVersionUID(tree, c);
  3757         // where
  3758         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  3759         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  3760             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  3761                 if (types.isSameType(al.head.annotationType.type, t))
  3762                     return al.head.pos();
  3765             return null;
  3768         /** check if a class is a subtype of Serializable, if that is available. */
  3769         private boolean isSerializable(ClassSymbol c) {
  3770             try {
  3771                 syms.serializableType.complete();
  3773             catch (CompletionFailure e) {
  3774                 return false;
  3776             return types.isSubtype(c.type, syms.serializableType);
  3779         /** Check that an appropriate serialVersionUID member is defined. */
  3780         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3782             // check for presence of serialVersionUID
  3783             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3784             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3785             if (e.scope == null) {
  3786                 log.warning(LintCategory.SERIAL,
  3787                         tree.pos(), "missing.SVUID", c);
  3788                 return;
  3791             // check that it is static final
  3792             VarSymbol svuid = (VarSymbol)e.sym;
  3793             if ((svuid.flags() & (STATIC | FINAL)) !=
  3794                 (STATIC | FINAL))
  3795                 log.warning(LintCategory.SERIAL,
  3796                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3798             // check that it is long
  3799             else if (!svuid.type.hasTag(LONG))
  3800                 log.warning(LintCategory.SERIAL,
  3801                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3803             // check constant
  3804             else if (svuid.getConstValue() == null)
  3805                 log.warning(LintCategory.SERIAL,
  3806                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3809     private Type capture(Type type) {
  3810         return types.capture(type);
  3813     // <editor-fold desc="post-attribution visitor">
  3815     /**
  3816      * Handle missing types/symbols in an AST. This routine is useful when
  3817      * the compiler has encountered some errors (which might have ended up
  3818      * terminating attribution abruptly); if the compiler is used in fail-over
  3819      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3820      * prevents NPE to be progagated during subsequent compilation steps.
  3821      */
  3822     public void postAttr(JCTree tree) {
  3823         new PostAttrAnalyzer().scan(tree);
  3826     class PostAttrAnalyzer extends TreeScanner {
  3828         private void initTypeIfNeeded(JCTree that) {
  3829             if (that.type == null) {
  3830                 that.type = syms.unknownType;
  3834         @Override
  3835         public void scan(JCTree tree) {
  3836             if (tree == null) return;
  3837             if (tree instanceof JCExpression) {
  3838                 initTypeIfNeeded(tree);
  3840             super.scan(tree);
  3843         @Override
  3844         public void visitIdent(JCIdent that) {
  3845             if (that.sym == null) {
  3846                 that.sym = syms.unknownSymbol;
  3850         @Override
  3851         public void visitSelect(JCFieldAccess that) {
  3852             if (that.sym == null) {
  3853                 that.sym = syms.unknownSymbol;
  3855             super.visitSelect(that);
  3858         @Override
  3859         public void visitClassDef(JCClassDecl that) {
  3860             initTypeIfNeeded(that);
  3861             if (that.sym == null) {
  3862                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3864             super.visitClassDef(that);
  3867         @Override
  3868         public void visitMethodDef(JCMethodDecl that) {
  3869             initTypeIfNeeded(that);
  3870             if (that.sym == null) {
  3871                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3873             super.visitMethodDef(that);
  3876         @Override
  3877         public void visitVarDef(JCVariableDecl that) {
  3878             initTypeIfNeeded(that);
  3879             if (that.sym == null) {
  3880                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3881                 that.sym.adr = 0;
  3883             super.visitVarDef(that);
  3886         @Override
  3887         public void visitNewClass(JCNewClass that) {
  3888             if (that.constructor == null) {
  3889                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3891             if (that.constructorType == null) {
  3892                 that.constructorType = syms.unknownType;
  3894             super.visitNewClass(that);
  3897         @Override
  3898         public void visitAssignop(JCAssignOp that) {
  3899             if (that.operator == null)
  3900                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3901             super.visitAssignop(that);
  3904         @Override
  3905         public void visitBinary(JCBinary that) {
  3906             if (that.operator == null)
  3907                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3908             super.visitBinary(that);
  3911         @Override
  3912         public void visitUnary(JCUnary that) {
  3913             if (that.operator == null)
  3914                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3915             super.visitUnary(that);
  3918         @Override
  3919         public void visitReference(JCMemberReference that) {
  3920             super.visitReference(that);
  3921             if (that.sym == null) {
  3922                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  3926     // </editor-fold>

mercurial