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

Thu, 24 Jul 2008 11:12:41 +0100

author
mcimadamore
date
Thu, 24 Jul 2008 11:12:41 +0100
changeset 79
36df13bde238
parent 54
eaf608c64fec
child 80
5c9cdeb740f2
permissions
-rw-r--r--

6594284: NPE thrown when calling a method on an intersection type
Summary: javac should report an error when the capture of an actual type parameter does not exist
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2008 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 Name.Table 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 Annotate annotate;
    84     public static Attr instance(Context context) {
    85         Attr instance = context.get(attrKey);
    86         if (instance == null)
    87             instance = new Attr(context);
    88         return instance;
    89     }
    91     protected Attr(Context context) {
    92         context.put(attrKey, this);
    94         names = Name.Table.instance(context);
    95         log = Log.instance(context);
    96         syms = Symtab.instance(context);
    97         rs = Resolve.instance(context);
    98         chk = Check.instance(context);
    99         memberEnter = MemberEnter.instance(context);
   100         make = TreeMaker.instance(context);
   101         enter = Enter.instance(context);
   102         cfolder = ConstFold.instance(context);
   103         target = Target.instance(context);
   104         types = Types.instance(context);
   105         annotate = Annotate.instance(context);
   107         Options options = Options.instance(context);
   109         Source source = Source.instance(context);
   110         allowGenerics = source.allowGenerics();
   111         allowVarargs = source.allowVarargs();
   112         allowEnums = source.allowEnums();
   113         allowBoxing = source.allowBoxing();
   114         allowCovariantReturns = source.allowCovariantReturns();
   115         allowAnonOuterThis = source.allowAnonOuterThis();
   116         relax = (options.get("-retrofit") != null ||
   117                  options.get("-relax") != null);
   118         useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
   119     }
   121     /** Switch: relax some constraints for retrofit mode.
   122      */
   123     boolean relax;
   125     /** Switch: support generics?
   126      */
   127     boolean allowGenerics;
   129     /** Switch: allow variable-arity methods.
   130      */
   131     boolean allowVarargs;
   133     /** Switch: support enums?
   134      */
   135     boolean allowEnums;
   137     /** Switch: support boxing and unboxing?
   138      */
   139     boolean allowBoxing;
   141     /** Switch: support covariant result types?
   142      */
   143     boolean allowCovariantReturns;
   145     /** Switch: allow references to surrounding object from anonymous
   146      * objects during constructor call?
   147      */
   148     boolean allowAnonOuterThis;
   150     /**
   151      * Switch: warn about use of variable before declaration?
   152      * RFE: 6425594
   153      */
   154     boolean useBeforeDeclarationWarning;
   156     /** Check kind and type of given tree against protokind and prototype.
   157      *  If check succeeds, store type in tree and return it.
   158      *  If check fails, store errType in tree and return it.
   159      *  No checks are performed if the prototype is a method type.
   160      *  Its not necessary in this case since we know that kind and type
   161      *  are correct.
   162      *
   163      *  @param tree     The tree whose kind and type is checked
   164      *  @param owntype  The computed type of the tree
   165      *  @param ownkind  The computed kind of the tree
   166      *  @param pkind    The expected kind (or: protokind) of the tree
   167      *  @param pt       The expected type (or: prototype) of the tree
   168      */
   169     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   170         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   171             if ((ownkind & ~pkind) == 0) {
   172                 owntype = chk.checkType(tree.pos(), owntype, pt);
   173             } else {
   174                 log.error(tree.pos(), "unexpected.type",
   175                           Resolve.kindNames(pkind),
   176                           Resolve.kindName(ownkind));
   177                 owntype = syms.errType;
   178             }
   179         }
   180         tree.type = owntype;
   181         return owntype;
   182     }
   184     /** Is given blank final variable assignable, i.e. in a scope where it
   185      *  may be assigned to even though it is final?
   186      *  @param v      The blank final variable.
   187      *  @param env    The current environment.
   188      */
   189     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   190         Symbol owner = env.info.scope.owner;
   191            // owner refers to the innermost variable, method or
   192            // initializer block declaration at this point.
   193         return
   194             v.owner == owner
   195             ||
   196             ((owner.name == names.init ||    // i.e. we are in a constructor
   197               owner.kind == VAR ||           // i.e. we are in a variable initializer
   198               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   199              &&
   200              v.owner == owner.owner
   201              &&
   202              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   203     }
   205     /** Check that variable can be assigned to.
   206      *  @param pos    The current source code position.
   207      *  @param v      The assigned varaible
   208      *  @param base   If the variable is referred to in a Select, the part
   209      *                to the left of the `.', null otherwise.
   210      *  @param env    The current environment.
   211      */
   212     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   213         if ((v.flags() & FINAL) != 0 &&
   214             ((v.flags() & HASINIT) != 0
   215              ||
   216              !((base == null ||
   217                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   218                isAssignableAsBlankFinal(v, env)))) {
   219             log.error(pos, "cant.assign.val.to.final.var", v);
   220         }
   221     }
   223     /** Does tree represent a static reference to an identifier?
   224      *  It is assumed that tree is either a SELECT or an IDENT.
   225      *  We have to weed out selects from non-type names here.
   226      *  @param tree    The candidate tree.
   227      */
   228     boolean isStaticReference(JCTree tree) {
   229         if (tree.getTag() == JCTree.SELECT) {
   230             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   231             if (lsym == null || lsym.kind != TYP) {
   232                 return false;
   233             }
   234         }
   235         return true;
   236     }
   238     /** Is this symbol a type?
   239      */
   240     static boolean isType(Symbol sym) {
   241         return sym != null && sym.kind == TYP;
   242     }
   244     /** The current `this' symbol.
   245      *  @param env    The current environment.
   246      */
   247     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   248         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   249     }
   251     /** Attribute a parsed identifier.
   252      * @param tree Parsed identifier name
   253      * @param topLevel The toplevel to use
   254      */
   255     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   256         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   257         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   258                                            syms.errSymbol.name,
   259                                            null, null, null, null);
   260         localEnv.enclClass.sym = syms.errSymbol;
   261         return tree.accept(identAttributer, localEnv);
   262     }
   263     // where
   264         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   265         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   266             @Override
   267             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   268                 Symbol site = visit(node.getExpression(), env);
   269                 if (site.kind == ERR)
   270                     return site;
   271                 Name name = (Name)node.getIdentifier();
   272                 if (site.kind == PCK) {
   273                     env.toplevel.packge = (PackageSymbol)site;
   274                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   275                 } else {
   276                     env.enclClass.sym = (ClassSymbol)site;
   277                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   278                 }
   279             }
   281             @Override
   282             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   283                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   284             }
   285         }
   287     public Type coerce(Type etype, Type ttype) {
   288         return cfolder.coerce(etype, ttype);
   289     }
   291     public Type attribType(JCTree node, TypeSymbol sym) {
   292         Env<AttrContext> env = enter.typeEnvs.get(sym);
   293         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   294         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   295     }
   297     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   298         breakTree = tree;
   299         JavaFileObject prev = log.useSource(null);
   300         try {
   301             attribExpr(expr, env);
   302         } catch (BreakAttr b) {
   303             return b.env;
   304         } finally {
   305             breakTree = null;
   306             log.useSource(prev);
   307         }
   308         return env;
   309     }
   311     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   312         breakTree = tree;
   313         JavaFileObject prev = log.useSource(null);
   314         try {
   315             attribStat(stmt, env);
   316         } catch (BreakAttr b) {
   317             return b.env;
   318         } finally {
   319             breakTree = null;
   320             log.useSource(prev);
   321         }
   322         return env;
   323     }
   325     private JCTree breakTree = null;
   327     private static class BreakAttr extends RuntimeException {
   328         static final long serialVersionUID = -6924771130405446405L;
   329         private Env<AttrContext> env;
   330         private BreakAttr(Env<AttrContext> env) {
   331             this.env = env;
   332         }
   333     }
   336 /* ************************************************************************
   337  * Visitor methods
   338  *************************************************************************/
   340     /** Visitor argument: the current environment.
   341      */
   342     Env<AttrContext> env;
   344     /** Visitor argument: the currently expected proto-kind.
   345      */
   346     int pkind;
   348     /** Visitor argument: the currently expected proto-type.
   349      */
   350     Type pt;
   352     /** Visitor result: the computed type.
   353      */
   354     Type result;
   356     /** Visitor method: attribute a tree, catching any completion failure
   357      *  exceptions. Return the tree's type.
   358      *
   359      *  @param tree    The tree to be visited.
   360      *  @param env     The environment visitor argument.
   361      *  @param pkind   The protokind visitor argument.
   362      *  @param pt      The prototype visitor argument.
   363      */
   364     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   365         Env<AttrContext> prevEnv = this.env;
   366         int prevPkind = this.pkind;
   367         Type prevPt = this.pt;
   368         try {
   369             this.env = env;
   370             this.pkind = pkind;
   371             this.pt = pt;
   372             tree.accept(this);
   373             if (tree == breakTree)
   374                 throw new BreakAttr(env);
   375             return result;
   376         } catch (CompletionFailure ex) {
   377             tree.type = syms.errType;
   378             return chk.completionError(tree.pos(), ex);
   379         } finally {
   380             this.env = prevEnv;
   381             this.pkind = prevPkind;
   382             this.pt = prevPt;
   383         }
   384     }
   386     /** Derived visitor method: attribute an expression tree.
   387      */
   388     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   389         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   390     }
   392     /** Derived visitor method: attribute an expression tree with
   393      *  no constraints on the computed type.
   394      */
   395     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   396         return attribTree(tree, env, VAL, Type.noType);
   397     }
   399     /** Derived visitor method: attribute a type tree.
   400      */
   401     Type attribType(JCTree tree, Env<AttrContext> env) {
   402         Type result = attribTree(tree, env, TYP, Type.noType);
   403         return result;
   404     }
   406     /** Derived visitor method: attribute a statement or definition tree.
   407      */
   408     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   409         return attribTree(tree, env, NIL, Type.noType);
   410     }
   412     /** Attribute a list of expressions, returning a list of types.
   413      */
   414     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   415         ListBuffer<Type> ts = new ListBuffer<Type>();
   416         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   417             ts.append(attribExpr(l.head, env, pt));
   418         return ts.toList();
   419     }
   421     /** Attribute a list of statements, returning nothing.
   422      */
   423     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   424         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   425             attribStat(l.head, env);
   426     }
   428     /** Attribute the arguments in a method call, returning a list of types.
   429      */
   430     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   431         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   432         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   433             argtypes.append(chk.checkNonVoid(
   434                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   435         return argtypes.toList();
   436     }
   438     /** Attribute a type argument list, returning a list of types.
   439      */
   440     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   441         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   442         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   443             argtypes.append(chk.checkRefType(l.head.pos(), attribType(l.head, env)));
   444         return argtypes.toList();
   445     }
   448     /**
   449      * Attribute type variables (of generic classes or methods).
   450      * Compound types are attributed later in attribBounds.
   451      * @param typarams the type variables to enter
   452      * @param env      the current environment
   453      */
   454     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   455         for (JCTypeParameter tvar : typarams) {
   456             TypeVar a = (TypeVar)tvar.type;
   457             a.tsym.flags_field |= UNATTRIBUTED;
   458             a.bound = Type.noType;
   459             if (!tvar.bounds.isEmpty()) {
   460                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   461                 for (JCExpression bound : tvar.bounds.tail)
   462                     bounds = bounds.prepend(attribType(bound, env));
   463                 types.setBounds(a, bounds.reverse());
   464             } else {
   465                 // if no bounds are given, assume a single bound of
   466                 // java.lang.Object.
   467                 types.setBounds(a, List.of(syms.objectType));
   468             }
   469             a.tsym.flags_field &= ~UNATTRIBUTED;
   470         }
   471         for (JCTypeParameter tvar : typarams)
   472             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   473         attribStats(typarams, env);
   474     }
   476     void attribBounds(List<JCTypeParameter> typarams) {
   477         for (JCTypeParameter typaram : typarams) {
   478             Type bound = typaram.type.getUpperBound();
   479             if (bound != null && bound.tsym instanceof ClassSymbol) {
   480                 ClassSymbol c = (ClassSymbol)bound.tsym;
   481                 if ((c.flags_field & COMPOUND) != 0) {
   482                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   483                     attribClass(typaram.pos(), c);
   484                 }
   485             }
   486         }
   487     }
   489     /**
   490      * Attribute the type references in a list of annotations.
   491      */
   492     void attribAnnotationTypes(List<JCAnnotation> annotations,
   493                                Env<AttrContext> env) {
   494         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   495             JCAnnotation a = al.head;
   496             attribType(a.annotationType, env);
   497         }
   498     }
   500     /** Attribute type reference in an `extends' or `implements' clause.
   501      *
   502      *  @param tree              The tree making up the type reference.
   503      *  @param env               The environment current at the reference.
   504      *  @param classExpected     true if only a class is expected here.
   505      *  @param interfaceExpected true if only an interface is expected here.
   506      */
   507     Type attribBase(JCTree tree,
   508                     Env<AttrContext> env,
   509                     boolean classExpected,
   510                     boolean interfaceExpected,
   511                     boolean checkExtensible) {
   512         Type t = attribType(tree, env);
   513         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   514     }
   515     Type checkBase(Type t,
   516                    JCTree tree,
   517                    Env<AttrContext> env,
   518                    boolean classExpected,
   519                    boolean interfaceExpected,
   520                    boolean checkExtensible) {
   521         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   522             // check that type variable is already visible
   523             if (t.getUpperBound() == null) {
   524                 log.error(tree.pos(), "illegal.forward.ref");
   525                 return syms.errType;
   526             }
   527         } else {
   528             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   529         }
   530         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   531             log.error(tree.pos(), "intf.expected.here");
   532             // return errType is necessary since otherwise there might
   533             // be undetected cycles which cause attribution to loop
   534             return syms.errType;
   535         } else if (checkExtensible &&
   536                    classExpected &&
   537                    (t.tsym.flags() & INTERFACE) != 0) {
   538             log.error(tree.pos(), "no.intf.expected.here");
   539             return syms.errType;
   540         }
   541         if (checkExtensible &&
   542             ((t.tsym.flags() & FINAL) != 0)) {
   543             log.error(tree.pos(),
   544                       "cant.inherit.from.final", t.tsym);
   545         }
   546         chk.checkNonCyclic(tree.pos(), t);
   547         return t;
   548     }
   550     public void visitClassDef(JCClassDecl tree) {
   551         // Local classes have not been entered yet, so we need to do it now:
   552         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   553             enter.classEnter(tree, env);
   555         ClassSymbol c = tree.sym;
   556         if (c == null) {
   557             // exit in case something drastic went wrong during enter.
   558             result = null;
   559         } else {
   560             // make sure class has been completed:
   561             c.complete();
   563             // If this class appears as an anonymous class
   564             // in a superclass constructor call where
   565             // no explicit outer instance is given,
   566             // disable implicit outer instance from being passed.
   567             // (This would be an illegal access to "this before super").
   568             if (env.info.isSelfCall &&
   569                 env.tree.getTag() == JCTree.NEWCLASS &&
   570                 ((JCNewClass) env.tree).encl == null)
   571             {
   572                 c.flags_field |= NOOUTERTHIS;
   573             }
   574             attribClass(tree.pos(), c);
   575             result = tree.type = c.type;
   576         }
   577     }
   579     public void visitMethodDef(JCMethodDecl tree) {
   580         MethodSymbol m = tree.sym;
   582         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   583         Lint prevLint = chk.setLint(lint);
   584         try {
   585             chk.checkDeprecatedAnnotation(tree.pos(), m);
   587             attribBounds(tree.typarams);
   589             // If we override any other methods, check that we do so properly.
   590             // JLS ???
   591             chk.checkOverride(tree, m);
   593             // Create a new environment with local scope
   594             // for attributing the method.
   595             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   597             localEnv.info.lint = lint;
   599             // Enter all type parameters into the local method scope.
   600             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   601                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   603             ClassSymbol owner = env.enclClass.sym;
   604             if ((owner.flags() & ANNOTATION) != 0 &&
   605                 tree.params.nonEmpty())
   606                 log.error(tree.params.head.pos(),
   607                           "intf.annotation.members.cant.have.params");
   609             // Attribute all value parameters.
   610             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   611                 attribStat(l.head, localEnv);
   612             }
   614             // Check that type parameters are well-formed.
   615             chk.validateTypeParams(tree.typarams);
   616             if ((owner.flags() & ANNOTATION) != 0 &&
   617                 tree.typarams.nonEmpty())
   618                 log.error(tree.typarams.head.pos(),
   619                           "intf.annotation.members.cant.have.type.params");
   621             // Check that result type is well-formed.
   622             chk.validate(tree.restype);
   623             if ((owner.flags() & ANNOTATION) != 0)
   624                 chk.validateAnnotationType(tree.restype);
   626             if ((owner.flags() & ANNOTATION) != 0)
   627                 chk.validateAnnotationMethod(tree.pos(), m);
   629             // Check that all exceptions mentioned in the throws clause extend
   630             // java.lang.Throwable.
   631             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
   632                 log.error(tree.thrown.head.pos(),
   633                           "throws.not.allowed.in.intf.annotation");
   634             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   635                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   637             if (tree.body == null) {
   638                 // Empty bodies are only allowed for
   639                 // abstract, native, or interface methods, or for methods
   640                 // in a retrofit signature class.
   641                 if ((owner.flags() & INTERFACE) == 0 &&
   642                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   643                     !relax)
   644                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   645                 if (tree.defaultValue != null) {
   646                     if ((owner.flags() & ANNOTATION) == 0)
   647                         log.error(tree.pos(),
   648                                   "default.allowed.in.intf.annotation.member");
   649                 }
   650             } else if ((owner.flags() & INTERFACE) != 0) {
   651                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   652             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   653                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   654             } else if ((tree.mods.flags & NATIVE) != 0) {
   655                 log.error(tree.pos(), "native.meth.cant.have.body");
   656             } else {
   657                 // Add an implicit super() call unless an explicit call to
   658                 // super(...) or this(...) is given
   659                 // or we are compiling class java.lang.Object.
   660                 if (tree.name == names.init && owner.type != syms.objectType) {
   661                     JCBlock body = tree.body;
   662                     if (body.stats.isEmpty() ||
   663                         !TreeInfo.isSelfCall(body.stats.head)) {
   664                         body.stats = body.stats.
   665                             prepend(memberEnter.SuperCall(make.at(body.pos),
   666                                                           List.<Type>nil(),
   667                                                           List.<JCVariableDecl>nil(),
   668                                                           false));
   669                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   670                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   671                                TreeInfo.isSuperCall(body.stats.head)) {
   672                         // enum constructors are not allowed to call super
   673                         // directly, so make sure there aren't any super calls
   674                         // in enum constructors, except in the compiler
   675                         // generated one.
   676                         log.error(tree.body.stats.head.pos(),
   677                                   "call.to.super.not.allowed.in.enum.ctor",
   678                                   env.enclClass.sym);
   679                     }
   680                 }
   682                 // Attribute method body.
   683                 attribStat(tree.body, localEnv);
   684             }
   685             localEnv.info.scope.leave();
   686             result = tree.type = m.type;
   687             chk.validateAnnotations(tree.mods.annotations, m);
   689         }
   690         finally {
   691             chk.setLint(prevLint);
   692         }
   693     }
   695     public void visitVarDef(JCVariableDecl tree) {
   696         // Local variables have not been entered yet, so we need to do it now:
   697         if (env.info.scope.owner.kind == MTH) {
   698             if (tree.sym != null) {
   699                 // parameters have already been entered
   700                 env.info.scope.enter(tree.sym);
   701             } else {
   702                 memberEnter.memberEnter(tree, env);
   703                 annotate.flush();
   704             }
   705         }
   707         // Check that the variable's declared type is well-formed.
   708         chk.validate(tree.vartype);
   710         VarSymbol v = tree.sym;
   711         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   712         Lint prevLint = chk.setLint(lint);
   714         try {
   715             chk.checkDeprecatedAnnotation(tree.pos(), v);
   717             if (tree.init != null) {
   718                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   719                     // In this case, `v' is final.  Ensure that it's initializer is
   720                     // evaluated.
   721                     v.getConstValue(); // ensure initializer is evaluated
   722                 } else {
   723                     // Attribute initializer in a new environment
   724                     // with the declared variable as owner.
   725                     // Check that initializer conforms to variable's declared type.
   726                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   727                     initEnv.info.lint = lint;
   728                     // In order to catch self-references, we set the variable's
   729                     // declaration position to maximal possible value, effectively
   730                     // marking the variable as undefined.
   731                     v.pos = Position.MAXPOS;
   732                     attribExpr(tree.init, initEnv, v.type);
   733                     v.pos = tree.pos;
   734                 }
   735             }
   736             result = tree.type = v.type;
   737             chk.validateAnnotations(tree.mods.annotations, v);
   738         }
   739         finally {
   740             chk.setLint(prevLint);
   741         }
   742     }
   744     public void visitSkip(JCSkip tree) {
   745         result = null;
   746     }
   748     public void visitBlock(JCBlock tree) {
   749         if (env.info.scope.owner.kind == TYP) {
   750             // Block is a static or instance initializer;
   751             // let the owner of the environment be a freshly
   752             // created BLOCK-method.
   753             Env<AttrContext> localEnv =
   754                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   755             localEnv.info.scope.owner =
   756                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   757                                  env.info.scope.owner);
   758             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   759             attribStats(tree.stats, localEnv);
   760         } else {
   761             // Create a new local environment with a local scope.
   762             Env<AttrContext> localEnv =
   763                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   764             attribStats(tree.stats, localEnv);
   765             localEnv.info.scope.leave();
   766         }
   767         result = null;
   768     }
   770     public void visitDoLoop(JCDoWhileLoop tree) {
   771         attribStat(tree.body, env.dup(tree));
   772         attribExpr(tree.cond, env, syms.booleanType);
   773         result = null;
   774     }
   776     public void visitWhileLoop(JCWhileLoop tree) {
   777         attribExpr(tree.cond, env, syms.booleanType);
   778         attribStat(tree.body, env.dup(tree));
   779         result = null;
   780     }
   782     public void visitForLoop(JCForLoop tree) {
   783         Env<AttrContext> loopEnv =
   784             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   785         attribStats(tree.init, loopEnv);
   786         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   787         loopEnv.tree = tree; // before, we were not in loop!
   788         attribStats(tree.step, loopEnv);
   789         attribStat(tree.body, loopEnv);
   790         loopEnv.info.scope.leave();
   791         result = null;
   792     }
   794     public void visitForeachLoop(JCEnhancedForLoop tree) {
   795         Env<AttrContext> loopEnv =
   796             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   797         attribStat(tree.var, loopEnv);
   798         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   799         chk.checkNonVoid(tree.pos(), exprType);
   800         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   801         if (elemtype == null) {
   802             // or perhaps expr implements Iterable<T>?
   803             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   804             if (base == null) {
   805                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   806                 elemtype = syms.errType;
   807             } else {
   808                 List<Type> iterableParams = base.allparams();
   809                 elemtype = iterableParams.isEmpty()
   810                     ? syms.objectType
   811                     : types.upperBound(iterableParams.head);
   812             }
   813         }
   814         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   815         loopEnv.tree = tree; // before, we were not in loop!
   816         attribStat(tree.body, loopEnv);
   817         loopEnv.info.scope.leave();
   818         result = null;
   819     }
   821     public void visitLabelled(JCLabeledStatement tree) {
   822         // Check that label is not used in an enclosing statement
   823         Env<AttrContext> env1 = env;
   824         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   825             if (env1.tree.getTag() == JCTree.LABELLED &&
   826                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   827                 log.error(tree.pos(), "label.already.in.use",
   828                           tree.label);
   829                 break;
   830             }
   831             env1 = env1.next;
   832         }
   834         attribStat(tree.body, env.dup(tree));
   835         result = null;
   836     }
   838     public void visitSwitch(JCSwitch tree) {
   839         Type seltype = attribExpr(tree.selector, env);
   841         Env<AttrContext> switchEnv =
   842             env.dup(tree, env.info.dup(env.info.scope.dup()));
   844         boolean enumSwitch =
   845             allowEnums &&
   846             (seltype.tsym.flags() & Flags.ENUM) != 0;
   847         if (!enumSwitch)
   848             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   850         // Attribute all cases and
   851         // check that there are no duplicate case labels or default clauses.
   852         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   853         boolean hasDefault = false;      // Is there a default label?
   854         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   855             JCCase c = l.head;
   856             Env<AttrContext> caseEnv =
   857                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   858             if (c.pat != null) {
   859                 if (enumSwitch) {
   860                     Symbol sym = enumConstant(c.pat, seltype);
   861                     if (sym == null) {
   862                         log.error(c.pat.pos(), "enum.const.req");
   863                     } else if (!labels.add(sym)) {
   864                         log.error(c.pos(), "duplicate.case.label");
   865                     }
   866                 } else {
   867                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   868                     if (pattype.tag != ERROR) {
   869                         if (pattype.constValue() == null) {
   870                             log.error(c.pat.pos(), "const.expr.req");
   871                         } else if (labels.contains(pattype.constValue())) {
   872                             log.error(c.pos(), "duplicate.case.label");
   873                         } else {
   874                             labels.add(pattype.constValue());
   875                         }
   876                     }
   877                 }
   878             } else if (hasDefault) {
   879                 log.error(c.pos(), "duplicate.default.label");
   880             } else {
   881                 hasDefault = true;
   882             }
   883             attribStats(c.stats, caseEnv);
   884             caseEnv.info.scope.leave();
   885             addVars(c.stats, switchEnv.info.scope);
   886         }
   888         switchEnv.info.scope.leave();
   889         result = null;
   890     }
   891     // where
   892         /** Add any variables defined in stats to the switch scope. */
   893         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   894             for (;stats.nonEmpty(); stats = stats.tail) {
   895                 JCTree stat = stats.head;
   896                 if (stat.getTag() == JCTree.VARDEF)
   897                     switchScope.enter(((JCVariableDecl) stat).sym);
   898             }
   899         }
   900     // where
   901     /** Return the selected enumeration constant symbol, or null. */
   902     private Symbol enumConstant(JCTree tree, Type enumType) {
   903         if (tree.getTag() != JCTree.IDENT) {
   904             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   905             return syms.errSymbol;
   906         }
   907         JCIdent ident = (JCIdent)tree;
   908         Name name = ident.name;
   909         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   910              e.scope != null; e = e.next()) {
   911             if (e.sym.kind == VAR) {
   912                 Symbol s = ident.sym = e.sym;
   913                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   914                 ident.type = s.type;
   915                 return ((s.flags_field & Flags.ENUM) == 0)
   916                     ? null : s;
   917             }
   918         }
   919         return null;
   920     }
   922     public void visitSynchronized(JCSynchronized tree) {
   923         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
   924         attribStat(tree.body, env);
   925         result = null;
   926     }
   928     public void visitTry(JCTry tree) {
   929         // Attribute body
   930         attribStat(tree.body, env.dup(tree, env.info.dup()));
   932         // Attribute catch clauses
   933         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   934             JCCatch c = l.head;
   935             Env<AttrContext> catchEnv =
   936                 env.dup(c, env.info.dup(env.info.scope.dup()));
   937             Type ctype = attribStat(c.param, catchEnv);
   938             if (c.param.type.tsym.kind == Kinds.VAR) {
   939                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
   940             }
   941             chk.checkType(c.param.vartype.pos(),
   942                           chk.checkClassType(c.param.vartype.pos(), ctype),
   943                           syms.throwableType);
   944             attribStat(c.body, catchEnv);
   945             catchEnv.info.scope.leave();
   946         }
   948         // Attribute finalizer
   949         if (tree.finalizer != null) attribStat(tree.finalizer, env);
   950         result = null;
   951     }
   953     public void visitConditional(JCConditional tree) {
   954         attribExpr(tree.cond, env, syms.booleanType);
   955         attribExpr(tree.truepart, env);
   956         attribExpr(tree.falsepart, env);
   957         result = check(tree,
   958                        capture(condType(tree.pos(), tree.cond.type,
   959                                         tree.truepart.type, tree.falsepart.type)),
   960                        VAL, pkind, pt);
   961     }
   962     //where
   963         /** Compute the type of a conditional expression, after
   964          *  checking that it exists. See Spec 15.25.
   965          *
   966          *  @param pos      The source position to be used for
   967          *                  error diagnostics.
   968          *  @param condtype The type of the expression's condition.
   969          *  @param thentype The type of the expression's then-part.
   970          *  @param elsetype The type of the expression's else-part.
   971          */
   972         private Type condType(DiagnosticPosition pos,
   973                               Type condtype,
   974                               Type thentype,
   975                               Type elsetype) {
   976             Type ctype = condType1(pos, condtype, thentype, elsetype);
   978             // If condition and both arms are numeric constants,
   979             // evaluate at compile-time.
   980             return ((condtype.constValue() != null) &&
   981                     (thentype.constValue() != null) &&
   982                     (elsetype.constValue() != null))
   983                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
   984                 : ctype;
   985         }
   986         /** Compute the type of a conditional expression, after
   987          *  checking that it exists.  Does not take into
   988          *  account the special case where condition and both arms
   989          *  are constants.
   990          *
   991          *  @param pos      The source position to be used for error
   992          *                  diagnostics.
   993          *  @param condtype The type of the expression's condition.
   994          *  @param thentype The type of the expression's then-part.
   995          *  @param elsetype The type of the expression's else-part.
   996          */
   997         private Type condType1(DiagnosticPosition pos, Type condtype,
   998                                Type thentype, Type elsetype) {
   999             // If same type, that is the result
  1000             if (types.isSameType(thentype, elsetype))
  1001                 return thentype.baseType();
  1003             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1004                 ? thentype : types.unboxedType(thentype);
  1005             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1006                 ? elsetype : types.unboxedType(elsetype);
  1008             // Otherwise, if both arms can be converted to a numeric
  1009             // type, return the least numeric type that fits both arms
  1010             // (i.e. return larger of the two, or return int if one
  1011             // arm is short, the other is char).
  1012             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1013                 // If one arm has an integer subrange type (i.e., byte,
  1014                 // short, or char), and the other is an integer constant
  1015                 // that fits into the subrange, return the subrange type.
  1016                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1017                     types.isAssignable(elseUnboxed, thenUnboxed))
  1018                     return thenUnboxed.baseType();
  1019                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1020                     types.isAssignable(thenUnboxed, elseUnboxed))
  1021                     return elseUnboxed.baseType();
  1023                 for (int i = BYTE; i < VOID; i++) {
  1024                     Type candidate = syms.typeOfTag[i];
  1025                     if (types.isSubtype(thenUnboxed, candidate) &&
  1026                         types.isSubtype(elseUnboxed, candidate))
  1027                         return candidate;
  1031             // Those were all the cases that could result in a primitive
  1032             if (allowBoxing) {
  1033                 if (thentype.isPrimitive())
  1034                     thentype = types.boxedClass(thentype).type;
  1035                 if (elsetype.isPrimitive())
  1036                     elsetype = types.boxedClass(elsetype).type;
  1039             if (types.isSubtype(thentype, elsetype))
  1040                 return elsetype.baseType();
  1041             if (types.isSubtype(elsetype, thentype))
  1042                 return thentype.baseType();
  1044             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1045                 log.error(pos, "neither.conditional.subtype",
  1046                           thentype, elsetype);
  1047                 return thentype.baseType();
  1050             // both are known to be reference types.  The result is
  1051             // lub(thentype,elsetype). This cannot fail, as it will
  1052             // always be possible to infer "Object" if nothing better.
  1053             return types.lub(thentype.baseType(), elsetype.baseType());
  1056     public void visitIf(JCIf tree) {
  1057         attribExpr(tree.cond, env, syms.booleanType);
  1058         attribStat(tree.thenpart, env);
  1059         if (tree.elsepart != null)
  1060             attribStat(tree.elsepart, env);
  1061         chk.checkEmptyIf(tree);
  1062         result = null;
  1065     public void visitExec(JCExpressionStatement tree) {
  1066         attribExpr(tree.expr, env);
  1067         result = null;
  1070     public void visitBreak(JCBreak tree) {
  1071         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1072         result = null;
  1075     public void visitContinue(JCContinue tree) {
  1076         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1077         result = null;
  1079     //where
  1080         /** Return the target of a break or continue statement, if it exists,
  1081          *  report an error if not.
  1082          *  Note: The target of a labelled break or continue is the
  1083          *  (non-labelled) statement tree referred to by the label,
  1084          *  not the tree representing the labelled statement itself.
  1086          *  @param pos     The position to be used for error diagnostics
  1087          *  @param tag     The tag of the jump statement. This is either
  1088          *                 Tree.BREAK or Tree.CONTINUE.
  1089          *  @param label   The label of the jump statement, or null if no
  1090          *                 label is given.
  1091          *  @param env     The environment current at the jump statement.
  1092          */
  1093         private JCTree findJumpTarget(DiagnosticPosition pos,
  1094                                     int tag,
  1095                                     Name label,
  1096                                     Env<AttrContext> env) {
  1097             // Search environments outwards from the point of jump.
  1098             Env<AttrContext> env1 = env;
  1099             LOOP:
  1100             while (env1 != null) {
  1101                 switch (env1.tree.getTag()) {
  1102                 case JCTree.LABELLED:
  1103                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1104                     if (label == labelled.label) {
  1105                         // If jump is a continue, check that target is a loop.
  1106                         if (tag == JCTree.CONTINUE) {
  1107                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1108                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1109                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1110                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1111                                 log.error(pos, "not.loop.label", label);
  1112                             // Found labelled statement target, now go inwards
  1113                             // to next non-labelled tree.
  1114                             return TreeInfo.referencedStatement(labelled);
  1115                         } else {
  1116                             return labelled;
  1119                     break;
  1120                 case JCTree.DOLOOP:
  1121                 case JCTree.WHILELOOP:
  1122                 case JCTree.FORLOOP:
  1123                 case JCTree.FOREACHLOOP:
  1124                     if (label == null) return env1.tree;
  1125                     break;
  1126                 case JCTree.SWITCH:
  1127                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1128                     break;
  1129                 case JCTree.METHODDEF:
  1130                 case JCTree.CLASSDEF:
  1131                     break LOOP;
  1132                 default:
  1134                 env1 = env1.next;
  1136             if (label != null)
  1137                 log.error(pos, "undef.label", label);
  1138             else if (tag == JCTree.CONTINUE)
  1139                 log.error(pos, "cont.outside.loop");
  1140             else
  1141                 log.error(pos, "break.outside.switch.loop");
  1142             return null;
  1145     public void visitReturn(JCReturn tree) {
  1146         // Check that there is an enclosing method which is
  1147         // nested within than the enclosing class.
  1148         if (env.enclMethod == null ||
  1149             env.enclMethod.sym.owner != env.enclClass.sym) {
  1150             log.error(tree.pos(), "ret.outside.meth");
  1152         } else {
  1153             // Attribute return expression, if it exists, and check that
  1154             // it conforms to result type of enclosing method.
  1155             Symbol m = env.enclMethod.sym;
  1156             if (m.type.getReturnType().tag == VOID) {
  1157                 if (tree.expr != null)
  1158                     log.error(tree.expr.pos(),
  1159                               "cant.ret.val.from.meth.decl.void");
  1160             } else if (tree.expr == null) {
  1161                 log.error(tree.pos(), "missing.ret.val");
  1162             } else {
  1163                 attribExpr(tree.expr, env, m.type.getReturnType());
  1166         result = null;
  1169     public void visitThrow(JCThrow tree) {
  1170         attribExpr(tree.expr, env, syms.throwableType);
  1171         result = null;
  1174     public void visitAssert(JCAssert tree) {
  1175         attribExpr(tree.cond, env, syms.booleanType);
  1176         if (tree.detail != null) {
  1177             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1179         result = null;
  1182      /** Visitor method for method invocations.
  1183      *  NOTE: The method part of an application will have in its type field
  1184      *        the return type of the method, not the method's type itself!
  1185      */
  1186     public void visitApply(JCMethodInvocation tree) {
  1187         // The local environment of a method application is
  1188         // a new environment nested in the current one.
  1189         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1191         // The types of the actual method arguments.
  1192         List<Type> argtypes;
  1194         // The types of the actual method type arguments.
  1195         List<Type> typeargtypes = null;
  1197         Name methName = TreeInfo.name(tree.meth);
  1199         boolean isConstructorCall =
  1200             methName == names._this || methName == names._super;
  1202         if (isConstructorCall) {
  1203             // We are seeing a ...this(...) or ...super(...) call.
  1204             // Check that this is the first statement in a constructor.
  1205             if (checkFirstConstructorStat(tree, env)) {
  1207                 // Record the fact
  1208                 // that this is a constructor call (using isSelfCall).
  1209                 localEnv.info.isSelfCall = true;
  1211                 // Attribute arguments, yielding list of argument types.
  1212                 argtypes = attribArgs(tree.args, localEnv);
  1213                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1215                 // Variable `site' points to the class in which the called
  1216                 // constructor is defined.
  1217                 Type site = env.enclClass.sym.type;
  1218                 if (methName == names._super) {
  1219                     if (site == syms.objectType) {
  1220                         log.error(tree.meth.pos(), "no.superclass", site);
  1221                         site = syms.errType;
  1222                     } else {
  1223                         site = types.supertype(site);
  1227                 if (site.tag == CLASS) {
  1228                     if (site.getEnclosingType().tag == CLASS) {
  1229                         // we are calling a nested class
  1231                         if (tree.meth.getTag() == JCTree.SELECT) {
  1232                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1234                             // We are seeing a prefixed call, of the form
  1235                             //     <expr>.super(...).
  1236                             // Check that the prefix expression conforms
  1237                             // to the outer instance type of the class.
  1238                             chk.checkRefType(qualifier.pos(),
  1239                                              attribExpr(qualifier, localEnv,
  1240                                                         site.getEnclosingType()));
  1241                         } else if (methName == names._super) {
  1242                             // qualifier omitted; check for existence
  1243                             // of an appropriate implicit qualifier.
  1244                             rs.resolveImplicitThis(tree.meth.pos(),
  1245                                                    localEnv, site);
  1247                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1248                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1249                                   site.tsym);
  1252                     // if we're calling a java.lang.Enum constructor,
  1253                     // prefix the implicit String and int parameters
  1254                     if (site.tsym == syms.enumSym && allowEnums)
  1255                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1257                     // Resolve the called constructor under the assumption
  1258                     // that we are referring to a superclass instance of the
  1259                     // current instance (JLS ???).
  1260                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1261                     localEnv.info.selectSuper = true;
  1262                     localEnv.info.varArgs = false;
  1263                     Symbol sym = rs.resolveConstructor(
  1264                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1265                     localEnv.info.selectSuper = selectSuperPrev;
  1267                     // Set method symbol to resolved constructor...
  1268                     TreeInfo.setSymbol(tree.meth, sym);
  1270                     // ...and check that it is legal in the current context.
  1271                     // (this will also set the tree's type)
  1272                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1273                     checkId(tree.meth, site, sym, localEnv, MTH,
  1274                             mpt, tree.varargsElement != null);
  1276                 // Otherwise, `site' is an error type and we do nothing
  1278             result = tree.type = syms.voidType;
  1279         } else {
  1280             // Otherwise, we are seeing a regular method call.
  1281             // Attribute the arguments, yielding list of argument types, ...
  1282             argtypes = attribArgs(tree.args, localEnv);
  1283             typeargtypes = attribTypes(tree.typeargs, localEnv);
  1285             // ... and attribute the method using as a prototype a methodtype
  1286             // whose formal argument types is exactly the list of actual
  1287             // arguments (this will also set the method symbol).
  1288             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1289             localEnv.info.varArgs = false;
  1290             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1291             if (localEnv.info.varArgs)
  1292                 assert mtype.isErroneous() || tree.varargsElement != null;
  1294             // Compute the result type.
  1295             Type restype = mtype.getReturnType();
  1296             assert restype.tag != WILDCARD : mtype;
  1298             // as a special case, array.clone() has a result that is
  1299             // the same as static type of the array being cloned
  1300             if (tree.meth.getTag() == JCTree.SELECT &&
  1301                 allowCovariantReturns &&
  1302                 methName == names.clone &&
  1303                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1304                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1306             // as a special case, x.getClass() has type Class<? extends |X|>
  1307             if (allowGenerics &&
  1308                 methName == names.getClass && tree.args.isEmpty()) {
  1309                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1310                     ? ((JCFieldAccess) tree.meth).selected.type
  1311                     : env.enclClass.sym.type;
  1312                 restype = new
  1313                     ClassType(restype.getEnclosingType(),
  1314                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1315                                                                BoundKind.EXTENDS,
  1316                                                                syms.boundClass)),
  1317                               restype.tsym);
  1320             // Check that value of resulting type is admissible in the
  1321             // current context.  Also, capture the return type
  1322             result = check(tree, capture(restype), VAL, pkind, pt);
  1324         chk.validate(tree.typeargs);
  1326     //where
  1327         /** Check that given application node appears as first statement
  1328          *  in a constructor call.
  1329          *  @param tree   The application node
  1330          *  @param env    The environment current at the application.
  1331          */
  1332         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1333             JCMethodDecl enclMethod = env.enclMethod;
  1334             if (enclMethod != null && enclMethod.name == names.init) {
  1335                 JCBlock body = enclMethod.body;
  1336                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1337                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1338                     return true;
  1340             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1341                       TreeInfo.name(tree.meth));
  1342             return false;
  1345         /** Obtain a method type with given argument types.
  1346          */
  1347         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1348             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1349             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1352     public void visitNewClass(JCNewClass tree) {
  1353         Type owntype = syms.errType;
  1355         // The local environment of a class creation is
  1356         // a new environment nested in the current one.
  1357         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1359         // The anonymous inner class definition of the new expression,
  1360         // if one is defined by it.
  1361         JCClassDecl cdef = tree.def;
  1363         // If enclosing class is given, attribute it, and
  1364         // complete class name to be fully qualified
  1365         JCExpression clazz = tree.clazz; // Class field following new
  1366         JCExpression clazzid =          // Identifier in class field
  1367             (clazz.getTag() == JCTree.TYPEAPPLY)
  1368             ? ((JCTypeApply) clazz).clazz
  1369             : clazz;
  1371         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1373         if (tree.encl != null) {
  1374             // We are seeing a qualified new, of the form
  1375             //    <expr>.new C <...> (...) ...
  1376             // In this case, we let clazz stand for the name of the
  1377             // allocated class C prefixed with the type of the qualifier
  1378             // expression, so that we can
  1379             // resolve it with standard techniques later. I.e., if
  1380             // <expr> has type T, then <expr>.new C <...> (...)
  1381             // yields a clazz T.C.
  1382             Type encltype = chk.checkRefType(tree.encl.pos(),
  1383                                              attribExpr(tree.encl, env));
  1384             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1385                                                  ((JCIdent) clazzid).name);
  1386             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1387                 clazz = make.at(tree.pos).
  1388                     TypeApply(clazzid1,
  1389                               ((JCTypeApply) clazz).arguments);
  1390             else
  1391                 clazz = clazzid1;
  1392 //          System.out.println(clazz + " generated.");//DEBUG
  1395         // Attribute clazz expression and store
  1396         // symbol + type back into the attributed tree.
  1397         Type clazztype = chk.checkClassType(
  1398             tree.clazz.pos(), attribType(clazz, env), true);
  1399         chk.validate(clazz);
  1400         if (tree.encl != null) {
  1401             // We have to work in this case to store
  1402             // symbol + type back into the attributed tree.
  1403             tree.clazz.type = clazztype;
  1404             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1405             clazzid.type = ((JCIdent) clazzid).sym.type;
  1406             if (!clazztype.isErroneous()) {
  1407                 if (cdef != null && clazztype.tsym.isInterface()) {
  1408                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1409                 } else if (clazztype.tsym.isStatic()) {
  1410                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1413         } else if (!clazztype.tsym.isInterface() &&
  1414                    clazztype.getEnclosingType().tag == CLASS) {
  1415             // Check for the existence of an apropos outer instance
  1416             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1419         // Attribute constructor arguments.
  1420         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1421         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1423         // If we have made no mistakes in the class type...
  1424         if (clazztype.tag == CLASS) {
  1425             // Enums may not be instantiated except implicitly
  1426             if (allowEnums &&
  1427                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1428                 (env.tree.getTag() != JCTree.VARDEF ||
  1429                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1430                  ((JCVariableDecl) env.tree).init != tree))
  1431                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1432             // Check that class is not abstract
  1433             if (cdef == null &&
  1434                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1435                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1436                           clazztype.tsym);
  1437             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1438                 // Check that no constructor arguments are given to
  1439                 // anonymous classes implementing an interface
  1440                 if (!argtypes.isEmpty())
  1441                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1443                 if (!typeargtypes.isEmpty())
  1444                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1446                 // Error recovery: pretend no arguments were supplied.
  1447                 argtypes = List.nil();
  1448                 typeargtypes = List.nil();
  1451             // Resolve the called constructor under the assumption
  1452             // that we are referring to a superclass instance of the
  1453             // current instance (JLS ???).
  1454             else {
  1455                 localEnv.info.selectSuper = cdef != null;
  1456                 localEnv.info.varArgs = false;
  1457                 tree.constructor = rs.resolveConstructor(
  1458                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1459                 Type ctorType = checkMethod(clazztype,
  1460                                             tree.constructor,
  1461                                             localEnv,
  1462                                             tree.args,
  1463                                             argtypes,
  1464                                             typeargtypes,
  1465                                             localEnv.info.varArgs);
  1466                 if (localEnv.info.varArgs)
  1467                     assert ctorType.isErroneous() || tree.varargsElement != null;
  1470             if (cdef != null) {
  1471                 // We are seeing an anonymous class instance creation.
  1472                 // In this case, the class instance creation
  1473                 // expression
  1474                 //
  1475                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1476                 //
  1477                 // is represented internally as
  1478                 //
  1479                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1480                 //
  1481                 // This expression is then *transformed* as follows:
  1482                 //
  1483                 // (1) add a STATIC flag to the class definition
  1484                 //     if the current environment is static
  1485                 // (2) add an extends or implements clause
  1486                 // (3) add a constructor.
  1487                 //
  1488                 // For instance, if C is a class, and ET is the type of E,
  1489                 // the expression
  1490                 //
  1491                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1492                 //
  1493                 // is translated to (where X is a fresh name and typarams is the
  1494                 // parameter list of the super constructor):
  1495                 //
  1496                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1497                 //     X extends C<typargs2> {
  1498                 //       <typarams> X(ET e, args) {
  1499                 //         e.<typeargs1>super(args)
  1500                 //       }
  1501                 //       ...
  1502                 //     }
  1503                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1505                 if (clazztype.tsym.isInterface()) {
  1506                     cdef.implementing = List.of(clazz);
  1507                 } else {
  1508                     cdef.extending = clazz;
  1511                 attribStat(cdef, localEnv);
  1513                 // If an outer instance is given,
  1514                 // prefix it to the constructor arguments
  1515                 // and delete it from the new expression
  1516                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1517                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1518                     argtypes = argtypes.prepend(tree.encl.type);
  1519                     tree.encl = null;
  1522                 // Reassign clazztype and recompute constructor.
  1523                 clazztype = cdef.sym.type;
  1524                 Symbol sym = rs.resolveConstructor(
  1525                     tree.pos(), localEnv, clazztype, argtypes,
  1526                     typeargtypes, true, tree.varargsElement != null);
  1527                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1528                 tree.constructor = sym;
  1531             if (tree.constructor != null && tree.constructor.kind == MTH)
  1532                 owntype = clazztype;
  1534         result = check(tree, owntype, VAL, pkind, pt);
  1535         chk.validate(tree.typeargs);
  1538     /** Make an attributed null check tree.
  1539      */
  1540     public JCExpression makeNullCheck(JCExpression arg) {
  1541         // optimization: X.this is never null; skip null check
  1542         Name name = TreeInfo.name(arg);
  1543         if (name == names._this || name == names._super) return arg;
  1545         int optag = JCTree.NULLCHK;
  1546         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1547         tree.operator = syms.nullcheck;
  1548         tree.type = arg.type;
  1549         return tree;
  1552     public void visitNewArray(JCNewArray tree) {
  1553         Type owntype = syms.errType;
  1554         Type elemtype;
  1555         if (tree.elemtype != null) {
  1556             elemtype = attribType(tree.elemtype, env);
  1557             chk.validate(tree.elemtype);
  1558             owntype = elemtype;
  1559             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1560                 attribExpr(l.head, env, syms.intType);
  1561                 owntype = new ArrayType(owntype, syms.arrayClass);
  1563         } else {
  1564             // we are seeing an untyped aggregate { ... }
  1565             // this is allowed only if the prototype is an array
  1566             if (pt.tag == ARRAY) {
  1567                 elemtype = types.elemtype(pt);
  1568             } else {
  1569                 if (pt.tag != ERROR) {
  1570                     log.error(tree.pos(), "illegal.initializer.for.type",
  1571                               pt);
  1573                 elemtype = syms.errType;
  1576         if (tree.elems != null) {
  1577             attribExprs(tree.elems, env, elemtype);
  1578             owntype = new ArrayType(elemtype, syms.arrayClass);
  1580         if (!types.isReifiable(elemtype))
  1581             log.error(tree.pos(), "generic.array.creation");
  1582         result = check(tree, owntype, VAL, pkind, pt);
  1585     public void visitParens(JCParens tree) {
  1586         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1587         result = check(tree, owntype, pkind, pkind, pt);
  1588         Symbol sym = TreeInfo.symbol(tree);
  1589         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1590             log.error(tree.pos(), "illegal.start.of.type");
  1593     public void visitAssign(JCAssign tree) {
  1594         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1595         Type capturedType = capture(owntype);
  1596         attribExpr(tree.rhs, env, owntype);
  1597         result = check(tree, capturedType, VAL, pkind, pt);
  1600     public void visitAssignop(JCAssignOp tree) {
  1601         // Attribute arguments.
  1602         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1603         Type operand = attribExpr(tree.rhs, env);
  1604         // Find operator.
  1605         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1606             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1607             owntype, operand);
  1609         if (operator.kind == MTH) {
  1610             chk.checkOperator(tree.pos(),
  1611                               (OperatorSymbol)operator,
  1612                               tree.getTag() - JCTree.ASGOffset,
  1613                               owntype,
  1614                               operand);
  1615             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1616             chk.checkCastable(tree.rhs.pos(),
  1617                               operator.type.getReturnType(),
  1618                               owntype);
  1620         result = check(tree, owntype, VAL, pkind, pt);
  1623     public void visitUnary(JCUnary tree) {
  1624         // Attribute arguments.
  1625         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1626             ? attribTree(tree.arg, env, VAR, Type.noType)
  1627             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1629         // Find operator.
  1630         Symbol operator = tree.operator =
  1631             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1633         Type owntype = syms.errType;
  1634         if (operator.kind == MTH) {
  1635             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1636                 ? tree.arg.type
  1637                 : operator.type.getReturnType();
  1638             int opc = ((OperatorSymbol)operator).opcode;
  1640             // If the argument is constant, fold it.
  1641             if (argtype.constValue() != null) {
  1642                 Type ctype = cfolder.fold1(opc, argtype);
  1643                 if (ctype != null) {
  1644                     owntype = cfolder.coerce(ctype, owntype);
  1646                     // Remove constant types from arguments to
  1647                     // conserve space. The parser will fold concatenations
  1648                     // of string literals; the code here also
  1649                     // gets rid of intermediate results when some of the
  1650                     // operands are constant identifiers.
  1651                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1652                         tree.arg.type = syms.stringType;
  1657         result = check(tree, owntype, VAL, pkind, pt);
  1660     public void visitBinary(JCBinary tree) {
  1661         // Attribute arguments.
  1662         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1663         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1665         // Find operator.
  1666         Symbol operator = tree.operator =
  1667             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1669         Type owntype = syms.errType;
  1670         if (operator.kind == MTH) {
  1671             owntype = operator.type.getReturnType();
  1672             int opc = chk.checkOperator(tree.lhs.pos(),
  1673                                         (OperatorSymbol)operator,
  1674                                         tree.getTag(),
  1675                                         left,
  1676                                         right);
  1678             // If both arguments are constants, fold them.
  1679             if (left.constValue() != null && right.constValue() != null) {
  1680                 Type ctype = cfolder.fold2(opc, left, right);
  1681                 if (ctype != null) {
  1682                     owntype = cfolder.coerce(ctype, owntype);
  1684                     // Remove constant types from arguments to
  1685                     // conserve space. The parser will fold concatenations
  1686                     // of string literals; the code here also
  1687                     // gets rid of intermediate results when some of the
  1688                     // operands are constant identifiers.
  1689                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1690                         tree.lhs.type = syms.stringType;
  1692                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1693                         tree.rhs.type = syms.stringType;
  1698             // Check that argument types of a reference ==, != are
  1699             // castable to each other, (JLS???).
  1700             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  1701                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  1702                     log.error(tree.pos(), "incomparable.types", left, right);
  1706             chk.checkDivZero(tree.rhs.pos(), operator, right);
  1708         result = check(tree, owntype, VAL, pkind, pt);
  1711     public void visitTypeCast(JCTypeCast tree) {
  1712         Type clazztype = attribType(tree.clazz, env);
  1713         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  1714         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1715         if (exprtype.constValue() != null)
  1716             owntype = cfolder.coerce(exprtype, owntype);
  1717         result = check(tree, capture(owntype), VAL, pkind, pt);
  1720     public void visitTypeTest(JCInstanceOf tree) {
  1721         Type exprtype = chk.checkNullOrRefType(
  1722             tree.expr.pos(), attribExpr(tree.expr, env));
  1723         Type clazztype = chk.checkReifiableReferenceType(
  1724             tree.clazz.pos(), attribType(tree.clazz, env));
  1725         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1726         result = check(tree, syms.booleanType, VAL, pkind, pt);
  1729     public void visitIndexed(JCArrayAccess tree) {
  1730         Type owntype = syms.errType;
  1731         Type atype = attribExpr(tree.indexed, env);
  1732         attribExpr(tree.index, env, syms.intType);
  1733         if (types.isArray(atype))
  1734             owntype = types.elemtype(atype);
  1735         else if (atype.tag != ERROR)
  1736             log.error(tree.pos(), "array.req.but.found", atype);
  1737         if ((pkind & VAR) == 0) owntype = capture(owntype);
  1738         result = check(tree, owntype, VAR, pkind, pt);
  1741     public void visitIdent(JCIdent tree) {
  1742         Symbol sym;
  1743         boolean varArgs = false;
  1745         // Find symbol
  1746         if (pt.tag == METHOD || pt.tag == FORALL) {
  1747             // If we are looking for a method, the prototype `pt' will be a
  1748             // method type with the type of the call's arguments as parameters.
  1749             env.info.varArgs = false;
  1750             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  1751             varArgs = env.info.varArgs;
  1752         } else if (tree.sym != null && tree.sym.kind != VAR) {
  1753             sym = tree.sym;
  1754         } else {
  1755             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  1757         tree.sym = sym;
  1759         // (1) Also find the environment current for the class where
  1760         //     sym is defined (`symEnv').
  1761         // Only for pre-tiger versions (1.4 and earlier):
  1762         // (2) Also determine whether we access symbol out of an anonymous
  1763         //     class in a this or super call.  This is illegal for instance
  1764         //     members since such classes don't carry a this$n link.
  1765         //     (`noOuterThisPath').
  1766         Env<AttrContext> symEnv = env;
  1767         boolean noOuterThisPath = false;
  1768         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  1769             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  1770             sym.owner.kind == TYP &&
  1771             tree.name != names._this && tree.name != names._super) {
  1773             // Find environment in which identifier is defined.
  1774             while (symEnv.outer != null &&
  1775                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  1776                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  1777                     noOuterThisPath = !allowAnonOuterThis;
  1778                 symEnv = symEnv.outer;
  1782         // If symbol is a variable, ...
  1783         if (sym.kind == VAR) {
  1784             VarSymbol v = (VarSymbol)sym;
  1786             // ..., evaluate its initializer, if it has one, and check for
  1787             // illegal forward reference.
  1788             checkInit(tree, env, v, false);
  1790             // If symbol is a local variable accessed from an embedded
  1791             // inner class check that it is final.
  1792             if (v.owner.kind == MTH &&
  1793                 v.owner != env.info.scope.owner &&
  1794                 (v.flags_field & FINAL) == 0) {
  1795                 log.error(tree.pos(),
  1796                           "local.var.accessed.from.icls.needs.final",
  1797                           v);
  1800             // If we are expecting a variable (as opposed to a value), check
  1801             // that the variable is assignable in the current environment.
  1802             if (pkind == VAR)
  1803                 checkAssignable(tree.pos(), v, null, env);
  1806         // In a constructor body,
  1807         // if symbol is a field or instance method, check that it is
  1808         // not accessed before the supertype constructor is called.
  1809         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  1810             (sym.kind & (VAR | MTH)) != 0 &&
  1811             sym.owner.kind == TYP &&
  1812             (sym.flags() & STATIC) == 0) {
  1813             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  1815         Env<AttrContext> env1 = env;
  1816         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  1817             // If the found symbol is inaccessible, then it is
  1818             // accessed through an enclosing instance.  Locate this
  1819             // enclosing instance:
  1820             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  1821                 env1 = env1.outer;
  1823         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  1826     public void visitSelect(JCFieldAccess tree) {
  1827         // Determine the expected kind of the qualifier expression.
  1828         int skind = 0;
  1829         if (tree.name == names._this || tree.name == names._super ||
  1830             tree.name == names._class)
  1832             skind = TYP;
  1833         } else {
  1834             if ((pkind & PCK) != 0) skind = skind | PCK;
  1835             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  1836             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  1839         // Attribute the qualifier expression, and determine its symbol (if any).
  1840         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  1841         if ((pkind & (PCK | TYP)) == 0)
  1842             site = capture(site); // Capture field access
  1844         // don't allow T.class T[].class, etc
  1845         if (skind == TYP) {
  1846             Type elt = site;
  1847             while (elt.tag == ARRAY)
  1848                 elt = ((ArrayType)elt).elemtype;
  1849             if (elt.tag == TYPEVAR) {
  1850                 log.error(tree.pos(), "type.var.cant.be.deref");
  1851                 result = syms.errType;
  1852                 return;
  1856         // If qualifier symbol is a type or `super', assert `selectSuper'
  1857         // for the selection. This is relevant for determining whether
  1858         // protected symbols are accessible.
  1859         Symbol sitesym = TreeInfo.symbol(tree.selected);
  1860         boolean selectSuperPrev = env.info.selectSuper;
  1861         env.info.selectSuper =
  1862             sitesym != null &&
  1863             sitesym.name == names._super;
  1865         // If selected expression is polymorphic, strip
  1866         // type parameters and remember in env.info.tvars, so that
  1867         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  1868         if (tree.selected.type.tag == FORALL) {
  1869             ForAll pstype = (ForAll)tree.selected.type;
  1870             env.info.tvars = pstype.tvars;
  1871             site = tree.selected.type = pstype.qtype;
  1874         // Determine the symbol represented by the selection.
  1875         env.info.varArgs = false;
  1876         Symbol sym = selectSym(tree, site, env, pt, pkind);
  1877         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  1878             site = capture(site);
  1879             sym = selectSym(tree, site, env, pt, pkind);
  1881         boolean varArgs = env.info.varArgs;
  1882         tree.sym = sym;
  1884         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  1885             while (site.tag == TYPEVAR) site = site.getUpperBound();
  1886             site = capture(site);
  1889         // If that symbol is a variable, ...
  1890         if (sym.kind == VAR) {
  1891             VarSymbol v = (VarSymbol)sym;
  1893             // ..., evaluate its initializer, if it has one, and check for
  1894             // illegal forward reference.
  1895             checkInit(tree, env, v, true);
  1897             // If we are expecting a variable (as opposed to a value), check
  1898             // that the variable is assignable in the current environment.
  1899             if (pkind == VAR)
  1900                 checkAssignable(tree.pos(), v, tree.selected, env);
  1903         // Disallow selecting a type from an expression
  1904         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  1905             tree.type = check(tree.selected, pt,
  1906                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  1909         if (isType(sitesym)) {
  1910             if (sym.name == names._this) {
  1911                 // If `C' is the currently compiled class, check that
  1912                 // C.this' does not appear in a call to a super(...)
  1913                 if (env.info.isSelfCall &&
  1914                     site.tsym == env.enclClass.sym) {
  1915                     chk.earlyRefError(tree.pos(), sym);
  1917             } else {
  1918                 // Check if type-qualified fields or methods are static (JLS)
  1919                 if ((sym.flags() & STATIC) == 0 &&
  1920                     sym.name != names._super &&
  1921                     (sym.kind == VAR || sym.kind == MTH)) {
  1922                     rs.access(rs.new StaticError(sym),
  1923                               tree.pos(), site, sym.name, true);
  1928         // If we are selecting an instance member via a `super', ...
  1929         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  1931             // Check that super-qualified symbols are not abstract (JLS)
  1932             rs.checkNonAbstract(tree.pos(), sym);
  1934             if (site.isRaw()) {
  1935                 // Determine argument types for site.
  1936                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  1937                 if (site1 != null) site = site1;
  1941         env.info.selectSuper = selectSuperPrev;
  1942         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  1943         env.info.tvars = List.nil();
  1945     //where
  1946         /** Determine symbol referenced by a Select expression,
  1948          *  @param tree   The select tree.
  1949          *  @param site   The type of the selected expression,
  1950          *  @param env    The current environment.
  1951          *  @param pt     The current prototype.
  1952          *  @param pkind  The expected kind(s) of the Select expression.
  1953          */
  1954         private Symbol selectSym(JCFieldAccess tree,
  1955                                  Type site,
  1956                                  Env<AttrContext> env,
  1957                                  Type pt,
  1958                                  int pkind) {
  1959             DiagnosticPosition pos = tree.pos();
  1960             Name name = tree.name;
  1962             switch (site.tag) {
  1963             case PACKAGE:
  1964                 return rs.access(
  1965                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  1966                     pos, site, name, true);
  1967             case ARRAY:
  1968             case CLASS:
  1969                 if (pt.tag == METHOD || pt.tag == FORALL) {
  1970                     return rs.resolveQualifiedMethod(
  1971                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  1972                 } else if (name == names._this || name == names._super) {
  1973                     return rs.resolveSelf(pos, env, site.tsym, name);
  1974                 } else if (name == names._class) {
  1975                     // In this case, we have already made sure in
  1976                     // visitSelect that qualifier expression is a type.
  1977                     Type t = syms.classType;
  1978                     List<Type> typeargs = allowGenerics
  1979                         ? List.of(types.erasure(site))
  1980                         : List.<Type>nil();
  1981                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  1982                     return new VarSymbol(
  1983                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  1984                 } else {
  1985                     // We are seeing a plain identifier as selector.
  1986                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  1987                     if ((pkind & ERRONEOUS) == 0)
  1988                         sym = rs.access(sym, pos, site, name, true);
  1989                     return sym;
  1991             case WILDCARD:
  1992                 throw new AssertionError(tree);
  1993             case TYPEVAR:
  1994                 // Normally, site.getUpperBound() shouldn't be null.
  1995                 // It should only happen during memberEnter/attribBase
  1996                 // when determining the super type which *must* be
  1997                 // done before attributing the type variables.  In
  1998                 // other words, we are seeing this illegal program:
  1999                 // class B<T> extends A<T.foo> {}
  2000                 Symbol sym = (site.getUpperBound() != null)
  2001                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2002                     : null;
  2003                 if (sym == null || isType(sym)) {
  2004                     log.error(pos, "type.var.cant.be.deref");
  2005                     return syms.errSymbol;
  2006                 } else {
  2007                     return sym;
  2009             case ERROR:
  2010                 // preserve identifier names through errors
  2011                 return new ErrorType(name, site.tsym).tsym;
  2012             default:
  2013                 // The qualifier expression is of a primitive type -- only
  2014                 // .class is allowed for these.
  2015                 if (name == names._class) {
  2016                     // In this case, we have already made sure in Select that
  2017                     // qualifier expression is a type.
  2018                     Type t = syms.classType;
  2019                     Type arg = types.boxedClass(site).type;
  2020                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2021                     return new VarSymbol(
  2022                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2023                 } else {
  2024                     log.error(pos, "cant.deref", site);
  2025                     return syms.errSymbol;
  2030         /** Determine type of identifier or select expression and check that
  2031          *  (1) the referenced symbol is not deprecated
  2032          *  (2) the symbol's type is safe (@see checkSafe)
  2033          *  (3) if symbol is a variable, check that its type and kind are
  2034          *      compatible with the prototype and protokind.
  2035          *  (4) if symbol is an instance field of a raw type,
  2036          *      which is being assigned to, issue an unchecked warning if its
  2037          *      type changes under erasure.
  2038          *  (5) if symbol is an instance method of a raw type, issue an
  2039          *      unchecked warning if its argument types change under erasure.
  2040          *  If checks succeed:
  2041          *    If symbol is a constant, return its constant type
  2042          *    else if symbol is a method, return its result type
  2043          *    otherwise return its type.
  2044          *  Otherwise return errType.
  2046          *  @param tree       The syntax tree representing the identifier
  2047          *  @param site       If this is a select, the type of the selected
  2048          *                    expression, otherwise the type of the current class.
  2049          *  @param sym        The symbol representing the identifier.
  2050          *  @param env        The current environment.
  2051          *  @param pkind      The set of expected kinds.
  2052          *  @param pt         The expected type.
  2053          */
  2054         Type checkId(JCTree tree,
  2055                      Type site,
  2056                      Symbol sym,
  2057                      Env<AttrContext> env,
  2058                      int pkind,
  2059                      Type pt,
  2060                      boolean useVarargs) {
  2061             if (pt.isErroneous()) return syms.errType;
  2062             Type owntype; // The computed type of this identifier occurrence.
  2063             switch (sym.kind) {
  2064             case TYP:
  2065                 // For types, the computed type equals the symbol's type,
  2066                 // except for two situations:
  2067                 owntype = sym.type;
  2068                 if (owntype.tag == CLASS) {
  2069                     Type ownOuter = owntype.getEnclosingType();
  2071                     // (a) If the symbol's type is parameterized, erase it
  2072                     // because no type parameters were given.
  2073                     // We recover generic outer type later in visitTypeApply.
  2074                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2075                         owntype = types.erasure(owntype);
  2078                     // (b) If the symbol's type is an inner class, then
  2079                     // we have to interpret its outer type as a superclass
  2080                     // of the site type. Example:
  2081                     //
  2082                     // class Tree<A> { class Visitor { ... } }
  2083                     // class PointTree extends Tree<Point> { ... }
  2084                     // ...PointTree.Visitor...
  2085                     //
  2086                     // Then the type of the last expression above is
  2087                     // Tree<Point>.Visitor.
  2088                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2089                         Type normOuter = site;
  2090                         if (normOuter.tag == CLASS)
  2091                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2092                         if (normOuter == null) // perhaps from an import
  2093                             normOuter = types.erasure(ownOuter);
  2094                         if (normOuter != ownOuter)
  2095                             owntype = new ClassType(
  2096                                 normOuter, List.<Type>nil(), owntype.tsym);
  2099                 break;
  2100             case VAR:
  2101                 VarSymbol v = (VarSymbol)sym;
  2102                 // Test (4): if symbol is an instance field of a raw type,
  2103                 // which is being assigned to, issue an unchecked warning if
  2104                 // its type changes under erasure.
  2105                 if (allowGenerics &&
  2106                     pkind == VAR &&
  2107                     v.owner.kind == TYP &&
  2108                     (v.flags() & STATIC) == 0 &&
  2109                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2110                     Type s = types.asOuterSuper(site, v.owner);
  2111                     if (s != null &&
  2112                         s.isRaw() &&
  2113                         !types.isSameType(v.type, v.erasure(types))) {
  2114                         chk.warnUnchecked(tree.pos(),
  2115                                           "unchecked.assign.to.var",
  2116                                           v, s);
  2119                 // The computed type of a variable is the type of the
  2120                 // variable symbol, taken as a member of the site type.
  2121                 owntype = (sym.owner.kind == TYP &&
  2122                            sym.name != names._this && sym.name != names._super)
  2123                     ? types.memberType(site, sym)
  2124                     : sym.type;
  2126                 if (env.info.tvars.nonEmpty()) {
  2127                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2128                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2129                         if (!owntype.contains(l.head)) {
  2130                             log.error(tree.pos(), "undetermined.type", owntype1);
  2131                             owntype1 = syms.errType;
  2133                     owntype = owntype1;
  2136                 // If the variable is a constant, record constant value in
  2137                 // computed type.
  2138                 if (v.getConstValue() != null && isStaticReference(tree))
  2139                     owntype = owntype.constType(v.getConstValue());
  2141                 if (pkind == VAL) {
  2142                     owntype = capture(owntype); // capture "names as expressions"
  2144                 break;
  2145             case MTH: {
  2146                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2147                 owntype = checkMethod(site, sym, env, app.args,
  2148                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2149                                       env.info.varArgs);
  2150                 break;
  2152             case PCK: case ERR:
  2153                 owntype = sym.type;
  2154                 break;
  2155             default:
  2156                 throw new AssertionError("unexpected kind: " + sym.kind +
  2157                                          " in tree " + tree);
  2160             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2161             // (for constructors, the error was given when the constructor was
  2162             // resolved)
  2163             if (sym.name != names.init &&
  2164                 (sym.flags() & DEPRECATED) != 0 &&
  2165                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2166                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2167                 chk.warnDeprecated(tree.pos(), sym);
  2169             if ((sym.flags() & PROPRIETARY) != 0)
  2170                 log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2172             // Test (3): if symbol is a variable, check that its type and
  2173             // kind are compatible with the prototype and protokind.
  2174             return check(tree, owntype, sym.kind, pkind, pt);
  2177         /** Check that variable is initialized and evaluate the variable's
  2178          *  initializer, if not yet done. Also check that variable is not
  2179          *  referenced before it is defined.
  2180          *  @param tree    The tree making up the variable reference.
  2181          *  @param env     The current environment.
  2182          *  @param v       The variable's symbol.
  2183          */
  2184         private void checkInit(JCTree tree,
  2185                                Env<AttrContext> env,
  2186                                VarSymbol v,
  2187                                boolean onlyWarning) {
  2188 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2189 //                             tree.pos + " " + v.pos + " " +
  2190 //                             Resolve.isStatic(env));//DEBUG
  2192             // A forward reference is diagnosed if the declaration position
  2193             // of the variable is greater than the current tree position
  2194             // and the tree and variable definition occur in the same class
  2195             // definition.  Note that writes don't count as references.
  2196             // This check applies only to class and instance
  2197             // variables.  Local variables follow different scope rules,
  2198             // and are subject to definite assignment checking.
  2199             if (v.pos > tree.pos &&
  2200                 v.owner.kind == TYP &&
  2201                 canOwnInitializer(env.info.scope.owner) &&
  2202                 v.owner == env.info.scope.owner.enclClass() &&
  2203                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2204                 (env.tree.getTag() != JCTree.ASSIGN ||
  2205                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2207                 if (!onlyWarning || isStaticEnumField(v)) {
  2208                     log.error(tree.pos(), "illegal.forward.ref");
  2209                 } else if (useBeforeDeclarationWarning) {
  2210                     log.warning(tree.pos(), "forward.ref", v);
  2214             v.getConstValue(); // ensure initializer is evaluated
  2216             checkEnumInitializer(tree, env, v);
  2219         /**
  2220          * Check for illegal references to static members of enum.  In
  2221          * an enum type, constructors and initializers may not
  2222          * reference its static members unless they are constant.
  2224          * @param tree    The tree making up the variable reference.
  2225          * @param env     The current environment.
  2226          * @param v       The variable's symbol.
  2227          * @see JLS 3rd Ed. (8.9 Enums)
  2228          */
  2229         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2230             // JLS 3rd Ed.:
  2231             //
  2232             // "It is a compile-time error to reference a static field
  2233             // of an enum type that is not a compile-time constant
  2234             // (15.28) from constructors, instance initializer blocks,
  2235             // or instance variable initializer expressions of that
  2236             // type. It is a compile-time error for the constructors,
  2237             // instance initializer blocks, or instance variable
  2238             // initializer expressions of an enum constant e to refer
  2239             // to itself or to an enum constant of the same type that
  2240             // is declared to the right of e."
  2241             if (isStaticEnumField(v)) {
  2242                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2244                 if (enclClass == null || enclClass.owner == null)
  2245                     return;
  2247                 // See if the enclosing class is the enum (or a
  2248                 // subclass thereof) declaring v.  If not, this
  2249                 // reference is OK.
  2250                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2251                     return;
  2253                 // If the reference isn't from an initializer, then
  2254                 // the reference is OK.
  2255                 if (!Resolve.isInitializer(env))
  2256                     return;
  2258                 log.error(tree.pos(), "illegal.enum.static.ref");
  2262         /** Is the given symbol a static, non-constant field of an Enum?
  2263          *  Note: enum literals should not be regarded as such
  2264          */
  2265         private boolean isStaticEnumField(VarSymbol v) {
  2266             return Flags.isEnum(v.owner) &&
  2267                    Flags.isStatic(v) &&
  2268                    !Flags.isConstant(v) &&
  2269                    v.name != names._class;
  2272         /** Can the given symbol be the owner of code which forms part
  2273          *  if class initialization? This is the case if the symbol is
  2274          *  a type or field, or if the symbol is the synthetic method.
  2275          *  owning a block.
  2276          */
  2277         private boolean canOwnInitializer(Symbol sym) {
  2278             return
  2279                 (sym.kind & (VAR | TYP)) != 0 ||
  2280                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2283     Warner noteWarner = new Warner();
  2285     /**
  2286      * Check that method arguments conform to its instantation.
  2287      **/
  2288     public Type checkMethod(Type site,
  2289                             Symbol sym,
  2290                             Env<AttrContext> env,
  2291                             final List<JCExpression> argtrees,
  2292                             List<Type> argtypes,
  2293                             List<Type> typeargtypes,
  2294                             boolean useVarargs) {
  2295         // Test (5): if symbol is an instance method of a raw type, issue
  2296         // an unchecked warning if its argument types change under erasure.
  2297         if (allowGenerics &&
  2298             (sym.flags() & STATIC) == 0 &&
  2299             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2300             Type s = types.asOuterSuper(site, sym.owner);
  2301             if (s != null && s.isRaw() &&
  2302                 !types.isSameTypes(sym.type.getParameterTypes(),
  2303                                    sym.erasure(types).getParameterTypes())) {
  2304                 chk.warnUnchecked(env.tree.pos(),
  2305                                   "unchecked.call.mbr.of.raw.type",
  2306                                   sym, s);
  2310         // Compute the identifier's instantiated type.
  2311         // For methods, we need to compute the instance type by
  2312         // Resolve.instantiate from the symbol's type as well as
  2313         // any type arguments and value arguments.
  2314         noteWarner.warned = false;
  2315         Type owntype = rs.instantiate(env,
  2316                                       site,
  2317                                       sym,
  2318                                       argtypes,
  2319                                       typeargtypes,
  2320                                       true,
  2321                                       useVarargs,
  2322                                       noteWarner);
  2323         boolean warned = noteWarner.warned;
  2325         // If this fails, something went wrong; we should not have
  2326         // found the identifier in the first place.
  2327         if (owntype == null) {
  2328             if (!pt.isErroneous())
  2329                 log.error(env.tree.pos(),
  2330                           "internal.error.cant.instantiate",
  2331                           sym, site,
  2332                           Type.toString(pt.getParameterTypes()));
  2333             owntype = syms.errType;
  2334         } else {
  2335             // System.out.println("call   : " + env.tree);
  2336             // System.out.println("method : " + owntype);
  2337             // System.out.println("actuals: " + argtypes);
  2338             List<Type> formals = owntype.getParameterTypes();
  2339             Type last = useVarargs ? formals.last() : null;
  2340             if (sym.name==names.init &&
  2341                 sym.owner == syms.enumSym)
  2342                 formals = formals.tail.tail;
  2343             List<JCExpression> args = argtrees;
  2344             while (formals.head != last) {
  2345                 JCTree arg = args.head;
  2346                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2347                 assertConvertible(arg, arg.type, formals.head, warn);
  2348                 warned |= warn.warned;
  2349                 args = args.tail;
  2350                 formals = formals.tail;
  2352             if (useVarargs) {
  2353                 Type varArg = types.elemtype(last);
  2354                 while (args.tail != null) {
  2355                     JCTree arg = args.head;
  2356                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2357                     assertConvertible(arg, arg.type, varArg, warn);
  2358                     warned |= warn.warned;
  2359                     args = args.tail;
  2361             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2362                 // non-varargs call to varargs method
  2363                 Type varParam = owntype.getParameterTypes().last();
  2364                 Type lastArg = argtypes.last();
  2365                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2366                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2367                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2368                                 types.elemtype(varParam),
  2369                                 varParam);
  2372             if (warned && sym.type.tag == FORALL) {
  2373                 String typeargs = "";
  2374                 if (typeargtypes != null && typeargtypes.nonEmpty()) {
  2375                     typeargs = "<" + Type.toString(typeargtypes) + ">";
  2377                 chk.warnUnchecked(env.tree.pos(),
  2378                                   "unchecked.meth.invocation.applied",
  2379                                   sym,
  2380                                   sym.location(),
  2381                                   typeargs,
  2382                                   Type.toString(argtypes));
  2383                 owntype = new MethodType(owntype.getParameterTypes(),
  2384                                          types.erasure(owntype.getReturnType()),
  2385                                          owntype.getThrownTypes(),
  2386                                          syms.methodClass);
  2388             if (useVarargs) {
  2389                 JCTree tree = env.tree;
  2390                 Type argtype = owntype.getParameterTypes().last();
  2391                 if (!types.isReifiable(argtype))
  2392                     chk.warnUnchecked(env.tree.pos(),
  2393                                       "unchecked.generic.array.creation",
  2394                                       argtype);
  2395                 Type elemtype = types.elemtype(argtype);
  2396                 switch (tree.getTag()) {
  2397                 case JCTree.APPLY:
  2398                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2399                     break;
  2400                 case JCTree.NEWCLASS:
  2401                     ((JCNewClass) tree).varargsElement = elemtype;
  2402                     break;
  2403                 default:
  2404                     throw new AssertionError(""+tree);
  2408         return owntype;
  2411     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2412         if (types.isConvertible(actual, formal, warn))
  2413             return;
  2415         if (formal.isCompound()
  2416             && types.isSubtype(actual, types.supertype(formal))
  2417             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2418             return;
  2420         if (false) {
  2421             // TODO: make assertConvertible work
  2422             chk.typeError(tree.pos(), JCDiagnostic.fragment("incompatible.types"), actual, formal);
  2423             throw new AssertionError("Tree: " + tree
  2424                                      + " actual:" + actual
  2425                                      + " formal: " + formal);
  2429     public void visitLiteral(JCLiteral tree) {
  2430         result = check(
  2431             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2433     //where
  2434     /** Return the type of a literal with given type tag.
  2435      */
  2436     Type litType(int tag) {
  2437         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2440     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2441         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2444     public void visitTypeArray(JCArrayTypeTree tree) {
  2445         Type etype = attribType(tree.elemtype, env);
  2446         Type type = new ArrayType(etype, syms.arrayClass);
  2447         result = check(tree, type, TYP, pkind, pt);
  2450     /** Visitor method for parameterized types.
  2451      *  Bound checking is left until later, since types are attributed
  2452      *  before supertype structure is completely known
  2453      */
  2454     public void visitTypeApply(JCTypeApply tree) {
  2455         Type owntype = syms.errType;
  2457         // Attribute functor part of application and make sure it's a class.
  2458         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2460         // Attribute type parameters
  2461         List<Type> actuals = attribTypes(tree.arguments, env);
  2463         if (clazztype.tag == CLASS) {
  2464             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2466             if (actuals.length() == formals.length()) {
  2467                 List<Type> a = actuals;
  2468                 List<Type> f = formals;
  2469                 while (a.nonEmpty()) {
  2470                     a.head = a.head.withTypeVar(f.head);
  2471                     a = a.tail;
  2472                     f = f.tail;
  2474                 // Compute the proper generic outer
  2475                 Type clazzOuter = clazztype.getEnclosingType();
  2476                 if (clazzOuter.tag == CLASS) {
  2477                     Type site;
  2478                     if (tree.clazz.getTag() == JCTree.IDENT) {
  2479                         site = env.enclClass.sym.type;
  2480                     } else if (tree.clazz.getTag() == JCTree.SELECT) {
  2481                         site = ((JCFieldAccess) tree.clazz).selected.type;
  2482                     } else throw new AssertionError(""+tree);
  2483                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2484                         if (site.tag == CLASS)
  2485                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2486                         if (site == null)
  2487                             site = types.erasure(clazzOuter);
  2488                         clazzOuter = site;
  2491                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2492             } else {
  2493                 if (formals.length() != 0) {
  2494                     log.error(tree.pos(), "wrong.number.type.args",
  2495                               Integer.toString(formals.length()));
  2496                 } else {
  2497                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2499                 owntype = syms.errType;
  2502         result = check(tree, owntype, TYP, pkind, pt);
  2505     public void visitTypeParameter(JCTypeParameter tree) {
  2506         TypeVar a = (TypeVar)tree.type;
  2507         Set<Type> boundSet = new HashSet<Type>();
  2508         if (a.bound.isErroneous())
  2509             return;
  2510         List<Type> bs = types.getBounds(a);
  2511         if (tree.bounds.nonEmpty()) {
  2512             // accept class or interface or typevar as first bound.
  2513             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2514             boundSet.add(types.erasure(b));
  2515             if (b.tag == TYPEVAR) {
  2516                 // if first bound was a typevar, do not accept further bounds.
  2517                 if (tree.bounds.tail.nonEmpty()) {
  2518                     log.error(tree.bounds.tail.head.pos(),
  2519                               "type.var.may.not.be.followed.by.other.bounds");
  2520                     tree.bounds = List.of(tree.bounds.head);
  2521                     a.bound = bs.head;
  2523             } else {
  2524                 // if first bound was a class or interface, accept only interfaces
  2525                 // as further bounds.
  2526                 for (JCExpression bound : tree.bounds.tail) {
  2527                     bs = bs.tail;
  2528                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2529                     if (i.tag == CLASS)
  2530                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2534         bs = types.getBounds(a);
  2536         // in case of multiple bounds ...
  2537         if (bs.length() > 1) {
  2538             // ... the variable's bound is a class type flagged COMPOUND
  2539             // (see comment for TypeVar.bound).
  2540             // In this case, generate a class tree that represents the
  2541             // bound class, ...
  2542             JCTree extending;
  2543             List<JCExpression> implementing;
  2544             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2545                 extending = tree.bounds.head;
  2546                 implementing = tree.bounds.tail;
  2547             } else {
  2548                 extending = null;
  2549                 implementing = tree.bounds;
  2551             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2552                 make.Modifiers(PUBLIC | ABSTRACT),
  2553                 tree.name, List.<JCTypeParameter>nil(),
  2554                 extending, implementing, List.<JCTree>nil());
  2556             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2557             assert (c.flags() & COMPOUND) != 0;
  2558             cd.sym = c;
  2559             c.sourcefile = env.toplevel.sourcefile;
  2561             // ... and attribute the bound class
  2562             c.flags_field |= UNATTRIBUTED;
  2563             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2564             enter.typeEnvs.put(c, cenv);
  2569     public void visitWildcard(JCWildcard tree) {
  2570         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2571         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2572             ? syms.objectType
  2573             : attribType(tree.inner, env);
  2574         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2575                                               tree.kind.kind,
  2576                                               syms.boundClass),
  2577                        TYP, pkind, pt);
  2580     public void visitAnnotation(JCAnnotation tree) {
  2581         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2582         result = tree.type = syms.errType;
  2585     public void visitErroneous(JCErroneous tree) {
  2586         if (tree.errs != null)
  2587             for (JCTree err : tree.errs)
  2588                 attribTree(err, env, ERR, pt);
  2589         result = tree.type = syms.errType;
  2592     /** Default visitor method for all other trees.
  2593      */
  2594     public void visitTree(JCTree tree) {
  2595         throw new AssertionError();
  2598     /** Main method: attribute class definition associated with given class symbol.
  2599      *  reporting completion failures at the given position.
  2600      *  @param pos The source position at which completion errors are to be
  2601      *             reported.
  2602      *  @param c   The class symbol whose definition will be attributed.
  2603      */
  2604     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2605         try {
  2606             annotate.flush();
  2607             attribClass(c);
  2608         } catch (CompletionFailure ex) {
  2609             chk.completionError(pos, ex);
  2613     /** Attribute class definition associated with given class symbol.
  2614      *  @param c   The class symbol whose definition will be attributed.
  2615      */
  2616     void attribClass(ClassSymbol c) throws CompletionFailure {
  2617         if (c.type.tag == ERROR) return;
  2619         // Check for cycles in the inheritance graph, which can arise from
  2620         // ill-formed class files.
  2621         chk.checkNonCyclic(null, c.type);
  2623         Type st = types.supertype(c.type);
  2624         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2625             // First, attribute superclass.
  2626             if (st.tag == CLASS)
  2627                 attribClass((ClassSymbol)st.tsym);
  2629             // Next attribute owner, if it is a class.
  2630             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2631                 attribClass((ClassSymbol)c.owner);
  2634         // The previous operations might have attributed the current class
  2635         // if there was a cycle. So we test first whether the class is still
  2636         // UNATTRIBUTED.
  2637         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2638             c.flags_field &= ~UNATTRIBUTED;
  2640             // Get environment current at the point of class definition.
  2641             Env<AttrContext> env = enter.typeEnvs.get(c);
  2643             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2644             // because the annotations were not available at the time the env was created. Therefore,
  2645             // we look up the environment chain for the first enclosing environment for which the
  2646             // lint value is set. Typically, this is the parent env, but might be further if there
  2647             // are any envs created as a result of TypeParameter nodes.
  2648             Env<AttrContext> lintEnv = env;
  2649             while (lintEnv.info.lint == null)
  2650                 lintEnv = lintEnv.next;
  2652             // Having found the enclosing lint value, we can initialize the lint value for this class
  2653             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2655             Lint prevLint = chk.setLint(env.info.lint);
  2656             JavaFileObject prev = log.useSource(c.sourcefile);
  2658             try {
  2659                 // java.lang.Enum may not be subclassed by a non-enum
  2660                 if (st.tsym == syms.enumSym &&
  2661                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  2662                     log.error(env.tree.pos(), "enum.no.subclassing");
  2664                 // Enums may not be extended by source-level classes
  2665                 if (st.tsym != null &&
  2666                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  2667                     ((c.flags_field & Flags.ENUM) == 0) &&
  2668                     !target.compilerBootstrap(c)) {
  2669                     log.error(env.tree.pos(), "enum.types.not.extensible");
  2671                 attribClassBody(env, c);
  2673                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  2674             } finally {
  2675                 log.useSource(prev);
  2676                 chk.setLint(prevLint);
  2682     public void visitImport(JCImport tree) {
  2683         // nothing to do
  2686     /** Finish the attribution of a class. */
  2687     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  2688         JCClassDecl tree = (JCClassDecl)env.tree;
  2689         assert c == tree.sym;
  2691         // Validate annotations
  2692         chk.validateAnnotations(tree.mods.annotations, c);
  2694         // Validate type parameters, supertype and interfaces.
  2695         attribBounds(tree.typarams);
  2696         chk.validateTypeParams(tree.typarams);
  2697         chk.validate(tree.extending);
  2698         chk.validate(tree.implementing);
  2700         // If this is a non-abstract class, check that it has no abstract
  2701         // methods or unimplemented methods of an implemented interface.
  2702         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  2703             if (!relax)
  2704                 chk.checkAllDefined(tree.pos(), c);
  2707         if ((c.flags() & ANNOTATION) != 0) {
  2708             if (tree.implementing.nonEmpty())
  2709                 log.error(tree.implementing.head.pos(),
  2710                           "cant.extend.intf.annotation");
  2711             if (tree.typarams.nonEmpty())
  2712                 log.error(tree.typarams.head.pos(),
  2713                           "intf.annotation.cant.have.type.params");
  2714         } else {
  2715             // Check that all extended classes and interfaces
  2716             // are compatible (i.e. no two define methods with same arguments
  2717             // yet different return types).  (JLS 8.4.6.3)
  2718             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  2721         // Check that class does not import the same parameterized interface
  2722         // with two different argument lists.
  2723         chk.checkClassBounds(tree.pos(), c.type);
  2725         tree.type = c.type;
  2727         boolean assertsEnabled = false;
  2728         assert assertsEnabled = true;
  2729         if (assertsEnabled) {
  2730             for (List<JCTypeParameter> l = tree.typarams;
  2731                  l.nonEmpty(); l = l.tail)
  2732                 assert env.info.scope.lookup(l.head.name).scope != null;
  2735         // Check that a generic class doesn't extend Throwable
  2736         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  2737             log.error(tree.extending.pos(), "generic.throwable");
  2739         // Check that all methods which implement some
  2740         // method conform to the method they implement.
  2741         chk.checkImplementations(tree);
  2743         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2744             // Attribute declaration
  2745             attribStat(l.head, env);
  2746             // Check that declarations in inner classes are not static (JLS 8.1.2)
  2747             // Make an exception for static constants.
  2748             if (c.owner.kind != PCK &&
  2749                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  2750                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  2751                 Symbol sym = null;
  2752                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  2753                 if (sym == null ||
  2754                     sym.kind != VAR ||
  2755                     ((VarSymbol) sym).getConstValue() == null)
  2756                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  2760         // Check for cycles among non-initial constructors.
  2761         chk.checkCyclicConstructors(tree);
  2763         // Check for cycles among annotation elements.
  2764         chk.checkNonCyclicElements(tree);
  2766         // Check for proper use of serialVersionUID
  2767         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  2768             isSerializable(c) &&
  2769             (c.flags() & Flags.ENUM) == 0 &&
  2770             (c.flags() & ABSTRACT) == 0) {
  2771             checkSerialVersionUID(tree, c);
  2774         // where
  2775         /** check if a class is a subtype of Serializable, if that is available. */
  2776         private boolean isSerializable(ClassSymbol c) {
  2777             try {
  2778                 syms.serializableType.complete();
  2780             catch (CompletionFailure e) {
  2781                 return false;
  2783             return types.isSubtype(c.type, syms.serializableType);
  2786         /** Check that an appropriate serialVersionUID member is defined. */
  2787         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  2789             // check for presence of serialVersionUID
  2790             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  2791             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  2792             if (e.scope == null) {
  2793                 log.warning(tree.pos(), "missing.SVUID", c);
  2794                 return;
  2797             // check that it is static final
  2798             VarSymbol svuid = (VarSymbol)e.sym;
  2799             if ((svuid.flags() & (STATIC | FINAL)) !=
  2800                 (STATIC | FINAL))
  2801                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  2803             // check that it is long
  2804             else if (svuid.type.tag != TypeTags.LONG)
  2805                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  2807             // check constant
  2808             else if (svuid.getConstValue() == null)
  2809                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  2812     private Type capture(Type type) {
  2813         return types.capture(type);

mercurial