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

Wed, 23 Apr 2008 17:10:03 +0100

author
mcimadamore
date
Wed, 23 Apr 2008 17:10:03 +0100
changeset 33
ec29a1a284ca
parent 28
e7bf2e39b8fe
child 42
f7e64b33d5a4
permissions
-rw-r--r--

6682380: Foreach loop with generics inside finally block crashes javac with -target 1.5
Summary: A missing type-erasure in Lower.java causes the compiler to crash since JDK6
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2006 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             if (!tvar.bounds.isEmpty()) {
   458                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   459                 for (JCExpression bound : tvar.bounds.tail)
   460                     bounds = bounds.prepend(attribType(bound, env));
   461                 types.setBounds(a, bounds.reverse());
   462             } else {
   463                 // if no bounds are given, assume a single bound of
   464                 // java.lang.Object.
   465                 types.setBounds(a, List.of(syms.objectType));
   466             }
   467         }
   468     }
   470     void attribBounds(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   471         for (JCTypeParameter tvar : typarams)
   472             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   473         attribStats(typarams, env);
   474         for (JCTypeParameter typaram : typarams) {
   475             Type bound = typaram.type.getUpperBound();
   476             if (bound != null && bound.tsym instanceof ClassSymbol) {
   477                 ClassSymbol c = (ClassSymbol)bound.tsym;
   478                 if ((c.flags_field & COMPOUND) != 0) {
   479                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   480                     attribClass(typaram.pos(), c);
   481                 }
   482             }
   483         }
   484     }
   486     /**
   487      * Attribute the type references in a list of annotations.
   488      */
   489     void attribAnnotationTypes(List<JCAnnotation> annotations,
   490                                Env<AttrContext> env) {
   491         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   492             JCAnnotation a = al.head;
   493             attribType(a.annotationType, env);
   494         }
   495     }
   497     /** Attribute type reference in an `extends' or `implements' clause.
   498      *
   499      *  @param tree              The tree making up the type reference.
   500      *  @param env               The environment current at the reference.
   501      *  @param classExpected     true if only a class is expected here.
   502      *  @param interfaceExpected true if only an interface is expected here.
   503      */
   504     Type attribBase(JCTree tree,
   505                     Env<AttrContext> env,
   506                     boolean classExpected,
   507                     boolean interfaceExpected,
   508                     boolean checkExtensible) {
   509         Type t = attribType(tree, env);
   510         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   511     }
   512     Type checkBase(Type t,
   513                    JCTree tree,
   514                    Env<AttrContext> env,
   515                    boolean classExpected,
   516                    boolean interfaceExpected,
   517                    boolean checkExtensible) {
   518         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   519             // check that type variable is already visible
   520             if (t.getUpperBound() == null) {
   521                 log.error(tree.pos(), "illegal.forward.ref");
   522                 return syms.errType;
   523             }
   524         } else {
   525             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   526         }
   527         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   528             log.error(tree.pos(), "intf.expected.here");
   529             // return errType is necessary since otherwise there might
   530             // be undetected cycles which cause attribution to loop
   531             return syms.errType;
   532         } else if (checkExtensible &&
   533                    classExpected &&
   534                    (t.tsym.flags() & INTERFACE) != 0) {
   535             log.error(tree.pos(), "no.intf.expected.here");
   536             return syms.errType;
   537         }
   538         if (checkExtensible &&
   539             ((t.tsym.flags() & FINAL) != 0)) {
   540             log.error(tree.pos(),
   541                       "cant.inherit.from.final", t.tsym);
   542         }
   543         chk.checkNonCyclic(tree.pos(), t);
   544         return t;
   545     }
   547     public void visitClassDef(JCClassDecl tree) {
   548         // Local classes have not been entered yet, so we need to do it now:
   549         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   550             enter.classEnter(tree, env);
   552         ClassSymbol c = tree.sym;
   553         if (c == null) {
   554             // exit in case something drastic went wrong during enter.
   555             result = null;
   556         } else {
   557             // make sure class has been completed:
   558             c.complete();
   560             // If this class appears as an anonymous class
   561             // in a superclass constructor call where
   562             // no explicit outer instance is given,
   563             // disable implicit outer instance from being passed.
   564             // (This would be an illegal access to "this before super").
   565             if (env.info.isSelfCall &&
   566                 env.tree.getTag() == JCTree.NEWCLASS &&
   567                 ((JCNewClass) env.tree).encl == null)
   568             {
   569                 c.flags_field |= NOOUTERTHIS;
   570             }
   571             attribClass(tree.pos(), c);
   572             result = tree.type = c.type;
   573         }
   574     }
   576     public void visitMethodDef(JCMethodDecl tree) {
   577         MethodSymbol m = tree.sym;
   579         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   580         Lint prevLint = chk.setLint(lint);
   581         try {
   582             chk.checkDeprecatedAnnotation(tree.pos(), m);
   584             attribBounds(tree.typarams, env);
   586             // If we override any other methods, check that we do so properly.
   587             // JLS ???
   588             chk.checkOverride(tree, m);
   590             // Create a new environment with local scope
   591             // for attributing the method.
   592             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   594             localEnv.info.lint = lint;
   596             // Enter all type parameters into the local method scope.
   597             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   598                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   600             ClassSymbol owner = env.enclClass.sym;
   601             if ((owner.flags() & ANNOTATION) != 0 &&
   602                 tree.params.nonEmpty())
   603                 log.error(tree.params.head.pos(),
   604                           "intf.annotation.members.cant.have.params");
   606             // Attribute all value parameters.
   607             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   608                 attribStat(l.head, localEnv);
   609             }
   611             // Check that type parameters are well-formed.
   612             chk.validateTypeParams(tree.typarams);
   613             if ((owner.flags() & ANNOTATION) != 0 &&
   614                 tree.typarams.nonEmpty())
   615                 log.error(tree.typarams.head.pos(),
   616                           "intf.annotation.members.cant.have.type.params");
   618             // Check that result type is well-formed.
   619             chk.validate(tree.restype);
   620             if ((owner.flags() & ANNOTATION) != 0)
   621                 chk.validateAnnotationType(tree.restype);
   623             if ((owner.flags() & ANNOTATION) != 0)
   624                 chk.validateAnnotationMethod(tree.pos(), m);
   626             // Check that all exceptions mentioned in the throws clause extend
   627             // java.lang.Throwable.
   628             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
   629                 log.error(tree.thrown.head.pos(),
   630                           "throws.not.allowed.in.intf.annotation");
   631             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   632                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   634             if (tree.body == null) {
   635                 // Empty bodies are only allowed for
   636                 // abstract, native, or interface methods, or for methods
   637                 // in a retrofit signature class.
   638                 if ((owner.flags() & INTERFACE) == 0 &&
   639                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   640                     !relax)
   641                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   642                 if (tree.defaultValue != null) {
   643                     if ((owner.flags() & ANNOTATION) == 0)
   644                         log.error(tree.pos(),
   645                                   "default.allowed.in.intf.annotation.member");
   646                 }
   647             } else if ((owner.flags() & INTERFACE) != 0) {
   648                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   649             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   650                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   651             } else if ((tree.mods.flags & NATIVE) != 0) {
   652                 log.error(tree.pos(), "native.meth.cant.have.body");
   653             } else {
   654                 // Add an implicit super() call unless an explicit call to
   655                 // super(...) or this(...) is given
   656                 // or we are compiling class java.lang.Object.
   657                 if (tree.name == names.init && owner.type != syms.objectType) {
   658                     JCBlock body = tree.body;
   659                     if (body.stats.isEmpty() ||
   660                         !TreeInfo.isSelfCall(body.stats.head)) {
   661                         body.stats = body.stats.
   662                             prepend(memberEnter.SuperCall(make.at(body.pos),
   663                                                           List.<Type>nil(),
   664                                                           List.<JCVariableDecl>nil(),
   665                                                           false));
   666                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   667                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   668                                TreeInfo.isSuperCall(body.stats.head)) {
   669                         // enum constructors are not allowed to call super
   670                         // directly, so make sure there aren't any super calls
   671                         // in enum constructors, except in the compiler
   672                         // generated one.
   673                         log.error(tree.body.stats.head.pos(),
   674                                   "call.to.super.not.allowed.in.enum.ctor",
   675                                   env.enclClass.sym);
   676                     }
   677                 }
   679                 // Attribute method body.
   680                 attribStat(tree.body, localEnv);
   681             }
   682             localEnv.info.scope.leave();
   683             result = tree.type = m.type;
   684             chk.validateAnnotations(tree.mods.annotations, m);
   686         }
   687         finally {
   688             chk.setLint(prevLint);
   689         }
   690     }
   692     public void visitVarDef(JCVariableDecl tree) {
   693         // Local variables have not been entered yet, so we need to do it now:
   694         if (env.info.scope.owner.kind == MTH) {
   695             if (tree.sym != null) {
   696                 // parameters have already been entered
   697                 env.info.scope.enter(tree.sym);
   698             } else {
   699                 memberEnter.memberEnter(tree, env);
   700                 annotate.flush();
   701             }
   702         }
   704         // Check that the variable's declared type is well-formed.
   705         chk.validate(tree.vartype);
   707         VarSymbol v = tree.sym;
   708         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   709         Lint prevLint = chk.setLint(lint);
   711         try {
   712             chk.checkDeprecatedAnnotation(tree.pos(), v);
   714             if (tree.init != null) {
   715                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   716                     // In this case, `v' is final.  Ensure that it's initializer is
   717                     // evaluated.
   718                     v.getConstValue(); // ensure initializer is evaluated
   719                 } else {
   720                     // Attribute initializer in a new environment
   721                     // with the declared variable as owner.
   722                     // Check that initializer conforms to variable's declared type.
   723                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   724                     initEnv.info.lint = lint;
   725                     // In order to catch self-references, we set the variable's
   726                     // declaration position to maximal possible value, effectively
   727                     // marking the variable as undefined.
   728                     v.pos = Position.MAXPOS;
   729                     attribExpr(tree.init, initEnv, v.type);
   730                     v.pos = tree.pos;
   731                 }
   732             }
   733             result = tree.type = v.type;
   734             chk.validateAnnotations(tree.mods.annotations, v);
   735         }
   736         finally {
   737             chk.setLint(prevLint);
   738         }
   739     }
   741     public void visitSkip(JCSkip tree) {
   742         result = null;
   743     }
   745     public void visitBlock(JCBlock tree) {
   746         if (env.info.scope.owner.kind == TYP) {
   747             // Block is a static or instance initializer;
   748             // let the owner of the environment be a freshly
   749             // created BLOCK-method.
   750             Env<AttrContext> localEnv =
   751                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   752             localEnv.info.scope.owner =
   753                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   754                                  env.info.scope.owner);
   755             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   756             attribStats(tree.stats, localEnv);
   757         } else {
   758             // Create a new local environment with a local scope.
   759             Env<AttrContext> localEnv =
   760                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   761             attribStats(tree.stats, localEnv);
   762             localEnv.info.scope.leave();
   763         }
   764         result = null;
   765     }
   767     public void visitDoLoop(JCDoWhileLoop tree) {
   768         attribStat(tree.body, env.dup(tree));
   769         attribExpr(tree.cond, env, syms.booleanType);
   770         result = null;
   771     }
   773     public void visitWhileLoop(JCWhileLoop tree) {
   774         attribExpr(tree.cond, env, syms.booleanType);
   775         attribStat(tree.body, env.dup(tree));
   776         result = null;
   777     }
   779     public void visitForLoop(JCForLoop tree) {
   780         Env<AttrContext> loopEnv =
   781             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   782         attribStats(tree.init, loopEnv);
   783         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   784         loopEnv.tree = tree; // before, we were not in loop!
   785         attribStats(tree.step, loopEnv);
   786         attribStat(tree.body, loopEnv);
   787         loopEnv.info.scope.leave();
   788         result = null;
   789     }
   791     public void visitForeachLoop(JCEnhancedForLoop tree) {
   792         Env<AttrContext> loopEnv =
   793             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   794         attribStat(tree.var, loopEnv);
   795         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   796         chk.checkNonVoid(tree.pos(), exprType);
   797         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   798         if (elemtype == null) {
   799             // or perhaps expr implements Iterable<T>?
   800             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   801             if (base == null) {
   802                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   803                 elemtype = syms.errType;
   804             } else {
   805                 List<Type> iterableParams = base.allparams();
   806                 elemtype = iterableParams.isEmpty()
   807                     ? syms.objectType
   808                     : types.upperBound(iterableParams.head);
   809             }
   810         }
   811         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   812         loopEnv.tree = tree; // before, we were not in loop!
   813         attribStat(tree.body, loopEnv);
   814         loopEnv.info.scope.leave();
   815         result = null;
   816     }
   818     public void visitLabelled(JCLabeledStatement tree) {
   819         // Check that label is not used in an enclosing statement
   820         Env<AttrContext> env1 = env;
   821         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   822             if (env1.tree.getTag() == JCTree.LABELLED &&
   823                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   824                 log.error(tree.pos(), "label.already.in.use",
   825                           tree.label);
   826                 break;
   827             }
   828             env1 = env1.next;
   829         }
   831         attribStat(tree.body, env.dup(tree));
   832         result = null;
   833     }
   835     public void visitSwitch(JCSwitch tree) {
   836         Type seltype = attribExpr(tree.selector, env);
   838         Env<AttrContext> switchEnv =
   839             env.dup(tree, env.info.dup(env.info.scope.dup()));
   841         boolean enumSwitch =
   842             allowEnums &&
   843             (seltype.tsym.flags() & Flags.ENUM) != 0;
   844         if (!enumSwitch)
   845             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   847         // Attribute all cases and
   848         // check that there are no duplicate case labels or default clauses.
   849         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   850         boolean hasDefault = false;      // Is there a default label?
   851         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   852             JCCase c = l.head;
   853             Env<AttrContext> caseEnv =
   854                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   855             if (c.pat != null) {
   856                 if (enumSwitch) {
   857                     Symbol sym = enumConstant(c.pat, seltype);
   858                     if (sym == null) {
   859                         log.error(c.pat.pos(), "enum.const.req");
   860                     } else if (!labels.add(sym)) {
   861                         log.error(c.pos(), "duplicate.case.label");
   862                     }
   863                 } else {
   864                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   865                     if (pattype.tag != ERROR) {
   866                         if (pattype.constValue() == null) {
   867                             log.error(c.pat.pos(), "const.expr.req");
   868                         } else if (labels.contains(pattype.constValue())) {
   869                             log.error(c.pos(), "duplicate.case.label");
   870                         } else {
   871                             labels.add(pattype.constValue());
   872                         }
   873                     }
   874                 }
   875             } else if (hasDefault) {
   876                 log.error(c.pos(), "duplicate.default.label");
   877             } else {
   878                 hasDefault = true;
   879             }
   880             attribStats(c.stats, caseEnv);
   881             caseEnv.info.scope.leave();
   882             addVars(c.stats, switchEnv.info.scope);
   883         }
   885         switchEnv.info.scope.leave();
   886         result = null;
   887     }
   888     // where
   889         /** Add any variables defined in stats to the switch scope. */
   890         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   891             for (;stats.nonEmpty(); stats = stats.tail) {
   892                 JCTree stat = stats.head;
   893                 if (stat.getTag() == JCTree.VARDEF)
   894                     switchScope.enter(((JCVariableDecl) stat).sym);
   895             }
   896         }
   897     // where
   898     /** Return the selected enumeration constant symbol, or null. */
   899     private Symbol enumConstant(JCTree tree, Type enumType) {
   900         if (tree.getTag() != JCTree.IDENT) {
   901             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   902             return syms.errSymbol;
   903         }
   904         JCIdent ident = (JCIdent)tree;
   905         Name name = ident.name;
   906         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   907              e.scope != null; e = e.next()) {
   908             if (e.sym.kind == VAR) {
   909                 Symbol s = ident.sym = e.sym;
   910                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   911                 ident.type = s.type;
   912                 return ((s.flags_field & Flags.ENUM) == 0)
   913                     ? null : s;
   914             }
   915         }
   916         return null;
   917     }
   919     public void visitSynchronized(JCSynchronized tree) {
   920         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
   921         attribStat(tree.body, env);
   922         result = null;
   923     }
   925     public void visitTry(JCTry tree) {
   926         // Attribute body
   927         attribStat(tree.body, env.dup(tree, env.info.dup()));
   929         // Attribute catch clauses
   930         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   931             JCCatch c = l.head;
   932             Env<AttrContext> catchEnv =
   933                 env.dup(c, env.info.dup(env.info.scope.dup()));
   934             Type ctype = attribStat(c.param, catchEnv);
   935             if (c.param.type.tsym.kind == Kinds.VAR) {
   936                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
   937             }
   938             chk.checkType(c.param.vartype.pos(),
   939                           chk.checkClassType(c.param.vartype.pos(), ctype),
   940                           syms.throwableType);
   941             attribStat(c.body, catchEnv);
   942             catchEnv.info.scope.leave();
   943         }
   945         // Attribute finalizer
   946         if (tree.finalizer != null) attribStat(tree.finalizer, env);
   947         result = null;
   948     }
   950     public void visitConditional(JCConditional tree) {
   951         attribExpr(tree.cond, env, syms.booleanType);
   952         attribExpr(tree.truepart, env);
   953         attribExpr(tree.falsepart, env);
   954         result = check(tree,
   955                        capture(condType(tree.pos(), tree.cond.type,
   956                                         tree.truepart.type, tree.falsepart.type)),
   957                        VAL, pkind, pt);
   958     }
   959     //where
   960         /** Compute the type of a conditional expression, after
   961          *  checking that it exists. See Spec 15.25.
   962          *
   963          *  @param pos      The source position to be used for
   964          *                  error diagnostics.
   965          *  @param condtype The type of the expression's condition.
   966          *  @param thentype The type of the expression's then-part.
   967          *  @param elsetype The type of the expression's else-part.
   968          */
   969         private Type condType(DiagnosticPosition pos,
   970                               Type condtype,
   971                               Type thentype,
   972                               Type elsetype) {
   973             Type ctype = condType1(pos, condtype, thentype, elsetype);
   975             // If condition and both arms are numeric constants,
   976             // evaluate at compile-time.
   977             return ((condtype.constValue() != null) &&
   978                     (thentype.constValue() != null) &&
   979                     (elsetype.constValue() != null))
   980                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
   981                 : ctype;
   982         }
   983         /** Compute the type of a conditional expression, after
   984          *  checking that it exists.  Does not take into
   985          *  account the special case where condition and both arms
   986          *  are constants.
   987          *
   988          *  @param pos      The source position to be used for error
   989          *                  diagnostics.
   990          *  @param condtype The type of the expression's condition.
   991          *  @param thentype The type of the expression's then-part.
   992          *  @param elsetype The type of the expression's else-part.
   993          */
   994         private Type condType1(DiagnosticPosition pos, Type condtype,
   995                                Type thentype, Type elsetype) {
   996             // If same type, that is the result
   997             if (types.isSameType(thentype, elsetype))
   998                 return thentype.baseType();
  1000             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1001                 ? thentype : types.unboxedType(thentype);
  1002             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1003                 ? elsetype : types.unboxedType(elsetype);
  1005             // Otherwise, if both arms can be converted to a numeric
  1006             // type, return the least numeric type that fits both arms
  1007             // (i.e. return larger of the two, or return int if one
  1008             // arm is short, the other is char).
  1009             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1010                 // If one arm has an integer subrange type (i.e., byte,
  1011                 // short, or char), and the other is an integer constant
  1012                 // that fits into the subrange, return the subrange type.
  1013                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1014                     types.isAssignable(elseUnboxed, thenUnboxed))
  1015                     return thenUnboxed.baseType();
  1016                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1017                     types.isAssignable(thenUnboxed, elseUnboxed))
  1018                     return elseUnboxed.baseType();
  1020                 for (int i = BYTE; i < VOID; i++) {
  1021                     Type candidate = syms.typeOfTag[i];
  1022                     if (types.isSubtype(thenUnboxed, candidate) &&
  1023                         types.isSubtype(elseUnboxed, candidate))
  1024                         return candidate;
  1028             // Those were all the cases that could result in a primitive
  1029             if (allowBoxing) {
  1030                 if (thentype.isPrimitive())
  1031                     thentype = types.boxedClass(thentype).type;
  1032                 if (elsetype.isPrimitive())
  1033                     elsetype = types.boxedClass(elsetype).type;
  1036             if (types.isSubtype(thentype, elsetype))
  1037                 return elsetype.baseType();
  1038             if (types.isSubtype(elsetype, thentype))
  1039                 return thentype.baseType();
  1041             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1042                 log.error(pos, "neither.conditional.subtype",
  1043                           thentype, elsetype);
  1044                 return thentype.baseType();
  1047             // both are known to be reference types.  The result is
  1048             // lub(thentype,elsetype). This cannot fail, as it will
  1049             // always be possible to infer "Object" if nothing better.
  1050             return types.lub(thentype.baseType(), elsetype.baseType());
  1053     public void visitIf(JCIf tree) {
  1054         attribExpr(tree.cond, env, syms.booleanType);
  1055         attribStat(tree.thenpart, env);
  1056         if (tree.elsepart != null)
  1057             attribStat(tree.elsepart, env);
  1058         chk.checkEmptyIf(tree);
  1059         result = null;
  1062     public void visitExec(JCExpressionStatement tree) {
  1063         attribExpr(tree.expr, env);
  1064         result = null;
  1067     public void visitBreak(JCBreak tree) {
  1068         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1069         result = null;
  1072     public void visitContinue(JCContinue tree) {
  1073         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1074         result = null;
  1076     //where
  1077         /** Return the target of a break or continue statement, if it exists,
  1078          *  report an error if not.
  1079          *  Note: The target of a labelled break or continue is the
  1080          *  (non-labelled) statement tree referred to by the label,
  1081          *  not the tree representing the labelled statement itself.
  1083          *  @param pos     The position to be used for error diagnostics
  1084          *  @param tag     The tag of the jump statement. This is either
  1085          *                 Tree.BREAK or Tree.CONTINUE.
  1086          *  @param label   The label of the jump statement, or null if no
  1087          *                 label is given.
  1088          *  @param env     The environment current at the jump statement.
  1089          */
  1090         private JCTree findJumpTarget(DiagnosticPosition pos,
  1091                                     int tag,
  1092                                     Name label,
  1093                                     Env<AttrContext> env) {
  1094             // Search environments outwards from the point of jump.
  1095             Env<AttrContext> env1 = env;
  1096             LOOP:
  1097             while (env1 != null) {
  1098                 switch (env1.tree.getTag()) {
  1099                 case JCTree.LABELLED:
  1100                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1101                     if (label == labelled.label) {
  1102                         // If jump is a continue, check that target is a loop.
  1103                         if (tag == JCTree.CONTINUE) {
  1104                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1105                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1106                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1107                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1108                                 log.error(pos, "not.loop.label", label);
  1109                             // Found labelled statement target, now go inwards
  1110                             // to next non-labelled tree.
  1111                             return TreeInfo.referencedStatement(labelled);
  1112                         } else {
  1113                             return labelled;
  1116                     break;
  1117                 case JCTree.DOLOOP:
  1118                 case JCTree.WHILELOOP:
  1119                 case JCTree.FORLOOP:
  1120                 case JCTree.FOREACHLOOP:
  1121                     if (label == null) return env1.tree;
  1122                     break;
  1123                 case JCTree.SWITCH:
  1124                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1125                     break;
  1126                 case JCTree.METHODDEF:
  1127                 case JCTree.CLASSDEF:
  1128                     break LOOP;
  1129                 default:
  1131                 env1 = env1.next;
  1133             if (label != null)
  1134                 log.error(pos, "undef.label", label);
  1135             else if (tag == JCTree.CONTINUE)
  1136                 log.error(pos, "cont.outside.loop");
  1137             else
  1138                 log.error(pos, "break.outside.switch.loop");
  1139             return null;
  1142     public void visitReturn(JCReturn tree) {
  1143         // Check that there is an enclosing method which is
  1144         // nested within than the enclosing class.
  1145         if (env.enclMethod == null ||
  1146             env.enclMethod.sym.owner != env.enclClass.sym) {
  1147             log.error(tree.pos(), "ret.outside.meth");
  1149         } else {
  1150             // Attribute return expression, if it exists, and check that
  1151             // it conforms to result type of enclosing method.
  1152             Symbol m = env.enclMethod.sym;
  1153             if (m.type.getReturnType().tag == VOID) {
  1154                 if (tree.expr != null)
  1155                     log.error(tree.expr.pos(),
  1156                               "cant.ret.val.from.meth.decl.void");
  1157             } else if (tree.expr == null) {
  1158                 log.error(tree.pos(), "missing.ret.val");
  1159             } else {
  1160                 attribExpr(tree.expr, env, m.type.getReturnType());
  1163         result = null;
  1166     public void visitThrow(JCThrow tree) {
  1167         attribExpr(tree.expr, env, syms.throwableType);
  1168         result = null;
  1171     public void visitAssert(JCAssert tree) {
  1172         attribExpr(tree.cond, env, syms.booleanType);
  1173         if (tree.detail != null) {
  1174             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1176         result = null;
  1179      /** Visitor method for method invocations.
  1180      *  NOTE: The method part of an application will have in its type field
  1181      *        the return type of the method, not the method's type itself!
  1182      */
  1183     public void visitApply(JCMethodInvocation tree) {
  1184         // The local environment of a method application is
  1185         // a new environment nested in the current one.
  1186         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1188         // The types of the actual method arguments.
  1189         List<Type> argtypes;
  1191         // The types of the actual method type arguments.
  1192         List<Type> typeargtypes = null;
  1194         Name methName = TreeInfo.name(tree.meth);
  1196         boolean isConstructorCall =
  1197             methName == names._this || methName == names._super;
  1199         if (isConstructorCall) {
  1200             // We are seeing a ...this(...) or ...super(...) call.
  1201             // Check that this is the first statement in a constructor.
  1202             if (checkFirstConstructorStat(tree, env)) {
  1204                 // Record the fact
  1205                 // that this is a constructor call (using isSelfCall).
  1206                 localEnv.info.isSelfCall = true;
  1208                 // Attribute arguments, yielding list of argument types.
  1209                 argtypes = attribArgs(tree.args, localEnv);
  1210                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1212                 // Variable `site' points to the class in which the called
  1213                 // constructor is defined.
  1214                 Type site = env.enclClass.sym.type;
  1215                 if (methName == names._super) {
  1216                     if (site == syms.objectType) {
  1217                         log.error(tree.meth.pos(), "no.superclass", site);
  1218                         site = syms.errType;
  1219                     } else {
  1220                         site = types.supertype(site);
  1224                 if (site.tag == CLASS) {
  1225                     if (site.getEnclosingType().tag == CLASS) {
  1226                         // we are calling a nested class
  1228                         if (tree.meth.getTag() == JCTree.SELECT) {
  1229                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1231                             // We are seeing a prefixed call, of the form
  1232                             //     <expr>.super(...).
  1233                             // Check that the prefix expression conforms
  1234                             // to the outer instance type of the class.
  1235                             chk.checkRefType(qualifier.pos(),
  1236                                              attribExpr(qualifier, localEnv,
  1237                                                         site.getEnclosingType()));
  1238                         } else if (methName == names._super) {
  1239                             // qualifier omitted; check for existence
  1240                             // of an appropriate implicit qualifier.
  1241                             rs.resolveImplicitThis(tree.meth.pos(),
  1242                                                    localEnv, site);
  1244                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1245                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1246                                   site.tsym);
  1249                     // if we're calling a java.lang.Enum constructor,
  1250                     // prefix the implicit String and int parameters
  1251                     if (site.tsym == syms.enumSym && allowEnums)
  1252                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1254                     // Resolve the called constructor under the assumption
  1255                     // that we are referring to a superclass instance of the
  1256                     // current instance (JLS ???).
  1257                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1258                     localEnv.info.selectSuper = true;
  1259                     localEnv.info.varArgs = false;
  1260                     Symbol sym = rs.resolveConstructor(
  1261                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1262                     localEnv.info.selectSuper = selectSuperPrev;
  1264                     // Set method symbol to resolved constructor...
  1265                     TreeInfo.setSymbol(tree.meth, sym);
  1267                     // ...and check that it is legal in the current context.
  1268                     // (this will also set the tree's type)
  1269                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1270                     checkId(tree.meth, site, sym, localEnv, MTH,
  1271                             mpt, tree.varargsElement != null);
  1273                 // Otherwise, `site' is an error type and we do nothing
  1275             result = tree.type = syms.voidType;
  1276         } else {
  1277             // Otherwise, we are seeing a regular method call.
  1278             // Attribute the arguments, yielding list of argument types, ...
  1279             argtypes = attribArgs(tree.args, localEnv);
  1280             typeargtypes = attribTypes(tree.typeargs, localEnv);
  1282             // ... and attribute the method using as a prototype a methodtype
  1283             // whose formal argument types is exactly the list of actual
  1284             // arguments (this will also set the method symbol).
  1285             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1286             localEnv.info.varArgs = false;
  1287             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1288             if (localEnv.info.varArgs)
  1289                 assert mtype.isErroneous() || tree.varargsElement != null;
  1291             // Compute the result type.
  1292             Type restype = mtype.getReturnType();
  1293             assert restype.tag != WILDCARD : mtype;
  1295             // as a special case, array.clone() has a result that is
  1296             // the same as static type of the array being cloned
  1297             if (tree.meth.getTag() == JCTree.SELECT &&
  1298                 allowCovariantReturns &&
  1299                 methName == names.clone &&
  1300                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1301                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1303             // as a special case, x.getClass() has type Class<? extends |X|>
  1304             if (allowGenerics &&
  1305                 methName == names.getClass && tree.args.isEmpty()) {
  1306                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1307                     ? ((JCFieldAccess) tree.meth).selected.type
  1308                     : env.enclClass.sym.type;
  1309                 restype = new
  1310                     ClassType(restype.getEnclosingType(),
  1311                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1312                                                                BoundKind.EXTENDS,
  1313                                                                syms.boundClass)),
  1314                               restype.tsym);
  1317             // Check that value of resulting type is admissible in the
  1318             // current context.  Also, capture the return type
  1319             result = check(tree, capture(restype), VAL, pkind, pt);
  1321         chk.validate(tree.typeargs);
  1323     //where
  1324         /** Check that given application node appears as first statement
  1325          *  in a constructor call.
  1326          *  @param tree   The application node
  1327          *  @param env    The environment current at the application.
  1328          */
  1329         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1330             JCMethodDecl enclMethod = env.enclMethod;
  1331             if (enclMethod != null && enclMethod.name == names.init) {
  1332                 JCBlock body = enclMethod.body;
  1333                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1334                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1335                     return true;
  1337             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1338                       TreeInfo.name(tree.meth));
  1339             return false;
  1342         /** Obtain a method type with given argument types.
  1343          */
  1344         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1345             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1346             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1349     public void visitNewClass(JCNewClass tree) {
  1350         Type owntype = syms.errType;
  1352         // The local environment of a class creation is
  1353         // a new environment nested in the current one.
  1354         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1356         // The anonymous inner class definition of the new expression,
  1357         // if one is defined by it.
  1358         JCClassDecl cdef = tree.def;
  1360         // If enclosing class is given, attribute it, and
  1361         // complete class name to be fully qualified
  1362         JCExpression clazz = tree.clazz; // Class field following new
  1363         JCExpression clazzid =          // Identifier in class field
  1364             (clazz.getTag() == JCTree.TYPEAPPLY)
  1365             ? ((JCTypeApply) clazz).clazz
  1366             : clazz;
  1368         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1370         if (tree.encl != null) {
  1371             // We are seeing a qualified new, of the form
  1372             //    <expr>.new C <...> (...) ...
  1373             // In this case, we let clazz stand for the name of the
  1374             // allocated class C prefixed with the type of the qualifier
  1375             // expression, so that we can
  1376             // resolve it with standard techniques later. I.e., if
  1377             // <expr> has type T, then <expr>.new C <...> (...)
  1378             // yields a clazz T.C.
  1379             Type encltype = chk.checkRefType(tree.encl.pos(),
  1380                                              attribExpr(tree.encl, env));
  1381             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1382                                                  ((JCIdent) clazzid).name);
  1383             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1384                 clazz = make.at(tree.pos).
  1385                     TypeApply(clazzid1,
  1386                               ((JCTypeApply) clazz).arguments);
  1387             else
  1388                 clazz = clazzid1;
  1389 //          System.out.println(clazz + " generated.");//DEBUG
  1392         // Attribute clazz expression and store
  1393         // symbol + type back into the attributed tree.
  1394         Type clazztype = chk.checkClassType(
  1395             tree.clazz.pos(), attribType(clazz, env), true);
  1396         chk.validate(clazz);
  1397         if (tree.encl != null) {
  1398             // We have to work in this case to store
  1399             // symbol + type back into the attributed tree.
  1400             tree.clazz.type = clazztype;
  1401             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1402             clazzid.type = ((JCIdent) clazzid).sym.type;
  1403             if (!clazztype.isErroneous()) {
  1404                 if (cdef != null && clazztype.tsym.isInterface()) {
  1405                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1406                 } else if (clazztype.tsym.isStatic()) {
  1407                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1410         } else if (!clazztype.tsym.isInterface() &&
  1411                    clazztype.getEnclosingType().tag == CLASS) {
  1412             // Check for the existence of an apropos outer instance
  1413             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1416         // Attribute constructor arguments.
  1417         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1418         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1420         // If we have made no mistakes in the class type...
  1421         if (clazztype.tag == CLASS) {
  1422             // Enums may not be instantiated except implicitly
  1423             if (allowEnums &&
  1424                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1425                 (env.tree.getTag() != JCTree.VARDEF ||
  1426                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1427                  ((JCVariableDecl) env.tree).init != tree))
  1428                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1429             // Check that class is not abstract
  1430             if (cdef == null &&
  1431                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1432                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1433                           clazztype.tsym);
  1434             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1435                 // Check that no constructor arguments are given to
  1436                 // anonymous classes implementing an interface
  1437                 if (!argtypes.isEmpty())
  1438                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1440                 if (!typeargtypes.isEmpty())
  1441                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1443                 // Error recovery: pretend no arguments were supplied.
  1444                 argtypes = List.nil();
  1445                 typeargtypes = List.nil();
  1448             // Resolve the called constructor under the assumption
  1449             // that we are referring to a superclass instance of the
  1450             // current instance (JLS ???).
  1451             else {
  1452                 localEnv.info.selectSuper = cdef != null;
  1453                 localEnv.info.varArgs = false;
  1454                 tree.constructor = rs.resolveConstructor(
  1455                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1456                 Type ctorType = checkMethod(clazztype,
  1457                                             tree.constructor,
  1458                                             localEnv,
  1459                                             tree.args,
  1460                                             argtypes,
  1461                                             typeargtypes,
  1462                                             localEnv.info.varArgs);
  1463                 if (localEnv.info.varArgs)
  1464                     assert ctorType.isErroneous() || tree.varargsElement != null;
  1467             if (cdef != null) {
  1468                 // We are seeing an anonymous class instance creation.
  1469                 // In this case, the class instance creation
  1470                 // expression
  1471                 //
  1472                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1473                 //
  1474                 // is represented internally as
  1475                 //
  1476                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1477                 //
  1478                 // This expression is then *transformed* as follows:
  1479                 //
  1480                 // (1) add a STATIC flag to the class definition
  1481                 //     if the current environment is static
  1482                 // (2) add an extends or implements clause
  1483                 // (3) add a constructor.
  1484                 //
  1485                 // For instance, if C is a class, and ET is the type of E,
  1486                 // the expression
  1487                 //
  1488                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1489                 //
  1490                 // is translated to (where X is a fresh name and typarams is the
  1491                 // parameter list of the super constructor):
  1492                 //
  1493                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1494                 //     X extends C<typargs2> {
  1495                 //       <typarams> X(ET e, args) {
  1496                 //         e.<typeargs1>super(args)
  1497                 //       }
  1498                 //       ...
  1499                 //     }
  1500                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1502                 if (clazztype.tsym.isInterface()) {
  1503                     cdef.implementing = List.of(clazz);
  1504                 } else {
  1505                     cdef.extending = clazz;
  1508                 attribStat(cdef, localEnv);
  1510                 // If an outer instance is given,
  1511                 // prefix it to the constructor arguments
  1512                 // and delete it from the new expression
  1513                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1514                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1515                     argtypes = argtypes.prepend(tree.encl.type);
  1516                     tree.encl = null;
  1519                 // Reassign clazztype and recompute constructor.
  1520                 clazztype = cdef.sym.type;
  1521                 Symbol sym = rs.resolveConstructor(
  1522                     tree.pos(), localEnv, clazztype, argtypes,
  1523                     typeargtypes, true, tree.varargsElement != null);
  1524                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1525                 tree.constructor = sym;
  1528             if (tree.constructor != null && tree.constructor.kind == MTH)
  1529                 owntype = clazztype;
  1531         result = check(tree, owntype, VAL, pkind, pt);
  1532         chk.validate(tree.typeargs);
  1535     /** Make an attributed null check tree.
  1536      */
  1537     public JCExpression makeNullCheck(JCExpression arg) {
  1538         // optimization: X.this is never null; skip null check
  1539         Name name = TreeInfo.name(arg);
  1540         if (name == names._this || name == names._super) return arg;
  1542         int optag = JCTree.NULLCHK;
  1543         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1544         tree.operator = syms.nullcheck;
  1545         tree.type = arg.type;
  1546         return tree;
  1549     public void visitNewArray(JCNewArray tree) {
  1550         Type owntype = syms.errType;
  1551         Type elemtype;
  1552         if (tree.elemtype != null) {
  1553             elemtype = attribType(tree.elemtype, env);
  1554             chk.validate(tree.elemtype);
  1555             owntype = elemtype;
  1556             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1557                 attribExpr(l.head, env, syms.intType);
  1558                 owntype = new ArrayType(owntype, syms.arrayClass);
  1560         } else {
  1561             // we are seeing an untyped aggregate { ... }
  1562             // this is allowed only if the prototype is an array
  1563             if (pt.tag == ARRAY) {
  1564                 elemtype = types.elemtype(pt);
  1565             } else {
  1566                 if (pt.tag != ERROR) {
  1567                     log.error(tree.pos(), "illegal.initializer.for.type",
  1568                               pt);
  1570                 elemtype = syms.errType;
  1573         if (tree.elems != null) {
  1574             attribExprs(tree.elems, env, elemtype);
  1575             owntype = new ArrayType(elemtype, syms.arrayClass);
  1577         if (!types.isReifiable(elemtype))
  1578             log.error(tree.pos(), "generic.array.creation");
  1579         result = check(tree, owntype, VAL, pkind, pt);
  1582     public void visitParens(JCParens tree) {
  1583         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1584         result = check(tree, owntype, pkind, pkind, pt);
  1585         Symbol sym = TreeInfo.symbol(tree);
  1586         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1587             log.error(tree.pos(), "illegal.start.of.type");
  1590     public void visitAssign(JCAssign tree) {
  1591         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1592         Type capturedType = capture(owntype);
  1593         attribExpr(tree.rhs, env, owntype);
  1594         result = check(tree, capturedType, VAL, pkind, pt);
  1597     public void visitAssignop(JCAssignOp tree) {
  1598         // Attribute arguments.
  1599         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1600         Type operand = attribExpr(tree.rhs, env);
  1601         // Find operator.
  1602         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1603             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1604             owntype, operand);
  1606         if (operator.kind == MTH) {
  1607             chk.checkOperator(tree.pos(),
  1608                               (OperatorSymbol)operator,
  1609                               tree.getTag() - JCTree.ASGOffset,
  1610                               owntype,
  1611                               operand);
  1612             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1613             chk.checkCastable(tree.rhs.pos(),
  1614                               operator.type.getReturnType(),
  1615                               owntype);
  1617         result = check(tree, owntype, VAL, pkind, pt);
  1620     public void visitUnary(JCUnary tree) {
  1621         // Attribute arguments.
  1622         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1623             ? attribTree(tree.arg, env, VAR, Type.noType)
  1624             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1626         // Find operator.
  1627         Symbol operator = tree.operator =
  1628             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1630         Type owntype = syms.errType;
  1631         if (operator.kind == MTH) {
  1632             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1633                 ? tree.arg.type
  1634                 : operator.type.getReturnType();
  1635             int opc = ((OperatorSymbol)operator).opcode;
  1637             // If the argument is constant, fold it.
  1638             if (argtype.constValue() != null) {
  1639                 Type ctype = cfolder.fold1(opc, argtype);
  1640                 if (ctype != null) {
  1641                     owntype = cfolder.coerce(ctype, owntype);
  1643                     // Remove constant types from arguments to
  1644                     // conserve space. The parser will fold concatenations
  1645                     // of string literals; the code here also
  1646                     // gets rid of intermediate results when some of the
  1647                     // operands are constant identifiers.
  1648                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1649                         tree.arg.type = syms.stringType;
  1654         result = check(tree, owntype, VAL, pkind, pt);
  1657     public void visitBinary(JCBinary tree) {
  1658         // Attribute arguments.
  1659         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1660         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1662         // Find operator.
  1663         Symbol operator = tree.operator =
  1664             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1666         Type owntype = syms.errType;
  1667         if (operator.kind == MTH) {
  1668             owntype = operator.type.getReturnType();
  1669             int opc = chk.checkOperator(tree.lhs.pos(),
  1670                                         (OperatorSymbol)operator,
  1671                                         tree.getTag(),
  1672                                         left,
  1673                                         right);
  1675             // If both arguments are constants, fold them.
  1676             if (left.constValue() != null && right.constValue() != null) {
  1677                 Type ctype = cfolder.fold2(opc, left, right);
  1678                 if (ctype != null) {
  1679                     owntype = cfolder.coerce(ctype, owntype);
  1681                     // Remove constant types from arguments to
  1682                     // conserve space. The parser will fold concatenations
  1683                     // of string literals; the code here also
  1684                     // gets rid of intermediate results when some of the
  1685                     // operands are constant identifiers.
  1686                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1687                         tree.lhs.type = syms.stringType;
  1689                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1690                         tree.rhs.type = syms.stringType;
  1695             // Check that argument types of a reference ==, != are
  1696             // castable to each other, (JLS???).
  1697             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  1698                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  1699                     log.error(tree.pos(), "incomparable.types", left, right);
  1703             chk.checkDivZero(tree.rhs.pos(), operator, right);
  1705         result = check(tree, owntype, VAL, pkind, pt);
  1708     public void visitTypeCast(JCTypeCast tree) {
  1709         Type clazztype = attribType(tree.clazz, env);
  1710         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  1711         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1712         if (exprtype.constValue() != null)
  1713             owntype = cfolder.coerce(exprtype, owntype);
  1714         result = check(tree, capture(owntype), VAL, pkind, pt);
  1717     public void visitTypeTest(JCInstanceOf tree) {
  1718         Type exprtype = chk.checkNullOrRefType(
  1719             tree.expr.pos(), attribExpr(tree.expr, env));
  1720         Type clazztype = chk.checkReifiableReferenceType(
  1721             tree.clazz.pos(), attribType(tree.clazz, env));
  1722         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1723         result = check(tree, syms.booleanType, VAL, pkind, pt);
  1726     public void visitIndexed(JCArrayAccess tree) {
  1727         Type owntype = syms.errType;
  1728         Type atype = attribExpr(tree.indexed, env);
  1729         attribExpr(tree.index, env, syms.intType);
  1730         if (types.isArray(atype))
  1731             owntype = types.elemtype(atype);
  1732         else if (atype.tag != ERROR)
  1733             log.error(tree.pos(), "array.req.but.found", atype);
  1734         if ((pkind & VAR) == 0) owntype = capture(owntype);
  1735         result = check(tree, owntype, VAR, pkind, pt);
  1738     public void visitIdent(JCIdent tree) {
  1739         Symbol sym;
  1740         boolean varArgs = false;
  1742         // Find symbol
  1743         if (pt.tag == METHOD || pt.tag == FORALL) {
  1744             // If we are looking for a method, the prototype `pt' will be a
  1745             // method type with the type of the call's arguments as parameters.
  1746             env.info.varArgs = false;
  1747             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  1748             varArgs = env.info.varArgs;
  1749         } else if (tree.sym != null && tree.sym.kind != VAR) {
  1750             sym = tree.sym;
  1751         } else {
  1752             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  1754         tree.sym = sym;
  1756         // (1) Also find the environment current for the class where
  1757         //     sym is defined (`symEnv').
  1758         // Only for pre-tiger versions (1.4 and earlier):
  1759         // (2) Also determine whether we access symbol out of an anonymous
  1760         //     class in a this or super call.  This is illegal for instance
  1761         //     members since such classes don't carry a this$n link.
  1762         //     (`noOuterThisPath').
  1763         Env<AttrContext> symEnv = env;
  1764         boolean noOuterThisPath = false;
  1765         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  1766             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  1767             sym.owner.kind == TYP &&
  1768             tree.name != names._this && tree.name != names._super) {
  1770             // Find environment in which identifier is defined.
  1771             while (symEnv.outer != null &&
  1772                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  1773                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  1774                     noOuterThisPath = !allowAnonOuterThis;
  1775                 symEnv = symEnv.outer;
  1779         // If symbol is a variable, ...
  1780         if (sym.kind == VAR) {
  1781             VarSymbol v = (VarSymbol)sym;
  1783             // ..., evaluate its initializer, if it has one, and check for
  1784             // illegal forward reference.
  1785             checkInit(tree, env, v, false);
  1787             // If symbol is a local variable accessed from an embedded
  1788             // inner class check that it is final.
  1789             if (v.owner.kind == MTH &&
  1790                 v.owner != env.info.scope.owner &&
  1791                 (v.flags_field & FINAL) == 0) {
  1792                 log.error(tree.pos(),
  1793                           "local.var.accessed.from.icls.needs.final",
  1794                           v);
  1797             // If we are expecting a variable (as opposed to a value), check
  1798             // that the variable is assignable in the current environment.
  1799             if (pkind == VAR)
  1800                 checkAssignable(tree.pos(), v, null, env);
  1803         // In a constructor body,
  1804         // if symbol is a field or instance method, check that it is
  1805         // not accessed before the supertype constructor is called.
  1806         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  1807             (sym.kind & (VAR | MTH)) != 0 &&
  1808             sym.owner.kind == TYP &&
  1809             (sym.flags() & STATIC) == 0) {
  1810             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  1812         Env<AttrContext> env1 = env;
  1813         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  1814             // If the found symbol is inaccessible, then it is
  1815             // accessed through an enclosing instance.  Locate this
  1816             // enclosing instance:
  1817             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  1818                 env1 = env1.outer;
  1820         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  1823     public void visitSelect(JCFieldAccess tree) {
  1824         // Determine the expected kind of the qualifier expression.
  1825         int skind = 0;
  1826         if (tree.name == names._this || tree.name == names._super ||
  1827             tree.name == names._class)
  1829             skind = TYP;
  1830         } else {
  1831             if ((pkind & PCK) != 0) skind = skind | PCK;
  1832             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  1833             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  1836         // Attribute the qualifier expression, and determine its symbol (if any).
  1837         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  1838         if ((pkind & (PCK | TYP)) == 0)
  1839             site = capture(site); // Capture field access
  1841         // don't allow T.class T[].class, etc
  1842         if (skind == TYP) {
  1843             Type elt = site;
  1844             while (elt.tag == ARRAY)
  1845                 elt = ((ArrayType)elt).elemtype;
  1846             if (elt.tag == TYPEVAR) {
  1847                 log.error(tree.pos(), "type.var.cant.be.deref");
  1848                 result = syms.errType;
  1849                 return;
  1853         // If qualifier symbol is a type or `super', assert `selectSuper'
  1854         // for the selection. This is relevant for determining whether
  1855         // protected symbols are accessible.
  1856         Symbol sitesym = TreeInfo.symbol(tree.selected);
  1857         boolean selectSuperPrev = env.info.selectSuper;
  1858         env.info.selectSuper =
  1859             sitesym != null &&
  1860             sitesym.name == names._super;
  1862         // If selected expression is polymorphic, strip
  1863         // type parameters and remember in env.info.tvars, so that
  1864         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  1865         if (tree.selected.type.tag == FORALL) {
  1866             ForAll pstype = (ForAll)tree.selected.type;
  1867             env.info.tvars = pstype.tvars;
  1868             site = tree.selected.type = pstype.qtype;
  1871         // Determine the symbol represented by the selection.
  1872         env.info.varArgs = false;
  1873         Symbol sym = selectSym(tree, site, env, pt, pkind);
  1874         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  1875             site = capture(site);
  1876             sym = selectSym(tree, site, env, pt, pkind);
  1878         boolean varArgs = env.info.varArgs;
  1879         tree.sym = sym;
  1881         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  1882             while (site.tag == TYPEVAR) site = site.getUpperBound();
  1883             site = capture(site);
  1886         // If that symbol is a variable, ...
  1887         if (sym.kind == VAR) {
  1888             VarSymbol v = (VarSymbol)sym;
  1890             // ..., evaluate its initializer, if it has one, and check for
  1891             // illegal forward reference.
  1892             checkInit(tree, env, v, true);
  1894             // If we are expecting a variable (as opposed to a value), check
  1895             // that the variable is assignable in the current environment.
  1896             if (pkind == VAR)
  1897                 checkAssignable(tree.pos(), v, tree.selected, env);
  1900         // Disallow selecting a type from an expression
  1901         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  1902             tree.type = check(tree.selected, pt,
  1903                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  1906         if (isType(sitesym)) {
  1907             if (sym.name == names._this) {
  1908                 // If `C' is the currently compiled class, check that
  1909                 // C.this' does not appear in a call to a super(...)
  1910                 if (env.info.isSelfCall &&
  1911                     site.tsym == env.enclClass.sym) {
  1912                     chk.earlyRefError(tree.pos(), sym);
  1914             } else {
  1915                 // Check if type-qualified fields or methods are static (JLS)
  1916                 if ((sym.flags() & STATIC) == 0 &&
  1917                     sym.name != names._super &&
  1918                     (sym.kind == VAR || sym.kind == MTH)) {
  1919                     rs.access(rs.new StaticError(sym),
  1920                               tree.pos(), site, sym.name, true);
  1925         // If we are selecting an instance member via a `super', ...
  1926         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  1928             // Check that super-qualified symbols are not abstract (JLS)
  1929             rs.checkNonAbstract(tree.pos(), sym);
  1931             if (site.isRaw()) {
  1932                 // Determine argument types for site.
  1933                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  1934                 if (site1 != null) site = site1;
  1938         env.info.selectSuper = selectSuperPrev;
  1939         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  1940         env.info.tvars = List.nil();
  1942     //where
  1943         /** Determine symbol referenced by a Select expression,
  1945          *  @param tree   The select tree.
  1946          *  @param site   The type of the selected expression,
  1947          *  @param env    The current environment.
  1948          *  @param pt     The current prototype.
  1949          *  @param pkind  The expected kind(s) of the Select expression.
  1950          */
  1951         private Symbol selectSym(JCFieldAccess tree,
  1952                                  Type site,
  1953                                  Env<AttrContext> env,
  1954                                  Type pt,
  1955                                  int pkind) {
  1956             DiagnosticPosition pos = tree.pos();
  1957             Name name = tree.name;
  1959             switch (site.tag) {
  1960             case PACKAGE:
  1961                 return rs.access(
  1962                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  1963                     pos, site, name, true);
  1964             case ARRAY:
  1965             case CLASS:
  1966                 if (pt.tag == METHOD || pt.tag == FORALL) {
  1967                     return rs.resolveQualifiedMethod(
  1968                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  1969                 } else if (name == names._this || name == names._super) {
  1970                     return rs.resolveSelf(pos, env, site.tsym, name);
  1971                 } else if (name == names._class) {
  1972                     // In this case, we have already made sure in
  1973                     // visitSelect that qualifier expression is a type.
  1974                     Type t = syms.classType;
  1975                     List<Type> typeargs = allowGenerics
  1976                         ? List.of(types.erasure(site))
  1977                         : List.<Type>nil();
  1978                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  1979                     return new VarSymbol(
  1980                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  1981                 } else {
  1982                     // We are seeing a plain identifier as selector.
  1983                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  1984                     if ((pkind & ERRONEOUS) == 0)
  1985                         sym = rs.access(sym, pos, site, name, true);
  1986                     return sym;
  1988             case WILDCARD:
  1989                 throw new AssertionError(tree);
  1990             case TYPEVAR:
  1991                 // Normally, site.getUpperBound() shouldn't be null.
  1992                 // It should only happen during memberEnter/attribBase
  1993                 // when determining the super type which *must* be
  1994                 // done before attributing the type variables.  In
  1995                 // other words, we are seeing this illegal program:
  1996                 // class B<T> extends A<T.foo> {}
  1997                 Symbol sym = (site.getUpperBound() != null)
  1998                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  1999                     : null;
  2000                 if (sym == null || isType(sym)) {
  2001                     log.error(pos, "type.var.cant.be.deref");
  2002                     return syms.errSymbol;
  2003                 } else {
  2004                     return sym;
  2006             case ERROR:
  2007                 // preserve identifier names through errors
  2008                 return new ErrorType(name, site.tsym).tsym;
  2009             default:
  2010                 // The qualifier expression is of a primitive type -- only
  2011                 // .class is allowed for these.
  2012                 if (name == names._class) {
  2013                     // In this case, we have already made sure in Select that
  2014                     // qualifier expression is a type.
  2015                     Type t = syms.classType;
  2016                     Type arg = types.boxedClass(site).type;
  2017                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2018                     return new VarSymbol(
  2019                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2020                 } else {
  2021                     log.error(pos, "cant.deref", site);
  2022                     return syms.errSymbol;
  2027         /** Determine type of identifier or select expression and check that
  2028          *  (1) the referenced symbol is not deprecated
  2029          *  (2) the symbol's type is safe (@see checkSafe)
  2030          *  (3) if symbol is a variable, check that its type and kind are
  2031          *      compatible with the prototype and protokind.
  2032          *  (4) if symbol is an instance field of a raw type,
  2033          *      which is being assigned to, issue an unchecked warning if its
  2034          *      type changes under erasure.
  2035          *  (5) if symbol is an instance method of a raw type, issue an
  2036          *      unchecked warning if its argument types change under erasure.
  2037          *  If checks succeed:
  2038          *    If symbol is a constant, return its constant type
  2039          *    else if symbol is a method, return its result type
  2040          *    otherwise return its type.
  2041          *  Otherwise return errType.
  2043          *  @param tree       The syntax tree representing the identifier
  2044          *  @param site       If this is a select, the type of the selected
  2045          *                    expression, otherwise the type of the current class.
  2046          *  @param sym        The symbol representing the identifier.
  2047          *  @param env        The current environment.
  2048          *  @param pkind      The set of expected kinds.
  2049          *  @param pt         The expected type.
  2050          */
  2051         Type checkId(JCTree tree,
  2052                      Type site,
  2053                      Symbol sym,
  2054                      Env<AttrContext> env,
  2055                      int pkind,
  2056                      Type pt,
  2057                      boolean useVarargs) {
  2058             if (pt.isErroneous()) return syms.errType;
  2059             Type owntype; // The computed type of this identifier occurrence.
  2060             switch (sym.kind) {
  2061             case TYP:
  2062                 // For types, the computed type equals the symbol's type,
  2063                 // except for two situations:
  2064                 owntype = sym.type;
  2065                 if (owntype.tag == CLASS) {
  2066                     Type ownOuter = owntype.getEnclosingType();
  2068                     // (a) If the symbol's type is parameterized, erase it
  2069                     // because no type parameters were given.
  2070                     // We recover generic outer type later in visitTypeApply.
  2071                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2072                         owntype = types.erasure(owntype);
  2075                     // (b) If the symbol's type is an inner class, then
  2076                     // we have to interpret its outer type as a superclass
  2077                     // of the site type. Example:
  2078                     //
  2079                     // class Tree<A> { class Visitor { ... } }
  2080                     // class PointTree extends Tree<Point> { ... }
  2081                     // ...PointTree.Visitor...
  2082                     //
  2083                     // Then the type of the last expression above is
  2084                     // Tree<Point>.Visitor.
  2085                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2086                         Type normOuter = site;
  2087                         if (normOuter.tag == CLASS)
  2088                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2089                         if (normOuter == null) // perhaps from an import
  2090                             normOuter = types.erasure(ownOuter);
  2091                         if (normOuter != ownOuter)
  2092                             owntype = new ClassType(
  2093                                 normOuter, List.<Type>nil(), owntype.tsym);
  2096                 break;
  2097             case VAR:
  2098                 VarSymbol v = (VarSymbol)sym;
  2099                 // Test (4): if symbol is an instance field of a raw type,
  2100                 // which is being assigned to, issue an unchecked warning if
  2101                 // its type changes under erasure.
  2102                 if (allowGenerics &&
  2103                     pkind == VAR &&
  2104                     v.owner.kind == TYP &&
  2105                     (v.flags() & STATIC) == 0 &&
  2106                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2107                     Type s = types.asOuterSuper(site, v.owner);
  2108                     if (s != null &&
  2109                         s.isRaw() &&
  2110                         !types.isSameType(v.type, v.erasure(types))) {
  2111                         chk.warnUnchecked(tree.pos(),
  2112                                           "unchecked.assign.to.var",
  2113                                           v, s);
  2116                 // The computed type of a variable is the type of the
  2117                 // variable symbol, taken as a member of the site type.
  2118                 owntype = (sym.owner.kind == TYP &&
  2119                            sym.name != names._this && sym.name != names._super)
  2120                     ? types.memberType(site, sym)
  2121                     : sym.type;
  2123                 if (env.info.tvars.nonEmpty()) {
  2124                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2125                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2126                         if (!owntype.contains(l.head)) {
  2127                             log.error(tree.pos(), "undetermined.type", owntype1);
  2128                             owntype1 = syms.errType;
  2130                     owntype = owntype1;
  2133                 // If the variable is a constant, record constant value in
  2134                 // computed type.
  2135                 if (v.getConstValue() != null && isStaticReference(tree))
  2136                     owntype = owntype.constType(v.getConstValue());
  2138                 if (pkind == VAL) {
  2139                     owntype = capture(owntype); // capture "names as expressions"
  2141                 break;
  2142             case MTH: {
  2143                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2144                 owntype = checkMethod(site, sym, env, app.args,
  2145                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2146                                       env.info.varArgs);
  2147                 break;
  2149             case PCK: case ERR:
  2150                 owntype = sym.type;
  2151                 break;
  2152             default:
  2153                 throw new AssertionError("unexpected kind: " + sym.kind +
  2154                                          " in tree " + tree);
  2157             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2158             // (for constructors, the error was given when the constructor was
  2159             // resolved)
  2160             if (sym.name != names.init &&
  2161                 (sym.flags() & DEPRECATED) != 0 &&
  2162                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2163                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2164                 chk.warnDeprecated(tree.pos(), sym);
  2166             if ((sym.flags() & PROPRIETARY) != 0)
  2167                 log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2169             // Test (3): if symbol is a variable, check that its type and
  2170             // kind are compatible with the prototype and protokind.
  2171             return check(tree, owntype, sym.kind, pkind, pt);
  2174         /** Check that variable is initialized and evaluate the variable's
  2175          *  initializer, if not yet done. Also check that variable is not
  2176          *  referenced before it is defined.
  2177          *  @param tree    The tree making up the variable reference.
  2178          *  @param env     The current environment.
  2179          *  @param v       The variable's symbol.
  2180          */
  2181         private void checkInit(JCTree tree,
  2182                                Env<AttrContext> env,
  2183                                VarSymbol v,
  2184                                boolean onlyWarning) {
  2185 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2186 //                             tree.pos + " " + v.pos + " " +
  2187 //                             Resolve.isStatic(env));//DEBUG
  2189             // A forward reference is diagnosed if the declaration position
  2190             // of the variable is greater than the current tree position
  2191             // and the tree and variable definition occur in the same class
  2192             // definition.  Note that writes don't count as references.
  2193             // This check applies only to class and instance
  2194             // variables.  Local variables follow different scope rules,
  2195             // and are subject to definite assignment checking.
  2196             if (v.pos > tree.pos &&
  2197                 v.owner.kind == TYP &&
  2198                 canOwnInitializer(env.info.scope.owner) &&
  2199                 v.owner == env.info.scope.owner.enclClass() &&
  2200                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2201                 (env.tree.getTag() != JCTree.ASSIGN ||
  2202                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2204                 if (!onlyWarning || isStaticEnumField(v)) {
  2205                     log.error(tree.pos(), "illegal.forward.ref");
  2206                 } else if (useBeforeDeclarationWarning) {
  2207                     log.warning(tree.pos(), "forward.ref", v);
  2211             v.getConstValue(); // ensure initializer is evaluated
  2213             checkEnumInitializer(tree, env, v);
  2216         /**
  2217          * Check for illegal references to static members of enum.  In
  2218          * an enum type, constructors and initializers may not
  2219          * reference its static members unless they are constant.
  2221          * @param tree    The tree making up the variable reference.
  2222          * @param env     The current environment.
  2223          * @param v       The variable's symbol.
  2224          * @see JLS 3rd Ed. (8.9 Enums)
  2225          */
  2226         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2227             // JLS 3rd Ed.:
  2228             //
  2229             // "It is a compile-time error to reference a static field
  2230             // of an enum type that is not a compile-time constant
  2231             // (15.28) from constructors, instance initializer blocks,
  2232             // or instance variable initializer expressions of that
  2233             // type. It is a compile-time error for the constructors,
  2234             // instance initializer blocks, or instance variable
  2235             // initializer expressions of an enum constant e to refer
  2236             // to itself or to an enum constant of the same type that
  2237             // is declared to the right of e."
  2238             if (isStaticEnumField(v)) {
  2239                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2241                 if (enclClass == null || enclClass.owner == null)
  2242                     return;
  2244                 // See if the enclosing class is the enum (or a
  2245                 // subclass thereof) declaring v.  If not, this
  2246                 // reference is OK.
  2247                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2248                     return;
  2250                 // If the reference isn't from an initializer, then
  2251                 // the reference is OK.
  2252                 if (!Resolve.isInitializer(env))
  2253                     return;
  2255                 log.error(tree.pos(), "illegal.enum.static.ref");
  2259         /** Is the given symbol a static, non-constant field of an Enum?
  2260          *  Note: enum literals should not be regarded as such
  2261          */
  2262         private boolean isStaticEnumField(VarSymbol v) {
  2263             return Flags.isEnum(v.owner) &&
  2264                    Flags.isStatic(v) &&
  2265                    !Flags.isConstant(v) &&
  2266                    v.name != names._class;
  2269         /** Can the given symbol be the owner of code which forms part
  2270          *  if class initialization? This is the case if the symbol is
  2271          *  a type or field, or if the symbol is the synthetic method.
  2272          *  owning a block.
  2273          */
  2274         private boolean canOwnInitializer(Symbol sym) {
  2275             return
  2276                 (sym.kind & (VAR | TYP)) != 0 ||
  2277                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2280     Warner noteWarner = new Warner();
  2282     /**
  2283      * Check that method arguments conform to its instantation.
  2284      **/
  2285     public Type checkMethod(Type site,
  2286                             Symbol sym,
  2287                             Env<AttrContext> env,
  2288                             final List<JCExpression> argtrees,
  2289                             List<Type> argtypes,
  2290                             List<Type> typeargtypes,
  2291                             boolean useVarargs) {
  2292         // Test (5): if symbol is an instance method of a raw type, issue
  2293         // an unchecked warning if its argument types change under erasure.
  2294         if (allowGenerics &&
  2295             (sym.flags() & STATIC) == 0 &&
  2296             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2297             Type s = types.asOuterSuper(site, sym.owner);
  2298             if (s != null && s.isRaw() &&
  2299                 !types.isSameTypes(sym.type.getParameterTypes(),
  2300                                    sym.erasure(types).getParameterTypes())) {
  2301                 chk.warnUnchecked(env.tree.pos(),
  2302                                   "unchecked.call.mbr.of.raw.type",
  2303                                   sym, s);
  2307         // Compute the identifier's instantiated type.
  2308         // For methods, we need to compute the instance type by
  2309         // Resolve.instantiate from the symbol's type as well as
  2310         // any type arguments and value arguments.
  2311         noteWarner.warned = false;
  2312         Type owntype = rs.instantiate(env,
  2313                                       site,
  2314                                       sym,
  2315                                       argtypes,
  2316                                       typeargtypes,
  2317                                       true,
  2318                                       useVarargs,
  2319                                       noteWarner);
  2320         boolean warned = noteWarner.warned;
  2322         // If this fails, something went wrong; we should not have
  2323         // found the identifier in the first place.
  2324         if (owntype == null) {
  2325             if (!pt.isErroneous())
  2326                 log.error(env.tree.pos(),
  2327                           "internal.error.cant.instantiate",
  2328                           sym, site,
  2329                           Type.toString(pt.getParameterTypes()));
  2330             owntype = syms.errType;
  2331         } else {
  2332             // System.out.println("call   : " + env.tree);
  2333             // System.out.println("method : " + owntype);
  2334             // System.out.println("actuals: " + argtypes);
  2335             List<Type> formals = owntype.getParameterTypes();
  2336             Type last = useVarargs ? formals.last() : null;
  2337             if (sym.name==names.init &&
  2338                 sym.owner == syms.enumSym)
  2339                 formals = formals.tail.tail;
  2340             List<JCExpression> args = argtrees;
  2341             while (formals.head != last) {
  2342                 JCTree arg = args.head;
  2343                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2344                 assertConvertible(arg, arg.type, formals.head, warn);
  2345                 warned |= warn.warned;
  2346                 args = args.tail;
  2347                 formals = formals.tail;
  2349             if (useVarargs) {
  2350                 Type varArg = types.elemtype(last);
  2351                 while (args.tail != null) {
  2352                     JCTree arg = args.head;
  2353                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2354                     assertConvertible(arg, arg.type, varArg, warn);
  2355                     warned |= warn.warned;
  2356                     args = args.tail;
  2358             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2359                 // non-varargs call to varargs method
  2360                 Type varParam = owntype.getParameterTypes().last();
  2361                 Type lastArg = argtypes.last();
  2362                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2363                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2364                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2365                                 types.elemtype(varParam),
  2366                                 varParam);
  2369             if (warned && sym.type.tag == FORALL) {
  2370                 String typeargs = "";
  2371                 if (typeargtypes != null && typeargtypes.nonEmpty()) {
  2372                     typeargs = "<" + Type.toString(typeargtypes) + ">";
  2374                 chk.warnUnchecked(env.tree.pos(),
  2375                                   "unchecked.meth.invocation.applied",
  2376                                   sym,
  2377                                   sym.location(),
  2378                                   typeargs,
  2379                                   Type.toString(argtypes));
  2380                 owntype = new MethodType(owntype.getParameterTypes(),
  2381                                          types.erasure(owntype.getReturnType()),
  2382                                          owntype.getThrownTypes(),
  2383                                          syms.methodClass);
  2385             if (useVarargs) {
  2386                 JCTree tree = env.tree;
  2387                 Type argtype = owntype.getParameterTypes().last();
  2388                 if (!types.isReifiable(argtype))
  2389                     chk.warnUnchecked(env.tree.pos(),
  2390                                       "unchecked.generic.array.creation",
  2391                                       argtype);
  2392                 Type elemtype = types.elemtype(argtype);
  2393                 switch (tree.getTag()) {
  2394                 case JCTree.APPLY:
  2395                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2396                     break;
  2397                 case JCTree.NEWCLASS:
  2398                     ((JCNewClass) tree).varargsElement = elemtype;
  2399                     break;
  2400                 default:
  2401                     throw new AssertionError(""+tree);
  2405         return owntype;
  2408     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2409         if (types.isConvertible(actual, formal, warn))
  2410             return;
  2412         if (formal.isCompound()
  2413             && types.isSubtype(actual, types.supertype(formal))
  2414             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2415             return;
  2417         if (false) {
  2418             // TODO: make assertConvertible work
  2419             chk.typeError(tree.pos(), JCDiagnostic.fragment("incompatible.types"), actual, formal);
  2420             throw new AssertionError("Tree: " + tree
  2421                                      + " actual:" + actual
  2422                                      + " formal: " + formal);
  2426     public void visitLiteral(JCLiteral tree) {
  2427         result = check(
  2428             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2430     //where
  2431     /** Return the type of a literal with given type tag.
  2432      */
  2433     Type litType(int tag) {
  2434         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2437     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2438         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2441     public void visitTypeArray(JCArrayTypeTree tree) {
  2442         Type etype = attribType(tree.elemtype, env);
  2443         Type type = new ArrayType(etype, syms.arrayClass);
  2444         result = check(tree, type, TYP, pkind, pt);
  2447     /** Visitor method for parameterized types.
  2448      *  Bound checking is left until later, since types are attributed
  2449      *  before supertype structure is completely known
  2450      */
  2451     public void visitTypeApply(JCTypeApply tree) {
  2452         Type owntype = syms.errType;
  2454         // Attribute functor part of application and make sure it's a class.
  2455         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2457         // Attribute type parameters
  2458         List<Type> actuals = attribTypes(tree.arguments, env);
  2460         if (clazztype.tag == CLASS) {
  2461             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2463             if (actuals.length() == formals.length()) {
  2464                 List<Type> a = actuals;
  2465                 List<Type> f = formals;
  2466                 while (a.nonEmpty()) {
  2467                     a.head = a.head.withTypeVar(f.head);
  2468                     a = a.tail;
  2469                     f = f.tail;
  2471                 // Compute the proper generic outer
  2472                 Type clazzOuter = clazztype.getEnclosingType();
  2473                 if (clazzOuter.tag == CLASS) {
  2474                     Type site;
  2475                     if (tree.clazz.getTag() == JCTree.IDENT) {
  2476                         site = env.enclClass.sym.type;
  2477                     } else if (tree.clazz.getTag() == JCTree.SELECT) {
  2478                         site = ((JCFieldAccess) tree.clazz).selected.type;
  2479                     } else throw new AssertionError(""+tree);
  2480                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2481                         if (site.tag == CLASS)
  2482                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2483                         if (site == null)
  2484                             site = types.erasure(clazzOuter);
  2485                         clazzOuter = site;
  2488                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2489             } else {
  2490                 if (formals.length() != 0) {
  2491                     log.error(tree.pos(), "wrong.number.type.args",
  2492                               Integer.toString(formals.length()));
  2493                 } else {
  2494                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2496                 owntype = syms.errType;
  2499         result = check(tree, owntype, TYP, pkind, pt);
  2502     public void visitTypeParameter(JCTypeParameter tree) {
  2503         TypeVar a = (TypeVar)tree.type;
  2504         Set<Type> boundSet = new HashSet<Type>();
  2505         if (a.bound.isErroneous())
  2506             return;
  2507         List<Type> bs = types.getBounds(a);
  2508         if (tree.bounds.nonEmpty()) {
  2509             // accept class or interface or typevar as first bound.
  2510             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2511             boundSet.add(types.erasure(b));
  2512             if (b.tag == TYPEVAR) {
  2513                 // if first bound was a typevar, do not accept further bounds.
  2514                 if (tree.bounds.tail.nonEmpty()) {
  2515                     log.error(tree.bounds.tail.head.pos(),
  2516                               "type.var.may.not.be.followed.by.other.bounds");
  2517                     tree.bounds = List.of(tree.bounds.head);
  2518                     a.bound = bs.head;
  2520             } else {
  2521                 // if first bound was a class or interface, accept only interfaces
  2522                 // as further bounds.
  2523                 for (JCExpression bound : tree.bounds.tail) {
  2524                     bs = bs.tail;
  2525                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2526                     if (i.tag == CLASS)
  2527                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2531         bs = types.getBounds(a);
  2533         // in case of multiple bounds ...
  2534         if (bs.length() > 1) {
  2535             // ... the variable's bound is a class type flagged COMPOUND
  2536             // (see comment for TypeVar.bound).
  2537             // In this case, generate a class tree that represents the
  2538             // bound class, ...
  2539             JCTree extending;
  2540             List<JCExpression> implementing;
  2541             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2542                 extending = tree.bounds.head;
  2543                 implementing = tree.bounds.tail;
  2544             } else {
  2545                 extending = null;
  2546                 implementing = tree.bounds;
  2548             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2549                 make.Modifiers(PUBLIC | ABSTRACT),
  2550                 tree.name, List.<JCTypeParameter>nil(),
  2551                 extending, implementing, List.<JCTree>nil());
  2553             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2554             assert (c.flags() & COMPOUND) != 0;
  2555             cd.sym = c;
  2556             c.sourcefile = env.toplevel.sourcefile;
  2558             // ... and attribute the bound class
  2559             c.flags_field |= UNATTRIBUTED;
  2560             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2561             enter.typeEnvs.put(c, cenv);
  2566     public void visitWildcard(JCWildcard tree) {
  2567         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2568         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2569             ? syms.objectType
  2570             : attribType(tree.inner, env);
  2571         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2572                                               tree.kind.kind,
  2573                                               syms.boundClass),
  2574                        TYP, pkind, pt);
  2577     public void visitAnnotation(JCAnnotation tree) {
  2578         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2579         result = tree.type = syms.errType;
  2582     public void visitErroneous(JCErroneous tree) {
  2583         if (tree.errs != null)
  2584             for (JCTree err : tree.errs)
  2585                 attribTree(err, env, ERR, pt);
  2586         result = tree.type = syms.errType;
  2589     /** Default visitor method for all other trees.
  2590      */
  2591     public void visitTree(JCTree tree) {
  2592         throw new AssertionError();
  2595     /** Main method: attribute class definition associated with given class symbol.
  2596      *  reporting completion failures at the given position.
  2597      *  @param pos The source position at which completion errors are to be
  2598      *             reported.
  2599      *  @param c   The class symbol whose definition will be attributed.
  2600      */
  2601     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2602         try {
  2603             annotate.flush();
  2604             attribClass(c);
  2605         } catch (CompletionFailure ex) {
  2606             chk.completionError(pos, ex);
  2610     /** Attribute class definition associated with given class symbol.
  2611      *  @param c   The class symbol whose definition will be attributed.
  2612      */
  2613     void attribClass(ClassSymbol c) throws CompletionFailure {
  2614         if (c.type.tag == ERROR) return;
  2616         // Check for cycles in the inheritance graph, which can arise from
  2617         // ill-formed class files.
  2618         chk.checkNonCyclic(null, c.type);
  2620         Type st = types.supertype(c.type);
  2621         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2622             // First, attribute superclass.
  2623             if (st.tag == CLASS)
  2624                 attribClass((ClassSymbol)st.tsym);
  2626             // Next attribute owner, if it is a class.
  2627             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2628                 attribClass((ClassSymbol)c.owner);
  2631         // The previous operations might have attributed the current class
  2632         // if there was a cycle. So we test first whether the class is still
  2633         // UNATTRIBUTED.
  2634         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2635             c.flags_field &= ~UNATTRIBUTED;
  2637             // Get environment current at the point of class definition.
  2638             Env<AttrContext> env = enter.typeEnvs.get(c);
  2640             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2641             // because the annotations were not available at the time the env was created. Therefore,
  2642             // we look up the environment chain for the first enclosing environment for which the
  2643             // lint value is set. Typically, this is the parent env, but might be further if there
  2644             // are any envs created as a result of TypeParameter nodes.
  2645             Env<AttrContext> lintEnv = env;
  2646             while (lintEnv.info.lint == null)
  2647                 lintEnv = lintEnv.next;
  2649             // Having found the enclosing lint value, we can initialize the lint value for this class
  2650             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2652             Lint prevLint = chk.setLint(env.info.lint);
  2653             JavaFileObject prev = log.useSource(c.sourcefile);
  2655             try {
  2656                 // java.lang.Enum may not be subclassed by a non-enum
  2657                 if (st.tsym == syms.enumSym &&
  2658                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  2659                     log.error(env.tree.pos(), "enum.no.subclassing");
  2661                 // Enums may not be extended by source-level classes
  2662                 if (st.tsym != null &&
  2663                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  2664                     ((c.flags_field & Flags.ENUM) == 0) &&
  2665                     !target.compilerBootstrap(c)) {
  2666                     log.error(env.tree.pos(), "enum.types.not.extensible");
  2668                 attribClassBody(env, c);
  2670                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  2671             } finally {
  2672                 log.useSource(prev);
  2673                 chk.setLint(prevLint);
  2679     public void visitImport(JCImport tree) {
  2680         // nothing to do
  2683     /** Finish the attribution of a class. */
  2684     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  2685         JCClassDecl tree = (JCClassDecl)env.tree;
  2686         assert c == tree.sym;
  2688         // Validate annotations
  2689         chk.validateAnnotations(tree.mods.annotations, c);
  2691         // Validate type parameters, supertype and interfaces.
  2692         attribBounds(tree.typarams, env);
  2693         chk.validateTypeParams(tree.typarams);
  2694         chk.validate(tree.extending);
  2695         chk.validate(tree.implementing);
  2697         // If this is a non-abstract class, check that it has no abstract
  2698         // methods or unimplemented methods of an implemented interface.
  2699         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  2700             if (!relax)
  2701                 chk.checkAllDefined(tree.pos(), c);
  2704         if ((c.flags() & ANNOTATION) != 0) {
  2705             if (tree.implementing.nonEmpty())
  2706                 log.error(tree.implementing.head.pos(),
  2707                           "cant.extend.intf.annotation");
  2708             if (tree.typarams.nonEmpty())
  2709                 log.error(tree.typarams.head.pos(),
  2710                           "intf.annotation.cant.have.type.params");
  2711         } else {
  2712             // Check that all extended classes and interfaces
  2713             // are compatible (i.e. no two define methods with same arguments
  2714             // yet different return types).  (JLS 8.4.6.3)
  2715             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  2718         // Check that class does not import the same parameterized interface
  2719         // with two different argument lists.
  2720         chk.checkClassBounds(tree.pos(), c.type);
  2722         tree.type = c.type;
  2724         boolean assertsEnabled = false;
  2725         assert assertsEnabled = true;
  2726         if (assertsEnabled) {
  2727             for (List<JCTypeParameter> l = tree.typarams;
  2728                  l.nonEmpty(); l = l.tail)
  2729                 assert env.info.scope.lookup(l.head.name).scope != null;
  2732         // Check that a generic class doesn't extend Throwable
  2733         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  2734             log.error(tree.extending.pos(), "generic.throwable");
  2736         // Check that all methods which implement some
  2737         // method conform to the method they implement.
  2738         chk.checkImplementations(tree);
  2740         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2741             // Attribute declaration
  2742             attribStat(l.head, env);
  2743             // Check that declarations in inner classes are not static (JLS 8.1.2)
  2744             // Make an exception for static constants.
  2745             if (c.owner.kind != PCK &&
  2746                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  2747                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  2748                 Symbol sym = null;
  2749                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  2750                 if (sym == null ||
  2751                     sym.kind != VAR ||
  2752                     ((VarSymbol) sym).getConstValue() == null)
  2753                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  2757         // Check for cycles among non-initial constructors.
  2758         chk.checkCyclicConstructors(tree);
  2760         // Check for cycles among annotation elements.
  2761         chk.checkNonCyclicElements(tree);
  2763         // Check for proper use of serialVersionUID
  2764         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  2765             isSerializable(c) &&
  2766             (c.flags() & Flags.ENUM) == 0 &&
  2767             (c.flags() & ABSTRACT) == 0) {
  2768             checkSerialVersionUID(tree, c);
  2771         // where
  2772         /** check if a class is a subtype of Serializable, if that is available. */
  2773         private boolean isSerializable(ClassSymbol c) {
  2774             try {
  2775                 syms.serializableType.complete();
  2777             catch (CompletionFailure e) {
  2778                 return false;
  2780             return types.isSubtype(c.type, syms.serializableType);
  2783         /** Check that an appropriate serialVersionUID member is defined. */
  2784         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  2786             // check for presence of serialVersionUID
  2787             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  2788             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  2789             if (e.scope == null) {
  2790                 log.warning(tree.pos(), "missing.SVUID", c);
  2791                 return;
  2794             // check that it is static final
  2795             VarSymbol svuid = (VarSymbol)e.sym;
  2796             if ((svuid.flags() & (STATIC | FINAL)) !=
  2797                 (STATIC | FINAL))
  2798                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  2800             // check that it is long
  2801             else if (svuid.type.tag != TypeTags.LONG)
  2802                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  2804             // check constant
  2805             else if (svuid.getConstValue() == null)
  2806                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  2809     private Type capture(Type type) {
  2810         return types.capture(type);

mercurial