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

Tue, 24 Feb 2009 17:48:53 -0800

author
darcy
date
Tue, 24 Feb 2009 17:48:53 -0800
changeset 232
1fbc1cc6e260
parent 186
09eb1acc9610
child 229
03bcd66bd8e7
permissions
-rw-r--r--

6498938: Faulty comparison of TypeMirror objects in getElementsAnnotatedWith implementation
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.jvm.Target;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.tree.JCTree.*;
    43 import com.sun.tools.javac.code.Type.*;
    45 import com.sun.source.tree.IdentifierTree;
    46 import com.sun.source.tree.MemberSelectTree;
    47 import com.sun.source.tree.TreeVisitor;
    48 import com.sun.source.util.SimpleTreeVisitor;
    50 import static com.sun.tools.javac.code.Flags.*;
    51 import static com.sun.tools.javac.code.Kinds.*;
    52 import static com.sun.tools.javac.code.TypeTags.*;
    54 /** This is the main context-dependent analysis phase in GJC. It
    55  *  encompasses name resolution, type checking and constant folding as
    56  *  subtasks. Some subtasks involve auxiliary classes.
    57  *  @see Check
    58  *  @see Resolve
    59  *  @see ConstFold
    60  *  @see Infer
    61  *
    62  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    63  *  you write code that depends on this, you do so at your own risk.
    64  *  This code and its internal interfaces are subject to change or
    65  *  deletion without notice.</b>
    66  */
    67 public class Attr extends JCTree.Visitor {
    68     protected static final Context.Key<Attr> attrKey =
    69         new Context.Key<Attr>();
    71     final Names names;
    72     final Log log;
    73     final Symtab syms;
    74     final Resolve rs;
    75     final Check chk;
    76     final MemberEnter memberEnter;
    77     final TreeMaker make;
    78     final ConstFold cfolder;
    79     final Enter enter;
    80     final Target target;
    81     final Types types;
    82     final JCDiagnostic.Factory diags;
    83     final Annotate annotate;
    85     public static Attr instance(Context context) {
    86         Attr instance = context.get(attrKey);
    87         if (instance == null)
    88             instance = new Attr(context);
    89         return instance;
    90     }
    92     protected Attr(Context context) {
    93         context.put(attrKey, this);
    95         names = Names.instance(context);
    96         log = Log.instance(context);
    97         syms = Symtab.instance(context);
    98         rs = Resolve.instance(context);
    99         chk = Check.instance(context);
   100         memberEnter = MemberEnter.instance(context);
   101         make = TreeMaker.instance(context);
   102         enter = Enter.instance(context);
   103         cfolder = ConstFold.instance(context);
   104         target = Target.instance(context);
   105         types = Types.instance(context);
   106         diags = JCDiagnostic.Factory.instance(context);
   107         annotate = Annotate.instance(context);
   109         Options options = Options.instance(context);
   111         Source source = Source.instance(context);
   112         allowGenerics = source.allowGenerics();
   113         allowVarargs = source.allowVarargs();
   114         allowEnums = source.allowEnums();
   115         allowBoxing = source.allowBoxing();
   116         allowCovariantReturns = source.allowCovariantReturns();
   117         allowAnonOuterThis = source.allowAnonOuterThis();
   118         relax = (options.get("-retrofit") != null ||
   119                  options.get("-relax") != null);
   120         useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
   121     }
   123     /** Switch: relax some constraints for retrofit mode.
   124      */
   125     boolean relax;
   127     /** Switch: support generics?
   128      */
   129     boolean allowGenerics;
   131     /** Switch: allow variable-arity methods.
   132      */
   133     boolean allowVarargs;
   135     /** Switch: support enums?
   136      */
   137     boolean allowEnums;
   139     /** Switch: support boxing and unboxing?
   140      */
   141     boolean allowBoxing;
   143     /** Switch: support covariant result types?
   144      */
   145     boolean allowCovariantReturns;
   147     /** Switch: allow references to surrounding object from anonymous
   148      * objects during constructor call?
   149      */
   150     boolean allowAnonOuterThis;
   152     /**
   153      * Switch: warn about use of variable before declaration?
   154      * RFE: 6425594
   155      */
   156     boolean useBeforeDeclarationWarning;
   158     /** Check kind and type of given tree against protokind and prototype.
   159      *  If check succeeds, store type in tree and return it.
   160      *  If check fails, store errType in tree and return it.
   161      *  No checks are performed if the prototype is a method type.
   162      *  It is not necessary in this case since we know that kind and type
   163      *  are correct.
   164      *
   165      *  @param tree     The tree whose kind and type is checked
   166      *  @param owntype  The computed type of the tree
   167      *  @param ownkind  The computed kind of the tree
   168      *  @param pkind    The expected kind (or: protokind) of the tree
   169      *  @param pt       The expected type (or: prototype) of the tree
   170      */
   171     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   172         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   173             if ((ownkind & ~pkind) == 0) {
   174                 owntype = chk.checkType(tree.pos(), owntype, pt);
   175             } else {
   176                 log.error(tree.pos(), "unexpected.type",
   177                           kindNames(pkind),
   178                           kindName(ownkind));
   179                 owntype = types.createErrorType(owntype);
   180             }
   181         }
   182         tree.type = owntype;
   183         return owntype;
   184     }
   186     /** Is given blank final variable assignable, i.e. in a scope where it
   187      *  may be assigned to even though it is final?
   188      *  @param v      The blank final variable.
   189      *  @param env    The current environment.
   190      */
   191     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   192         Symbol owner = env.info.scope.owner;
   193            // owner refers to the innermost variable, method or
   194            // initializer block declaration at this point.
   195         return
   196             v.owner == owner
   197             ||
   198             ((owner.name == names.init ||    // i.e. we are in a constructor
   199               owner.kind == VAR ||           // i.e. we are in a variable initializer
   200               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   201              &&
   202              v.owner == owner.owner
   203              &&
   204              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   205     }
   207     /** Check that variable can be assigned to.
   208      *  @param pos    The current source code position.
   209      *  @param v      The assigned varaible
   210      *  @param base   If the variable is referred to in a Select, the part
   211      *                to the left of the `.', null otherwise.
   212      *  @param env    The current environment.
   213      */
   214     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   215         if ((v.flags() & FINAL) != 0 &&
   216             ((v.flags() & HASINIT) != 0
   217              ||
   218              !((base == null ||
   219                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   220                isAssignableAsBlankFinal(v, env)))) {
   221             log.error(pos, "cant.assign.val.to.final.var", v);
   222         }
   223     }
   225     /** Does tree represent a static reference to an identifier?
   226      *  It is assumed that tree is either a SELECT or an IDENT.
   227      *  We have to weed out selects from non-type names here.
   228      *  @param tree    The candidate tree.
   229      */
   230     boolean isStaticReference(JCTree tree) {
   231         if (tree.getTag() == JCTree.SELECT) {
   232             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   233             if (lsym == null || lsym.kind != TYP) {
   234                 return false;
   235             }
   236         }
   237         return true;
   238     }
   240     /** Is this symbol a type?
   241      */
   242     static boolean isType(Symbol sym) {
   243         return sym != null && sym.kind == TYP;
   244     }
   246     /** The current `this' symbol.
   247      *  @param env    The current environment.
   248      */
   249     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   250         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   251     }
   253     /** Attribute a parsed identifier.
   254      * @param tree Parsed identifier name
   255      * @param topLevel The toplevel to use
   256      */
   257     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   258         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   259         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   260                                            syms.errSymbol.name,
   261                                            null, null, null, null);
   262         localEnv.enclClass.sym = syms.errSymbol;
   263         return tree.accept(identAttributer, localEnv);
   264     }
   265     // where
   266         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   267         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   268             @Override
   269             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   270                 Symbol site = visit(node.getExpression(), env);
   271                 if (site.kind == ERR)
   272                     return site;
   273                 Name name = (Name)node.getIdentifier();
   274                 if (site.kind == PCK) {
   275                     env.toplevel.packge = (PackageSymbol)site;
   276                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   277                 } else {
   278                     env.enclClass.sym = (ClassSymbol)site;
   279                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   280                 }
   281             }
   283             @Override
   284             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   285                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   286             }
   287         }
   289     public Type coerce(Type etype, Type ttype) {
   290         return cfolder.coerce(etype, ttype);
   291     }
   293     public Type attribType(JCTree node, TypeSymbol sym) {
   294         Env<AttrContext> env = enter.typeEnvs.get(sym);
   295         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   296         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   297     }
   299     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   300         breakTree = tree;
   301         JavaFileObject prev = log.useSource(null);
   302         try {
   303             attribExpr(expr, env);
   304         } catch (BreakAttr b) {
   305             return b.env;
   306         } finally {
   307             breakTree = null;
   308             log.useSource(prev);
   309         }
   310         return env;
   311     }
   313     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   314         breakTree = tree;
   315         JavaFileObject prev = log.useSource(null);
   316         try {
   317             attribStat(stmt, env);
   318         } catch (BreakAttr b) {
   319             return b.env;
   320         } finally {
   321             breakTree = null;
   322             log.useSource(prev);
   323         }
   324         return env;
   325     }
   327     private JCTree breakTree = null;
   329     private static class BreakAttr extends RuntimeException {
   330         static final long serialVersionUID = -6924771130405446405L;
   331         private Env<AttrContext> env;
   332         private BreakAttr(Env<AttrContext> env) {
   333             this.env = env;
   334         }
   335     }
   338 /* ************************************************************************
   339  * Visitor methods
   340  *************************************************************************/
   342     /** Visitor argument: the current environment.
   343      */
   344     Env<AttrContext> env;
   346     /** Visitor argument: the currently expected proto-kind.
   347      */
   348     int pkind;
   350     /** Visitor argument: the currently expected proto-type.
   351      */
   352     Type pt;
   354     /** Visitor result: the computed type.
   355      */
   356     Type result;
   358     /** Visitor method: attribute a tree, catching any completion failure
   359      *  exceptions. Return the tree's type.
   360      *
   361      *  @param tree    The tree to be visited.
   362      *  @param env     The environment visitor argument.
   363      *  @param pkind   The protokind visitor argument.
   364      *  @param pt      The prototype visitor argument.
   365      */
   366     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   367         Env<AttrContext> prevEnv = this.env;
   368         int prevPkind = this.pkind;
   369         Type prevPt = this.pt;
   370         try {
   371             this.env = env;
   372             this.pkind = pkind;
   373             this.pt = pt;
   374             tree.accept(this);
   375             if (tree == breakTree)
   376                 throw new BreakAttr(env);
   377             return result;
   378         } catch (CompletionFailure ex) {
   379             tree.type = syms.errType;
   380             return chk.completionError(tree.pos(), ex);
   381         } finally {
   382             this.env = prevEnv;
   383             this.pkind = prevPkind;
   384             this.pt = prevPt;
   385         }
   386     }
   388     /** Derived visitor method: attribute an expression tree.
   389      */
   390     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   391         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   392     }
   394     /** Derived visitor method: attribute an expression tree with
   395      *  no constraints on the computed type.
   396      */
   397     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   398         return attribTree(tree, env, VAL, Type.noType);
   399     }
   401     /** Derived visitor method: attribute a type tree.
   402      */
   403     Type attribType(JCTree tree, Env<AttrContext> env) {
   404         Type result = attribTree(tree, env, TYP, Type.noType);
   405         return result;
   406     }
   408     /** Derived visitor method: attribute a statement or definition tree.
   409      */
   410     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   411         return attribTree(tree, env, NIL, Type.noType);
   412     }
   414     /** Attribute a list of expressions, returning a list of types.
   415      */
   416     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   417         ListBuffer<Type> ts = new ListBuffer<Type>();
   418         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   419             ts.append(attribExpr(l.head, env, pt));
   420         return ts.toList();
   421     }
   423     /** Attribute a list of statements, returning nothing.
   424      */
   425     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   426         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   427             attribStat(l.head, env);
   428     }
   430     /** Attribute the arguments in a method call, returning a list of types.
   431      */
   432     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   433         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   434         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   435             argtypes.append(chk.checkNonVoid(
   436                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   437         return argtypes.toList();
   438     }
   440     /** Attribute a type argument list, returning a list of types.
   441      */
   442     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   443         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   444         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   445             argtypes.append(chk.checkRefType(l.head.pos(), attribType(l.head, env)));
   446         return argtypes.toList();
   447     }
   450     /**
   451      * Attribute type variables (of generic classes or methods).
   452      * Compound types are attributed later in attribBounds.
   453      * @param typarams the type variables to enter
   454      * @param env      the current environment
   455      */
   456     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   457         for (JCTypeParameter tvar : typarams) {
   458             TypeVar a = (TypeVar)tvar.type;
   459             a.tsym.flags_field |= UNATTRIBUTED;
   460             a.bound = Type.noType;
   461             if (!tvar.bounds.isEmpty()) {
   462                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   463                 for (JCExpression bound : tvar.bounds.tail)
   464                     bounds = bounds.prepend(attribType(bound, env));
   465                 types.setBounds(a, bounds.reverse());
   466             } else {
   467                 // if no bounds are given, assume a single bound of
   468                 // java.lang.Object.
   469                 types.setBounds(a, List.of(syms.objectType));
   470             }
   471             a.tsym.flags_field &= ~UNATTRIBUTED;
   472         }
   473         for (JCTypeParameter tvar : typarams)
   474             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   475         attribStats(typarams, env);
   476     }
   478     void attribBounds(List<JCTypeParameter> typarams) {
   479         for (JCTypeParameter typaram : typarams) {
   480             Type bound = typaram.type.getUpperBound();
   481             if (bound != null && bound.tsym instanceof ClassSymbol) {
   482                 ClassSymbol c = (ClassSymbol)bound.tsym;
   483                 if ((c.flags_field & COMPOUND) != 0) {
   484                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   485                     attribClass(typaram.pos(), c);
   486                 }
   487             }
   488         }
   489     }
   491     /**
   492      * Attribute the type references in a list of annotations.
   493      */
   494     void attribAnnotationTypes(List<JCAnnotation> annotations,
   495                                Env<AttrContext> env) {
   496         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   497             JCAnnotation a = al.head;
   498             attribType(a.annotationType, env);
   499         }
   500     }
   502     /** Attribute type reference in an `extends' or `implements' clause.
   503      *
   504      *  @param tree              The tree making up the type reference.
   505      *  @param env               The environment current at the reference.
   506      *  @param classExpected     true if only a class is expected here.
   507      *  @param interfaceExpected true if only an interface is expected here.
   508      */
   509     Type attribBase(JCTree tree,
   510                     Env<AttrContext> env,
   511                     boolean classExpected,
   512                     boolean interfaceExpected,
   513                     boolean checkExtensible) {
   514         Type t = attribType(tree, env);
   515         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   516     }
   517     Type checkBase(Type t,
   518                    JCTree tree,
   519                    Env<AttrContext> env,
   520                    boolean classExpected,
   521                    boolean interfaceExpected,
   522                    boolean checkExtensible) {
   523         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   524             // check that type variable is already visible
   525             if (t.getUpperBound() == null) {
   526                 log.error(tree.pos(), "illegal.forward.ref");
   527                 return types.createErrorType(t);
   528             }
   529         } else {
   530             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   531         }
   532         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   533             log.error(tree.pos(), "intf.expected.here");
   534             // return errType is necessary since otherwise there might
   535             // be undetected cycles which cause attribution to loop
   536             return types.createErrorType(t);
   537         } else if (checkExtensible &&
   538                    classExpected &&
   539                    (t.tsym.flags() & INTERFACE) != 0) {
   540             log.error(tree.pos(), "no.intf.expected.here");
   541             return types.createErrorType(t);
   542         }
   543         if (checkExtensible &&
   544             ((t.tsym.flags() & FINAL) != 0)) {
   545             log.error(tree.pos(),
   546                       "cant.inherit.from.final", t.tsym);
   547         }
   548         chk.checkNonCyclic(tree.pos(), t);
   549         return t;
   550     }
   552     public void visitClassDef(JCClassDecl tree) {
   553         // Local classes have not been entered yet, so we need to do it now:
   554         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   555             enter.classEnter(tree, env);
   557         ClassSymbol c = tree.sym;
   558         if (c == null) {
   559             // exit in case something drastic went wrong during enter.
   560             result = null;
   561         } else {
   562             // make sure class has been completed:
   563             c.complete();
   565             // If this class appears as an anonymous class
   566             // in a superclass constructor call where
   567             // no explicit outer instance is given,
   568             // disable implicit outer instance from being passed.
   569             // (This would be an illegal access to "this before super").
   570             if (env.info.isSelfCall &&
   571                 env.tree.getTag() == JCTree.NEWCLASS &&
   572                 ((JCNewClass) env.tree).encl == null)
   573             {
   574                 c.flags_field |= NOOUTERTHIS;
   575             }
   576             attribClass(tree.pos(), c);
   577             result = tree.type = c.type;
   578         }
   579     }
   581     public void visitMethodDef(JCMethodDecl tree) {
   582         MethodSymbol m = tree.sym;
   584         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   585         Lint prevLint = chk.setLint(lint);
   586         try {
   587             chk.checkDeprecatedAnnotation(tree.pos(), m);
   589             attribBounds(tree.typarams);
   591             // If we override any other methods, check that we do so properly.
   592             // JLS ???
   593             chk.checkOverride(tree, m);
   595             // Create a new environment with local scope
   596             // for attributing the method.
   597             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   599             localEnv.info.lint = lint;
   601             // Enter all type parameters into the local method scope.
   602             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   603                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   605             ClassSymbol owner = env.enclClass.sym;
   606             if ((owner.flags() & ANNOTATION) != 0 &&
   607                 tree.params.nonEmpty())
   608                 log.error(tree.params.head.pos(),
   609                           "intf.annotation.members.cant.have.params");
   611             // Attribute all value parameters.
   612             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   613                 attribStat(l.head, localEnv);
   614             }
   616             // Check that type parameters are well-formed.
   617             chk.validate(tree.typarams, localEnv);
   618             if ((owner.flags() & ANNOTATION) != 0 &&
   619                 tree.typarams.nonEmpty())
   620                 log.error(tree.typarams.head.pos(),
   621                           "intf.annotation.members.cant.have.type.params");
   623             // Check that result type is well-formed.
   624             chk.validate(tree.restype, localEnv);
   625             if ((owner.flags() & ANNOTATION) != 0)
   626                 chk.validateAnnotationType(tree.restype);
   628             if ((owner.flags() & ANNOTATION) != 0)
   629                 chk.validateAnnotationMethod(tree.pos(), m);
   631             // Check that all exceptions mentioned in the throws clause extend
   632             // java.lang.Throwable.
   633             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
   634                 log.error(tree.thrown.head.pos(),
   635                           "throws.not.allowed.in.intf.annotation");
   636             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   637                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   639             if (tree.body == null) {
   640                 // Empty bodies are only allowed for
   641                 // abstract, native, or interface methods, or for methods
   642                 // in a retrofit signature class.
   643                 if ((owner.flags() & INTERFACE) == 0 &&
   644                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   645                     !relax)
   646                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   647                 if (tree.defaultValue != null) {
   648                     if ((owner.flags() & ANNOTATION) == 0)
   649                         log.error(tree.pos(),
   650                                   "default.allowed.in.intf.annotation.member");
   651                 }
   652             } else if ((owner.flags() & INTERFACE) != 0) {
   653                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   654             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   655                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   656             } else if ((tree.mods.flags & NATIVE) != 0) {
   657                 log.error(tree.pos(), "native.meth.cant.have.body");
   658             } else {
   659                 // Add an implicit super() call unless an explicit call to
   660                 // super(...) or this(...) is given
   661                 // or we are compiling class java.lang.Object.
   662                 if (tree.name == names.init && owner.type != syms.objectType) {
   663                     JCBlock body = tree.body;
   664                     if (body.stats.isEmpty() ||
   665                         !TreeInfo.isSelfCall(body.stats.head)) {
   666                         body.stats = body.stats.
   667                             prepend(memberEnter.SuperCall(make.at(body.pos),
   668                                                           List.<Type>nil(),
   669                                                           List.<JCVariableDecl>nil(),
   670                                                           false));
   671                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   672                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   673                                TreeInfo.isSuperCall(body.stats.head)) {
   674                         // enum constructors are not allowed to call super
   675                         // directly, so make sure there aren't any super calls
   676                         // in enum constructors, except in the compiler
   677                         // generated one.
   678                         log.error(tree.body.stats.head.pos(),
   679                                   "call.to.super.not.allowed.in.enum.ctor",
   680                                   env.enclClass.sym);
   681                     }
   682                 }
   684                 // Attribute method body.
   685                 attribStat(tree.body, localEnv);
   686             }
   687             localEnv.info.scope.leave();
   688             result = tree.type = m.type;
   689             chk.validateAnnotations(tree.mods.annotations, m);
   691         }
   692         finally {
   693             chk.setLint(prevLint);
   694         }
   695     }
   697     public void visitVarDef(JCVariableDecl tree) {
   698         // Local variables have not been entered yet, so we need to do it now:
   699         if (env.info.scope.owner.kind == MTH) {
   700             if (tree.sym != null) {
   701                 // parameters have already been entered
   702                 env.info.scope.enter(tree.sym);
   703             } else {
   704                 memberEnter.memberEnter(tree, env);
   705                 annotate.flush();
   706             }
   707         }
   709         VarSymbol v = tree.sym;
   710         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   711         Lint prevLint = chk.setLint(lint);
   713         // Check that the variable's declared type is well-formed.
   714         chk.validate(tree.vartype, env);
   716         try {
   717             chk.checkDeprecatedAnnotation(tree.pos(), v);
   719             if (tree.init != null) {
   720                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   721                     // In this case, `v' is final.  Ensure that it's initializer is
   722                     // evaluated.
   723                     v.getConstValue(); // ensure initializer is evaluated
   724                 } else {
   725                     // Attribute initializer in a new environment
   726                     // with the declared variable as owner.
   727                     // Check that initializer conforms to variable's declared type.
   728                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   729                     initEnv.info.lint = lint;
   730                     // In order to catch self-references, we set the variable's
   731                     // declaration position to maximal possible value, effectively
   732                     // marking the variable as undefined.
   733                     initEnv.info.enclVar = v;
   734                     attribExpr(tree.init, initEnv, v.type);
   735                 }
   736             }
   737             result = tree.type = v.type;
   738             chk.validateAnnotations(tree.mods.annotations, v);
   739         }
   740         finally {
   741             chk.setLint(prevLint);
   742         }
   743     }
   745     public void visitSkip(JCSkip tree) {
   746         result = null;
   747     }
   749     public void visitBlock(JCBlock tree) {
   750         if (env.info.scope.owner.kind == TYP) {
   751             // Block is a static or instance initializer;
   752             // let the owner of the environment be a freshly
   753             // created BLOCK-method.
   754             Env<AttrContext> localEnv =
   755                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   756             localEnv.info.scope.owner =
   757                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   758                                  env.info.scope.owner);
   759             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   760             attribStats(tree.stats, localEnv);
   761         } else {
   762             // Create a new local environment with a local scope.
   763             Env<AttrContext> localEnv =
   764                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   765             attribStats(tree.stats, localEnv);
   766             localEnv.info.scope.leave();
   767         }
   768         result = null;
   769     }
   771     public void visitDoLoop(JCDoWhileLoop tree) {
   772         attribStat(tree.body, env.dup(tree));
   773         attribExpr(tree.cond, env, syms.booleanType);
   774         result = null;
   775     }
   777     public void visitWhileLoop(JCWhileLoop tree) {
   778         attribExpr(tree.cond, env, syms.booleanType);
   779         attribStat(tree.body, env.dup(tree));
   780         result = null;
   781     }
   783     public void visitForLoop(JCForLoop tree) {
   784         Env<AttrContext> loopEnv =
   785             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   786         attribStats(tree.init, loopEnv);
   787         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   788         loopEnv.tree = tree; // before, we were not in loop!
   789         attribStats(tree.step, loopEnv);
   790         attribStat(tree.body, loopEnv);
   791         loopEnv.info.scope.leave();
   792         result = null;
   793     }
   795     public void visitForeachLoop(JCEnhancedForLoop tree) {
   796         Env<AttrContext> loopEnv =
   797             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   798         attribStat(tree.var, loopEnv);
   799         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   800         chk.checkNonVoid(tree.pos(), exprType);
   801         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   802         if (elemtype == null) {
   803             // or perhaps expr implements Iterable<T>?
   804             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   805             if (base == null) {
   806                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   807                 elemtype = types.createErrorType(exprType);
   808             } else {
   809                 List<Type> iterableParams = base.allparams();
   810                 elemtype = iterableParams.isEmpty()
   811                     ? syms.objectType
   812                     : types.upperBound(iterableParams.head);
   813             }
   814         }
   815         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   816         loopEnv.tree = tree; // before, we were not in loop!
   817         attribStat(tree.body, loopEnv);
   818         loopEnv.info.scope.leave();
   819         result = null;
   820     }
   822     public void visitLabelled(JCLabeledStatement tree) {
   823         // Check that label is not used in an enclosing statement
   824         Env<AttrContext> env1 = env;
   825         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   826             if (env1.tree.getTag() == JCTree.LABELLED &&
   827                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   828                 log.error(tree.pos(), "label.already.in.use",
   829                           tree.label);
   830                 break;
   831             }
   832             env1 = env1.next;
   833         }
   835         attribStat(tree.body, env.dup(tree));
   836         result = null;
   837     }
   839     public void visitSwitch(JCSwitch tree) {
   840         Type seltype = attribExpr(tree.selector, env);
   842         Env<AttrContext> switchEnv =
   843             env.dup(tree, env.info.dup(env.info.scope.dup()));
   845         boolean enumSwitch =
   846             allowEnums &&
   847             (seltype.tsym.flags() & Flags.ENUM) != 0;
   848         if (!enumSwitch)
   849             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   851         // Attribute all cases and
   852         // check that there are no duplicate case labels or default clauses.
   853         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   854         boolean hasDefault = false;      // Is there a default label?
   855         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   856             JCCase c = l.head;
   857             Env<AttrContext> caseEnv =
   858                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   859             if (c.pat != null) {
   860                 if (enumSwitch) {
   861                     Symbol sym = enumConstant(c.pat, seltype);
   862                     if (sym == null) {
   863                         log.error(c.pat.pos(), "enum.const.req");
   864                     } else if (!labels.add(sym)) {
   865                         log.error(c.pos(), "duplicate.case.label");
   866                     }
   867                 } else {
   868                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   869                     if (pattype.tag != ERROR) {
   870                         if (pattype.constValue() == null) {
   871                             log.error(c.pat.pos(), "const.expr.req");
   872                         } else if (labels.contains(pattype.constValue())) {
   873                             log.error(c.pos(), "duplicate.case.label");
   874                         } else {
   875                             labels.add(pattype.constValue());
   876                         }
   877                     }
   878                 }
   879             } else if (hasDefault) {
   880                 log.error(c.pos(), "duplicate.default.label");
   881             } else {
   882                 hasDefault = true;
   883             }
   884             attribStats(c.stats, caseEnv);
   885             caseEnv.info.scope.leave();
   886             addVars(c.stats, switchEnv.info.scope);
   887         }
   889         switchEnv.info.scope.leave();
   890         result = null;
   891     }
   892     // where
   893         /** Add any variables defined in stats to the switch scope. */
   894         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   895             for (;stats.nonEmpty(); stats = stats.tail) {
   896                 JCTree stat = stats.head;
   897                 if (stat.getTag() == JCTree.VARDEF)
   898                     switchScope.enter(((JCVariableDecl) stat).sym);
   899             }
   900         }
   901     // where
   902     /** Return the selected enumeration constant symbol, or null. */
   903     private Symbol enumConstant(JCTree tree, Type enumType) {
   904         if (tree.getTag() != JCTree.IDENT) {
   905             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   906             return syms.errSymbol;
   907         }
   908         JCIdent ident = (JCIdent)tree;
   909         Name name = ident.name;
   910         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   911              e.scope != null; e = e.next()) {
   912             if (e.sym.kind == VAR) {
   913                 Symbol s = ident.sym = e.sym;
   914                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   915                 ident.type = s.type;
   916                 return ((s.flags_field & Flags.ENUM) == 0)
   917                     ? null : s;
   918             }
   919         }
   920         return null;
   921     }
   923     public void visitSynchronized(JCSynchronized tree) {
   924         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
   925         attribStat(tree.body, env);
   926         result = null;
   927     }
   929     public void visitTry(JCTry tree) {
   930         // Attribute body
   931         attribStat(tree.body, env.dup(tree, env.info.dup()));
   933         // Attribute catch clauses
   934         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   935             JCCatch c = l.head;
   936             Env<AttrContext> catchEnv =
   937                 env.dup(c, env.info.dup(env.info.scope.dup()));
   938             Type ctype = attribStat(c.param, catchEnv);
   939             if (c.param.type.tsym.kind == Kinds.VAR) {
   940                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
   941             }
   942             chk.checkType(c.param.vartype.pos(),
   943                           chk.checkClassType(c.param.vartype.pos(), ctype),
   944                           syms.throwableType);
   945             attribStat(c.body, catchEnv);
   946             catchEnv.info.scope.leave();
   947         }
   949         // Attribute finalizer
   950         if (tree.finalizer != null) attribStat(tree.finalizer, env);
   951         result = null;
   952     }
   954     public void visitConditional(JCConditional tree) {
   955         attribExpr(tree.cond, env, syms.booleanType);
   956         attribExpr(tree.truepart, env);
   957         attribExpr(tree.falsepart, env);
   958         result = check(tree,
   959                        capture(condType(tree.pos(), tree.cond.type,
   960                                         tree.truepart.type, tree.falsepart.type)),
   961                        VAL, pkind, pt);
   962     }
   963     //where
   964         /** Compute the type of a conditional expression, after
   965          *  checking that it exists. See Spec 15.25.
   966          *
   967          *  @param pos      The source position to be used for
   968          *                  error diagnostics.
   969          *  @param condtype The type of the expression's condition.
   970          *  @param thentype The type of the expression's then-part.
   971          *  @param elsetype The type of the expression's else-part.
   972          */
   973         private Type condType(DiagnosticPosition pos,
   974                               Type condtype,
   975                               Type thentype,
   976                               Type elsetype) {
   977             Type ctype = condType1(pos, condtype, thentype, elsetype);
   979             // If condition and both arms are numeric constants,
   980             // evaluate at compile-time.
   981             return ((condtype.constValue() != null) &&
   982                     (thentype.constValue() != null) &&
   983                     (elsetype.constValue() != null))
   984                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
   985                 : ctype;
   986         }
   987         /** Compute the type of a conditional expression, after
   988          *  checking that it exists.  Does not take into
   989          *  account the special case where condition and both arms
   990          *  are constants.
   991          *
   992          *  @param pos      The source position to be used for error
   993          *                  diagnostics.
   994          *  @param condtype The type of the expression's condition.
   995          *  @param thentype The type of the expression's then-part.
   996          *  @param elsetype The type of the expression's else-part.
   997          */
   998         private Type condType1(DiagnosticPosition pos, Type condtype,
   999                                Type thentype, Type elsetype) {
  1000             // If same type, that is the result
  1001             if (types.isSameType(thentype, elsetype))
  1002                 return thentype.baseType();
  1004             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1005                 ? thentype : types.unboxedType(thentype);
  1006             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1007                 ? elsetype : types.unboxedType(elsetype);
  1009             // Otherwise, if both arms can be converted to a numeric
  1010             // type, return the least numeric type that fits both arms
  1011             // (i.e. return larger of the two, or return int if one
  1012             // arm is short, the other is char).
  1013             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1014                 // If one arm has an integer subrange type (i.e., byte,
  1015                 // short, or char), and the other is an integer constant
  1016                 // that fits into the subrange, return the subrange type.
  1017                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1018                     types.isAssignable(elseUnboxed, thenUnboxed))
  1019                     return thenUnboxed.baseType();
  1020                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1021                     types.isAssignable(thenUnboxed, elseUnboxed))
  1022                     return elseUnboxed.baseType();
  1024                 for (int i = BYTE; i < VOID; i++) {
  1025                     Type candidate = syms.typeOfTag[i];
  1026                     if (types.isSubtype(thenUnboxed, candidate) &&
  1027                         types.isSubtype(elseUnboxed, candidate))
  1028                         return candidate;
  1032             // Those were all the cases that could result in a primitive
  1033             if (allowBoxing) {
  1034                 if (thentype.isPrimitive())
  1035                     thentype = types.boxedClass(thentype).type;
  1036                 if (elsetype.isPrimitive())
  1037                     elsetype = types.boxedClass(elsetype).type;
  1040             if (types.isSubtype(thentype, elsetype))
  1041                 return elsetype.baseType();
  1042             if (types.isSubtype(elsetype, thentype))
  1043                 return thentype.baseType();
  1045             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1046                 log.error(pos, "neither.conditional.subtype",
  1047                           thentype, elsetype);
  1048                 return thentype.baseType();
  1051             // both are known to be reference types.  The result is
  1052             // lub(thentype,elsetype). This cannot fail, as it will
  1053             // always be possible to infer "Object" if nothing better.
  1054             return types.lub(thentype.baseType(), elsetype.baseType());
  1057     public void visitIf(JCIf tree) {
  1058         attribExpr(tree.cond, env, syms.booleanType);
  1059         attribStat(tree.thenpart, env);
  1060         if (tree.elsepart != null)
  1061             attribStat(tree.elsepart, env);
  1062         chk.checkEmptyIf(tree);
  1063         result = null;
  1066     public void visitExec(JCExpressionStatement tree) {
  1067         attribExpr(tree.expr, env);
  1068         result = null;
  1071     public void visitBreak(JCBreak tree) {
  1072         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1073         result = null;
  1076     public void visitContinue(JCContinue tree) {
  1077         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1078         result = null;
  1080     //where
  1081         /** Return the target of a break or continue statement, if it exists,
  1082          *  report an error if not.
  1083          *  Note: The target of a labelled break or continue is the
  1084          *  (non-labelled) statement tree referred to by the label,
  1085          *  not the tree representing the labelled statement itself.
  1087          *  @param pos     The position to be used for error diagnostics
  1088          *  @param tag     The tag of the jump statement. This is either
  1089          *                 Tree.BREAK or Tree.CONTINUE.
  1090          *  @param label   The label of the jump statement, or null if no
  1091          *                 label is given.
  1092          *  @param env     The environment current at the jump statement.
  1093          */
  1094         private JCTree findJumpTarget(DiagnosticPosition pos,
  1095                                     int tag,
  1096                                     Name label,
  1097                                     Env<AttrContext> env) {
  1098             // Search environments outwards from the point of jump.
  1099             Env<AttrContext> env1 = env;
  1100             LOOP:
  1101             while (env1 != null) {
  1102                 switch (env1.tree.getTag()) {
  1103                 case JCTree.LABELLED:
  1104                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1105                     if (label == labelled.label) {
  1106                         // If jump is a continue, check that target is a loop.
  1107                         if (tag == JCTree.CONTINUE) {
  1108                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1109                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1110                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1111                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1112                                 log.error(pos, "not.loop.label", label);
  1113                             // Found labelled statement target, now go inwards
  1114                             // to next non-labelled tree.
  1115                             return TreeInfo.referencedStatement(labelled);
  1116                         } else {
  1117                             return labelled;
  1120                     break;
  1121                 case JCTree.DOLOOP:
  1122                 case JCTree.WHILELOOP:
  1123                 case JCTree.FORLOOP:
  1124                 case JCTree.FOREACHLOOP:
  1125                     if (label == null) return env1.tree;
  1126                     break;
  1127                 case JCTree.SWITCH:
  1128                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1129                     break;
  1130                 case JCTree.METHODDEF:
  1131                 case JCTree.CLASSDEF:
  1132                     break LOOP;
  1133                 default:
  1135                 env1 = env1.next;
  1137             if (label != null)
  1138                 log.error(pos, "undef.label", label);
  1139             else if (tag == JCTree.CONTINUE)
  1140                 log.error(pos, "cont.outside.loop");
  1141             else
  1142                 log.error(pos, "break.outside.switch.loop");
  1143             return null;
  1146     public void visitReturn(JCReturn tree) {
  1147         // Check that there is an enclosing method which is
  1148         // nested within than the enclosing class.
  1149         if (env.enclMethod == null ||
  1150             env.enclMethod.sym.owner != env.enclClass.sym) {
  1151             log.error(tree.pos(), "ret.outside.meth");
  1153         } else {
  1154             // Attribute return expression, if it exists, and check that
  1155             // it conforms to result type of enclosing method.
  1156             Symbol m = env.enclMethod.sym;
  1157             if (m.type.getReturnType().tag == VOID) {
  1158                 if (tree.expr != null)
  1159                     log.error(tree.expr.pos(),
  1160                               "cant.ret.val.from.meth.decl.void");
  1161             } else if (tree.expr == null) {
  1162                 log.error(tree.pos(), "missing.ret.val");
  1163             } else {
  1164                 attribExpr(tree.expr, env, m.type.getReturnType());
  1167         result = null;
  1170     public void visitThrow(JCThrow tree) {
  1171         attribExpr(tree.expr, env, syms.throwableType);
  1172         result = null;
  1175     public void visitAssert(JCAssert tree) {
  1176         attribExpr(tree.cond, env, syms.booleanType);
  1177         if (tree.detail != null) {
  1178             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1180         result = null;
  1183      /** Visitor method for method invocations.
  1184      *  NOTE: The method part of an application will have in its type field
  1185      *        the return type of the method, not the method's type itself!
  1186      */
  1187     public void visitApply(JCMethodInvocation tree) {
  1188         // The local environment of a method application is
  1189         // a new environment nested in the current one.
  1190         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1192         // The types of the actual method arguments.
  1193         List<Type> argtypes;
  1195         // The types of the actual method type arguments.
  1196         List<Type> typeargtypes = null;
  1198         Name methName = TreeInfo.name(tree.meth);
  1200         boolean isConstructorCall =
  1201             methName == names._this || methName == names._super;
  1203         if (isConstructorCall) {
  1204             // We are seeing a ...this(...) or ...super(...) call.
  1205             // Check that this is the first statement in a constructor.
  1206             if (checkFirstConstructorStat(tree, env)) {
  1208                 // Record the fact
  1209                 // that this is a constructor call (using isSelfCall).
  1210                 localEnv.info.isSelfCall = true;
  1212                 // Attribute arguments, yielding list of argument types.
  1213                 argtypes = attribArgs(tree.args, localEnv);
  1214                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1216                 // Variable `site' points to the class in which the called
  1217                 // constructor is defined.
  1218                 Type site = env.enclClass.sym.type;
  1219                 if (methName == names._super) {
  1220                     if (site == syms.objectType) {
  1221                         log.error(tree.meth.pos(), "no.superclass", site);
  1222                         site = types.createErrorType(syms.objectType);
  1223                     } else {
  1224                         site = types.supertype(site);
  1228                 if (site.tag == CLASS) {
  1229                     if (site.getEnclosingType().tag == CLASS) {
  1230                         // we are calling a nested class
  1232                         if (tree.meth.getTag() == JCTree.SELECT) {
  1233                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1235                             // We are seeing a prefixed call, of the form
  1236                             //     <expr>.super(...).
  1237                             // Check that the prefix expression conforms
  1238                             // to the outer instance type of the class.
  1239                             chk.checkRefType(qualifier.pos(),
  1240                                              attribExpr(qualifier, localEnv,
  1241                                                         site.getEnclosingType()));
  1242                         } else if (methName == names._super) {
  1243                             // qualifier omitted; check for existence
  1244                             // of an appropriate implicit qualifier.
  1245                             rs.resolveImplicitThis(tree.meth.pos(),
  1246                                                    localEnv, site);
  1248                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1249                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1250                                   site.tsym);
  1253                     // if we're calling a java.lang.Enum constructor,
  1254                     // prefix the implicit String and int parameters
  1255                     if (site.tsym == syms.enumSym && allowEnums)
  1256                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1258                     // Resolve the called constructor under the assumption
  1259                     // that we are referring to a superclass instance of the
  1260                     // current instance (JLS ???).
  1261                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1262                     localEnv.info.selectSuper = true;
  1263                     localEnv.info.varArgs = false;
  1264                     Symbol sym = rs.resolveConstructor(
  1265                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1266                     localEnv.info.selectSuper = selectSuperPrev;
  1268                     // Set method symbol to resolved constructor...
  1269                     TreeInfo.setSymbol(tree.meth, sym);
  1271                     // ...and check that it is legal in the current context.
  1272                     // (this will also set the tree's type)
  1273                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1274                     checkId(tree.meth, site, sym, localEnv, MTH,
  1275                             mpt, tree.varargsElement != null);
  1277                 // Otherwise, `site' is an error type and we do nothing
  1279             result = tree.type = syms.voidType;
  1280         } else {
  1281             // Otherwise, we are seeing a regular method call.
  1282             // Attribute the arguments, yielding list of argument types, ...
  1283             argtypes = attribArgs(tree.args, localEnv);
  1284             typeargtypes = attribTypes(tree.typeargs, localEnv);
  1286             // ... and attribute the method using as a prototype a methodtype
  1287             // whose formal argument types is exactly the list of actual
  1288             // arguments (this will also set the method symbol).
  1289             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1290             localEnv.info.varArgs = false;
  1291             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1292             if (localEnv.info.varArgs)
  1293                 assert mtype.isErroneous() || tree.varargsElement != null;
  1295             // Compute the result type.
  1296             Type restype = mtype.getReturnType();
  1297             assert restype.tag != WILDCARD : mtype;
  1299             // as a special case, array.clone() has a result that is
  1300             // the same as static type of the array being cloned
  1301             if (tree.meth.getTag() == JCTree.SELECT &&
  1302                 allowCovariantReturns &&
  1303                 methName == names.clone &&
  1304                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1305                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1307             // as a special case, x.getClass() has type Class<? extends |X|>
  1308             if (allowGenerics &&
  1309                 methName == names.getClass && tree.args.isEmpty()) {
  1310                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1311                     ? ((JCFieldAccess) tree.meth).selected.type
  1312                     : env.enclClass.sym.type;
  1313                 restype = new
  1314                     ClassType(restype.getEnclosingType(),
  1315                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1316                                                                BoundKind.EXTENDS,
  1317                                                                syms.boundClass)),
  1318                               restype.tsym);
  1321             // Check that value of resulting type is admissible in the
  1322             // current context.  Also, capture the return type
  1323             result = check(tree, capture(restype), VAL, pkind, pt);
  1325         chk.validate(tree.typeargs, localEnv);
  1327     //where
  1328         /** Check that given application node appears as first statement
  1329          *  in a constructor call.
  1330          *  @param tree   The application node
  1331          *  @param env    The environment current at the application.
  1332          */
  1333         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1334             JCMethodDecl enclMethod = env.enclMethod;
  1335             if (enclMethod != null && enclMethod.name == names.init) {
  1336                 JCBlock body = enclMethod.body;
  1337                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1338                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1339                     return true;
  1341             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1342                       TreeInfo.name(tree.meth));
  1343             return false;
  1346         /** Obtain a method type with given argument types.
  1347          */
  1348         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1349             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1350             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1353     public void visitNewClass(JCNewClass tree) {
  1354         Type owntype = types.createErrorType(tree.type);
  1356         // The local environment of a class creation is
  1357         // a new environment nested in the current one.
  1358         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1360         // The anonymous inner class definition of the new expression,
  1361         // if one is defined by it.
  1362         JCClassDecl cdef = tree.def;
  1364         // If enclosing class is given, attribute it, and
  1365         // complete class name to be fully qualified
  1366         JCExpression clazz = tree.clazz; // Class field following new
  1367         JCExpression clazzid =          // Identifier in class field
  1368             (clazz.getTag() == JCTree.TYPEAPPLY)
  1369             ? ((JCTypeApply) clazz).clazz
  1370             : clazz;
  1372         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1374         if (tree.encl != null) {
  1375             // We are seeing a qualified new, of the form
  1376             //    <expr>.new C <...> (...) ...
  1377             // In this case, we let clazz stand for the name of the
  1378             // allocated class C prefixed with the type of the qualifier
  1379             // expression, so that we can
  1380             // resolve it with standard techniques later. I.e., if
  1381             // <expr> has type T, then <expr>.new C <...> (...)
  1382             // yields a clazz T.C.
  1383             Type encltype = chk.checkRefType(tree.encl.pos(),
  1384                                              attribExpr(tree.encl, env));
  1385             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1386                                                  ((JCIdent) clazzid).name);
  1387             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1388                 clazz = make.at(tree.pos).
  1389                     TypeApply(clazzid1,
  1390                               ((JCTypeApply) clazz).arguments);
  1391             else
  1392                 clazz = clazzid1;
  1393 //          System.out.println(clazz + " generated.");//DEBUG
  1396         // Attribute clazz expression and store
  1397         // symbol + type back into the attributed tree.
  1398         Type clazztype = chk.checkClassType(
  1399             tree.clazz.pos(), attribType(clazz, env), true);
  1400         chk.validate(clazz, localEnv);
  1401         if (tree.encl != null) {
  1402             // We have to work in this case to store
  1403             // symbol + type back into the attributed tree.
  1404             tree.clazz.type = clazztype;
  1405             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1406             clazzid.type = ((JCIdent) clazzid).sym.type;
  1407             if (!clazztype.isErroneous()) {
  1408                 if (cdef != null && clazztype.tsym.isInterface()) {
  1409                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1410                 } else if (clazztype.tsym.isStatic()) {
  1411                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1414         } else if (!clazztype.tsym.isInterface() &&
  1415                    clazztype.getEnclosingType().tag == CLASS) {
  1416             // Check for the existence of an apropos outer instance
  1417             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1420         // Attribute constructor arguments.
  1421         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1422         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1424         // If we have made no mistakes in the class type...
  1425         if (clazztype.tag == CLASS) {
  1426             // Enums may not be instantiated except implicitly
  1427             if (allowEnums &&
  1428                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1429                 (env.tree.getTag() != JCTree.VARDEF ||
  1430                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1431                  ((JCVariableDecl) env.tree).init != tree))
  1432                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1433             // Check that class is not abstract
  1434             if (cdef == null &&
  1435                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1436                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1437                           clazztype.tsym);
  1438             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1439                 // Check that no constructor arguments are given to
  1440                 // anonymous classes implementing an interface
  1441                 if (!argtypes.isEmpty())
  1442                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1444                 if (!typeargtypes.isEmpty())
  1445                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1447                 // Error recovery: pretend no arguments were supplied.
  1448                 argtypes = List.nil();
  1449                 typeargtypes = List.nil();
  1452             // Resolve the called constructor under the assumption
  1453             // that we are referring to a superclass instance of the
  1454             // current instance (JLS ???).
  1455             else {
  1456                 localEnv.info.selectSuper = cdef != null;
  1457                 localEnv.info.varArgs = false;
  1458                 tree.constructor = rs.resolveConstructor(
  1459                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1460                 tree.constructorType = checkMethod(clazztype,
  1461                                             tree.constructor,
  1462                                             localEnv,
  1463                                             tree.args,
  1464                                             argtypes,
  1465                                             typeargtypes,
  1466                                             localEnv.info.varArgs);
  1467                 if (localEnv.info.varArgs)
  1468                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
  1471             if (cdef != null) {
  1472                 // We are seeing an anonymous class instance creation.
  1473                 // In this case, the class instance creation
  1474                 // expression
  1475                 //
  1476                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1477                 //
  1478                 // is represented internally as
  1479                 //
  1480                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1481                 //
  1482                 // This expression is then *transformed* as follows:
  1483                 //
  1484                 // (1) add a STATIC flag to the class definition
  1485                 //     if the current environment is static
  1486                 // (2) add an extends or implements clause
  1487                 // (3) add a constructor.
  1488                 //
  1489                 // For instance, if C is a class, and ET is the type of E,
  1490                 // the expression
  1491                 //
  1492                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1493                 //
  1494                 // is translated to (where X is a fresh name and typarams is the
  1495                 // parameter list of the super constructor):
  1496                 //
  1497                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1498                 //     X extends C<typargs2> {
  1499                 //       <typarams> X(ET e, args) {
  1500                 //         e.<typeargs1>super(args)
  1501                 //       }
  1502                 //       ...
  1503                 //     }
  1504                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1506                 if (clazztype.tsym.isInterface()) {
  1507                     cdef.implementing = List.of(clazz);
  1508                 } else {
  1509                     cdef.extending = clazz;
  1512                 attribStat(cdef, localEnv);
  1514                 // If an outer instance is given,
  1515                 // prefix it to the constructor arguments
  1516                 // and delete it from the new expression
  1517                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1518                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1519                     argtypes = argtypes.prepend(tree.encl.type);
  1520                     tree.encl = null;
  1523                 // Reassign clazztype and recompute constructor.
  1524                 clazztype = cdef.sym.type;
  1525                 Symbol sym = rs.resolveConstructor(
  1526                     tree.pos(), localEnv, clazztype, argtypes,
  1527                     typeargtypes, true, tree.varargsElement != null);
  1528                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1529                 tree.constructor = sym;
  1530                 tree.constructorType = checkMethod(clazztype,
  1531                                             tree.constructor,
  1532                                             localEnv,
  1533                                             tree.args,
  1534                                             argtypes,
  1535                                             typeargtypes,
  1536                                             localEnv.info.varArgs);
  1539             if (tree.constructor != null && tree.constructor.kind == MTH)
  1540                 owntype = clazztype;
  1542         result = check(tree, owntype, VAL, pkind, pt);
  1543         chk.validate(tree.typeargs, localEnv);
  1546     /** Make an attributed null check tree.
  1547      */
  1548     public JCExpression makeNullCheck(JCExpression arg) {
  1549         // optimization: X.this is never null; skip null check
  1550         Name name = TreeInfo.name(arg);
  1551         if (name == names._this || name == names._super) return arg;
  1553         int optag = JCTree.NULLCHK;
  1554         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1555         tree.operator = syms.nullcheck;
  1556         tree.type = arg.type;
  1557         return tree;
  1560     public void visitNewArray(JCNewArray tree) {
  1561         Type owntype = types.createErrorType(tree.type);
  1562         Type elemtype;
  1563         if (tree.elemtype != null) {
  1564             elemtype = attribType(tree.elemtype, env);
  1565             chk.validate(tree.elemtype, env);
  1566             owntype = elemtype;
  1567             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1568                 attribExpr(l.head, env, syms.intType);
  1569                 owntype = new ArrayType(owntype, syms.arrayClass);
  1571         } else {
  1572             // we are seeing an untyped aggregate { ... }
  1573             // this is allowed only if the prototype is an array
  1574             if (pt.tag == ARRAY) {
  1575                 elemtype = types.elemtype(pt);
  1576             } else {
  1577                 if (pt.tag != ERROR) {
  1578                     log.error(tree.pos(), "illegal.initializer.for.type",
  1579                               pt);
  1581                 elemtype = types.createErrorType(pt);
  1584         if (tree.elems != null) {
  1585             attribExprs(tree.elems, env, elemtype);
  1586             owntype = new ArrayType(elemtype, syms.arrayClass);
  1588         if (!types.isReifiable(elemtype))
  1589             log.error(tree.pos(), "generic.array.creation");
  1590         result = check(tree, owntype, VAL, pkind, pt);
  1593     public void visitParens(JCParens tree) {
  1594         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1595         result = check(tree, owntype, pkind, pkind, pt);
  1596         Symbol sym = TreeInfo.symbol(tree);
  1597         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1598             log.error(tree.pos(), "illegal.start.of.type");
  1601     public void visitAssign(JCAssign tree) {
  1602         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1603         Type capturedType = capture(owntype);
  1604         attribExpr(tree.rhs, env, owntype);
  1605         result = check(tree, capturedType, VAL, pkind, pt);
  1608     public void visitAssignop(JCAssignOp tree) {
  1609         // Attribute arguments.
  1610         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1611         Type operand = attribExpr(tree.rhs, env);
  1612         // Find operator.
  1613         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1614             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1615             owntype, operand);
  1617         if (operator.kind == MTH) {
  1618             chk.checkOperator(tree.pos(),
  1619                               (OperatorSymbol)operator,
  1620                               tree.getTag() - JCTree.ASGOffset,
  1621                               owntype,
  1622                               operand);
  1623             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1624             chk.checkCastable(tree.rhs.pos(),
  1625                               operator.type.getReturnType(),
  1626                               owntype);
  1628         result = check(tree, owntype, VAL, pkind, pt);
  1631     public void visitUnary(JCUnary tree) {
  1632         // Attribute arguments.
  1633         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1634             ? attribTree(tree.arg, env, VAR, Type.noType)
  1635             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1637         // Find operator.
  1638         Symbol operator = tree.operator =
  1639             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1641         Type owntype = types.createErrorType(tree.type);
  1642         if (operator.kind == MTH) {
  1643             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1644                 ? tree.arg.type
  1645                 : operator.type.getReturnType();
  1646             int opc = ((OperatorSymbol)operator).opcode;
  1648             // If the argument is constant, fold it.
  1649             if (argtype.constValue() != null) {
  1650                 Type ctype = cfolder.fold1(opc, argtype);
  1651                 if (ctype != null) {
  1652                     owntype = cfolder.coerce(ctype, owntype);
  1654                     // Remove constant types from arguments to
  1655                     // conserve space. The parser will fold concatenations
  1656                     // of string literals; the code here also
  1657                     // gets rid of intermediate results when some of the
  1658                     // operands are constant identifiers.
  1659                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1660                         tree.arg.type = syms.stringType;
  1665         result = check(tree, owntype, VAL, pkind, pt);
  1668     public void visitBinary(JCBinary tree) {
  1669         // Attribute arguments.
  1670         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1671         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1673         // Find operator.
  1674         Symbol operator = tree.operator =
  1675             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1677         Type owntype = types.createErrorType(tree.type);
  1678         if (operator.kind == MTH) {
  1679             owntype = operator.type.getReturnType();
  1680             int opc = chk.checkOperator(tree.lhs.pos(),
  1681                                         (OperatorSymbol)operator,
  1682                                         tree.getTag(),
  1683                                         left,
  1684                                         right);
  1686             // If both arguments are constants, fold them.
  1687             if (left.constValue() != null && right.constValue() != null) {
  1688                 Type ctype = cfolder.fold2(opc, left, right);
  1689                 if (ctype != null) {
  1690                     owntype = cfolder.coerce(ctype, owntype);
  1692                     // Remove constant types from arguments to
  1693                     // conserve space. The parser will fold concatenations
  1694                     // of string literals; the code here also
  1695                     // gets rid of intermediate results when some of the
  1696                     // operands are constant identifiers.
  1697                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1698                         tree.lhs.type = syms.stringType;
  1700                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1701                         tree.rhs.type = syms.stringType;
  1706             // Check that argument types of a reference ==, != are
  1707             // castable to each other, (JLS???).
  1708             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  1709                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  1710                     log.error(tree.pos(), "incomparable.types", left, right);
  1714             chk.checkDivZero(tree.rhs.pos(), operator, right);
  1716         result = check(tree, owntype, VAL, pkind, pt);
  1719     public void visitTypeCast(JCTypeCast tree) {
  1720         Type clazztype = attribType(tree.clazz, env);
  1721         chk.validate(tree.clazz, env);
  1722         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  1723         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1724         if (exprtype.constValue() != null)
  1725             owntype = cfolder.coerce(exprtype, owntype);
  1726         result = check(tree, capture(owntype), VAL, pkind, pt);
  1729     public void visitTypeTest(JCInstanceOf tree) {
  1730         Type exprtype = chk.checkNullOrRefType(
  1731             tree.expr.pos(), attribExpr(tree.expr, env));
  1732         Type clazztype = chk.checkReifiableReferenceType(
  1733             tree.clazz.pos(), attribType(tree.clazz, env));
  1734         chk.validate(tree.clazz, env);
  1735         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1736         result = check(tree, syms.booleanType, VAL, pkind, pt);
  1739     public void visitIndexed(JCArrayAccess tree) {
  1740         Type owntype = types.createErrorType(tree.type);
  1741         Type atype = attribExpr(tree.indexed, env);
  1742         attribExpr(tree.index, env, syms.intType);
  1743         if (types.isArray(atype))
  1744             owntype = types.elemtype(atype);
  1745         else if (atype.tag != ERROR)
  1746             log.error(tree.pos(), "array.req.but.found", atype);
  1747         if ((pkind & VAR) == 0) owntype = capture(owntype);
  1748         result = check(tree, owntype, VAR, pkind, pt);
  1751     public void visitIdent(JCIdent tree) {
  1752         Symbol sym;
  1753         boolean varArgs = false;
  1755         // Find symbol
  1756         if (pt.tag == METHOD || pt.tag == FORALL) {
  1757             // If we are looking for a method, the prototype `pt' will be a
  1758             // method type with the type of the call's arguments as parameters.
  1759             env.info.varArgs = false;
  1760             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  1761             varArgs = env.info.varArgs;
  1762         } else if (tree.sym != null && tree.sym.kind != VAR) {
  1763             sym = tree.sym;
  1764         } else {
  1765             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  1767         tree.sym = sym;
  1769         // (1) Also find the environment current for the class where
  1770         //     sym is defined (`symEnv').
  1771         // Only for pre-tiger versions (1.4 and earlier):
  1772         // (2) Also determine whether we access symbol out of an anonymous
  1773         //     class in a this or super call.  This is illegal for instance
  1774         //     members since such classes don't carry a this$n link.
  1775         //     (`noOuterThisPath').
  1776         Env<AttrContext> symEnv = env;
  1777         boolean noOuterThisPath = false;
  1778         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  1779             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  1780             sym.owner.kind == TYP &&
  1781             tree.name != names._this && tree.name != names._super) {
  1783             // Find environment in which identifier is defined.
  1784             while (symEnv.outer != null &&
  1785                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  1786                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  1787                     noOuterThisPath = !allowAnonOuterThis;
  1788                 symEnv = symEnv.outer;
  1792         // If symbol is a variable, ...
  1793         if (sym.kind == VAR) {
  1794             VarSymbol v = (VarSymbol)sym;
  1796             // ..., evaluate its initializer, if it has one, and check for
  1797             // illegal forward reference.
  1798             checkInit(tree, env, v, false);
  1800             // If symbol is a local variable accessed from an embedded
  1801             // inner class check that it is final.
  1802             if (v.owner.kind == MTH &&
  1803                 v.owner != env.info.scope.owner &&
  1804                 (v.flags_field & FINAL) == 0) {
  1805                 log.error(tree.pos(),
  1806                           "local.var.accessed.from.icls.needs.final",
  1807                           v);
  1810             // If we are expecting a variable (as opposed to a value), check
  1811             // that the variable is assignable in the current environment.
  1812             if (pkind == VAR)
  1813                 checkAssignable(tree.pos(), v, null, env);
  1816         // In a constructor body,
  1817         // if symbol is a field or instance method, check that it is
  1818         // not accessed before the supertype constructor is called.
  1819         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  1820             (sym.kind & (VAR | MTH)) != 0 &&
  1821             sym.owner.kind == TYP &&
  1822             (sym.flags() & STATIC) == 0) {
  1823             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  1825         Env<AttrContext> env1 = env;
  1826         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  1827             // If the found symbol is inaccessible, then it is
  1828             // accessed through an enclosing instance.  Locate this
  1829             // enclosing instance:
  1830             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  1831                 env1 = env1.outer;
  1833         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  1836     public void visitSelect(JCFieldAccess tree) {
  1837         // Determine the expected kind of the qualifier expression.
  1838         int skind = 0;
  1839         if (tree.name == names._this || tree.name == names._super ||
  1840             tree.name == names._class)
  1842             skind = TYP;
  1843         } else {
  1844             if ((pkind & PCK) != 0) skind = skind | PCK;
  1845             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  1846             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  1849         // Attribute the qualifier expression, and determine its symbol (if any).
  1850         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  1851         if ((pkind & (PCK | TYP)) == 0)
  1852             site = capture(site); // Capture field access
  1854         // don't allow T.class T[].class, etc
  1855         if (skind == TYP) {
  1856             Type elt = site;
  1857             while (elt.tag == ARRAY)
  1858                 elt = ((ArrayType)elt).elemtype;
  1859             if (elt.tag == TYPEVAR) {
  1860                 log.error(tree.pos(), "type.var.cant.be.deref");
  1861                 result = types.createErrorType(tree.type);
  1862                 return;
  1866         // If qualifier symbol is a type or `super', assert `selectSuper'
  1867         // for the selection. This is relevant for determining whether
  1868         // protected symbols are accessible.
  1869         Symbol sitesym = TreeInfo.symbol(tree.selected);
  1870         boolean selectSuperPrev = env.info.selectSuper;
  1871         env.info.selectSuper =
  1872             sitesym != null &&
  1873             sitesym.name == names._super;
  1875         // If selected expression is polymorphic, strip
  1876         // type parameters and remember in env.info.tvars, so that
  1877         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  1878         if (tree.selected.type.tag == FORALL) {
  1879             ForAll pstype = (ForAll)tree.selected.type;
  1880             env.info.tvars = pstype.tvars;
  1881             site = tree.selected.type = pstype.qtype;
  1884         // Determine the symbol represented by the selection.
  1885         env.info.varArgs = false;
  1886         Symbol sym = selectSym(tree, site, env, pt, pkind);
  1887         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  1888             site = capture(site);
  1889             sym = selectSym(tree, site, env, pt, pkind);
  1891         boolean varArgs = env.info.varArgs;
  1892         tree.sym = sym;
  1894         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  1895             while (site.tag == TYPEVAR) site = site.getUpperBound();
  1896             site = capture(site);
  1899         // If that symbol is a variable, ...
  1900         if (sym.kind == VAR) {
  1901             VarSymbol v = (VarSymbol)sym;
  1903             // ..., evaluate its initializer, if it has one, and check for
  1904             // illegal forward reference.
  1905             checkInit(tree, env, v, true);
  1907             // If we are expecting a variable (as opposed to a value), check
  1908             // that the variable is assignable in the current environment.
  1909             if (pkind == VAR)
  1910                 checkAssignable(tree.pos(), v, tree.selected, env);
  1913         // Disallow selecting a type from an expression
  1914         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  1915             tree.type = check(tree.selected, pt,
  1916                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  1919         if (isType(sitesym)) {
  1920             if (sym.name == names._this) {
  1921                 // If `C' is the currently compiled class, check that
  1922                 // C.this' does not appear in a call to a super(...)
  1923                 if (env.info.isSelfCall &&
  1924                     site.tsym == env.enclClass.sym) {
  1925                     chk.earlyRefError(tree.pos(), sym);
  1927             } else {
  1928                 // Check if type-qualified fields or methods are static (JLS)
  1929                 if ((sym.flags() & STATIC) == 0 &&
  1930                     sym.name != names._super &&
  1931                     (sym.kind == VAR || sym.kind == MTH)) {
  1932                     rs.access(rs.new StaticError(sym),
  1933                               tree.pos(), site, sym.name, true);
  1938         // If we are selecting an instance member via a `super', ...
  1939         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  1941             // Check that super-qualified symbols are not abstract (JLS)
  1942             rs.checkNonAbstract(tree.pos(), sym);
  1944             if (site.isRaw()) {
  1945                 // Determine argument types for site.
  1946                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  1947                 if (site1 != null) site = site1;
  1951         env.info.selectSuper = selectSuperPrev;
  1952         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  1953         env.info.tvars = List.nil();
  1955     //where
  1956         /** Determine symbol referenced by a Select expression,
  1958          *  @param tree   The select tree.
  1959          *  @param site   The type of the selected expression,
  1960          *  @param env    The current environment.
  1961          *  @param pt     The current prototype.
  1962          *  @param pkind  The expected kind(s) of the Select expression.
  1963          */
  1964         private Symbol selectSym(JCFieldAccess tree,
  1965                                  Type site,
  1966                                  Env<AttrContext> env,
  1967                                  Type pt,
  1968                                  int pkind) {
  1969             DiagnosticPosition pos = tree.pos();
  1970             Name name = tree.name;
  1972             switch (site.tag) {
  1973             case PACKAGE:
  1974                 return rs.access(
  1975                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  1976                     pos, site, name, true);
  1977             case ARRAY:
  1978             case CLASS:
  1979                 if (pt.tag == METHOD || pt.tag == FORALL) {
  1980                     return rs.resolveQualifiedMethod(
  1981                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  1982                 } else if (name == names._this || name == names._super) {
  1983                     return rs.resolveSelf(pos, env, site.tsym, name);
  1984                 } else if (name == names._class) {
  1985                     // In this case, we have already made sure in
  1986                     // visitSelect that qualifier expression is a type.
  1987                     Type t = syms.classType;
  1988                     List<Type> typeargs = allowGenerics
  1989                         ? List.of(types.erasure(site))
  1990                         : List.<Type>nil();
  1991                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  1992                     return new VarSymbol(
  1993                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  1994                 } else {
  1995                     // We are seeing a plain identifier as selector.
  1996                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  1997                     if ((pkind & ERRONEOUS) == 0)
  1998                         sym = rs.access(sym, pos, site, name, true);
  1999                     return sym;
  2001             case WILDCARD:
  2002                 throw new AssertionError(tree);
  2003             case TYPEVAR:
  2004                 // Normally, site.getUpperBound() shouldn't be null.
  2005                 // It should only happen during memberEnter/attribBase
  2006                 // when determining the super type which *must* be
  2007                 // done before attributing the type variables.  In
  2008                 // other words, we are seeing this illegal program:
  2009                 // class B<T> extends A<T.foo> {}
  2010                 Symbol sym = (site.getUpperBound() != null)
  2011                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2012                     : null;
  2013                 if (sym == null || isType(sym)) {
  2014                     log.error(pos, "type.var.cant.be.deref");
  2015                     return syms.errSymbol;
  2016                 } else {
  2017                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2018                         rs.new AccessError(env, site, sym) :
  2019                                 sym;
  2020                     rs.access(sym2, pos, site, name, true);
  2021                     return sym;
  2023             case ERROR:
  2024                 // preserve identifier names through errors
  2025                 return types.createErrorType(name, site.tsym, site).tsym;
  2026             default:
  2027                 // The qualifier expression is of a primitive type -- only
  2028                 // .class is allowed for these.
  2029                 if (name == names._class) {
  2030                     // In this case, we have already made sure in Select that
  2031                     // qualifier expression is a type.
  2032                     Type t = syms.classType;
  2033                     Type arg = types.boxedClass(site).type;
  2034                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2035                     return new VarSymbol(
  2036                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2037                 } else {
  2038                     log.error(pos, "cant.deref", site);
  2039                     return syms.errSymbol;
  2044         /** Determine type of identifier or select expression and check that
  2045          *  (1) the referenced symbol is not deprecated
  2046          *  (2) the symbol's type is safe (@see checkSafe)
  2047          *  (3) if symbol is a variable, check that its type and kind are
  2048          *      compatible with the prototype and protokind.
  2049          *  (4) if symbol is an instance field of a raw type,
  2050          *      which is being assigned to, issue an unchecked warning if its
  2051          *      type changes under erasure.
  2052          *  (5) if symbol is an instance method of a raw type, issue an
  2053          *      unchecked warning if its argument types change under erasure.
  2054          *  If checks succeed:
  2055          *    If symbol is a constant, return its constant type
  2056          *    else if symbol is a method, return its result type
  2057          *    otherwise return its type.
  2058          *  Otherwise return errType.
  2060          *  @param tree       The syntax tree representing the identifier
  2061          *  @param site       If this is a select, the type of the selected
  2062          *                    expression, otherwise the type of the current class.
  2063          *  @param sym        The symbol representing the identifier.
  2064          *  @param env        The current environment.
  2065          *  @param pkind      The set of expected kinds.
  2066          *  @param pt         The expected type.
  2067          */
  2068         Type checkId(JCTree tree,
  2069                      Type site,
  2070                      Symbol sym,
  2071                      Env<AttrContext> env,
  2072                      int pkind,
  2073                      Type pt,
  2074                      boolean useVarargs) {
  2075             if (pt.isErroneous()) return types.createErrorType(site);
  2076             Type owntype; // The computed type of this identifier occurrence.
  2077             switch (sym.kind) {
  2078             case TYP:
  2079                 // For types, the computed type equals the symbol's type,
  2080                 // except for two situations:
  2081                 owntype = sym.type;
  2082                 if (owntype.tag == CLASS) {
  2083                     Type ownOuter = owntype.getEnclosingType();
  2085                     // (a) If the symbol's type is parameterized, erase it
  2086                     // because no type parameters were given.
  2087                     // We recover generic outer type later in visitTypeApply.
  2088                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2089                         owntype = types.erasure(owntype);
  2092                     // (b) If the symbol's type is an inner class, then
  2093                     // we have to interpret its outer type as a superclass
  2094                     // of the site type. Example:
  2095                     //
  2096                     // class Tree<A> { class Visitor { ... } }
  2097                     // class PointTree extends Tree<Point> { ... }
  2098                     // ...PointTree.Visitor...
  2099                     //
  2100                     // Then the type of the last expression above is
  2101                     // Tree<Point>.Visitor.
  2102                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2103                         Type normOuter = site;
  2104                         if (normOuter.tag == CLASS)
  2105                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2106                         if (normOuter == null) // perhaps from an import
  2107                             normOuter = types.erasure(ownOuter);
  2108                         if (normOuter != ownOuter)
  2109                             owntype = new ClassType(
  2110                                 normOuter, List.<Type>nil(), owntype.tsym);
  2113                 break;
  2114             case VAR:
  2115                 VarSymbol v = (VarSymbol)sym;
  2116                 // Test (4): if symbol is an instance field of a raw type,
  2117                 // which is being assigned to, issue an unchecked warning if
  2118                 // its type changes under erasure.
  2119                 if (allowGenerics &&
  2120                     pkind == VAR &&
  2121                     v.owner.kind == TYP &&
  2122                     (v.flags() & STATIC) == 0 &&
  2123                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2124                     Type s = types.asOuterSuper(site, v.owner);
  2125                     if (s != null &&
  2126                         s.isRaw() &&
  2127                         !types.isSameType(v.type, v.erasure(types))) {
  2128                         chk.warnUnchecked(tree.pos(),
  2129                                           "unchecked.assign.to.var",
  2130                                           v, s);
  2133                 // The computed type of a variable is the type of the
  2134                 // variable symbol, taken as a member of the site type.
  2135                 owntype = (sym.owner.kind == TYP &&
  2136                            sym.name != names._this && sym.name != names._super)
  2137                     ? types.memberType(site, sym)
  2138                     : sym.type;
  2140                 if (env.info.tvars.nonEmpty()) {
  2141                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2142                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2143                         if (!owntype.contains(l.head)) {
  2144                             log.error(tree.pos(), "undetermined.type", owntype1);
  2145                             owntype1 = types.createErrorType(owntype1);
  2147                     owntype = owntype1;
  2150                 // If the variable is a constant, record constant value in
  2151                 // computed type.
  2152                 if (v.getConstValue() != null && isStaticReference(tree))
  2153                     owntype = owntype.constType(v.getConstValue());
  2155                 if (pkind == VAL) {
  2156                     owntype = capture(owntype); // capture "names as expressions"
  2158                 break;
  2159             case MTH: {
  2160                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2161                 owntype = checkMethod(site, sym, env, app.args,
  2162                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2163                                       env.info.varArgs);
  2164                 break;
  2166             case PCK: case ERR:
  2167                 owntype = sym.type;
  2168                 break;
  2169             default:
  2170                 throw new AssertionError("unexpected kind: " + sym.kind +
  2171                                          " in tree " + tree);
  2174             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2175             // (for constructors, the error was given when the constructor was
  2176             // resolved)
  2177             if (sym.name != names.init &&
  2178                 (sym.flags() & DEPRECATED) != 0 &&
  2179                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2180                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2181                 chk.warnDeprecated(tree.pos(), sym);
  2183             if ((sym.flags() & PROPRIETARY) != 0)
  2184                 log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2186             // Test (3): if symbol is a variable, check that its type and
  2187             // kind are compatible with the prototype and protokind.
  2188             return check(tree, owntype, sym.kind, pkind, pt);
  2191         /** Check that variable is initialized and evaluate the variable's
  2192          *  initializer, if not yet done. Also check that variable is not
  2193          *  referenced before it is defined.
  2194          *  @param tree    The tree making up the variable reference.
  2195          *  @param env     The current environment.
  2196          *  @param v       The variable's symbol.
  2197          */
  2198         private void checkInit(JCTree tree,
  2199                                Env<AttrContext> env,
  2200                                VarSymbol v,
  2201                                boolean onlyWarning) {
  2202 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2203 //                             tree.pos + " " + v.pos + " " +
  2204 //                             Resolve.isStatic(env));//DEBUG
  2206             // A forward reference is diagnosed if the declaration position
  2207             // of the variable is greater than the current tree position
  2208             // and the tree and variable definition occur in the same class
  2209             // definition.  Note that writes don't count as references.
  2210             // This check applies only to class and instance
  2211             // variables.  Local variables follow different scope rules,
  2212             // and are subject to definite assignment checking.
  2213             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2214                 v.owner.kind == TYP &&
  2215                 canOwnInitializer(env.info.scope.owner) &&
  2216                 v.owner == env.info.scope.owner.enclClass() &&
  2217                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2218                 (env.tree.getTag() != JCTree.ASSIGN ||
  2219                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2220                 String suffix = (env.info.enclVar == v) ?
  2221                                 "self.ref" : "forward.ref";
  2222                 if (!onlyWarning || isStaticEnumField(v)) {
  2223                     log.error(tree.pos(), "illegal." + suffix);
  2224                 } else if (useBeforeDeclarationWarning) {
  2225                     log.warning(tree.pos(), suffix, v);
  2229             v.getConstValue(); // ensure initializer is evaluated
  2231             checkEnumInitializer(tree, env, v);
  2234         /**
  2235          * Check for illegal references to static members of enum.  In
  2236          * an enum type, constructors and initializers may not
  2237          * reference its static members unless they are constant.
  2239          * @param tree    The tree making up the variable reference.
  2240          * @param env     The current environment.
  2241          * @param v       The variable's symbol.
  2242          * @see JLS 3rd Ed. (8.9 Enums)
  2243          */
  2244         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2245             // JLS 3rd Ed.:
  2246             //
  2247             // "It is a compile-time error to reference a static field
  2248             // of an enum type that is not a compile-time constant
  2249             // (15.28) from constructors, instance initializer blocks,
  2250             // or instance variable initializer expressions of that
  2251             // type. It is a compile-time error for the constructors,
  2252             // instance initializer blocks, or instance variable
  2253             // initializer expressions of an enum constant e to refer
  2254             // to itself or to an enum constant of the same type that
  2255             // is declared to the right of e."
  2256             if (isStaticEnumField(v)) {
  2257                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2259                 if (enclClass == null || enclClass.owner == null)
  2260                     return;
  2262                 // See if the enclosing class is the enum (or a
  2263                 // subclass thereof) declaring v.  If not, this
  2264                 // reference is OK.
  2265                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2266                     return;
  2268                 // If the reference isn't from an initializer, then
  2269                 // the reference is OK.
  2270                 if (!Resolve.isInitializer(env))
  2271                     return;
  2273                 log.error(tree.pos(), "illegal.enum.static.ref");
  2277         /** Is the given symbol a static, non-constant field of an Enum?
  2278          *  Note: enum literals should not be regarded as such
  2279          */
  2280         private boolean isStaticEnumField(VarSymbol v) {
  2281             return Flags.isEnum(v.owner) &&
  2282                    Flags.isStatic(v) &&
  2283                    !Flags.isConstant(v) &&
  2284                    v.name != names._class;
  2287         /** Can the given symbol be the owner of code which forms part
  2288          *  if class initialization? This is the case if the symbol is
  2289          *  a type or field, or if the symbol is the synthetic method.
  2290          *  owning a block.
  2291          */
  2292         private boolean canOwnInitializer(Symbol sym) {
  2293             return
  2294                 (sym.kind & (VAR | TYP)) != 0 ||
  2295                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2298     Warner noteWarner = new Warner();
  2300     /**
  2301      * Check that method arguments conform to its instantation.
  2302      **/
  2303     public Type checkMethod(Type site,
  2304                             Symbol sym,
  2305                             Env<AttrContext> env,
  2306                             final List<JCExpression> argtrees,
  2307                             List<Type> argtypes,
  2308                             List<Type> typeargtypes,
  2309                             boolean useVarargs) {
  2310         // Test (5): if symbol is an instance method of a raw type, issue
  2311         // an unchecked warning if its argument types change under erasure.
  2312         if (allowGenerics &&
  2313             (sym.flags() & STATIC) == 0 &&
  2314             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2315             Type s = types.asOuterSuper(site, sym.owner);
  2316             if (s != null && s.isRaw() &&
  2317                 !types.isSameTypes(sym.type.getParameterTypes(),
  2318                                    sym.erasure(types).getParameterTypes())) {
  2319                 chk.warnUnchecked(env.tree.pos(),
  2320                                   "unchecked.call.mbr.of.raw.type",
  2321                                   sym, s);
  2325         // Compute the identifier's instantiated type.
  2326         // For methods, we need to compute the instance type by
  2327         // Resolve.instantiate from the symbol's type as well as
  2328         // any type arguments and value arguments.
  2329         noteWarner.warned = false;
  2330         Type owntype = rs.instantiate(env,
  2331                                       site,
  2332                                       sym,
  2333                                       argtypes,
  2334                                       typeargtypes,
  2335                                       true,
  2336                                       useVarargs,
  2337                                       noteWarner);
  2338         boolean warned = noteWarner.warned;
  2340         // If this fails, something went wrong; we should not have
  2341         // found the identifier in the first place.
  2342         if (owntype == null) {
  2343             if (!pt.isErroneous())
  2344                 log.error(env.tree.pos(),
  2345                           "internal.error.cant.instantiate",
  2346                           sym, site,
  2347                           Type.toString(pt.getParameterTypes()));
  2348             owntype = types.createErrorType(site);
  2349         } else {
  2350             // System.out.println("call   : " + env.tree);
  2351             // System.out.println("method : " + owntype);
  2352             // System.out.println("actuals: " + argtypes);
  2353             List<Type> formals = owntype.getParameterTypes();
  2354             Type last = useVarargs ? formals.last() : null;
  2355             if (sym.name==names.init &&
  2356                 sym.owner == syms.enumSym)
  2357                 formals = formals.tail.tail;
  2358             List<JCExpression> args = argtrees;
  2359             while (formals.head != last) {
  2360                 JCTree arg = args.head;
  2361                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2362                 assertConvertible(arg, arg.type, formals.head, warn);
  2363                 warned |= warn.warned;
  2364                 args = args.tail;
  2365                 formals = formals.tail;
  2367             if (useVarargs) {
  2368                 Type varArg = types.elemtype(last);
  2369                 while (args.tail != null) {
  2370                     JCTree arg = args.head;
  2371                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2372                     assertConvertible(arg, arg.type, varArg, warn);
  2373                     warned |= warn.warned;
  2374                     args = args.tail;
  2376             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2377                 // non-varargs call to varargs method
  2378                 Type varParam = owntype.getParameterTypes().last();
  2379                 Type lastArg = argtypes.last();
  2380                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2381                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2382                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2383                                 types.elemtype(varParam),
  2384                                 varParam);
  2387             if (warned && sym.type.tag == FORALL) {
  2388                 chk.warnUnchecked(env.tree.pos(),
  2389                                   "unchecked.meth.invocation.applied",
  2390                                   kindName(sym),
  2391                                   sym.name,
  2392                                   rs.methodArguments(sym.type.getParameterTypes()),
  2393                                   rs.methodArguments(argtypes),
  2394                                   kindName(sym.location()),
  2395                                   sym.location());
  2396                 owntype = new MethodType(owntype.getParameterTypes(),
  2397                                          types.erasure(owntype.getReturnType()),
  2398                                          owntype.getThrownTypes(),
  2399                                          syms.methodClass);
  2401             if (useVarargs) {
  2402                 JCTree tree = env.tree;
  2403                 Type argtype = owntype.getParameterTypes().last();
  2404                 if (!types.isReifiable(argtype))
  2405                     chk.warnUnchecked(env.tree.pos(),
  2406                                       "unchecked.generic.array.creation",
  2407                                       argtype);
  2408                 Type elemtype = types.elemtype(argtype);
  2409                 switch (tree.getTag()) {
  2410                 case JCTree.APPLY:
  2411                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2412                     break;
  2413                 case JCTree.NEWCLASS:
  2414                     ((JCNewClass) tree).varargsElement = elemtype;
  2415                     break;
  2416                 default:
  2417                     throw new AssertionError(""+tree);
  2421         return owntype;
  2424     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2425         if (types.isConvertible(actual, formal, warn))
  2426             return;
  2428         if (formal.isCompound()
  2429             && types.isSubtype(actual, types.supertype(formal))
  2430             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2431             return;
  2433         if (false) {
  2434             // TODO: make assertConvertible work
  2435             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2436             throw new AssertionError("Tree: " + tree
  2437                                      + " actual:" + actual
  2438                                      + " formal: " + formal);
  2442     public void visitLiteral(JCLiteral tree) {
  2443         result = check(
  2444             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2446     //where
  2447     /** Return the type of a literal with given type tag.
  2448      */
  2449     Type litType(int tag) {
  2450         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2453     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2454         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2457     public void visitTypeArray(JCArrayTypeTree tree) {
  2458         Type etype = attribType(tree.elemtype, env);
  2459         Type type = new ArrayType(etype, syms.arrayClass);
  2460         result = check(tree, type, TYP, pkind, pt);
  2463     /** Visitor method for parameterized types.
  2464      *  Bound checking is left until later, since types are attributed
  2465      *  before supertype structure is completely known
  2466      */
  2467     public void visitTypeApply(JCTypeApply tree) {
  2468         Type owntype = types.createErrorType(tree.type);
  2470         // Attribute functor part of application and make sure it's a class.
  2471         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2473         // Attribute type parameters
  2474         List<Type> actuals = attribTypes(tree.arguments, env);
  2476         if (clazztype.tag == CLASS) {
  2477             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2479             if (actuals.length() == formals.length()) {
  2480                 List<Type> a = actuals;
  2481                 List<Type> f = formals;
  2482                 while (a.nonEmpty()) {
  2483                     a.head = a.head.withTypeVar(f.head);
  2484                     a = a.tail;
  2485                     f = f.tail;
  2487                 // Compute the proper generic outer
  2488                 Type clazzOuter = clazztype.getEnclosingType();
  2489                 if (clazzOuter.tag == CLASS) {
  2490                     Type site;
  2491                     if (tree.clazz.getTag() == JCTree.IDENT) {
  2492                         site = env.enclClass.sym.type;
  2493                     } else if (tree.clazz.getTag() == JCTree.SELECT) {
  2494                         site = ((JCFieldAccess) tree.clazz).selected.type;
  2495                     } else throw new AssertionError(""+tree);
  2496                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2497                         if (site.tag == CLASS)
  2498                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2499                         if (site == null)
  2500                             site = types.erasure(clazzOuter);
  2501                         clazzOuter = site;
  2504                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2505             } else {
  2506                 if (formals.length() != 0) {
  2507                     log.error(tree.pos(), "wrong.number.type.args",
  2508                               Integer.toString(formals.length()));
  2509                 } else {
  2510                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2512                 owntype = types.createErrorType(tree.type);
  2515         result = check(tree, owntype, TYP, pkind, pt);
  2518     public void visitTypeParameter(JCTypeParameter tree) {
  2519         TypeVar a = (TypeVar)tree.type;
  2520         Set<Type> boundSet = new HashSet<Type>();
  2521         if (a.bound.isErroneous())
  2522             return;
  2523         List<Type> bs = types.getBounds(a);
  2524         if (tree.bounds.nonEmpty()) {
  2525             // accept class or interface or typevar as first bound.
  2526             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2527             boundSet.add(types.erasure(b));
  2528             if (b.isErroneous()) {
  2529                 a.bound = b;
  2531             else if (b.tag == TYPEVAR) {
  2532                 // if first bound was a typevar, do not accept further bounds.
  2533                 if (tree.bounds.tail.nonEmpty()) {
  2534                     log.error(tree.bounds.tail.head.pos(),
  2535                               "type.var.may.not.be.followed.by.other.bounds");
  2536                     tree.bounds = List.of(tree.bounds.head);
  2537                     a.bound = bs.head;
  2539             } else {
  2540                 // if first bound was a class or interface, accept only interfaces
  2541                 // as further bounds.
  2542                 for (JCExpression bound : tree.bounds.tail) {
  2543                     bs = bs.tail;
  2544                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2545                     if (i.isErroneous())
  2546                         a.bound = i;
  2547                     else if (i.tag == CLASS)
  2548                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2552         bs = types.getBounds(a);
  2554         // in case of multiple bounds ...
  2555         if (bs.length() > 1) {
  2556             // ... the variable's bound is a class type flagged COMPOUND
  2557             // (see comment for TypeVar.bound).
  2558             // In this case, generate a class tree that represents the
  2559             // bound class, ...
  2560             JCTree extending;
  2561             List<JCExpression> implementing;
  2562             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2563                 extending = tree.bounds.head;
  2564                 implementing = tree.bounds.tail;
  2565             } else {
  2566                 extending = null;
  2567                 implementing = tree.bounds;
  2569             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2570                 make.Modifiers(PUBLIC | ABSTRACT),
  2571                 tree.name, List.<JCTypeParameter>nil(),
  2572                 extending, implementing, List.<JCTree>nil());
  2574             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2575             assert (c.flags() & COMPOUND) != 0;
  2576             cd.sym = c;
  2577             c.sourcefile = env.toplevel.sourcefile;
  2579             // ... and attribute the bound class
  2580             c.flags_field |= UNATTRIBUTED;
  2581             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2582             enter.typeEnvs.put(c, cenv);
  2587     public void visitWildcard(JCWildcard tree) {
  2588         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2589         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2590             ? syms.objectType
  2591             : attribType(tree.inner, env);
  2592         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2593                                               tree.kind.kind,
  2594                                               syms.boundClass),
  2595                        TYP, pkind, pt);
  2598     public void visitAnnotation(JCAnnotation tree) {
  2599         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2600         result = tree.type = syms.errType;
  2603     public void visitErroneous(JCErroneous tree) {
  2604         if (tree.errs != null)
  2605             for (JCTree err : tree.errs)
  2606                 attribTree(err, env, ERR, pt);
  2607         result = tree.type = syms.errType;
  2610     /** Default visitor method for all other trees.
  2611      */
  2612     public void visitTree(JCTree tree) {
  2613         throw new AssertionError();
  2616     /** Main method: attribute class definition associated with given class symbol.
  2617      *  reporting completion failures at the given position.
  2618      *  @param pos The source position at which completion errors are to be
  2619      *             reported.
  2620      *  @param c   The class symbol whose definition will be attributed.
  2621      */
  2622     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2623         try {
  2624             annotate.flush();
  2625             attribClass(c);
  2626         } catch (CompletionFailure ex) {
  2627             chk.completionError(pos, ex);
  2631     /** Attribute class definition associated with given class symbol.
  2632      *  @param c   The class symbol whose definition will be attributed.
  2633      */
  2634     void attribClass(ClassSymbol c) throws CompletionFailure {
  2635         if (c.type.tag == ERROR) return;
  2637         // Check for cycles in the inheritance graph, which can arise from
  2638         // ill-formed class files.
  2639         chk.checkNonCyclic(null, c.type);
  2641         Type st = types.supertype(c.type);
  2642         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2643             // First, attribute superclass.
  2644             if (st.tag == CLASS)
  2645                 attribClass((ClassSymbol)st.tsym);
  2647             // Next attribute owner, if it is a class.
  2648             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2649                 attribClass((ClassSymbol)c.owner);
  2652         // The previous operations might have attributed the current class
  2653         // if there was a cycle. So we test first whether the class is still
  2654         // UNATTRIBUTED.
  2655         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2656             c.flags_field &= ~UNATTRIBUTED;
  2658             // Get environment current at the point of class definition.
  2659             Env<AttrContext> env = enter.typeEnvs.get(c);
  2661             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2662             // because the annotations were not available at the time the env was created. Therefore,
  2663             // we look up the environment chain for the first enclosing environment for which the
  2664             // lint value is set. Typically, this is the parent env, but might be further if there
  2665             // are any envs created as a result of TypeParameter nodes.
  2666             Env<AttrContext> lintEnv = env;
  2667             while (lintEnv.info.lint == null)
  2668                 lintEnv = lintEnv.next;
  2670             // Having found the enclosing lint value, we can initialize the lint value for this class
  2671             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2673             Lint prevLint = chk.setLint(env.info.lint);
  2674             JavaFileObject prev = log.useSource(c.sourcefile);
  2676             try {
  2677                 // java.lang.Enum may not be subclassed by a non-enum
  2678                 if (st.tsym == syms.enumSym &&
  2679                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  2680                     log.error(env.tree.pos(), "enum.no.subclassing");
  2682                 // Enums may not be extended by source-level classes
  2683                 if (st.tsym != null &&
  2684                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  2685                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  2686                     !target.compilerBootstrap(c)) {
  2687                     log.error(env.tree.pos(), "enum.types.not.extensible");
  2689                 attribClassBody(env, c);
  2691                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  2692             } finally {
  2693                 log.useSource(prev);
  2694                 chk.setLint(prevLint);
  2700     public void visitImport(JCImport tree) {
  2701         // nothing to do
  2704     /** Finish the attribution of a class. */
  2705     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  2706         JCClassDecl tree = (JCClassDecl)env.tree;
  2707         assert c == tree.sym;
  2709         // Validate annotations
  2710         chk.validateAnnotations(tree.mods.annotations, c);
  2712         // Validate type parameters, supertype and interfaces.
  2713         attribBounds(tree.typarams);
  2714         chk.validate(tree.typarams, env);
  2715         chk.validate(tree.extending, env);
  2716         chk.validate(tree.implementing, env);
  2718         // If this is a non-abstract class, check that it has no abstract
  2719         // methods or unimplemented methods of an implemented interface.
  2720         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  2721             if (!relax)
  2722                 chk.checkAllDefined(tree.pos(), c);
  2725         if ((c.flags() & ANNOTATION) != 0) {
  2726             if (tree.implementing.nonEmpty())
  2727                 log.error(tree.implementing.head.pos(),
  2728                           "cant.extend.intf.annotation");
  2729             if (tree.typarams.nonEmpty())
  2730                 log.error(tree.typarams.head.pos(),
  2731                           "intf.annotation.cant.have.type.params");
  2732         } else {
  2733             // Check that all extended classes and interfaces
  2734             // are compatible (i.e. no two define methods with same arguments
  2735             // yet different return types).  (JLS 8.4.6.3)
  2736             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  2739         // Check that class does not import the same parameterized interface
  2740         // with two different argument lists.
  2741         chk.checkClassBounds(tree.pos(), c.type);
  2743         tree.type = c.type;
  2745         boolean assertsEnabled = false;
  2746         assert assertsEnabled = true;
  2747         if (assertsEnabled) {
  2748             for (List<JCTypeParameter> l = tree.typarams;
  2749                  l.nonEmpty(); l = l.tail)
  2750                 assert env.info.scope.lookup(l.head.name).scope != null;
  2753         // Check that a generic class doesn't extend Throwable
  2754         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  2755             log.error(tree.extending.pos(), "generic.throwable");
  2757         // Check that all methods which implement some
  2758         // method conform to the method they implement.
  2759         chk.checkImplementations(tree);
  2761         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2762             // Attribute declaration
  2763             attribStat(l.head, env);
  2764             // Check that declarations in inner classes are not static (JLS 8.1.2)
  2765             // Make an exception for static constants.
  2766             if (c.owner.kind != PCK &&
  2767                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  2768                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  2769                 Symbol sym = null;
  2770                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  2771                 if (sym == null ||
  2772                     sym.kind != VAR ||
  2773                     ((VarSymbol) sym).getConstValue() == null)
  2774                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  2778         // Check for cycles among non-initial constructors.
  2779         chk.checkCyclicConstructors(tree);
  2781         // Check for cycles among annotation elements.
  2782         chk.checkNonCyclicElements(tree);
  2784         // Check for proper use of serialVersionUID
  2785         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  2786             isSerializable(c) &&
  2787             (c.flags() & Flags.ENUM) == 0 &&
  2788             (c.flags() & ABSTRACT) == 0) {
  2789             checkSerialVersionUID(tree, c);
  2792         // where
  2793         /** check if a class is a subtype of Serializable, if that is available. */
  2794         private boolean isSerializable(ClassSymbol c) {
  2795             try {
  2796                 syms.serializableType.complete();
  2798             catch (CompletionFailure e) {
  2799                 return false;
  2801             return types.isSubtype(c.type, syms.serializableType);
  2804         /** Check that an appropriate serialVersionUID member is defined. */
  2805         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  2807             // check for presence of serialVersionUID
  2808             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  2809             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  2810             if (e.scope == null) {
  2811                 log.warning(tree.pos(), "missing.SVUID", c);
  2812                 return;
  2815             // check that it is static final
  2816             VarSymbol svuid = (VarSymbol)e.sym;
  2817             if ((svuid.flags() & (STATIC | FINAL)) !=
  2818                 (STATIC | FINAL))
  2819                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  2821             // check that it is long
  2822             else if (svuid.type.tag != TypeTags.LONG)
  2823                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  2825             // check constant
  2826             else if (svuid.getConstValue() == null)
  2827                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  2830     private Type capture(Type type) {
  2831         return types.capture(type);

mercurial