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

Tue, 28 Jul 2009 12:12:59 -0700

author
xdono
date
Tue, 28 Jul 2009 12:12:59 -0700
changeset 323
14b1a8ede954
parent 308
03944ee4fac4
child 358
62073a5becc5
permissions
-rw-r--r--

6862919: Update copyright year
Summary: Update copyright for files that have been modified in 2009, up to 07/09
Reviewed-by: tbell, ohair

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.jvm.Target;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.tree.JCTree.*;
    43 import com.sun.tools.javac.code.Type.*;
    45 import com.sun.source.tree.IdentifierTree;
    46 import com.sun.source.tree.MemberSelectTree;
    47 import com.sun.source.tree.TreeVisitor;
    48 import com.sun.source.util.SimpleTreeVisitor;
    50 import static com.sun.tools.javac.code.Flags.*;
    51 import static com.sun.tools.javac.code.Kinds.*;
    52 import static com.sun.tools.javac.code.TypeTags.*;
    54 /** This is the main context-dependent analysis phase in GJC. It
    55  *  encompasses name resolution, type checking and constant folding as
    56  *  subtasks. Some subtasks involve auxiliary classes.
    57  *  @see Check
    58  *  @see Resolve
    59  *  @see ConstFold
    60  *  @see Infer
    61  *
    62  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    63  *  you write code that depends on this, you do so at your own risk.
    64  *  This code and its internal interfaces are subject to change or
    65  *  deletion without notice.</b>
    66  */
    67 public class Attr extends JCTree.Visitor {
    68     protected static final Context.Key<Attr> attrKey =
    69         new Context.Key<Attr>();
    71     final Names names;
    72     final Log log;
    73     final Symtab syms;
    74     final Resolve rs;
    75     final Check chk;
    76     final MemberEnter memberEnter;
    77     final TreeMaker make;
    78     final ConstFold cfolder;
    79     final Enter enter;
    80     final Target target;
    81     final Types types;
    82     final JCDiagnostic.Factory diags;
    83     final Annotate annotate;
    85     public static Attr instance(Context context) {
    86         Attr instance = context.get(attrKey);
    87         if (instance == null)
    88             instance = new Attr(context);
    89         return instance;
    90     }
    92     protected Attr(Context context) {
    93         context.put(attrKey, this);
    95         names = Names.instance(context);
    96         log = Log.instance(context);
    97         syms = Symtab.instance(context);
    98         rs = Resolve.instance(context);
    99         chk = Check.instance(context);
   100         memberEnter = MemberEnter.instance(context);
   101         make = TreeMaker.instance(context);
   102         enter = Enter.instance(context);
   103         cfolder = ConstFold.instance(context);
   104         target = Target.instance(context);
   105         types = Types.instance(context);
   106         diags = JCDiagnostic.Factory.instance(context);
   107         annotate = Annotate.instance(context);
   109         Options options = Options.instance(context);
   111         Source source = Source.instance(context);
   112         allowGenerics = source.allowGenerics();
   113         allowVarargs = source.allowVarargs();
   114         allowEnums = source.allowEnums();
   115         allowBoxing = source.allowBoxing();
   116         allowCovariantReturns = source.allowCovariantReturns();
   117         allowAnonOuterThis = source.allowAnonOuterThis();
   118         relax = (options.get("-retrofit") != null ||
   119                  options.get("-relax") != null);
   120         useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
   121         allowInvokedynamic = options.get("invokedynamic") != null;
   122     }
   124     /** Switch: relax some constraints for retrofit mode.
   125      */
   126     boolean relax;
   128     /** Switch: support generics?
   129      */
   130     boolean allowGenerics;
   132     /** Switch: allow variable-arity methods.
   133      */
   134     boolean allowVarargs;
   136     /** Switch: support enums?
   137      */
   138     boolean allowEnums;
   140     /** Switch: support boxing and unboxing?
   141      */
   142     boolean allowBoxing;
   144     /** Switch: support covariant result types?
   145      */
   146     boolean allowCovariantReturns;
   148     /** Switch: allow references to surrounding object from anonymous
   149      * objects during constructor call?
   150      */
   151     boolean allowAnonOuterThis;
   153     /** Switch: allow invokedynamic syntax
   154      */
   155     boolean allowInvokedynamic;
   157     /**
   158      * Switch: warn about use of variable before declaration?
   159      * RFE: 6425594
   160      */
   161     boolean useBeforeDeclarationWarning;
   163     /** Check kind and type of given tree against protokind and prototype.
   164      *  If check succeeds, store type in tree and return it.
   165      *  If check fails, store errType in tree and return it.
   166      *  No checks are performed if the prototype is a method type.
   167      *  It is not necessary in this case since we know that kind and type
   168      *  are correct.
   169      *
   170      *  @param tree     The tree whose kind and type is checked
   171      *  @param owntype  The computed type of the tree
   172      *  @param ownkind  The computed kind of the tree
   173      *  @param pkind    The expected kind (or: protokind) of the tree
   174      *  @param pt       The expected type (or: prototype) of the tree
   175      */
   176     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   177         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   178             if ((ownkind & ~pkind) == 0) {
   179                 owntype = chk.checkType(tree.pos(), owntype, pt);
   180             } else {
   181                 log.error(tree.pos(), "unexpected.type",
   182                           kindNames(pkind),
   183                           kindName(ownkind));
   184                 owntype = types.createErrorType(owntype);
   185             }
   186         }
   187         tree.type = owntype;
   188         return owntype;
   189     }
   191     /** Is given blank final variable assignable, i.e. in a scope where it
   192      *  may be assigned to even though it is final?
   193      *  @param v      The blank final variable.
   194      *  @param env    The current environment.
   195      */
   196     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   197         Symbol owner = env.info.scope.owner;
   198            // owner refers to the innermost variable, method or
   199            // initializer block declaration at this point.
   200         return
   201             v.owner == owner
   202             ||
   203             ((owner.name == names.init ||    // i.e. we are in a constructor
   204               owner.kind == VAR ||           // i.e. we are in a variable initializer
   205               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   206              &&
   207              v.owner == owner.owner
   208              &&
   209              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   210     }
   212     /** Check that variable can be assigned to.
   213      *  @param pos    The current source code position.
   214      *  @param v      The assigned varaible
   215      *  @param base   If the variable is referred to in a Select, the part
   216      *                to the left of the `.', null otherwise.
   217      *  @param env    The current environment.
   218      */
   219     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   220         if ((v.flags() & FINAL) != 0 &&
   221             ((v.flags() & HASINIT) != 0
   222              ||
   223              !((base == null ||
   224                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   225                isAssignableAsBlankFinal(v, env)))) {
   226             log.error(pos, "cant.assign.val.to.final.var", v);
   227         }
   228     }
   230     /** Does tree represent a static reference to an identifier?
   231      *  It is assumed that tree is either a SELECT or an IDENT.
   232      *  We have to weed out selects from non-type names here.
   233      *  @param tree    The candidate tree.
   234      */
   235     boolean isStaticReference(JCTree tree) {
   236         if (tree.getTag() == JCTree.SELECT) {
   237             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   238             if (lsym == null || lsym.kind != TYP) {
   239                 return false;
   240             }
   241         }
   242         return true;
   243     }
   245     /** Is this symbol a type?
   246      */
   247     static boolean isType(Symbol sym) {
   248         return sym != null && sym.kind == TYP;
   249     }
   251     /** The current `this' symbol.
   252      *  @param env    The current environment.
   253      */
   254     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   255         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   256     }
   258     /** Attribute a parsed identifier.
   259      * @param tree Parsed identifier name
   260      * @param topLevel The toplevel to use
   261      */
   262     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   263         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   264         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   265                                            syms.errSymbol.name,
   266                                            null, null, null, null);
   267         localEnv.enclClass.sym = syms.errSymbol;
   268         return tree.accept(identAttributer, localEnv);
   269     }
   270     // where
   271         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   272         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   273             @Override
   274             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   275                 Symbol site = visit(node.getExpression(), env);
   276                 if (site.kind == ERR)
   277                     return site;
   278                 Name name = (Name)node.getIdentifier();
   279                 if (site.kind == PCK) {
   280                     env.toplevel.packge = (PackageSymbol)site;
   281                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   282                 } else {
   283                     env.enclClass.sym = (ClassSymbol)site;
   284                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   285                 }
   286             }
   288             @Override
   289             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   290                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   291             }
   292         }
   294     public Type coerce(Type etype, Type ttype) {
   295         return cfolder.coerce(etype, ttype);
   296     }
   298     public Type attribType(JCTree node, TypeSymbol sym) {
   299         Env<AttrContext> env = enter.typeEnvs.get(sym);
   300         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   301         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   302     }
   304     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   305         breakTree = tree;
   306         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   307         try {
   308             attribExpr(expr, env);
   309         } catch (BreakAttr b) {
   310             return b.env;
   311         } finally {
   312             breakTree = null;
   313             log.useSource(prev);
   314         }
   315         return env;
   316     }
   318     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   319         breakTree = tree;
   320         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   321         try {
   322             attribStat(stmt, env);
   323         } catch (BreakAttr b) {
   324             return b.env;
   325         } finally {
   326             breakTree = null;
   327             log.useSource(prev);
   328         }
   329         return env;
   330     }
   332     private JCTree breakTree = null;
   334     private static class BreakAttr extends RuntimeException {
   335         static final long serialVersionUID = -6924771130405446405L;
   336         private Env<AttrContext> env;
   337         private BreakAttr(Env<AttrContext> env) {
   338             this.env = env;
   339         }
   340     }
   343 /* ************************************************************************
   344  * Visitor methods
   345  *************************************************************************/
   347     /** Visitor argument: the current environment.
   348      */
   349     Env<AttrContext> env;
   351     /** Visitor argument: the currently expected proto-kind.
   352      */
   353     int pkind;
   355     /** Visitor argument: the currently expected proto-type.
   356      */
   357     Type pt;
   359     /** Visitor result: the computed type.
   360      */
   361     Type result;
   363     /** Visitor method: attribute a tree, catching any completion failure
   364      *  exceptions. Return the tree's type.
   365      *
   366      *  @param tree    The tree to be visited.
   367      *  @param env     The environment visitor argument.
   368      *  @param pkind   The protokind visitor argument.
   369      *  @param pt      The prototype visitor argument.
   370      */
   371     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   372         Env<AttrContext> prevEnv = this.env;
   373         int prevPkind = this.pkind;
   374         Type prevPt = this.pt;
   375         try {
   376             this.env = env;
   377             this.pkind = pkind;
   378             this.pt = pt;
   379             tree.accept(this);
   380             if (tree == breakTree)
   381                 throw new BreakAttr(env);
   382             return result;
   383         } catch (CompletionFailure ex) {
   384             tree.type = syms.errType;
   385             return chk.completionError(tree.pos(), ex);
   386         } finally {
   387             this.env = prevEnv;
   388             this.pkind = prevPkind;
   389             this.pt = prevPt;
   390         }
   391     }
   393     /** Derived visitor method: attribute an expression tree.
   394      */
   395     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   396         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   397     }
   399     /** Derived visitor method: attribute an expression tree with
   400      *  no constraints on the computed type.
   401      */
   402     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   403         return attribTree(tree, env, VAL, Type.noType);
   404     }
   406     /** Derived visitor method: attribute a type tree.
   407      */
   408     Type attribType(JCTree tree, Env<AttrContext> env) {
   409         Type result = attribTree(tree, env, TYP, Type.noType);
   410         return result;
   411     }
   413     /** Derived visitor method: attribute a statement or definition tree.
   414      */
   415     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   416         return attribTree(tree, env, NIL, Type.noType);
   417     }
   419     /** Attribute a list of expressions, returning a list of types.
   420      */
   421     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   422         ListBuffer<Type> ts = new ListBuffer<Type>();
   423         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   424             ts.append(attribExpr(l.head, env, pt));
   425         return ts.toList();
   426     }
   428     /** Attribute a list of statements, returning nothing.
   429      */
   430     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   431         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   432             attribStat(l.head, env);
   433     }
   435     /** Attribute the arguments in a method call, returning a list of types.
   436      */
   437     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   438         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   439         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   440             argtypes.append(chk.checkNonVoid(
   441                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   442         return argtypes.toList();
   443     }
   445     /** Attribute a type argument list, returning a list of types.
   446      *  Caller is responsible for calling checkRefTypes.
   447      */
   448     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   449         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   450         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   451             argtypes.append(attribType(l.head, env));
   452         return argtypes.toList();
   453     }
   455     /** Attribute a type argument list, returning a list of types.
   456      *  Check that all the types are references.
   457      */
   458     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   459         List<Type> types = attribAnyTypes(trees, env);
   460         return chk.checkRefTypes(trees, types);
   461     }
   463     /**
   464      * Attribute type variables (of generic classes or methods).
   465      * Compound types are attributed later in attribBounds.
   466      * @param typarams the type variables to enter
   467      * @param env      the current environment
   468      */
   469     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   470         for (JCTypeParameter tvar : typarams) {
   471             TypeVar a = (TypeVar)tvar.type;
   472             a.tsym.flags_field |= UNATTRIBUTED;
   473             a.bound = Type.noType;
   474             if (!tvar.bounds.isEmpty()) {
   475                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   476                 for (JCExpression bound : tvar.bounds.tail)
   477                     bounds = bounds.prepend(attribType(bound, env));
   478                 types.setBounds(a, bounds.reverse());
   479             } else {
   480                 // if no bounds are given, assume a single bound of
   481                 // java.lang.Object.
   482                 types.setBounds(a, List.of(syms.objectType));
   483             }
   484             a.tsym.flags_field &= ~UNATTRIBUTED;
   485         }
   486         for (JCTypeParameter tvar : typarams)
   487             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   488         attribStats(typarams, env);
   489     }
   491     void attribBounds(List<JCTypeParameter> typarams) {
   492         for (JCTypeParameter typaram : typarams) {
   493             Type bound = typaram.type.getUpperBound();
   494             if (bound != null && bound.tsym instanceof ClassSymbol) {
   495                 ClassSymbol c = (ClassSymbol)bound.tsym;
   496                 if ((c.flags_field & COMPOUND) != 0) {
   497                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   498                     attribClass(typaram.pos(), c);
   499                 }
   500             }
   501         }
   502     }
   504     /**
   505      * Attribute the type references in a list of annotations.
   506      */
   507     void attribAnnotationTypes(List<JCAnnotation> annotations,
   508                                Env<AttrContext> env) {
   509         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   510             JCAnnotation a = al.head;
   511             attribType(a.annotationType, env);
   512         }
   513     }
   515     /** Attribute type reference in an `extends' or `implements' clause.
   516      *
   517      *  @param tree              The tree making up the type reference.
   518      *  @param env               The environment current at the reference.
   519      *  @param classExpected     true if only a class is expected here.
   520      *  @param interfaceExpected true if only an interface is expected here.
   521      */
   522     Type attribBase(JCTree tree,
   523                     Env<AttrContext> env,
   524                     boolean classExpected,
   525                     boolean interfaceExpected,
   526                     boolean checkExtensible) {
   527         Type t = attribType(tree, env);
   528         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   529     }
   530     Type checkBase(Type t,
   531                    JCTree tree,
   532                    Env<AttrContext> env,
   533                    boolean classExpected,
   534                    boolean interfaceExpected,
   535                    boolean checkExtensible) {
   536         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   537             // check that type variable is already visible
   538             if (t.getUpperBound() == null) {
   539                 log.error(tree.pos(), "illegal.forward.ref");
   540                 return types.createErrorType(t);
   541             }
   542         } else {
   543             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   544         }
   545         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   546             log.error(tree.pos(), "intf.expected.here");
   547             // return errType is necessary since otherwise there might
   548             // be undetected cycles which cause attribution to loop
   549             return types.createErrorType(t);
   550         } else if (checkExtensible &&
   551                    classExpected &&
   552                    (t.tsym.flags() & INTERFACE) != 0) {
   553             log.error(tree.pos(), "no.intf.expected.here");
   554             return types.createErrorType(t);
   555         }
   556         if (checkExtensible &&
   557             ((t.tsym.flags() & FINAL) != 0)) {
   558             log.error(tree.pos(),
   559                       "cant.inherit.from.final", t.tsym);
   560         }
   561         chk.checkNonCyclic(tree.pos(), t);
   562         return t;
   563     }
   565     public void visitClassDef(JCClassDecl tree) {
   566         // Local classes have not been entered yet, so we need to do it now:
   567         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   568             enter.classEnter(tree, env);
   570         ClassSymbol c = tree.sym;
   571         if (c == null) {
   572             // exit in case something drastic went wrong during enter.
   573             result = null;
   574         } else {
   575             // make sure class has been completed:
   576             c.complete();
   578             // If this class appears as an anonymous class
   579             // in a superclass constructor call where
   580             // no explicit outer instance is given,
   581             // disable implicit outer instance from being passed.
   582             // (This would be an illegal access to "this before super").
   583             if (env.info.isSelfCall &&
   584                 env.tree.getTag() == JCTree.NEWCLASS &&
   585                 ((JCNewClass) env.tree).encl == null)
   586             {
   587                 c.flags_field |= NOOUTERTHIS;
   588             }
   589             attribClass(tree.pos(), c);
   590             result = tree.type = c.type;
   591         }
   592     }
   594     public void visitMethodDef(JCMethodDecl tree) {
   595         MethodSymbol m = tree.sym;
   597         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   598         Lint prevLint = chk.setLint(lint);
   599         try {
   600             chk.checkDeprecatedAnnotation(tree.pos(), m);
   602             attribBounds(tree.typarams);
   604             // If we override any other methods, check that we do so properly.
   605             // JLS ???
   606             chk.checkOverride(tree, m);
   608             // Create a new environment with local scope
   609             // for attributing the method.
   610             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   612             localEnv.info.lint = lint;
   614             // Enter all type parameters into the local method scope.
   615             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   616                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   618             ClassSymbol owner = env.enclClass.sym;
   619             if ((owner.flags() & ANNOTATION) != 0 &&
   620                 tree.params.nonEmpty())
   621                 log.error(tree.params.head.pos(),
   622                           "intf.annotation.members.cant.have.params");
   624             // Attribute all value parameters.
   625             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   626                 attribStat(l.head, localEnv);
   627             }
   629             // Check that type parameters are well-formed.
   630             chk.validate(tree.typarams, localEnv);
   631             if ((owner.flags() & ANNOTATION) != 0 &&
   632                 tree.typarams.nonEmpty())
   633                 log.error(tree.typarams.head.pos(),
   634                           "intf.annotation.members.cant.have.type.params");
   636             // Check that result type is well-formed.
   637             chk.validate(tree.restype, localEnv);
   638             if ((owner.flags() & ANNOTATION) != 0)
   639                 chk.validateAnnotationType(tree.restype);
   641             if ((owner.flags() & ANNOTATION) != 0)
   642                 chk.validateAnnotationMethod(tree.pos(), m);
   644             // Check that all exceptions mentioned in the throws clause extend
   645             // java.lang.Throwable.
   646             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
   647                 log.error(tree.thrown.head.pos(),
   648                           "throws.not.allowed.in.intf.annotation");
   649             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   650                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   652             if (tree.body == null) {
   653                 // Empty bodies are only allowed for
   654                 // abstract, native, or interface methods, or for methods
   655                 // in a retrofit signature class.
   656                 if ((owner.flags() & INTERFACE) == 0 &&
   657                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   658                     !relax)
   659                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   660                 if (tree.defaultValue != null) {
   661                     if ((owner.flags() & ANNOTATION) == 0)
   662                         log.error(tree.pos(),
   663                                   "default.allowed.in.intf.annotation.member");
   664                 }
   665             } else if ((owner.flags() & INTERFACE) != 0) {
   666                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   667             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   668                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   669             } else if ((tree.mods.flags & NATIVE) != 0) {
   670                 log.error(tree.pos(), "native.meth.cant.have.body");
   671             } else {
   672                 // Add an implicit super() call unless an explicit call to
   673                 // super(...) or this(...) is given
   674                 // or we are compiling class java.lang.Object.
   675                 if (tree.name == names.init && owner.type != syms.objectType) {
   676                     JCBlock body = tree.body;
   677                     if (body.stats.isEmpty() ||
   678                         !TreeInfo.isSelfCall(body.stats.head)) {
   679                         body.stats = body.stats.
   680                             prepend(memberEnter.SuperCall(make.at(body.pos),
   681                                                           List.<Type>nil(),
   682                                                           List.<JCVariableDecl>nil(),
   683                                                           false));
   684                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   685                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   686                                TreeInfo.isSuperCall(body.stats.head)) {
   687                         // enum constructors are not allowed to call super
   688                         // directly, so make sure there aren't any super calls
   689                         // in enum constructors, except in the compiler
   690                         // generated one.
   691                         log.error(tree.body.stats.head.pos(),
   692                                   "call.to.super.not.allowed.in.enum.ctor",
   693                                   env.enclClass.sym);
   694                     }
   695                 }
   697                 // Attribute method body.
   698                 attribStat(tree.body, localEnv);
   699             }
   700             localEnv.info.scope.leave();
   701             result = tree.type = m.type;
   702             chk.validateAnnotations(tree.mods.annotations, m);
   703         }
   704         finally {
   705             chk.setLint(prevLint);
   706         }
   707     }
   709     public void visitVarDef(JCVariableDecl tree) {
   710         // Local variables have not been entered yet, so we need to do it now:
   711         if (env.info.scope.owner.kind == MTH) {
   712             if (tree.sym != null) {
   713                 // parameters have already been entered
   714                 env.info.scope.enter(tree.sym);
   715             } else {
   716                 memberEnter.memberEnter(tree, env);
   717                 annotate.flush();
   718             }
   719         }
   721         VarSymbol v = tree.sym;
   722         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   723         Lint prevLint = chk.setLint(lint);
   725         // Check that the variable's declared type is well-formed.
   726         chk.validate(tree.vartype, env);
   728         try {
   729             chk.checkDeprecatedAnnotation(tree.pos(), v);
   731             if (tree.init != null) {
   732                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   733                     // In this case, `v' is final.  Ensure that it's initializer is
   734                     // evaluated.
   735                     v.getConstValue(); // ensure initializer is evaluated
   736                 } else {
   737                     // Attribute initializer in a new environment
   738                     // with the declared variable as owner.
   739                     // Check that initializer conforms to variable's declared type.
   740                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   741                     initEnv.info.lint = lint;
   742                     // In order to catch self-references, we set the variable's
   743                     // declaration position to maximal possible value, effectively
   744                     // marking the variable as undefined.
   745                     initEnv.info.enclVar = v;
   746                     attribExpr(tree.init, initEnv, v.type);
   747                 }
   748             }
   749             result = tree.type = v.type;
   750             chk.validateAnnotations(tree.mods.annotations, v);
   751         }
   752         finally {
   753             chk.setLint(prevLint);
   754         }
   755     }
   757     public void visitSkip(JCSkip tree) {
   758         result = null;
   759     }
   761     public void visitBlock(JCBlock tree) {
   762         if (env.info.scope.owner.kind == TYP) {
   763             // Block is a static or instance initializer;
   764             // let the owner of the environment be a freshly
   765             // created BLOCK-method.
   766             Env<AttrContext> localEnv =
   767                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   768             localEnv.info.scope.owner =
   769                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   770                                  env.info.scope.owner);
   771             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   772             attribStats(tree.stats, localEnv);
   773         } else {
   774             // Create a new local environment with a local scope.
   775             Env<AttrContext> localEnv =
   776                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   777             attribStats(tree.stats, localEnv);
   778             localEnv.info.scope.leave();
   779         }
   780         result = null;
   781     }
   783     public void visitDoLoop(JCDoWhileLoop tree) {
   784         attribStat(tree.body, env.dup(tree));
   785         attribExpr(tree.cond, env, syms.booleanType);
   786         result = null;
   787     }
   789     public void visitWhileLoop(JCWhileLoop tree) {
   790         attribExpr(tree.cond, env, syms.booleanType);
   791         attribStat(tree.body, env.dup(tree));
   792         result = null;
   793     }
   795     public void visitForLoop(JCForLoop tree) {
   796         Env<AttrContext> loopEnv =
   797             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   798         attribStats(tree.init, loopEnv);
   799         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   800         loopEnv.tree = tree; // before, we were not in loop!
   801         attribStats(tree.step, loopEnv);
   802         attribStat(tree.body, loopEnv);
   803         loopEnv.info.scope.leave();
   804         result = null;
   805     }
   807     public void visitForeachLoop(JCEnhancedForLoop tree) {
   808         Env<AttrContext> loopEnv =
   809             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   810         attribStat(tree.var, loopEnv);
   811         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   812         chk.checkNonVoid(tree.pos(), exprType);
   813         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   814         if (elemtype == null) {
   815             // or perhaps expr implements Iterable<T>?
   816             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   817             if (base == null) {
   818                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   819                 elemtype = types.createErrorType(exprType);
   820             } else {
   821                 List<Type> iterableParams = base.allparams();
   822                 elemtype = iterableParams.isEmpty()
   823                     ? syms.objectType
   824                     : types.upperBound(iterableParams.head);
   825             }
   826         }
   827         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   828         loopEnv.tree = tree; // before, we were not in loop!
   829         attribStat(tree.body, loopEnv);
   830         loopEnv.info.scope.leave();
   831         result = null;
   832     }
   834     public void visitLabelled(JCLabeledStatement tree) {
   835         // Check that label is not used in an enclosing statement
   836         Env<AttrContext> env1 = env;
   837         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   838             if (env1.tree.getTag() == JCTree.LABELLED &&
   839                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   840                 log.error(tree.pos(), "label.already.in.use",
   841                           tree.label);
   842                 break;
   843             }
   844             env1 = env1.next;
   845         }
   847         attribStat(tree.body, env.dup(tree));
   848         result = null;
   849     }
   851     public void visitSwitch(JCSwitch tree) {
   852         Type seltype = attribExpr(tree.selector, env);
   854         Env<AttrContext> switchEnv =
   855             env.dup(tree, env.info.dup(env.info.scope.dup()));
   857         boolean enumSwitch =
   858             allowEnums &&
   859             (seltype.tsym.flags() & Flags.ENUM) != 0;
   860         if (!enumSwitch)
   861             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   863         // Attribute all cases and
   864         // check that there are no duplicate case labels or default clauses.
   865         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   866         boolean hasDefault = false;      // Is there a default label?
   867         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   868             JCCase c = l.head;
   869             Env<AttrContext> caseEnv =
   870                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   871             if (c.pat != null) {
   872                 if (enumSwitch) {
   873                     Symbol sym = enumConstant(c.pat, seltype);
   874                     if (sym == null) {
   875                         log.error(c.pat.pos(), "enum.const.req");
   876                     } else if (!labels.add(sym)) {
   877                         log.error(c.pos(), "duplicate.case.label");
   878                     }
   879                 } else {
   880                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   881                     if (pattype.tag != ERROR) {
   882                         if (pattype.constValue() == null) {
   883                             log.error(c.pat.pos(), "const.expr.req");
   884                         } else if (labels.contains(pattype.constValue())) {
   885                             log.error(c.pos(), "duplicate.case.label");
   886                         } else {
   887                             labels.add(pattype.constValue());
   888                         }
   889                     }
   890                 }
   891             } else if (hasDefault) {
   892                 log.error(c.pos(), "duplicate.default.label");
   893             } else {
   894                 hasDefault = true;
   895             }
   896             attribStats(c.stats, caseEnv);
   897             caseEnv.info.scope.leave();
   898             addVars(c.stats, switchEnv.info.scope);
   899         }
   901         switchEnv.info.scope.leave();
   902         result = null;
   903     }
   904     // where
   905         /** Add any variables defined in stats to the switch scope. */
   906         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   907             for (;stats.nonEmpty(); stats = stats.tail) {
   908                 JCTree stat = stats.head;
   909                 if (stat.getTag() == JCTree.VARDEF)
   910                     switchScope.enter(((JCVariableDecl) stat).sym);
   911             }
   912         }
   913     // where
   914     /** Return the selected enumeration constant symbol, or null. */
   915     private Symbol enumConstant(JCTree tree, Type enumType) {
   916         if (tree.getTag() != JCTree.IDENT) {
   917             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   918             return syms.errSymbol;
   919         }
   920         JCIdent ident = (JCIdent)tree;
   921         Name name = ident.name;
   922         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   923              e.scope != null; e = e.next()) {
   924             if (e.sym.kind == VAR) {
   925                 Symbol s = ident.sym = e.sym;
   926                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   927                 ident.type = s.type;
   928                 return ((s.flags_field & Flags.ENUM) == 0)
   929                     ? null : s;
   930             }
   931         }
   932         return null;
   933     }
   935     public void visitSynchronized(JCSynchronized tree) {
   936         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
   937         attribStat(tree.body, env);
   938         result = null;
   939     }
   941     public void visitTry(JCTry tree) {
   942         // Attribute body
   943         attribStat(tree.body, env.dup(tree, env.info.dup()));
   945         // Attribute catch clauses
   946         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   947             JCCatch c = l.head;
   948             Env<AttrContext> catchEnv =
   949                 env.dup(c, env.info.dup(env.info.scope.dup()));
   950             Type ctype = attribStat(c.param, catchEnv);
   951             if (c.param.type.tsym.kind == Kinds.VAR) {
   952                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
   953             }
   954             chk.checkType(c.param.vartype.pos(),
   955                           chk.checkClassType(c.param.vartype.pos(), ctype),
   956                           syms.throwableType);
   957             attribStat(c.body, catchEnv);
   958             catchEnv.info.scope.leave();
   959         }
   961         // Attribute finalizer
   962         if (tree.finalizer != null) attribStat(tree.finalizer, env);
   963         result = null;
   964     }
   966     public void visitConditional(JCConditional tree) {
   967         attribExpr(tree.cond, env, syms.booleanType);
   968         attribExpr(tree.truepart, env);
   969         attribExpr(tree.falsepart, env);
   970         result = check(tree,
   971                        capture(condType(tree.pos(), tree.cond.type,
   972                                         tree.truepart.type, tree.falsepart.type)),
   973                        VAL, pkind, pt);
   974     }
   975     //where
   976         /** Compute the type of a conditional expression, after
   977          *  checking that it exists. See Spec 15.25.
   978          *
   979          *  @param pos      The source position to be used for
   980          *                  error diagnostics.
   981          *  @param condtype The type of the expression's condition.
   982          *  @param thentype The type of the expression's then-part.
   983          *  @param elsetype The type of the expression's else-part.
   984          */
   985         private Type condType(DiagnosticPosition pos,
   986                               Type condtype,
   987                               Type thentype,
   988                               Type elsetype) {
   989             Type ctype = condType1(pos, condtype, thentype, elsetype);
   991             // If condition and both arms are numeric constants,
   992             // evaluate at compile-time.
   993             return ((condtype.constValue() != null) &&
   994                     (thentype.constValue() != null) &&
   995                     (elsetype.constValue() != null))
   996                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
   997                 : ctype;
   998         }
   999         /** Compute the type of a conditional expression, after
  1000          *  checking that it exists.  Does not take into
  1001          *  account the special case where condition and both arms
  1002          *  are constants.
  1004          *  @param pos      The source position to be used for error
  1005          *                  diagnostics.
  1006          *  @param condtype The type of the expression's condition.
  1007          *  @param thentype The type of the expression's then-part.
  1008          *  @param elsetype The type of the expression's else-part.
  1009          */
  1010         private Type condType1(DiagnosticPosition pos, Type condtype,
  1011                                Type thentype, Type elsetype) {
  1012             // If same type, that is the result
  1013             if (types.isSameType(thentype, elsetype))
  1014                 return thentype.baseType();
  1016             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1017                 ? thentype : types.unboxedType(thentype);
  1018             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1019                 ? elsetype : types.unboxedType(elsetype);
  1021             // Otherwise, if both arms can be converted to a numeric
  1022             // type, return the least numeric type that fits both arms
  1023             // (i.e. return larger of the two, or return int if one
  1024             // arm is short, the other is char).
  1025             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1026                 // If one arm has an integer subrange type (i.e., byte,
  1027                 // short, or char), and the other is an integer constant
  1028                 // that fits into the subrange, return the subrange type.
  1029                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1030                     types.isAssignable(elseUnboxed, thenUnboxed))
  1031                     return thenUnboxed.baseType();
  1032                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1033                     types.isAssignable(thenUnboxed, elseUnboxed))
  1034                     return elseUnboxed.baseType();
  1036                 for (int i = BYTE; i < VOID; i++) {
  1037                     Type candidate = syms.typeOfTag[i];
  1038                     if (types.isSubtype(thenUnboxed, candidate) &&
  1039                         types.isSubtype(elseUnboxed, candidate))
  1040                         return candidate;
  1044             // Those were all the cases that could result in a primitive
  1045             if (allowBoxing) {
  1046                 if (thentype.isPrimitive())
  1047                     thentype = types.boxedClass(thentype).type;
  1048                 if (elsetype.isPrimitive())
  1049                     elsetype = types.boxedClass(elsetype).type;
  1052             if (types.isSubtype(thentype, elsetype))
  1053                 return elsetype.baseType();
  1054             if (types.isSubtype(elsetype, thentype))
  1055                 return thentype.baseType();
  1057             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1058                 log.error(pos, "neither.conditional.subtype",
  1059                           thentype, elsetype);
  1060                 return thentype.baseType();
  1063             // both are known to be reference types.  The result is
  1064             // lub(thentype,elsetype). This cannot fail, as it will
  1065             // always be possible to infer "Object" if nothing better.
  1066             return types.lub(thentype.baseType(), elsetype.baseType());
  1069     public void visitIf(JCIf tree) {
  1070         attribExpr(tree.cond, env, syms.booleanType);
  1071         attribStat(tree.thenpart, env);
  1072         if (tree.elsepart != null)
  1073             attribStat(tree.elsepart, env);
  1074         chk.checkEmptyIf(tree);
  1075         result = null;
  1078     public void visitExec(JCExpressionStatement tree) {
  1079         attribExpr(tree.expr, env);
  1080         result = null;
  1083     public void visitBreak(JCBreak tree) {
  1084         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1085         result = null;
  1088     public void visitContinue(JCContinue tree) {
  1089         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1090         result = null;
  1092     //where
  1093         /** Return the target of a break or continue statement, if it exists,
  1094          *  report an error if not.
  1095          *  Note: The target of a labelled break or continue is the
  1096          *  (non-labelled) statement tree referred to by the label,
  1097          *  not the tree representing the labelled statement itself.
  1099          *  @param pos     The position to be used for error diagnostics
  1100          *  @param tag     The tag of the jump statement. This is either
  1101          *                 Tree.BREAK or Tree.CONTINUE.
  1102          *  @param label   The label of the jump statement, or null if no
  1103          *                 label is given.
  1104          *  @param env     The environment current at the jump statement.
  1105          */
  1106         private JCTree findJumpTarget(DiagnosticPosition pos,
  1107                                     int tag,
  1108                                     Name label,
  1109                                     Env<AttrContext> env) {
  1110             // Search environments outwards from the point of jump.
  1111             Env<AttrContext> env1 = env;
  1112             LOOP:
  1113             while (env1 != null) {
  1114                 switch (env1.tree.getTag()) {
  1115                 case JCTree.LABELLED:
  1116                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1117                     if (label == labelled.label) {
  1118                         // If jump is a continue, check that target is a loop.
  1119                         if (tag == JCTree.CONTINUE) {
  1120                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1121                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1122                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1123                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1124                                 log.error(pos, "not.loop.label", label);
  1125                             // Found labelled statement target, now go inwards
  1126                             // to next non-labelled tree.
  1127                             return TreeInfo.referencedStatement(labelled);
  1128                         } else {
  1129                             return labelled;
  1132                     break;
  1133                 case JCTree.DOLOOP:
  1134                 case JCTree.WHILELOOP:
  1135                 case JCTree.FORLOOP:
  1136                 case JCTree.FOREACHLOOP:
  1137                     if (label == null) return env1.tree;
  1138                     break;
  1139                 case JCTree.SWITCH:
  1140                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1141                     break;
  1142                 case JCTree.METHODDEF:
  1143                 case JCTree.CLASSDEF:
  1144                     break LOOP;
  1145                 default:
  1147                 env1 = env1.next;
  1149             if (label != null)
  1150                 log.error(pos, "undef.label", label);
  1151             else if (tag == JCTree.CONTINUE)
  1152                 log.error(pos, "cont.outside.loop");
  1153             else
  1154                 log.error(pos, "break.outside.switch.loop");
  1155             return null;
  1158     public void visitReturn(JCReturn tree) {
  1159         // Check that there is an enclosing method which is
  1160         // nested within than the enclosing class.
  1161         if (env.enclMethod == null ||
  1162             env.enclMethod.sym.owner != env.enclClass.sym) {
  1163             log.error(tree.pos(), "ret.outside.meth");
  1165         } else {
  1166             // Attribute return expression, if it exists, and check that
  1167             // it conforms to result type of enclosing method.
  1168             Symbol m = env.enclMethod.sym;
  1169             if (m.type.getReturnType().tag == VOID) {
  1170                 if (tree.expr != null)
  1171                     log.error(tree.expr.pos(),
  1172                               "cant.ret.val.from.meth.decl.void");
  1173             } else if (tree.expr == null) {
  1174                 log.error(tree.pos(), "missing.ret.val");
  1175             } else {
  1176                 attribExpr(tree.expr, env, m.type.getReturnType());
  1179         result = null;
  1182     public void visitThrow(JCThrow tree) {
  1183         attribExpr(tree.expr, env, syms.throwableType);
  1184         result = null;
  1187     public void visitAssert(JCAssert tree) {
  1188         attribExpr(tree.cond, env, syms.booleanType);
  1189         if (tree.detail != null) {
  1190             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1192         result = null;
  1195      /** Visitor method for method invocations.
  1196      *  NOTE: The method part of an application will have in its type field
  1197      *        the return type of the method, not the method's type itself!
  1198      */
  1199     public void visitApply(JCMethodInvocation tree) {
  1200         // The local environment of a method application is
  1201         // a new environment nested in the current one.
  1202         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1204         // The types of the actual method arguments.
  1205         List<Type> argtypes;
  1207         // The types of the actual method type arguments.
  1208         List<Type> typeargtypes = null;
  1209         boolean typeargtypesNonRefOK = false;
  1211         Name methName = TreeInfo.name(tree.meth);
  1213         boolean isConstructorCall =
  1214             methName == names._this || methName == names._super;
  1216         if (isConstructorCall) {
  1217             // We are seeing a ...this(...) or ...super(...) call.
  1218             // Check that this is the first statement in a constructor.
  1219             if (checkFirstConstructorStat(tree, env)) {
  1221                 // Record the fact
  1222                 // that this is a constructor call (using isSelfCall).
  1223                 localEnv.info.isSelfCall = true;
  1225                 // Attribute arguments, yielding list of argument types.
  1226                 argtypes = attribArgs(tree.args, localEnv);
  1227                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1229                 // Variable `site' points to the class in which the called
  1230                 // constructor is defined.
  1231                 Type site = env.enclClass.sym.type;
  1232                 if (methName == names._super) {
  1233                     if (site == syms.objectType) {
  1234                         log.error(tree.meth.pos(), "no.superclass", site);
  1235                         site = types.createErrorType(syms.objectType);
  1236                     } else {
  1237                         site = types.supertype(site);
  1241                 if (site.tag == CLASS) {
  1242                     if (site.getEnclosingType().tag == CLASS) {
  1243                         // we are calling a nested class
  1245                         if (tree.meth.getTag() == JCTree.SELECT) {
  1246                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1248                             // We are seeing a prefixed call, of the form
  1249                             //     <expr>.super(...).
  1250                             // Check that the prefix expression conforms
  1251                             // to the outer instance type of the class.
  1252                             chk.checkRefType(qualifier.pos(),
  1253                                              attribExpr(qualifier, localEnv,
  1254                                                         site.getEnclosingType()));
  1255                         } else if (methName == names._super) {
  1256                             // qualifier omitted; check for existence
  1257                             // of an appropriate implicit qualifier.
  1258                             rs.resolveImplicitThis(tree.meth.pos(),
  1259                                                    localEnv, site);
  1261                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1262                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1263                                   site.tsym);
  1266                     // if we're calling a java.lang.Enum constructor,
  1267                     // prefix the implicit String and int parameters
  1268                     if (site.tsym == syms.enumSym && allowEnums)
  1269                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1271                     // Resolve the called constructor under the assumption
  1272                     // that we are referring to a superclass instance of the
  1273                     // current instance (JLS ???).
  1274                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1275                     localEnv.info.selectSuper = true;
  1276                     localEnv.info.varArgs = false;
  1277                     Symbol sym = rs.resolveConstructor(
  1278                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1279                     localEnv.info.selectSuper = selectSuperPrev;
  1281                     // Set method symbol to resolved constructor...
  1282                     TreeInfo.setSymbol(tree.meth, sym);
  1284                     // ...and check that it is legal in the current context.
  1285                     // (this will also set the tree's type)
  1286                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1287                     checkId(tree.meth, site, sym, localEnv, MTH,
  1288                             mpt, tree.varargsElement != null);
  1290                 // Otherwise, `site' is an error type and we do nothing
  1292             result = tree.type = syms.voidType;
  1293         } else {
  1294             // Otherwise, we are seeing a regular method call.
  1295             // Attribute the arguments, yielding list of argument types, ...
  1296             argtypes = attribArgs(tree.args, localEnv);
  1297             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1299             // ... and attribute the method using as a prototype a methodtype
  1300             // whose formal argument types is exactly the list of actual
  1301             // arguments (this will also set the method symbol).
  1302             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1303             localEnv.info.varArgs = false;
  1304             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1305             if (localEnv.info.varArgs)
  1306                 assert mtype.isErroneous() || tree.varargsElement != null;
  1308             // Compute the result type.
  1309             Type restype = mtype.getReturnType();
  1310             assert restype.tag != WILDCARD : mtype;
  1312             // as a special case, array.clone() has a result that is
  1313             // the same as static type of the array being cloned
  1314             if (tree.meth.getTag() == JCTree.SELECT &&
  1315                 allowCovariantReturns &&
  1316                 methName == names.clone &&
  1317                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1318                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1320             // as a special case, x.getClass() has type Class<? extends |X|>
  1321             if (allowGenerics &&
  1322                 methName == names.getClass && tree.args.isEmpty()) {
  1323                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1324                     ? ((JCFieldAccess) tree.meth).selected.type
  1325                     : env.enclClass.sym.type;
  1326                 restype = new
  1327                     ClassType(restype.getEnclosingType(),
  1328                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1329                                                                BoundKind.EXTENDS,
  1330                                                                syms.boundClass)),
  1331                               restype.tsym);
  1334             // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
  1335             // has type <T>, and T can be a primitive type.
  1336             if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
  1337               Type selt = ((JCFieldAccess) tree.meth).selected.type;
  1338               if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) {
  1339                   assert types.isSameType(restype, typeargtypes.head) : mtype;
  1340                   typeargtypesNonRefOK = true;
  1344             if (!typeargtypesNonRefOK) {
  1345                 chk.checkRefTypes(tree.typeargs, typeargtypes);
  1348             // Check that value of resulting type is admissible in the
  1349             // current context.  Also, capture the return type
  1350             result = check(tree, capture(restype), VAL, pkind, pt);
  1352         chk.validate(tree.typeargs, localEnv);
  1354     //where
  1355         /** Check that given application node appears as first statement
  1356          *  in a constructor call.
  1357          *  @param tree   The application node
  1358          *  @param env    The environment current at the application.
  1359          */
  1360         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1361             JCMethodDecl enclMethod = env.enclMethod;
  1362             if (enclMethod != null && enclMethod.name == names.init) {
  1363                 JCBlock body = enclMethod.body;
  1364                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1365                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1366                     return true;
  1368             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1369                       TreeInfo.name(tree.meth));
  1370             return false;
  1373         /** Obtain a method type with given argument types.
  1374          */
  1375         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1376             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1377             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1380     public void visitNewClass(JCNewClass tree) {
  1381         Type owntype = types.createErrorType(tree.type);
  1383         // The local environment of a class creation is
  1384         // a new environment nested in the current one.
  1385         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1387         // The anonymous inner class definition of the new expression,
  1388         // if one is defined by it.
  1389         JCClassDecl cdef = tree.def;
  1391         // If enclosing class is given, attribute it, and
  1392         // complete class name to be fully qualified
  1393         JCExpression clazz = tree.clazz; // Class field following new
  1394         JCExpression clazzid =          // Identifier in class field
  1395             (clazz.getTag() == JCTree.TYPEAPPLY)
  1396             ? ((JCTypeApply) clazz).clazz
  1397             : clazz;
  1399         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1401         if (tree.encl != null) {
  1402             // We are seeing a qualified new, of the form
  1403             //    <expr>.new C <...> (...) ...
  1404             // In this case, we let clazz stand for the name of the
  1405             // allocated class C prefixed with the type of the qualifier
  1406             // expression, so that we can
  1407             // resolve it with standard techniques later. I.e., if
  1408             // <expr> has type T, then <expr>.new C <...> (...)
  1409             // yields a clazz T.C.
  1410             Type encltype = chk.checkRefType(tree.encl.pos(),
  1411                                              attribExpr(tree.encl, env));
  1412             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1413                                                  ((JCIdent) clazzid).name);
  1414             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1415                 clazz = make.at(tree.pos).
  1416                     TypeApply(clazzid1,
  1417                               ((JCTypeApply) clazz).arguments);
  1418             else
  1419                 clazz = clazzid1;
  1420 //          System.out.println(clazz + " generated.");//DEBUG
  1423         // Attribute clazz expression and store
  1424         // symbol + type back into the attributed tree.
  1425         Type clazztype = chk.checkClassType(
  1426             tree.clazz.pos(), attribType(clazz, env), true);
  1427         chk.validate(clazz, localEnv);
  1428         if (tree.encl != null) {
  1429             // We have to work in this case to store
  1430             // symbol + type back into the attributed tree.
  1431             tree.clazz.type = clazztype;
  1432             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1433             clazzid.type = ((JCIdent) clazzid).sym.type;
  1434             if (!clazztype.isErroneous()) {
  1435                 if (cdef != null && clazztype.tsym.isInterface()) {
  1436                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1437                 } else if (clazztype.tsym.isStatic()) {
  1438                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1441         } else if (!clazztype.tsym.isInterface() &&
  1442                    clazztype.getEnclosingType().tag == CLASS) {
  1443             // Check for the existence of an apropos outer instance
  1444             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1447         // Attribute constructor arguments.
  1448         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1449         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1451         // If we have made no mistakes in the class type...
  1452         if (clazztype.tag == CLASS) {
  1453             // Enums may not be instantiated except implicitly
  1454             if (allowEnums &&
  1455                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1456                 (env.tree.getTag() != JCTree.VARDEF ||
  1457                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1458                  ((JCVariableDecl) env.tree).init != tree))
  1459                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1460             // Check that class is not abstract
  1461             if (cdef == null &&
  1462                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1463                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1464                           clazztype.tsym);
  1465             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1466                 // Check that no constructor arguments are given to
  1467                 // anonymous classes implementing an interface
  1468                 if (!argtypes.isEmpty())
  1469                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1471                 if (!typeargtypes.isEmpty())
  1472                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1474                 // Error recovery: pretend no arguments were supplied.
  1475                 argtypes = List.nil();
  1476                 typeargtypes = List.nil();
  1479             // Resolve the called constructor under the assumption
  1480             // that we are referring to a superclass instance of the
  1481             // current instance (JLS ???).
  1482             else {
  1483                 localEnv.info.selectSuper = cdef != null;
  1484                 localEnv.info.varArgs = false;
  1485                 tree.constructor = rs.resolveConstructor(
  1486                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1487                 tree.constructorType = checkMethod(clazztype,
  1488                                             tree.constructor,
  1489                                             localEnv,
  1490                                             tree.args,
  1491                                             argtypes,
  1492                                             typeargtypes,
  1493                                             localEnv.info.varArgs);
  1494                 if (localEnv.info.varArgs)
  1495                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
  1498             if (cdef != null) {
  1499                 // We are seeing an anonymous class instance creation.
  1500                 // In this case, the class instance creation
  1501                 // expression
  1502                 //
  1503                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1504                 //
  1505                 // is represented internally as
  1506                 //
  1507                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1508                 //
  1509                 // This expression is then *transformed* as follows:
  1510                 //
  1511                 // (1) add a STATIC flag to the class definition
  1512                 //     if the current environment is static
  1513                 // (2) add an extends or implements clause
  1514                 // (3) add a constructor.
  1515                 //
  1516                 // For instance, if C is a class, and ET is the type of E,
  1517                 // the expression
  1518                 //
  1519                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1520                 //
  1521                 // is translated to (where X is a fresh name and typarams is the
  1522                 // parameter list of the super constructor):
  1523                 //
  1524                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1525                 //     X extends C<typargs2> {
  1526                 //       <typarams> X(ET e, args) {
  1527                 //         e.<typeargs1>super(args)
  1528                 //       }
  1529                 //       ...
  1530                 //     }
  1531                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1533                 if (clazztype.tsym.isInterface()) {
  1534                     cdef.implementing = List.of(clazz);
  1535                 } else {
  1536                     cdef.extending = clazz;
  1539                 attribStat(cdef, localEnv);
  1541                 // If an outer instance is given,
  1542                 // prefix it to the constructor arguments
  1543                 // and delete it from the new expression
  1544                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1545                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1546                     argtypes = argtypes.prepend(tree.encl.type);
  1547                     tree.encl = null;
  1550                 // Reassign clazztype and recompute constructor.
  1551                 clazztype = cdef.sym.type;
  1552                 Symbol sym = rs.resolveConstructor(
  1553                     tree.pos(), localEnv, clazztype, argtypes,
  1554                     typeargtypes, true, tree.varargsElement != null);
  1555                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1556                 tree.constructor = sym;
  1557                 tree.constructorType = checkMethod(clazztype,
  1558                                             tree.constructor,
  1559                                             localEnv,
  1560                                             tree.args,
  1561                                             argtypes,
  1562                                             typeargtypes,
  1563                                             localEnv.info.varArgs);
  1566             if (tree.constructor != null && tree.constructor.kind == MTH)
  1567                 owntype = clazztype;
  1569         result = check(tree, owntype, VAL, pkind, pt);
  1570         chk.validate(tree.typeargs, localEnv);
  1573     /** Make an attributed null check tree.
  1574      */
  1575     public JCExpression makeNullCheck(JCExpression arg) {
  1576         // optimization: X.this is never null; skip null check
  1577         Name name = TreeInfo.name(arg);
  1578         if (name == names._this || name == names._super) return arg;
  1580         int optag = JCTree.NULLCHK;
  1581         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1582         tree.operator = syms.nullcheck;
  1583         tree.type = arg.type;
  1584         return tree;
  1587     public void visitNewArray(JCNewArray tree) {
  1588         Type owntype = types.createErrorType(tree.type);
  1589         Type elemtype;
  1590         if (tree.elemtype != null) {
  1591             elemtype = attribType(tree.elemtype, env);
  1592             chk.validate(tree.elemtype, env);
  1593             owntype = elemtype;
  1594             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1595                 attribExpr(l.head, env, syms.intType);
  1596                 owntype = new ArrayType(owntype, syms.arrayClass);
  1598         } else {
  1599             // we are seeing an untyped aggregate { ... }
  1600             // this is allowed only if the prototype is an array
  1601             if (pt.tag == ARRAY) {
  1602                 elemtype = types.elemtype(pt);
  1603             } else {
  1604                 if (pt.tag != ERROR) {
  1605                     log.error(tree.pos(), "illegal.initializer.for.type",
  1606                               pt);
  1608                 elemtype = types.createErrorType(pt);
  1611         if (tree.elems != null) {
  1612             attribExprs(tree.elems, env, elemtype);
  1613             owntype = new ArrayType(elemtype, syms.arrayClass);
  1615         if (!types.isReifiable(elemtype))
  1616             log.error(tree.pos(), "generic.array.creation");
  1617         result = check(tree, owntype, VAL, pkind, pt);
  1620     public void visitParens(JCParens tree) {
  1621         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1622         result = check(tree, owntype, pkind, pkind, pt);
  1623         Symbol sym = TreeInfo.symbol(tree);
  1624         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1625             log.error(tree.pos(), "illegal.start.of.type");
  1628     public void visitAssign(JCAssign tree) {
  1629         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1630         Type capturedType = capture(owntype);
  1631         attribExpr(tree.rhs, env, owntype);
  1632         result = check(tree, capturedType, VAL, pkind, pt);
  1635     public void visitAssignop(JCAssignOp tree) {
  1636         // Attribute arguments.
  1637         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1638         Type operand = attribExpr(tree.rhs, env);
  1639         // Find operator.
  1640         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1641             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1642             owntype, operand);
  1644         if (operator.kind == MTH) {
  1645             chk.checkOperator(tree.pos(),
  1646                               (OperatorSymbol)operator,
  1647                               tree.getTag() - JCTree.ASGOffset,
  1648                               owntype,
  1649                               operand);
  1650             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1651             chk.checkCastable(tree.rhs.pos(),
  1652                               operator.type.getReturnType(),
  1653                               owntype);
  1655         result = check(tree, owntype, VAL, pkind, pt);
  1658     public void visitUnary(JCUnary tree) {
  1659         // Attribute arguments.
  1660         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1661             ? attribTree(tree.arg, env, VAR, Type.noType)
  1662             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1664         // Find operator.
  1665         Symbol operator = tree.operator =
  1666             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1668         Type owntype = types.createErrorType(tree.type);
  1669         if (operator.kind == MTH) {
  1670             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1671                 ? tree.arg.type
  1672                 : operator.type.getReturnType();
  1673             int opc = ((OperatorSymbol)operator).opcode;
  1675             // If the argument is constant, fold it.
  1676             if (argtype.constValue() != null) {
  1677                 Type ctype = cfolder.fold1(opc, argtype);
  1678                 if (ctype != null) {
  1679                     owntype = cfolder.coerce(ctype, owntype);
  1681                     // Remove constant types from arguments to
  1682                     // conserve space. The parser will fold concatenations
  1683                     // of string literals; the code here also
  1684                     // gets rid of intermediate results when some of the
  1685                     // operands are constant identifiers.
  1686                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1687                         tree.arg.type = syms.stringType;
  1692         result = check(tree, owntype, VAL, pkind, pt);
  1695     public void visitBinary(JCBinary tree) {
  1696         // Attribute arguments.
  1697         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1698         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1700         // Find operator.
  1701         Symbol operator = tree.operator =
  1702             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1704         Type owntype = types.createErrorType(tree.type);
  1705         if (operator.kind == MTH) {
  1706             owntype = operator.type.getReturnType();
  1707             int opc = chk.checkOperator(tree.lhs.pos(),
  1708                                         (OperatorSymbol)operator,
  1709                                         tree.getTag(),
  1710                                         left,
  1711                                         right);
  1713             // If both arguments are constants, fold them.
  1714             if (left.constValue() != null && right.constValue() != null) {
  1715                 Type ctype = cfolder.fold2(opc, left, right);
  1716                 if (ctype != null) {
  1717                     owntype = cfolder.coerce(ctype, owntype);
  1719                     // Remove constant types from arguments to
  1720                     // conserve space. The parser will fold concatenations
  1721                     // of string literals; the code here also
  1722                     // gets rid of intermediate results when some of the
  1723                     // operands are constant identifiers.
  1724                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1725                         tree.lhs.type = syms.stringType;
  1727                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1728                         tree.rhs.type = syms.stringType;
  1733             // Check that argument types of a reference ==, != are
  1734             // castable to each other, (JLS???).
  1735             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  1736                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  1737                     log.error(tree.pos(), "incomparable.types", left, right);
  1741             chk.checkDivZero(tree.rhs.pos(), operator, right);
  1743         result = check(tree, owntype, VAL, pkind, pt);
  1746     public void visitTypeCast(JCTypeCast tree) {
  1747         Type clazztype = attribType(tree.clazz, env);
  1748         chk.validate(tree.clazz, env);
  1749         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  1750         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1751         if (exprtype.constValue() != null)
  1752             owntype = cfolder.coerce(exprtype, owntype);
  1753         result = check(tree, capture(owntype), VAL, pkind, pt);
  1756     public void visitTypeTest(JCInstanceOf tree) {
  1757         Type exprtype = chk.checkNullOrRefType(
  1758             tree.expr.pos(), attribExpr(tree.expr, env));
  1759         Type clazztype = chk.checkReifiableReferenceType(
  1760             tree.clazz.pos(), attribType(tree.clazz, env));
  1761         chk.validate(tree.clazz, env);
  1762         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1763         result = check(tree, syms.booleanType, VAL, pkind, pt);
  1766     public void visitIndexed(JCArrayAccess tree) {
  1767         Type owntype = types.createErrorType(tree.type);
  1768         Type atype = attribExpr(tree.indexed, env);
  1769         attribExpr(tree.index, env, syms.intType);
  1770         if (types.isArray(atype))
  1771             owntype = types.elemtype(atype);
  1772         else if (atype.tag != ERROR)
  1773             log.error(tree.pos(), "array.req.but.found", atype);
  1774         if ((pkind & VAR) == 0) owntype = capture(owntype);
  1775         result = check(tree, owntype, VAR, pkind, pt);
  1778     public void visitIdent(JCIdent tree) {
  1779         Symbol sym;
  1780         boolean varArgs = false;
  1782         // Find symbol
  1783         if (pt.tag == METHOD || pt.tag == FORALL) {
  1784             // If we are looking for a method, the prototype `pt' will be a
  1785             // method type with the type of the call's arguments as parameters.
  1786             env.info.varArgs = false;
  1787             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  1788             varArgs = env.info.varArgs;
  1789         } else if (tree.sym != null && tree.sym.kind != VAR) {
  1790             sym = tree.sym;
  1791         } else {
  1792             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  1794         tree.sym = sym;
  1796         // (1) Also find the environment current for the class where
  1797         //     sym is defined (`symEnv').
  1798         // Only for pre-tiger versions (1.4 and earlier):
  1799         // (2) Also determine whether we access symbol out of an anonymous
  1800         //     class in a this or super call.  This is illegal for instance
  1801         //     members since such classes don't carry a this$n link.
  1802         //     (`noOuterThisPath').
  1803         Env<AttrContext> symEnv = env;
  1804         boolean noOuterThisPath = false;
  1805         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  1806             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  1807             sym.owner.kind == TYP &&
  1808             tree.name != names._this && tree.name != names._super) {
  1810             // Find environment in which identifier is defined.
  1811             while (symEnv.outer != null &&
  1812                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  1813                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  1814                     noOuterThisPath = !allowAnonOuterThis;
  1815                 symEnv = symEnv.outer;
  1819         // If symbol is a variable, ...
  1820         if (sym.kind == VAR) {
  1821             VarSymbol v = (VarSymbol)sym;
  1823             // ..., evaluate its initializer, if it has one, and check for
  1824             // illegal forward reference.
  1825             checkInit(tree, env, v, false);
  1827             // If symbol is a local variable accessed from an embedded
  1828             // inner class check that it is final.
  1829             if (v.owner.kind == MTH &&
  1830                 v.owner != env.info.scope.owner &&
  1831                 (v.flags_field & FINAL) == 0) {
  1832                 log.error(tree.pos(),
  1833                           "local.var.accessed.from.icls.needs.final",
  1834                           v);
  1837             // If we are expecting a variable (as opposed to a value), check
  1838             // that the variable is assignable in the current environment.
  1839             if (pkind == VAR)
  1840                 checkAssignable(tree.pos(), v, null, env);
  1843         // In a constructor body,
  1844         // if symbol is a field or instance method, check that it is
  1845         // not accessed before the supertype constructor is called.
  1846         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  1847             (sym.kind & (VAR | MTH)) != 0 &&
  1848             sym.owner.kind == TYP &&
  1849             (sym.flags() & STATIC) == 0) {
  1850             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  1852         Env<AttrContext> env1 = env;
  1853         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  1854             // If the found symbol is inaccessible, then it is
  1855             // accessed through an enclosing instance.  Locate this
  1856             // enclosing instance:
  1857             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  1858                 env1 = env1.outer;
  1860         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  1863     public void visitSelect(JCFieldAccess tree) {
  1864         // Determine the expected kind of the qualifier expression.
  1865         int skind = 0;
  1866         if (tree.name == names._this || tree.name == names._super ||
  1867             tree.name == names._class)
  1869             skind = TYP;
  1870         } else {
  1871             if ((pkind & PCK) != 0) skind = skind | PCK;
  1872             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  1873             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  1876         // Attribute the qualifier expression, and determine its symbol (if any).
  1877         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  1878         if ((pkind & (PCK | TYP)) == 0)
  1879             site = capture(site); // Capture field access
  1881         // don't allow T.class T[].class, etc
  1882         if (skind == TYP) {
  1883             Type elt = site;
  1884             while (elt.tag == ARRAY)
  1885                 elt = ((ArrayType)elt).elemtype;
  1886             if (elt.tag == TYPEVAR) {
  1887                 log.error(tree.pos(), "type.var.cant.be.deref");
  1888                 result = types.createErrorType(tree.type);
  1889                 return;
  1893         // If qualifier symbol is a type or `super', assert `selectSuper'
  1894         // for the selection. This is relevant for determining whether
  1895         // protected symbols are accessible.
  1896         Symbol sitesym = TreeInfo.symbol(tree.selected);
  1897         boolean selectSuperPrev = env.info.selectSuper;
  1898         env.info.selectSuper =
  1899             sitesym != null &&
  1900             sitesym.name == names._super;
  1902         // If selected expression is polymorphic, strip
  1903         // type parameters and remember in env.info.tvars, so that
  1904         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  1905         if (tree.selected.type.tag == FORALL) {
  1906             ForAll pstype = (ForAll)tree.selected.type;
  1907             env.info.tvars = pstype.tvars;
  1908             site = tree.selected.type = pstype.qtype;
  1911         // Determine the symbol represented by the selection.
  1912         env.info.varArgs = false;
  1913         Symbol sym = selectSym(tree, site, env, pt, pkind);
  1914         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  1915             site = capture(site);
  1916             sym = selectSym(tree, site, env, pt, pkind);
  1918         boolean varArgs = env.info.varArgs;
  1919         tree.sym = sym;
  1921         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  1922             while (site.tag == TYPEVAR) site = site.getUpperBound();
  1923             site = capture(site);
  1926         // If that symbol is a variable, ...
  1927         if (sym.kind == VAR) {
  1928             VarSymbol v = (VarSymbol)sym;
  1930             // ..., evaluate its initializer, if it has one, and check for
  1931             // illegal forward reference.
  1932             checkInit(tree, env, v, true);
  1934             // If we are expecting a variable (as opposed to a value), check
  1935             // that the variable is assignable in the current environment.
  1936             if (pkind == VAR)
  1937                 checkAssignable(tree.pos(), v, tree.selected, env);
  1940         // Disallow selecting a type from an expression
  1941         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  1942             tree.type = check(tree.selected, pt,
  1943                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  1946         if (isType(sitesym)) {
  1947             if (sym.name == names._this) {
  1948                 // If `C' is the currently compiled class, check that
  1949                 // C.this' does not appear in a call to a super(...)
  1950                 if (env.info.isSelfCall &&
  1951                     site.tsym == env.enclClass.sym) {
  1952                     chk.earlyRefError(tree.pos(), sym);
  1954             } else {
  1955                 // Check if type-qualified fields or methods are static (JLS)
  1956                 if ((sym.flags() & STATIC) == 0 &&
  1957                     sym.name != names._super &&
  1958                     (sym.kind == VAR || sym.kind == MTH)) {
  1959                     rs.access(rs.new StaticError(sym),
  1960                               tree.pos(), site, sym.name, true);
  1965         // If we are selecting an instance member via a `super', ...
  1966         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  1968             // Check that super-qualified symbols are not abstract (JLS)
  1969             rs.checkNonAbstract(tree.pos(), sym);
  1971             if (site.isRaw()) {
  1972                 // Determine argument types for site.
  1973                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  1974                 if (site1 != null) site = site1;
  1978         env.info.selectSuper = selectSuperPrev;
  1979         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  1980         env.info.tvars = List.nil();
  1982     //where
  1983         /** Determine symbol referenced by a Select expression,
  1985          *  @param tree   The select tree.
  1986          *  @param site   The type of the selected expression,
  1987          *  @param env    The current environment.
  1988          *  @param pt     The current prototype.
  1989          *  @param pkind  The expected kind(s) of the Select expression.
  1990          */
  1991         private Symbol selectSym(JCFieldAccess tree,
  1992                                  Type site,
  1993                                  Env<AttrContext> env,
  1994                                  Type pt,
  1995                                  int pkind) {
  1996             DiagnosticPosition pos = tree.pos();
  1997             Name name = tree.name;
  1999             switch (site.tag) {
  2000             case PACKAGE:
  2001                 return rs.access(
  2002                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2003                     pos, site, name, true);
  2004             case ARRAY:
  2005             case CLASS:
  2006                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2007                     return rs.resolveQualifiedMethod(
  2008                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2009                 } else if (name == names._this || name == names._super) {
  2010                     return rs.resolveSelf(pos, env, site.tsym, name);
  2011                 } else if (name == names._class) {
  2012                     // In this case, we have already made sure in
  2013                     // visitSelect that qualifier expression is a type.
  2014                     Type t = syms.classType;
  2015                     List<Type> typeargs = allowGenerics
  2016                         ? List.of(types.erasure(site))
  2017                         : List.<Type>nil();
  2018                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2019                     return new VarSymbol(
  2020                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2021                 } else {
  2022                     // We are seeing a plain identifier as selector.
  2023                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2024                     if ((pkind & ERRONEOUS) == 0)
  2025                         sym = rs.access(sym, pos, site, name, true);
  2026                     return sym;
  2028             case WILDCARD:
  2029                 throw new AssertionError(tree);
  2030             case TYPEVAR:
  2031                 // Normally, site.getUpperBound() shouldn't be null.
  2032                 // It should only happen during memberEnter/attribBase
  2033                 // when determining the super type which *must* be
  2034                 // done before attributing the type variables.  In
  2035                 // other words, we are seeing this illegal program:
  2036                 // class B<T> extends A<T.foo> {}
  2037                 Symbol sym = (site.getUpperBound() != null)
  2038                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2039                     : null;
  2040                 if (sym == null || isType(sym)) {
  2041                     log.error(pos, "type.var.cant.be.deref");
  2042                     return syms.errSymbol;
  2043                 } else {
  2044                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2045                         rs.new AccessError(env, site, sym) :
  2046                                 sym;
  2047                     rs.access(sym2, pos, site, name, true);
  2048                     return sym;
  2050             case ERROR:
  2051                 // preserve identifier names through errors
  2052                 return types.createErrorType(name, site.tsym, site).tsym;
  2053             default:
  2054                 // The qualifier expression is of a primitive type -- only
  2055                 // .class is allowed for these.
  2056                 if (name == names._class) {
  2057                     // In this case, we have already made sure in Select that
  2058                     // qualifier expression is a type.
  2059                     Type t = syms.classType;
  2060                     Type arg = types.boxedClass(site).type;
  2061                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2062                     return new VarSymbol(
  2063                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2064                 } else {
  2065                     log.error(pos, "cant.deref", site);
  2066                     return syms.errSymbol;
  2071         /** Determine type of identifier or select expression and check that
  2072          *  (1) the referenced symbol is not deprecated
  2073          *  (2) the symbol's type is safe (@see checkSafe)
  2074          *  (3) if symbol is a variable, check that its type and kind are
  2075          *      compatible with the prototype and protokind.
  2076          *  (4) if symbol is an instance field of a raw type,
  2077          *      which is being assigned to, issue an unchecked warning if its
  2078          *      type changes under erasure.
  2079          *  (5) if symbol is an instance method of a raw type, issue an
  2080          *      unchecked warning if its argument types change under erasure.
  2081          *  If checks succeed:
  2082          *    If symbol is a constant, return its constant type
  2083          *    else if symbol is a method, return its result type
  2084          *    otherwise return its type.
  2085          *  Otherwise return errType.
  2087          *  @param tree       The syntax tree representing the identifier
  2088          *  @param site       If this is a select, the type of the selected
  2089          *                    expression, otherwise the type of the current class.
  2090          *  @param sym        The symbol representing the identifier.
  2091          *  @param env        The current environment.
  2092          *  @param pkind      The set of expected kinds.
  2093          *  @param pt         The expected type.
  2094          */
  2095         Type checkId(JCTree tree,
  2096                      Type site,
  2097                      Symbol sym,
  2098                      Env<AttrContext> env,
  2099                      int pkind,
  2100                      Type pt,
  2101                      boolean useVarargs) {
  2102             if (pt.isErroneous()) return types.createErrorType(site);
  2103             Type owntype; // The computed type of this identifier occurrence.
  2104             switch (sym.kind) {
  2105             case TYP:
  2106                 // For types, the computed type equals the symbol's type,
  2107                 // except for two situations:
  2108                 owntype = sym.type;
  2109                 if (owntype.tag == CLASS) {
  2110                     Type ownOuter = owntype.getEnclosingType();
  2112                     // (a) If the symbol's type is parameterized, erase it
  2113                     // because no type parameters were given.
  2114                     // We recover generic outer type later in visitTypeApply.
  2115                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2116                         owntype = types.erasure(owntype);
  2119                     // (b) If the symbol's type is an inner class, then
  2120                     // we have to interpret its outer type as a superclass
  2121                     // of the site type. Example:
  2122                     //
  2123                     // class Tree<A> { class Visitor { ... } }
  2124                     // class PointTree extends Tree<Point> { ... }
  2125                     // ...PointTree.Visitor...
  2126                     //
  2127                     // Then the type of the last expression above is
  2128                     // Tree<Point>.Visitor.
  2129                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2130                         Type normOuter = site;
  2131                         if (normOuter.tag == CLASS)
  2132                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2133                         if (normOuter == null) // perhaps from an import
  2134                             normOuter = types.erasure(ownOuter);
  2135                         if (normOuter != ownOuter)
  2136                             owntype = new ClassType(
  2137                                 normOuter, List.<Type>nil(), owntype.tsym);
  2140                 break;
  2141             case VAR:
  2142                 VarSymbol v = (VarSymbol)sym;
  2143                 // Test (4): if symbol is an instance field of a raw type,
  2144                 // which is being assigned to, issue an unchecked warning if
  2145                 // its type changes under erasure.
  2146                 if (allowGenerics &&
  2147                     pkind == VAR &&
  2148                     v.owner.kind == TYP &&
  2149                     (v.flags() & STATIC) == 0 &&
  2150                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2151                     Type s = types.asOuterSuper(site, v.owner);
  2152                     if (s != null &&
  2153                         s.isRaw() &&
  2154                         !types.isSameType(v.type, v.erasure(types))) {
  2155                         chk.warnUnchecked(tree.pos(),
  2156                                           "unchecked.assign.to.var",
  2157                                           v, s);
  2160                 // The computed type of a variable is the type of the
  2161                 // variable symbol, taken as a member of the site type.
  2162                 owntype = (sym.owner.kind == TYP &&
  2163                            sym.name != names._this && sym.name != names._super)
  2164                     ? types.memberType(site, sym)
  2165                     : sym.type;
  2167                 if (env.info.tvars.nonEmpty()) {
  2168                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2169                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2170                         if (!owntype.contains(l.head)) {
  2171                             log.error(tree.pos(), "undetermined.type", owntype1);
  2172                             owntype1 = types.createErrorType(owntype1);
  2174                     owntype = owntype1;
  2177                 // If the variable is a constant, record constant value in
  2178                 // computed type.
  2179                 if (v.getConstValue() != null && isStaticReference(tree))
  2180                     owntype = owntype.constType(v.getConstValue());
  2182                 if (pkind == VAL) {
  2183                     owntype = capture(owntype); // capture "names as expressions"
  2185                 break;
  2186             case MTH: {
  2187                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2188                 owntype = checkMethod(site, sym, env, app.args,
  2189                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2190                                       env.info.varArgs);
  2191                 break;
  2193             case PCK: case ERR:
  2194                 owntype = sym.type;
  2195                 break;
  2196             default:
  2197                 throw new AssertionError("unexpected kind: " + sym.kind +
  2198                                          " in tree " + tree);
  2201             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2202             // (for constructors, the error was given when the constructor was
  2203             // resolved)
  2204             if (sym.name != names.init &&
  2205                 (sym.flags() & DEPRECATED) != 0 &&
  2206                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2207                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2208                 chk.warnDeprecated(tree.pos(), sym);
  2210             if ((sym.flags() & PROPRIETARY) != 0)
  2211                 log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2213             // Test (3): if symbol is a variable, check that its type and
  2214             // kind are compatible with the prototype and protokind.
  2215             return check(tree, owntype, sym.kind, pkind, pt);
  2218         /** Check that variable is initialized and evaluate the variable's
  2219          *  initializer, if not yet done. Also check that variable is not
  2220          *  referenced before it is defined.
  2221          *  @param tree    The tree making up the variable reference.
  2222          *  @param env     The current environment.
  2223          *  @param v       The variable's symbol.
  2224          */
  2225         private void checkInit(JCTree tree,
  2226                                Env<AttrContext> env,
  2227                                VarSymbol v,
  2228                                boolean onlyWarning) {
  2229 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2230 //                             tree.pos + " " + v.pos + " " +
  2231 //                             Resolve.isStatic(env));//DEBUG
  2233             // A forward reference is diagnosed if the declaration position
  2234             // of the variable is greater than the current tree position
  2235             // and the tree and variable definition occur in the same class
  2236             // definition.  Note that writes don't count as references.
  2237             // This check applies only to class and instance
  2238             // variables.  Local variables follow different scope rules,
  2239             // and are subject to definite assignment checking.
  2240             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2241                 v.owner.kind == TYP &&
  2242                 canOwnInitializer(env.info.scope.owner) &&
  2243                 v.owner == env.info.scope.owner.enclClass() &&
  2244                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2245                 (env.tree.getTag() != JCTree.ASSIGN ||
  2246                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2247                 String suffix = (env.info.enclVar == v) ?
  2248                                 "self.ref" : "forward.ref";
  2249                 if (!onlyWarning || isStaticEnumField(v)) {
  2250                     log.error(tree.pos(), "illegal." + suffix);
  2251                 } else if (useBeforeDeclarationWarning) {
  2252                     log.warning(tree.pos(), suffix, v);
  2256             v.getConstValue(); // ensure initializer is evaluated
  2258             checkEnumInitializer(tree, env, v);
  2261         /**
  2262          * Check for illegal references to static members of enum.  In
  2263          * an enum type, constructors and initializers may not
  2264          * reference its static members unless they are constant.
  2266          * @param tree    The tree making up the variable reference.
  2267          * @param env     The current environment.
  2268          * @param v       The variable's symbol.
  2269          * @see JLS 3rd Ed. (8.9 Enums)
  2270          */
  2271         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2272             // JLS 3rd Ed.:
  2273             //
  2274             // "It is a compile-time error to reference a static field
  2275             // of an enum type that is not a compile-time constant
  2276             // (15.28) from constructors, instance initializer blocks,
  2277             // or instance variable initializer expressions of that
  2278             // type. It is a compile-time error for the constructors,
  2279             // instance initializer blocks, or instance variable
  2280             // initializer expressions of an enum constant e to refer
  2281             // to itself or to an enum constant of the same type that
  2282             // is declared to the right of e."
  2283             if (isStaticEnumField(v)) {
  2284                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2286                 if (enclClass == null || enclClass.owner == null)
  2287                     return;
  2289                 // See if the enclosing class is the enum (or a
  2290                 // subclass thereof) declaring v.  If not, this
  2291                 // reference is OK.
  2292                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2293                     return;
  2295                 // If the reference isn't from an initializer, then
  2296                 // the reference is OK.
  2297                 if (!Resolve.isInitializer(env))
  2298                     return;
  2300                 log.error(tree.pos(), "illegal.enum.static.ref");
  2304         /** Is the given symbol a static, non-constant field of an Enum?
  2305          *  Note: enum literals should not be regarded as such
  2306          */
  2307         private boolean isStaticEnumField(VarSymbol v) {
  2308             return Flags.isEnum(v.owner) &&
  2309                    Flags.isStatic(v) &&
  2310                    !Flags.isConstant(v) &&
  2311                    v.name != names._class;
  2314         /** Can the given symbol be the owner of code which forms part
  2315          *  if class initialization? This is the case if the symbol is
  2316          *  a type or field, or if the symbol is the synthetic method.
  2317          *  owning a block.
  2318          */
  2319         private boolean canOwnInitializer(Symbol sym) {
  2320             return
  2321                 (sym.kind & (VAR | TYP)) != 0 ||
  2322                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2325     Warner noteWarner = new Warner();
  2327     /**
  2328      * Check that method arguments conform to its instantation.
  2329      **/
  2330     public Type checkMethod(Type site,
  2331                             Symbol sym,
  2332                             Env<AttrContext> env,
  2333                             final List<JCExpression> argtrees,
  2334                             List<Type> argtypes,
  2335                             List<Type> typeargtypes,
  2336                             boolean useVarargs) {
  2337         // Test (5): if symbol is an instance method of a raw type, issue
  2338         // an unchecked warning if its argument types change under erasure.
  2339         if (allowGenerics &&
  2340             (sym.flags() & STATIC) == 0 &&
  2341             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2342             Type s = types.asOuterSuper(site, sym.owner);
  2343             if (s != null && s.isRaw() &&
  2344                 !types.isSameTypes(sym.type.getParameterTypes(),
  2345                                    sym.erasure(types).getParameterTypes())) {
  2346                 chk.warnUnchecked(env.tree.pos(),
  2347                                   "unchecked.call.mbr.of.raw.type",
  2348                                   sym, s);
  2352         // Compute the identifier's instantiated type.
  2353         // For methods, we need to compute the instance type by
  2354         // Resolve.instantiate from the symbol's type as well as
  2355         // any type arguments and value arguments.
  2356         noteWarner.warned = false;
  2357         Type owntype = rs.instantiate(env,
  2358                                       site,
  2359                                       sym,
  2360                                       argtypes,
  2361                                       typeargtypes,
  2362                                       true,
  2363                                       useVarargs,
  2364                                       noteWarner);
  2365         boolean warned = noteWarner.warned;
  2367         // If this fails, something went wrong; we should not have
  2368         // found the identifier in the first place.
  2369         if (owntype == null) {
  2370             if (!pt.isErroneous())
  2371                 log.error(env.tree.pos(),
  2372                           "internal.error.cant.instantiate",
  2373                           sym, site,
  2374                           Type.toString(pt.getParameterTypes()));
  2375             owntype = types.createErrorType(site);
  2376         } else {
  2377             // System.out.println("call   : " + env.tree);
  2378             // System.out.println("method : " + owntype);
  2379             // System.out.println("actuals: " + argtypes);
  2380             List<Type> formals = owntype.getParameterTypes();
  2381             Type last = useVarargs ? formals.last() : null;
  2382             if (sym.name==names.init &&
  2383                 sym.owner == syms.enumSym)
  2384                 formals = formals.tail.tail;
  2385             List<JCExpression> args = argtrees;
  2386             while (formals.head != last) {
  2387                 JCTree arg = args.head;
  2388                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2389                 assertConvertible(arg, arg.type, formals.head, warn);
  2390                 warned |= warn.warned;
  2391                 args = args.tail;
  2392                 formals = formals.tail;
  2394             if (useVarargs) {
  2395                 Type varArg = types.elemtype(last);
  2396                 while (args.tail != null) {
  2397                     JCTree arg = args.head;
  2398                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2399                     assertConvertible(arg, arg.type, varArg, warn);
  2400                     warned |= warn.warned;
  2401                     args = args.tail;
  2403             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2404                 // non-varargs call to varargs method
  2405                 Type varParam = owntype.getParameterTypes().last();
  2406                 Type lastArg = argtypes.last();
  2407                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2408                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2409                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2410                                 types.elemtype(varParam),
  2411                                 varParam);
  2414             if (warned && sym.type.tag == FORALL) {
  2415                 chk.warnUnchecked(env.tree.pos(),
  2416                                   "unchecked.meth.invocation.applied",
  2417                                   kindName(sym),
  2418                                   sym.name,
  2419                                   rs.methodArguments(sym.type.getParameterTypes()),
  2420                                   rs.methodArguments(argtypes),
  2421                                   kindName(sym.location()),
  2422                                   sym.location());
  2423                 owntype = new MethodType(owntype.getParameterTypes(),
  2424                                          types.erasure(owntype.getReturnType()),
  2425                                          owntype.getThrownTypes(),
  2426                                          syms.methodClass);
  2428             if (useVarargs) {
  2429                 JCTree tree = env.tree;
  2430                 Type argtype = owntype.getParameterTypes().last();
  2431                 if (!types.isReifiable(argtype))
  2432                     chk.warnUnchecked(env.tree.pos(),
  2433                                       "unchecked.generic.array.creation",
  2434                                       argtype);
  2435                 Type elemtype = types.elemtype(argtype);
  2436                 switch (tree.getTag()) {
  2437                 case JCTree.APPLY:
  2438                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2439                     break;
  2440                 case JCTree.NEWCLASS:
  2441                     ((JCNewClass) tree).varargsElement = elemtype;
  2442                     break;
  2443                 default:
  2444                     throw new AssertionError(""+tree);
  2448         return owntype;
  2451     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2452         if (types.isConvertible(actual, formal, warn))
  2453             return;
  2455         if (formal.isCompound()
  2456             && types.isSubtype(actual, types.supertype(formal))
  2457             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2458             return;
  2460         if (false) {
  2461             // TODO: make assertConvertible work
  2462             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2463             throw new AssertionError("Tree: " + tree
  2464                                      + " actual:" + actual
  2465                                      + " formal: " + formal);
  2469     public void visitLiteral(JCLiteral tree) {
  2470         result = check(
  2471             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2473     //where
  2474     /** Return the type of a literal with given type tag.
  2475      */
  2476     Type litType(int tag) {
  2477         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2480     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2481         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2484     public void visitTypeArray(JCArrayTypeTree tree) {
  2485         Type etype = attribType(tree.elemtype, env);
  2486         Type type = new ArrayType(etype, syms.arrayClass);
  2487         result = check(tree, type, TYP, pkind, pt);
  2490     /** Visitor method for parameterized types.
  2491      *  Bound checking is left until later, since types are attributed
  2492      *  before supertype structure is completely known
  2493      */
  2494     public void visitTypeApply(JCTypeApply tree) {
  2495         Type owntype = types.createErrorType(tree.type);
  2497         // Attribute functor part of application and make sure it's a class.
  2498         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2500         // Attribute type parameters
  2501         List<Type> actuals = attribTypes(tree.arguments, env);
  2503         if (clazztype.tag == CLASS) {
  2504             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2506             if (actuals.length() == formals.length()) {
  2507                 List<Type> a = actuals;
  2508                 List<Type> f = formals;
  2509                 while (a.nonEmpty()) {
  2510                     a.head = a.head.withTypeVar(f.head);
  2511                     a = a.tail;
  2512                     f = f.tail;
  2514                 // Compute the proper generic outer
  2515                 Type clazzOuter = clazztype.getEnclosingType();
  2516                 if (clazzOuter.tag == CLASS) {
  2517                     Type site;
  2518                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2519                     if (clazz.getTag() == JCTree.IDENT) {
  2520                         site = env.enclClass.sym.type;
  2521                     } else if (clazz.getTag() == JCTree.SELECT) {
  2522                         site = ((JCFieldAccess) clazz).selected.type;
  2523                     } else throw new AssertionError(""+tree);
  2524                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2525                         if (site.tag == CLASS)
  2526                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2527                         if (site == null)
  2528                             site = types.erasure(clazzOuter);
  2529                         clazzOuter = site;
  2532                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2533             } else {
  2534                 if (formals.length() != 0) {
  2535                     log.error(tree.pos(), "wrong.number.type.args",
  2536                               Integer.toString(formals.length()));
  2537                 } else {
  2538                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2540                 owntype = types.createErrorType(tree.type);
  2543         result = check(tree, owntype, TYP, pkind, pt);
  2546     public void visitTypeParameter(JCTypeParameter tree) {
  2547         TypeVar a = (TypeVar)tree.type;
  2548         Set<Type> boundSet = new HashSet<Type>();
  2549         if (a.bound.isErroneous())
  2550             return;
  2551         List<Type> bs = types.getBounds(a);
  2552         if (tree.bounds.nonEmpty()) {
  2553             // accept class or interface or typevar as first bound.
  2554             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2555             boundSet.add(types.erasure(b));
  2556             if (b.isErroneous()) {
  2557                 a.bound = b;
  2559             else if (b.tag == TYPEVAR) {
  2560                 // if first bound was a typevar, do not accept further bounds.
  2561                 if (tree.bounds.tail.nonEmpty()) {
  2562                     log.error(tree.bounds.tail.head.pos(),
  2563                               "type.var.may.not.be.followed.by.other.bounds");
  2564                     tree.bounds = List.of(tree.bounds.head);
  2565                     a.bound = bs.head;
  2567             } else {
  2568                 // if first bound was a class or interface, accept only interfaces
  2569                 // as further bounds.
  2570                 for (JCExpression bound : tree.bounds.tail) {
  2571                     bs = bs.tail;
  2572                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2573                     if (i.isErroneous())
  2574                         a.bound = i;
  2575                     else if (i.tag == CLASS)
  2576                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2580         bs = types.getBounds(a);
  2582         // in case of multiple bounds ...
  2583         if (bs.length() > 1) {
  2584             // ... the variable's bound is a class type flagged COMPOUND
  2585             // (see comment for TypeVar.bound).
  2586             // In this case, generate a class tree that represents the
  2587             // bound class, ...
  2588             JCTree extending;
  2589             List<JCExpression> implementing;
  2590             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2591                 extending = tree.bounds.head;
  2592                 implementing = tree.bounds.tail;
  2593             } else {
  2594                 extending = null;
  2595                 implementing = tree.bounds;
  2597             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2598                 make.Modifiers(PUBLIC | ABSTRACT),
  2599                 tree.name, List.<JCTypeParameter>nil(),
  2600                 extending, implementing, List.<JCTree>nil());
  2602             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2603             assert (c.flags() & COMPOUND) != 0;
  2604             cd.sym = c;
  2605             c.sourcefile = env.toplevel.sourcefile;
  2607             // ... and attribute the bound class
  2608             c.flags_field |= UNATTRIBUTED;
  2609             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2610             enter.typeEnvs.put(c, cenv);
  2615     public void visitWildcard(JCWildcard tree) {
  2616         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2617         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2618             ? syms.objectType
  2619             : attribType(tree.inner, env);
  2620         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2621                                               tree.kind.kind,
  2622                                               syms.boundClass),
  2623                        TYP, pkind, pt);
  2626     public void visitAnnotation(JCAnnotation tree) {
  2627         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2628         result = tree.type = syms.errType;
  2631     public void visitAnnotatedType(JCAnnotatedType tree) {
  2632         result = tree.type = attribType(tree.getUnderlyingType(), env);
  2635     public void visitErroneous(JCErroneous tree) {
  2636         if (tree.errs != null)
  2637             for (JCTree err : tree.errs)
  2638                 attribTree(err, env, ERR, pt);
  2639         result = tree.type = syms.errType;
  2642     /** Default visitor method for all other trees.
  2643      */
  2644     public void visitTree(JCTree tree) {
  2645         throw new AssertionError();
  2648     /** Main method: attribute class definition associated with given class symbol.
  2649      *  reporting completion failures at the given position.
  2650      *  @param pos The source position at which completion errors are to be
  2651      *             reported.
  2652      *  @param c   The class symbol whose definition will be attributed.
  2653      */
  2654     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2655         try {
  2656             annotate.flush();
  2657             attribClass(c);
  2658         } catch (CompletionFailure ex) {
  2659             chk.completionError(pos, ex);
  2663     /** Attribute class definition associated with given class symbol.
  2664      *  @param c   The class symbol whose definition will be attributed.
  2665      */
  2666     void attribClass(ClassSymbol c) throws CompletionFailure {
  2667         if (c.type.tag == ERROR) return;
  2669         // Check for cycles in the inheritance graph, which can arise from
  2670         // ill-formed class files.
  2671         chk.checkNonCyclic(null, c.type);
  2673         Type st = types.supertype(c.type);
  2674         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2675             // First, attribute superclass.
  2676             if (st.tag == CLASS)
  2677                 attribClass((ClassSymbol)st.tsym);
  2679             // Next attribute owner, if it is a class.
  2680             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2681                 attribClass((ClassSymbol)c.owner);
  2684         // The previous operations might have attributed the current class
  2685         // if there was a cycle. So we test first whether the class is still
  2686         // UNATTRIBUTED.
  2687         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2688             c.flags_field &= ~UNATTRIBUTED;
  2690             // Get environment current at the point of class definition.
  2691             Env<AttrContext> env = enter.typeEnvs.get(c);
  2693             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2694             // because the annotations were not available at the time the env was created. Therefore,
  2695             // we look up the environment chain for the first enclosing environment for which the
  2696             // lint value is set. Typically, this is the parent env, but might be further if there
  2697             // are any envs created as a result of TypeParameter nodes.
  2698             Env<AttrContext> lintEnv = env;
  2699             while (lintEnv.info.lint == null)
  2700                 lintEnv = lintEnv.next;
  2702             // Having found the enclosing lint value, we can initialize the lint value for this class
  2703             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2705             Lint prevLint = chk.setLint(env.info.lint);
  2706             JavaFileObject prev = log.useSource(c.sourcefile);
  2708             try {
  2709                 // java.lang.Enum may not be subclassed by a non-enum
  2710                 if (st.tsym == syms.enumSym &&
  2711                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  2712                     log.error(env.tree.pos(), "enum.no.subclassing");
  2714                 // Enums may not be extended by source-level classes
  2715                 if (st.tsym != null &&
  2716                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  2717                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  2718                     !target.compilerBootstrap(c)) {
  2719                     log.error(env.tree.pos(), "enum.types.not.extensible");
  2721                 attribClassBody(env, c);
  2723                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  2724             } finally {
  2725                 log.useSource(prev);
  2726                 chk.setLint(prevLint);
  2732     public void visitImport(JCImport tree) {
  2733         // nothing to do
  2736     /** Finish the attribution of a class. */
  2737     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  2738         JCClassDecl tree = (JCClassDecl)env.tree;
  2739         assert c == tree.sym;
  2741         // Validate annotations
  2742         chk.validateAnnotations(tree.mods.annotations, c);
  2744         // Validate type parameters, supertype and interfaces.
  2745         attribBounds(tree.typarams);
  2746         chk.validate(tree.typarams, env);
  2747         chk.validate(tree.extending, env);
  2748         chk.validate(tree.implementing, env);
  2750         // If this is a non-abstract class, check that it has no abstract
  2751         // methods or unimplemented methods of an implemented interface.
  2752         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  2753             if (!relax)
  2754                 chk.checkAllDefined(tree.pos(), c);
  2757         if ((c.flags() & ANNOTATION) != 0) {
  2758             if (tree.implementing.nonEmpty())
  2759                 log.error(tree.implementing.head.pos(),
  2760                           "cant.extend.intf.annotation");
  2761             if (tree.typarams.nonEmpty())
  2762                 log.error(tree.typarams.head.pos(),
  2763                           "intf.annotation.cant.have.type.params");
  2764         } else {
  2765             // Check that all extended classes and interfaces
  2766             // are compatible (i.e. no two define methods with same arguments
  2767             // yet different return types).  (JLS 8.4.6.3)
  2768             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  2771         // Check that class does not import the same parameterized interface
  2772         // with two different argument lists.
  2773         chk.checkClassBounds(tree.pos(), c.type);
  2775         tree.type = c.type;
  2777         boolean assertsEnabled = false;
  2778         assert assertsEnabled = true;
  2779         if (assertsEnabled) {
  2780             for (List<JCTypeParameter> l = tree.typarams;
  2781                  l.nonEmpty(); l = l.tail)
  2782                 assert env.info.scope.lookup(l.head.name).scope != null;
  2785         // Check that a generic class doesn't extend Throwable
  2786         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  2787             log.error(tree.extending.pos(), "generic.throwable");
  2789         // Check that all methods which implement some
  2790         // method conform to the method they implement.
  2791         chk.checkImplementations(tree);
  2793         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2794             // Attribute declaration
  2795             attribStat(l.head, env);
  2796             // Check that declarations in inner classes are not static (JLS 8.1.2)
  2797             // Make an exception for static constants.
  2798             if (c.owner.kind != PCK &&
  2799                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  2800                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  2801                 Symbol sym = null;
  2802                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  2803                 if (sym == null ||
  2804                     sym.kind != VAR ||
  2805                     ((VarSymbol) sym).getConstValue() == null)
  2806                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  2810         // Check for cycles among non-initial constructors.
  2811         chk.checkCyclicConstructors(tree);
  2813         // Check for cycles among annotation elements.
  2814         chk.checkNonCyclicElements(tree);
  2816         // Check for proper use of serialVersionUID
  2817         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  2818             isSerializable(c) &&
  2819             (c.flags() & Flags.ENUM) == 0 &&
  2820             (c.flags() & ABSTRACT) == 0) {
  2821             checkSerialVersionUID(tree, c);
  2824         // Check type annotations applicability rules
  2825         validateTypeAnnotations(tree);
  2827         // where
  2828         /** check if a class is a subtype of Serializable, if that is available. */
  2829         private boolean isSerializable(ClassSymbol c) {
  2830             try {
  2831                 syms.serializableType.complete();
  2833             catch (CompletionFailure e) {
  2834                 return false;
  2836             return types.isSubtype(c.type, syms.serializableType);
  2839         /** Check that an appropriate serialVersionUID member is defined. */
  2840         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  2842             // check for presence of serialVersionUID
  2843             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  2844             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  2845             if (e.scope == null) {
  2846                 log.warning(tree.pos(), "missing.SVUID", c);
  2847                 return;
  2850             // check that it is static final
  2851             VarSymbol svuid = (VarSymbol)e.sym;
  2852             if ((svuid.flags() & (STATIC | FINAL)) !=
  2853                 (STATIC | FINAL))
  2854                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  2856             // check that it is long
  2857             else if (svuid.type.tag != TypeTags.LONG)
  2858                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  2860             // check constant
  2861             else if (svuid.getConstValue() == null)
  2862                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  2865     private Type capture(Type type) {
  2866         return types.capture(type);
  2869     private void validateTypeAnnotations(JCTree tree) {
  2870         tree.accept(typeAnnotationsValidator);
  2872     //where
  2873     private final JCTree.Visitor typeAnnotationsValidator =
  2874         new TreeScanner() {
  2875         public void visitAnnotation(JCAnnotation tree) {
  2876             if (tree instanceof JCTypeAnnotation) {
  2877                 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
  2879             super.visitAnnotation(tree);
  2881         public void visitTypeParameter(JCTypeParameter tree) {
  2882             chk.validateTypeAnnotations(tree.annotations, true);
  2883             // don't call super. skip type annotations
  2884             scan(tree.bounds);
  2886         public void visitMethodDef(JCMethodDecl tree) {
  2887             // need to check static methods
  2888             if ((tree.sym.flags() & Flags.STATIC) != 0) {
  2889                 for (JCTypeAnnotation a : tree.receiverAnnotations) {
  2890                     if (chk.isTypeAnnotation(a, false))
  2891                         log.error(a.pos(), "annotation.type.not.applicable");
  2894             super.visitMethodDef(tree);
  2896     };

mercurial