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

Wed, 19 May 2010 16:42:37 +0100

author
mcimadamore
date
Wed, 19 May 2010 16:42:37 +0100
changeset 562
2881b376a689
parent 550
a6f2911a7c55
child 567
593a59e40bdb
permissions
-rw-r--r--

6946618: sqe test fails: javac/generics/NewOnTypeParm in pit jdk7 b91 in all platforms.
Summary: Bad cast to ClassType in the new diamond implementation fails if the target type of the instance creation expression is a type-variable
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.jvm.Target;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.tree.JCTree.*;
    43 import com.sun.tools.javac.code.Type.*;
    45 import com.sun.source.tree.IdentifierTree;
    46 import com.sun.source.tree.MemberSelectTree;
    47 import com.sun.source.tree.TreeVisitor;
    48 import com.sun.source.util.SimpleTreeVisitor;
    50 import static com.sun.tools.javac.code.Flags.*;
    51 import static com.sun.tools.javac.code.Kinds.*;
    52 import static com.sun.tools.javac.code.TypeTags.*;
    54 /** This is the main context-dependent analysis phase in GJC. It
    55  *  encompasses name resolution, type checking and constant folding as
    56  *  subtasks. Some subtasks involve auxiliary classes.
    57  *  @see Check
    58  *  @see Resolve
    59  *  @see ConstFold
    60  *  @see Infer
    61  *
    62  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    63  *  you write code that depends on this, you do so at your own risk.
    64  *  This code and its internal interfaces are subject to change or
    65  *  deletion without notice.</b>
    66  */
    67 public class Attr extends JCTree.Visitor {
    68     protected static final Context.Key<Attr> attrKey =
    69         new Context.Key<Attr>();
    71     final Names names;
    72     final Log log;
    73     final Symtab syms;
    74     final Resolve rs;
    75     final Infer infer;
    76     final Check chk;
    77     final MemberEnter memberEnter;
    78     final TreeMaker make;
    79     final ConstFold cfolder;
    80     final Enter enter;
    81     final Target target;
    82     final Types types;
    83     final JCDiagnostic.Factory diags;
    84     final Annotate annotate;
    86     public static Attr instance(Context context) {
    87         Attr instance = context.get(attrKey);
    88         if (instance == null)
    89             instance = new Attr(context);
    90         return instance;
    91     }
    93     protected Attr(Context context) {
    94         context.put(attrKey, this);
    96         names = Names.instance(context);
    97         log = Log.instance(context);
    98         syms = Symtab.instance(context);
    99         rs = Resolve.instance(context);
   100         chk = Check.instance(context);
   101         memberEnter = MemberEnter.instance(context);
   102         make = TreeMaker.instance(context);
   103         enter = Enter.instance(context);
   104         infer = Infer.instance(context);
   105         cfolder = ConstFold.instance(context);
   106         target = Target.instance(context);
   107         types = Types.instance(context);
   108         diags = JCDiagnostic.Factory.instance(context);
   109         annotate = Annotate.instance(context);
   111         Options options = Options.instance(context);
   113         Source source = Source.instance(context);
   114         allowGenerics = source.allowGenerics();
   115         allowVarargs = source.allowVarargs();
   116         allowEnums = source.allowEnums();
   117         allowBoxing = source.allowBoxing();
   118         allowCovariantReturns = source.allowCovariantReturns();
   119         allowAnonOuterThis = source.allowAnonOuterThis();
   120         allowStringsInSwitch = source.allowStringsInSwitch();
   121         sourceName = source.name;
   122         relax = (options.get("-retrofit") != null ||
   123                  options.get("-relax") != null);
   124         useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
   125         allowInvokedynamic = options.get("invokedynamic") != null;
   126         enableSunApiLintControl = options.get("enableSunApiLintControl") != null;
   127     }
   129     /** Switch: relax some constraints for retrofit mode.
   130      */
   131     boolean relax;
   133     /** Switch: support generics?
   134      */
   135     boolean allowGenerics;
   137     /** Switch: allow variable-arity methods.
   138      */
   139     boolean allowVarargs;
   141     /** Switch: support enums?
   142      */
   143     boolean allowEnums;
   145     /** Switch: support boxing and unboxing?
   146      */
   147     boolean allowBoxing;
   149     /** Switch: support covariant result types?
   150      */
   151     boolean allowCovariantReturns;
   153     /** Switch: allow references to surrounding object from anonymous
   154      * objects during constructor call?
   155      */
   156     boolean allowAnonOuterThis;
   158     /** Switch: allow invokedynamic syntax
   159      */
   160     boolean allowInvokedynamic;
   162     /**
   163      * Switch: warn about use of variable before declaration?
   164      * RFE: 6425594
   165      */
   166     boolean useBeforeDeclarationWarning;
   168     /**
   169      * Switch: allow lint infrastructure to control Sun proprietary
   170      * API warnings.
   171      */
   172     boolean enableSunApiLintControl;
   174     /**
   175      * Switch: allow strings in switch?
   176      */
   177     boolean allowStringsInSwitch;
   179     /**
   180      * Switch: name of source level; used for error reporting.
   181      */
   182     String sourceName;
   184     /** Check kind and type of given tree against protokind and prototype.
   185      *  If check succeeds, store type in tree and return it.
   186      *  If check fails, store errType in tree and return it.
   187      *  No checks are performed if the prototype is a method type.
   188      *  It is not necessary in this case since we know that kind and type
   189      *  are correct.
   190      *
   191      *  @param tree     The tree whose kind and type is checked
   192      *  @param owntype  The computed type of the tree
   193      *  @param ownkind  The computed kind of the tree
   194      *  @param pkind    The expected kind (or: protokind) of the tree
   195      *  @param pt       The expected type (or: prototype) of the tree
   196      */
   197     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   198         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   199             if ((ownkind & ~pkind) == 0) {
   200                 owntype = chk.checkType(tree.pos(), owntype, pt);
   201             } else {
   202                 log.error(tree.pos(), "unexpected.type",
   203                           kindNames(pkind),
   204                           kindName(ownkind));
   205                 owntype = types.createErrorType(owntype);
   206             }
   207         }
   208         tree.type = owntype;
   209         return owntype;
   210     }
   212     /** Is given blank final variable assignable, i.e. in a scope where it
   213      *  may be assigned to even though it is final?
   214      *  @param v      The blank final variable.
   215      *  @param env    The current environment.
   216      */
   217     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   218         Symbol owner = env.info.scope.owner;
   219            // owner refers to the innermost variable, method or
   220            // initializer block declaration at this point.
   221         return
   222             v.owner == owner
   223             ||
   224             ((owner.name == names.init ||    // i.e. we are in a constructor
   225               owner.kind == VAR ||           // i.e. we are in a variable initializer
   226               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   227              &&
   228              v.owner == owner.owner
   229              &&
   230              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   231     }
   233     /** Check that variable can be assigned to.
   234      *  @param pos    The current source code position.
   235      *  @param v      The assigned varaible
   236      *  @param base   If the variable is referred to in a Select, the part
   237      *                to the left of the `.', null otherwise.
   238      *  @param env    The current environment.
   239      */
   240     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   241         if ((v.flags() & FINAL) != 0 &&
   242             ((v.flags() & HASINIT) != 0
   243              ||
   244              !((base == null ||
   245                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   246                isAssignableAsBlankFinal(v, env)))) {
   247             log.error(pos, "cant.assign.val.to.final.var", v);
   248         }
   249     }
   251     /** Does tree represent a static reference to an identifier?
   252      *  It is assumed that tree is either a SELECT or an IDENT.
   253      *  We have to weed out selects from non-type names here.
   254      *  @param tree    The candidate tree.
   255      */
   256     boolean isStaticReference(JCTree tree) {
   257         if (tree.getTag() == JCTree.SELECT) {
   258             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   259             if (lsym == null || lsym.kind != TYP) {
   260                 return false;
   261             }
   262         }
   263         return true;
   264     }
   266     /** Is this symbol a type?
   267      */
   268     static boolean isType(Symbol sym) {
   269         return sym != null && sym.kind == TYP;
   270     }
   272     /** The current `this' symbol.
   273      *  @param env    The current environment.
   274      */
   275     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   276         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   277     }
   279     /** Attribute a parsed identifier.
   280      * @param tree Parsed identifier name
   281      * @param topLevel The toplevel to use
   282      */
   283     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   284         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   285         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   286                                            syms.errSymbol.name,
   287                                            null, null, null, null);
   288         localEnv.enclClass.sym = syms.errSymbol;
   289         return tree.accept(identAttributer, localEnv);
   290     }
   291     // where
   292         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   293         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   294             @Override
   295             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   296                 Symbol site = visit(node.getExpression(), env);
   297                 if (site.kind == ERR)
   298                     return site;
   299                 Name name = (Name)node.getIdentifier();
   300                 if (site.kind == PCK) {
   301                     env.toplevel.packge = (PackageSymbol)site;
   302                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   303                 } else {
   304                     env.enclClass.sym = (ClassSymbol)site;
   305                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   306                 }
   307             }
   309             @Override
   310             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   311                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   312             }
   313         }
   315     public Type coerce(Type etype, Type ttype) {
   316         return cfolder.coerce(etype, ttype);
   317     }
   319     public Type attribType(JCTree node, TypeSymbol sym) {
   320         Env<AttrContext> env = enter.typeEnvs.get(sym);
   321         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   322         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   323     }
   325     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   326         breakTree = tree;
   327         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   328         try {
   329             attribExpr(expr, env);
   330         } catch (BreakAttr b) {
   331             return b.env;
   332         } finally {
   333             breakTree = null;
   334             log.useSource(prev);
   335         }
   336         return env;
   337     }
   339     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   340         breakTree = tree;
   341         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   342         try {
   343             attribStat(stmt, env);
   344         } catch (BreakAttr b) {
   345             return b.env;
   346         } finally {
   347             breakTree = null;
   348             log.useSource(prev);
   349         }
   350         return env;
   351     }
   353     private JCTree breakTree = null;
   355     private static class BreakAttr extends RuntimeException {
   356         static final long serialVersionUID = -6924771130405446405L;
   357         private Env<AttrContext> env;
   358         private BreakAttr(Env<AttrContext> env) {
   359             this.env = env;
   360         }
   361     }
   364 /* ************************************************************************
   365  * Visitor methods
   366  *************************************************************************/
   368     /** Visitor argument: the current environment.
   369      */
   370     Env<AttrContext> env;
   372     /** Visitor argument: the currently expected proto-kind.
   373      */
   374     int pkind;
   376     /** Visitor argument: the currently expected proto-type.
   377      */
   378     Type pt;
   380     /** Visitor result: the computed type.
   381      */
   382     Type result;
   384     /** Visitor method: attribute a tree, catching any completion failure
   385      *  exceptions. Return the tree's type.
   386      *
   387      *  @param tree    The tree to be visited.
   388      *  @param env     The environment visitor argument.
   389      *  @param pkind   The protokind visitor argument.
   390      *  @param pt      The prototype visitor argument.
   391      */
   392     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   393         Env<AttrContext> prevEnv = this.env;
   394         int prevPkind = this.pkind;
   395         Type prevPt = this.pt;
   396         try {
   397             this.env = env;
   398             this.pkind = pkind;
   399             this.pt = pt;
   400             tree.accept(this);
   401             if (tree == breakTree)
   402                 throw new BreakAttr(env);
   403             return result;
   404         } catch (CompletionFailure ex) {
   405             tree.type = syms.errType;
   406             return chk.completionError(tree.pos(), ex);
   407         } finally {
   408             this.env = prevEnv;
   409             this.pkind = prevPkind;
   410             this.pt = prevPt;
   411         }
   412     }
   414     /** Derived visitor method: attribute an expression tree.
   415      */
   416     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   417         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   418     }
   420     /** Derived visitor method: attribute an expression tree with
   421      *  no constraints on the computed type.
   422      */
   423     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   424         return attribTree(tree, env, VAL, Type.noType);
   425     }
   427     /** Derived visitor method: attribute a type tree.
   428      */
   429     Type attribType(JCTree tree, Env<AttrContext> env) {
   430         Type result = attribType(tree, env, Type.noType);
   431         return result;
   432     }
   434     /** Derived visitor method: attribute a type tree.
   435      */
   436     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   437         Type result = attribTree(tree, env, TYP, pt);
   438         return result;
   439     }
   441     /** Derived visitor method: attribute a statement or definition tree.
   442      */
   443     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   444         return attribTree(tree, env, NIL, Type.noType);
   445     }
   447     /** Attribute a list of expressions, returning a list of types.
   448      */
   449     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   450         ListBuffer<Type> ts = new ListBuffer<Type>();
   451         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   452             ts.append(attribExpr(l.head, env, pt));
   453         return ts.toList();
   454     }
   456     /** Attribute a list of statements, returning nothing.
   457      */
   458     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   459         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   460             attribStat(l.head, env);
   461     }
   463     /** Attribute the arguments in a method call, returning a list of types.
   464      */
   465     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   466         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   467         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   468             argtypes.append(chk.checkNonVoid(
   469                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   470         return argtypes.toList();
   471     }
   473     /** Attribute a type argument list, returning a list of types.
   474      *  Caller is responsible for calling checkRefTypes.
   475      */
   476     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   477         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   478         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   479             argtypes.append(attribType(l.head, env));
   480         return argtypes.toList();
   481     }
   483     /** Attribute a type argument list, returning a list of types.
   484      *  Check that all the types are references.
   485      */
   486     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   487         List<Type> types = attribAnyTypes(trees, env);
   488         return chk.checkRefTypes(trees, types);
   489     }
   491     /**
   492      * Attribute type variables (of generic classes or methods).
   493      * Compound types are attributed later in attribBounds.
   494      * @param typarams the type variables to enter
   495      * @param env      the current environment
   496      */
   497     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   498         for (JCTypeParameter tvar : typarams) {
   499             TypeVar a = (TypeVar)tvar.type;
   500             a.tsym.flags_field |= UNATTRIBUTED;
   501             a.bound = Type.noType;
   502             if (!tvar.bounds.isEmpty()) {
   503                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   504                 for (JCExpression bound : tvar.bounds.tail)
   505                     bounds = bounds.prepend(attribType(bound, env));
   506                 types.setBounds(a, bounds.reverse());
   507             } else {
   508                 // if no bounds are given, assume a single bound of
   509                 // java.lang.Object.
   510                 types.setBounds(a, List.of(syms.objectType));
   511             }
   512             a.tsym.flags_field &= ~UNATTRIBUTED;
   513         }
   514         for (JCTypeParameter tvar : typarams)
   515             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   516         attribStats(typarams, env);
   517     }
   519     void attribBounds(List<JCTypeParameter> typarams) {
   520         for (JCTypeParameter typaram : typarams) {
   521             Type bound = typaram.type.getUpperBound();
   522             if (bound != null && bound.tsym instanceof ClassSymbol) {
   523                 ClassSymbol c = (ClassSymbol)bound.tsym;
   524                 if ((c.flags_field & COMPOUND) != 0) {
   525                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   526                     attribClass(typaram.pos(), c);
   527                 }
   528             }
   529         }
   530     }
   532     /**
   533      * Attribute the type references in a list of annotations.
   534      */
   535     void attribAnnotationTypes(List<JCAnnotation> annotations,
   536                                Env<AttrContext> env) {
   537         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   538             JCAnnotation a = al.head;
   539             attribType(a.annotationType, env);
   540         }
   541     }
   543     /** Attribute type reference in an `extends' or `implements' clause.
   544      *  Supertypes of anonymous inner classes are usually already attributed.
   545      *
   546      *  @param tree              The tree making up the type reference.
   547      *  @param env               The environment current at the reference.
   548      *  @param classExpected     true if only a class is expected here.
   549      *  @param interfaceExpected true if only an interface is expected here.
   550      */
   551     Type attribBase(JCTree tree,
   552                     Env<AttrContext> env,
   553                     boolean classExpected,
   554                     boolean interfaceExpected,
   555                     boolean checkExtensible) {
   556         Type t = tree.type != null ?
   557             tree.type :
   558             attribType(tree, env);
   559         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   560     }
   561     Type checkBase(Type t,
   562                    JCTree tree,
   563                    Env<AttrContext> env,
   564                    boolean classExpected,
   565                    boolean interfaceExpected,
   566                    boolean checkExtensible) {
   567         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   568             // check that type variable is already visible
   569             if (t.getUpperBound() == null) {
   570                 log.error(tree.pos(), "illegal.forward.ref");
   571                 return types.createErrorType(t);
   572             }
   573         } else {
   574             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   575         }
   576         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   577             log.error(tree.pos(), "intf.expected.here");
   578             // return errType is necessary since otherwise there might
   579             // be undetected cycles which cause attribution to loop
   580             return types.createErrorType(t);
   581         } else if (checkExtensible &&
   582                    classExpected &&
   583                    (t.tsym.flags() & INTERFACE) != 0) {
   584             log.error(tree.pos(), "no.intf.expected.here");
   585             return types.createErrorType(t);
   586         }
   587         if (checkExtensible &&
   588             ((t.tsym.flags() & FINAL) != 0)) {
   589             log.error(tree.pos(),
   590                       "cant.inherit.from.final", t.tsym);
   591         }
   592         chk.checkNonCyclic(tree.pos(), t);
   593         return t;
   594     }
   596     public void visitClassDef(JCClassDecl tree) {
   597         // Local classes have not been entered yet, so we need to do it now:
   598         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   599             enter.classEnter(tree, env);
   601         ClassSymbol c = tree.sym;
   602         if (c == null) {
   603             // exit in case something drastic went wrong during enter.
   604             result = null;
   605         } else {
   606             // make sure class has been completed:
   607             c.complete();
   609             // If this class appears as an anonymous class
   610             // in a superclass constructor call where
   611             // no explicit outer instance is given,
   612             // disable implicit outer instance from being passed.
   613             // (This would be an illegal access to "this before super").
   614             if (env.info.isSelfCall &&
   615                 env.tree.getTag() == JCTree.NEWCLASS &&
   616                 ((JCNewClass) env.tree).encl == null)
   617             {
   618                 c.flags_field |= NOOUTERTHIS;
   619             }
   620             attribClass(tree.pos(), c);
   621             result = tree.type = c.type;
   622         }
   623     }
   625     public void visitMethodDef(JCMethodDecl tree) {
   626         MethodSymbol m = tree.sym;
   628         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   629         Lint prevLint = chk.setLint(lint);
   630         try {
   631             chk.checkDeprecatedAnnotation(tree.pos(), m);
   633             attribBounds(tree.typarams);
   635             // If we override any other methods, check that we do so properly.
   636             // JLS ???
   637             chk.checkOverride(tree, m);
   639             // Create a new environment with local scope
   640             // for attributing the method.
   641             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   643             localEnv.info.lint = lint;
   645             // Enter all type parameters into the local method scope.
   646             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   647                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   649             ClassSymbol owner = env.enclClass.sym;
   650             if ((owner.flags() & ANNOTATION) != 0 &&
   651                 tree.params.nonEmpty())
   652                 log.error(tree.params.head.pos(),
   653                           "intf.annotation.members.cant.have.params");
   655             // Attribute all value parameters.
   656             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   657                 attribStat(l.head, localEnv);
   658             }
   660             // Check that type parameters are well-formed.
   661             chk.validate(tree.typarams, localEnv);
   662             if ((owner.flags() & ANNOTATION) != 0 &&
   663                 tree.typarams.nonEmpty())
   664                 log.error(tree.typarams.head.pos(),
   665                           "intf.annotation.members.cant.have.type.params");
   667             // Check that result type is well-formed.
   668             chk.validate(tree.restype, localEnv);
   669             if ((owner.flags() & ANNOTATION) != 0)
   670                 chk.validateAnnotationType(tree.restype);
   672             if ((owner.flags() & ANNOTATION) != 0)
   673                 chk.validateAnnotationMethod(tree.pos(), m);
   675             // Check that all exceptions mentioned in the throws clause extend
   676             // java.lang.Throwable.
   677             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
   678                 log.error(tree.thrown.head.pos(),
   679                           "throws.not.allowed.in.intf.annotation");
   680             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   681                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   683             if (tree.body == null) {
   684                 // Empty bodies are only allowed for
   685                 // abstract, native, or interface methods, or for methods
   686                 // in a retrofit signature class.
   687                 if ((owner.flags() & INTERFACE) == 0 &&
   688                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   689                     !relax)
   690                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   691                 if (tree.defaultValue != null) {
   692                     if ((owner.flags() & ANNOTATION) == 0)
   693                         log.error(tree.pos(),
   694                                   "default.allowed.in.intf.annotation.member");
   695                 }
   696             } else if ((owner.flags() & INTERFACE) != 0) {
   697                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   698             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   699                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   700             } else if ((tree.mods.flags & NATIVE) != 0) {
   701                 log.error(tree.pos(), "native.meth.cant.have.body");
   702             } else {
   703                 // Add an implicit super() call unless an explicit call to
   704                 // super(...) or this(...) is given
   705                 // or we are compiling class java.lang.Object.
   706                 if (tree.name == names.init && owner.type != syms.objectType) {
   707                     JCBlock body = tree.body;
   708                     if (body.stats.isEmpty() ||
   709                         !TreeInfo.isSelfCall(body.stats.head)) {
   710                         body.stats = body.stats.
   711                             prepend(memberEnter.SuperCall(make.at(body.pos),
   712                                                           List.<Type>nil(),
   713                                                           List.<JCVariableDecl>nil(),
   714                                                           false));
   715                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   716                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   717                                TreeInfo.isSuperCall(body.stats.head)) {
   718                         // enum constructors are not allowed to call super
   719                         // directly, so make sure there aren't any super calls
   720                         // in enum constructors, except in the compiler
   721                         // generated one.
   722                         log.error(tree.body.stats.head.pos(),
   723                                   "call.to.super.not.allowed.in.enum.ctor",
   724                                   env.enclClass.sym);
   725                     }
   726                 }
   728                 // Attribute method body.
   729                 attribStat(tree.body, localEnv);
   730             }
   731             localEnv.info.scope.leave();
   732             result = tree.type = m.type;
   733             chk.validateAnnotations(tree.mods.annotations, m);
   734         }
   735         finally {
   736             chk.setLint(prevLint);
   737         }
   738     }
   740     public void visitVarDef(JCVariableDecl tree) {
   741         // Local variables have not been entered yet, so we need to do it now:
   742         if (env.info.scope.owner.kind == MTH) {
   743             if (tree.sym != null) {
   744                 // parameters have already been entered
   745                 env.info.scope.enter(tree.sym);
   746             } else {
   747                 memberEnter.memberEnter(tree, env);
   748                 annotate.flush();
   749             }
   750         }
   752         VarSymbol v = tree.sym;
   753         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   754         Lint prevLint = chk.setLint(lint);
   756         // Check that the variable's declared type is well-formed.
   757         chk.validate(tree.vartype, env);
   759         try {
   760             chk.checkDeprecatedAnnotation(tree.pos(), v);
   762             if (tree.init != null) {
   763                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   764                     // In this case, `v' is final.  Ensure that it's initializer is
   765                     // evaluated.
   766                     v.getConstValue(); // ensure initializer is evaluated
   767                 } else {
   768                     // Attribute initializer in a new environment
   769                     // with the declared variable as owner.
   770                     // Check that initializer conforms to variable's declared type.
   771                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   772                     initEnv.info.lint = lint;
   773                     // In order to catch self-references, we set the variable's
   774                     // declaration position to maximal possible value, effectively
   775                     // marking the variable as undefined.
   776                     initEnv.info.enclVar = v;
   777                     attribExpr(tree.init, initEnv, v.type);
   778                 }
   779             }
   780             result = tree.type = v.type;
   781             chk.validateAnnotations(tree.mods.annotations, v);
   782         }
   783         finally {
   784             chk.setLint(prevLint);
   785         }
   786     }
   788     public void visitSkip(JCSkip tree) {
   789         result = null;
   790     }
   792     public void visitBlock(JCBlock tree) {
   793         if (env.info.scope.owner.kind == TYP) {
   794             // Block is a static or instance initializer;
   795             // let the owner of the environment be a freshly
   796             // created BLOCK-method.
   797             Env<AttrContext> localEnv =
   798                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   799             localEnv.info.scope.owner =
   800                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   801                                  env.info.scope.owner);
   802             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   803             attribStats(tree.stats, localEnv);
   804         } else {
   805             // Create a new local environment with a local scope.
   806             Env<AttrContext> localEnv =
   807                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   808             attribStats(tree.stats, localEnv);
   809             localEnv.info.scope.leave();
   810         }
   811         result = null;
   812     }
   814     public void visitDoLoop(JCDoWhileLoop tree) {
   815         attribStat(tree.body, env.dup(tree));
   816         attribExpr(tree.cond, env, syms.booleanType);
   817         result = null;
   818     }
   820     public void visitWhileLoop(JCWhileLoop tree) {
   821         attribExpr(tree.cond, env, syms.booleanType);
   822         attribStat(tree.body, env.dup(tree));
   823         result = null;
   824     }
   826     public void visitForLoop(JCForLoop tree) {
   827         Env<AttrContext> loopEnv =
   828             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   829         attribStats(tree.init, loopEnv);
   830         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   831         loopEnv.tree = tree; // before, we were not in loop!
   832         attribStats(tree.step, loopEnv);
   833         attribStat(tree.body, loopEnv);
   834         loopEnv.info.scope.leave();
   835         result = null;
   836     }
   838     public void visitForeachLoop(JCEnhancedForLoop tree) {
   839         Env<AttrContext> loopEnv =
   840             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   841         attribStat(tree.var, loopEnv);
   842         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   843         chk.checkNonVoid(tree.pos(), exprType);
   844         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   845         if (elemtype == null) {
   846             // or perhaps expr implements Iterable<T>?
   847             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   848             if (base == null) {
   849                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   850                 elemtype = types.createErrorType(exprType);
   851             } else {
   852                 List<Type> iterableParams = base.allparams();
   853                 elemtype = iterableParams.isEmpty()
   854                     ? syms.objectType
   855                     : types.upperBound(iterableParams.head);
   856             }
   857         }
   858         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   859         loopEnv.tree = tree; // before, we were not in loop!
   860         attribStat(tree.body, loopEnv);
   861         loopEnv.info.scope.leave();
   862         result = null;
   863     }
   865     public void visitLabelled(JCLabeledStatement tree) {
   866         // Check that label is not used in an enclosing statement
   867         Env<AttrContext> env1 = env;
   868         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   869             if (env1.tree.getTag() == JCTree.LABELLED &&
   870                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   871                 log.error(tree.pos(), "label.already.in.use",
   872                           tree.label);
   873                 break;
   874             }
   875             env1 = env1.next;
   876         }
   878         attribStat(tree.body, env.dup(tree));
   879         result = null;
   880     }
   882     public void visitSwitch(JCSwitch tree) {
   883         Type seltype = attribExpr(tree.selector, env);
   885         Env<AttrContext> switchEnv =
   886             env.dup(tree, env.info.dup(env.info.scope.dup()));
   888         boolean enumSwitch =
   889             allowEnums &&
   890             (seltype.tsym.flags() & Flags.ENUM) != 0;
   891         boolean stringSwitch = false;
   892         if (types.isSameType(seltype, syms.stringType)) {
   893             if (allowStringsInSwitch) {
   894                 stringSwitch = true;
   895             } else {
   896                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   897             }
   898         }
   899         if (!enumSwitch && !stringSwitch)
   900             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   902         // Attribute all cases and
   903         // check that there are no duplicate case labels or default clauses.
   904         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   905         boolean hasDefault = false;      // Is there a default label?
   906         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   907             JCCase c = l.head;
   908             Env<AttrContext> caseEnv =
   909                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   910             if (c.pat != null) {
   911                 if (enumSwitch) {
   912                     Symbol sym = enumConstant(c.pat, seltype);
   913                     if (sym == null) {
   914                         log.error(c.pat.pos(), "enum.const.req");
   915                     } else if (!labels.add(sym)) {
   916                         log.error(c.pos(), "duplicate.case.label");
   917                     }
   918                 } else {
   919                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   920                     if (pattype.tag != ERROR) {
   921                         if (pattype.constValue() == null) {
   922                             log.error(c.pat.pos(),
   923                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
   924                         } else if (labels.contains(pattype.constValue())) {
   925                             log.error(c.pos(), "duplicate.case.label");
   926                         } else {
   927                             labels.add(pattype.constValue());
   928                         }
   929                     }
   930                 }
   931             } else if (hasDefault) {
   932                 log.error(c.pos(), "duplicate.default.label");
   933             } else {
   934                 hasDefault = true;
   935             }
   936             attribStats(c.stats, caseEnv);
   937             caseEnv.info.scope.leave();
   938             addVars(c.stats, switchEnv.info.scope);
   939         }
   941         switchEnv.info.scope.leave();
   942         result = null;
   943     }
   944     // where
   945         /** Add any variables defined in stats to the switch scope. */
   946         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   947             for (;stats.nonEmpty(); stats = stats.tail) {
   948                 JCTree stat = stats.head;
   949                 if (stat.getTag() == JCTree.VARDEF)
   950                     switchScope.enter(((JCVariableDecl) stat).sym);
   951             }
   952         }
   953     // where
   954     /** Return the selected enumeration constant symbol, or null. */
   955     private Symbol enumConstant(JCTree tree, Type enumType) {
   956         if (tree.getTag() != JCTree.IDENT) {
   957             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   958             return syms.errSymbol;
   959         }
   960         JCIdent ident = (JCIdent)tree;
   961         Name name = ident.name;
   962         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   963              e.scope != null; e = e.next()) {
   964             if (e.sym.kind == VAR) {
   965                 Symbol s = ident.sym = e.sym;
   966                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   967                 ident.type = s.type;
   968                 return ((s.flags_field & Flags.ENUM) == 0)
   969                     ? null : s;
   970             }
   971         }
   972         return null;
   973     }
   975     public void visitSynchronized(JCSynchronized tree) {
   976         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
   977         attribStat(tree.body, env);
   978         result = null;
   979     }
   981     public void visitTry(JCTry tree) {
   982         // Attribute body
   983         attribStat(tree.body, env.dup(tree, env.info.dup()));
   985         // Attribute catch clauses
   986         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   987             JCCatch c = l.head;
   988             Env<AttrContext> catchEnv =
   989                 env.dup(c, env.info.dup(env.info.scope.dup()));
   990             Type ctype = attribStat(c.param, catchEnv);
   991             if (TreeInfo.isMultiCatch(c)) {
   992                 //check that multi-catch parameter is marked as final
   993                 if ((c.param.sym.flags() & FINAL) == 0) {
   994                     log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
   995                 }
   996                 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
   997             }
   998             if (c.param.type.tsym.kind == Kinds.VAR) {
   999                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1001             chk.checkType(c.param.vartype.pos(),
  1002                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1003                           syms.throwableType);
  1004             attribStat(c.body, catchEnv);
  1005             catchEnv.info.scope.leave();
  1008         // Attribute finalizer
  1009         if (tree.finalizer != null) attribStat(tree.finalizer, env);
  1010         result = null;
  1013     public void visitConditional(JCConditional tree) {
  1014         attribExpr(tree.cond, env, syms.booleanType);
  1015         attribExpr(tree.truepart, env);
  1016         attribExpr(tree.falsepart, env);
  1017         result = check(tree,
  1018                        capture(condType(tree.pos(), tree.cond.type,
  1019                                         tree.truepart.type, tree.falsepart.type)),
  1020                        VAL, pkind, pt);
  1022     //where
  1023         /** Compute the type of a conditional expression, after
  1024          *  checking that it exists. See Spec 15.25.
  1026          *  @param pos      The source position to be used for
  1027          *                  error diagnostics.
  1028          *  @param condtype The type of the expression's condition.
  1029          *  @param thentype The type of the expression's then-part.
  1030          *  @param elsetype The type of the expression's else-part.
  1031          */
  1032         private Type condType(DiagnosticPosition pos,
  1033                               Type condtype,
  1034                               Type thentype,
  1035                               Type elsetype) {
  1036             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1038             // If condition and both arms are numeric constants,
  1039             // evaluate at compile-time.
  1040             return ((condtype.constValue() != null) &&
  1041                     (thentype.constValue() != null) &&
  1042                     (elsetype.constValue() != null))
  1043                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1044                 : ctype;
  1046         /** Compute the type of a conditional expression, after
  1047          *  checking that it exists.  Does not take into
  1048          *  account the special case where condition and both arms
  1049          *  are constants.
  1051          *  @param pos      The source position to be used for error
  1052          *                  diagnostics.
  1053          *  @param condtype The type of the expression's condition.
  1054          *  @param thentype The type of the expression's then-part.
  1055          *  @param elsetype The type of the expression's else-part.
  1056          */
  1057         private Type condType1(DiagnosticPosition pos, Type condtype,
  1058                                Type thentype, Type elsetype) {
  1059             // If same type, that is the result
  1060             if (types.isSameType(thentype, elsetype))
  1061                 return thentype.baseType();
  1063             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1064                 ? thentype : types.unboxedType(thentype);
  1065             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1066                 ? elsetype : types.unboxedType(elsetype);
  1068             // Otherwise, if both arms can be converted to a numeric
  1069             // type, return the least numeric type that fits both arms
  1070             // (i.e. return larger of the two, or return int if one
  1071             // arm is short, the other is char).
  1072             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1073                 // If one arm has an integer subrange type (i.e., byte,
  1074                 // short, or char), and the other is an integer constant
  1075                 // that fits into the subrange, return the subrange type.
  1076                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1077                     types.isAssignable(elseUnboxed, thenUnboxed))
  1078                     return thenUnboxed.baseType();
  1079                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1080                     types.isAssignable(thenUnboxed, elseUnboxed))
  1081                     return elseUnboxed.baseType();
  1083                 for (int i = BYTE; i < VOID; i++) {
  1084                     Type candidate = syms.typeOfTag[i];
  1085                     if (types.isSubtype(thenUnboxed, candidate) &&
  1086                         types.isSubtype(elseUnboxed, candidate))
  1087                         return candidate;
  1091             // Those were all the cases that could result in a primitive
  1092             if (allowBoxing) {
  1093                 if (thentype.isPrimitive())
  1094                     thentype = types.boxedClass(thentype).type;
  1095                 if (elsetype.isPrimitive())
  1096                     elsetype = types.boxedClass(elsetype).type;
  1099             if (types.isSubtype(thentype, elsetype))
  1100                 return elsetype.baseType();
  1101             if (types.isSubtype(elsetype, thentype))
  1102                 return thentype.baseType();
  1104             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1105                 log.error(pos, "neither.conditional.subtype",
  1106                           thentype, elsetype);
  1107                 return thentype.baseType();
  1110             // both are known to be reference types.  The result is
  1111             // lub(thentype,elsetype). This cannot fail, as it will
  1112             // always be possible to infer "Object" if nothing better.
  1113             return types.lub(thentype.baseType(), elsetype.baseType());
  1116     public void visitIf(JCIf tree) {
  1117         attribExpr(tree.cond, env, syms.booleanType);
  1118         attribStat(tree.thenpart, env);
  1119         if (tree.elsepart != null)
  1120             attribStat(tree.elsepart, env);
  1121         chk.checkEmptyIf(tree);
  1122         result = null;
  1125     public void visitExec(JCExpressionStatement tree) {
  1126         attribExpr(tree.expr, env);
  1127         result = null;
  1130     public void visitBreak(JCBreak tree) {
  1131         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1132         result = null;
  1135     public void visitContinue(JCContinue tree) {
  1136         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1137         result = null;
  1139     //where
  1140         /** Return the target of a break or continue statement, if it exists,
  1141          *  report an error if not.
  1142          *  Note: The target of a labelled break or continue is the
  1143          *  (non-labelled) statement tree referred to by the label,
  1144          *  not the tree representing the labelled statement itself.
  1146          *  @param pos     The position to be used for error diagnostics
  1147          *  @param tag     The tag of the jump statement. This is either
  1148          *                 Tree.BREAK or Tree.CONTINUE.
  1149          *  @param label   The label of the jump statement, or null if no
  1150          *                 label is given.
  1151          *  @param env     The environment current at the jump statement.
  1152          */
  1153         private JCTree findJumpTarget(DiagnosticPosition pos,
  1154                                     int tag,
  1155                                     Name label,
  1156                                     Env<AttrContext> env) {
  1157             // Search environments outwards from the point of jump.
  1158             Env<AttrContext> env1 = env;
  1159             LOOP:
  1160             while (env1 != null) {
  1161                 switch (env1.tree.getTag()) {
  1162                 case JCTree.LABELLED:
  1163                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1164                     if (label == labelled.label) {
  1165                         // If jump is a continue, check that target is a loop.
  1166                         if (tag == JCTree.CONTINUE) {
  1167                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1168                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1169                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1170                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1171                                 log.error(pos, "not.loop.label", label);
  1172                             // Found labelled statement target, now go inwards
  1173                             // to next non-labelled tree.
  1174                             return TreeInfo.referencedStatement(labelled);
  1175                         } else {
  1176                             return labelled;
  1179                     break;
  1180                 case JCTree.DOLOOP:
  1181                 case JCTree.WHILELOOP:
  1182                 case JCTree.FORLOOP:
  1183                 case JCTree.FOREACHLOOP:
  1184                     if (label == null) return env1.tree;
  1185                     break;
  1186                 case JCTree.SWITCH:
  1187                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1188                     break;
  1189                 case JCTree.METHODDEF:
  1190                 case JCTree.CLASSDEF:
  1191                     break LOOP;
  1192                 default:
  1194                 env1 = env1.next;
  1196             if (label != null)
  1197                 log.error(pos, "undef.label", label);
  1198             else if (tag == JCTree.CONTINUE)
  1199                 log.error(pos, "cont.outside.loop");
  1200             else
  1201                 log.error(pos, "break.outside.switch.loop");
  1202             return null;
  1205     public void visitReturn(JCReturn tree) {
  1206         // Check that there is an enclosing method which is
  1207         // nested within than the enclosing class.
  1208         if (env.enclMethod == null ||
  1209             env.enclMethod.sym.owner != env.enclClass.sym) {
  1210             log.error(tree.pos(), "ret.outside.meth");
  1212         } else {
  1213             // Attribute return expression, if it exists, and check that
  1214             // it conforms to result type of enclosing method.
  1215             Symbol m = env.enclMethod.sym;
  1216             if (m.type.getReturnType().tag == VOID) {
  1217                 if (tree.expr != null)
  1218                     log.error(tree.expr.pos(),
  1219                               "cant.ret.val.from.meth.decl.void");
  1220             } else if (tree.expr == null) {
  1221                 log.error(tree.pos(), "missing.ret.val");
  1222             } else {
  1223                 attribExpr(tree.expr, env, m.type.getReturnType());
  1226         result = null;
  1229     public void visitThrow(JCThrow tree) {
  1230         attribExpr(tree.expr, env, syms.throwableType);
  1231         result = null;
  1234     public void visitAssert(JCAssert tree) {
  1235         attribExpr(tree.cond, env, syms.booleanType);
  1236         if (tree.detail != null) {
  1237             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1239         result = null;
  1242      /** Visitor method for method invocations.
  1243      *  NOTE: The method part of an application will have in its type field
  1244      *        the return type of the method, not the method's type itself!
  1245      */
  1246     public void visitApply(JCMethodInvocation tree) {
  1247         // The local environment of a method application is
  1248         // a new environment nested in the current one.
  1249         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1251         // The types of the actual method arguments.
  1252         List<Type> argtypes;
  1254         // The types of the actual method type arguments.
  1255         List<Type> typeargtypes = null;
  1256         boolean typeargtypesNonRefOK = false;
  1258         Name methName = TreeInfo.name(tree.meth);
  1260         boolean isConstructorCall =
  1261             methName == names._this || methName == names._super;
  1263         if (isConstructorCall) {
  1264             // We are seeing a ...this(...) or ...super(...) call.
  1265             // Check that this is the first statement in a constructor.
  1266             if (checkFirstConstructorStat(tree, env)) {
  1268                 // Record the fact
  1269                 // that this is a constructor call (using isSelfCall).
  1270                 localEnv.info.isSelfCall = true;
  1272                 // Attribute arguments, yielding list of argument types.
  1273                 argtypes = attribArgs(tree.args, localEnv);
  1274                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1276                 // Variable `site' points to the class in which the called
  1277                 // constructor is defined.
  1278                 Type site = env.enclClass.sym.type;
  1279                 if (methName == names._super) {
  1280                     if (site == syms.objectType) {
  1281                         log.error(tree.meth.pos(), "no.superclass", site);
  1282                         site = types.createErrorType(syms.objectType);
  1283                     } else {
  1284                         site = types.supertype(site);
  1288                 if (site.tag == CLASS) {
  1289                     Type encl = site.getEnclosingType();
  1290                     while (encl != null && encl.tag == TYPEVAR)
  1291                         encl = encl.getUpperBound();
  1292                     if (encl.tag == CLASS) {
  1293                         // we are calling a nested class
  1295                         if (tree.meth.getTag() == JCTree.SELECT) {
  1296                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1298                             // We are seeing a prefixed call, of the form
  1299                             //     <expr>.super(...).
  1300                             // Check that the prefix expression conforms
  1301                             // to the outer instance type of the class.
  1302                             chk.checkRefType(qualifier.pos(),
  1303                                              attribExpr(qualifier, localEnv,
  1304                                                         encl));
  1305                         } else if (methName == names._super) {
  1306                             // qualifier omitted; check for existence
  1307                             // of an appropriate implicit qualifier.
  1308                             rs.resolveImplicitThis(tree.meth.pos(),
  1309                                                    localEnv, site);
  1311                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1312                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1313                                   site.tsym);
  1316                     // if we're calling a java.lang.Enum constructor,
  1317                     // prefix the implicit String and int parameters
  1318                     if (site.tsym == syms.enumSym && allowEnums)
  1319                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1321                     // Resolve the called constructor under the assumption
  1322                     // that we are referring to a superclass instance of the
  1323                     // current instance (JLS ???).
  1324                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1325                     localEnv.info.selectSuper = true;
  1326                     localEnv.info.varArgs = false;
  1327                     Symbol sym = rs.resolveConstructor(
  1328                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1329                     localEnv.info.selectSuper = selectSuperPrev;
  1331                     // Set method symbol to resolved constructor...
  1332                     TreeInfo.setSymbol(tree.meth, sym);
  1334                     // ...and check that it is legal in the current context.
  1335                     // (this will also set the tree's type)
  1336                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1337                     checkId(tree.meth, site, sym, localEnv, MTH,
  1338                             mpt, tree.varargsElement != null);
  1340                 // Otherwise, `site' is an error type and we do nothing
  1342             result = tree.type = syms.voidType;
  1343         } else {
  1344             // Otherwise, we are seeing a regular method call.
  1345             // Attribute the arguments, yielding list of argument types, ...
  1346             argtypes = attribArgs(tree.args, localEnv);
  1347             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1349             // ... and attribute the method using as a prototype a methodtype
  1350             // whose formal argument types is exactly the list of actual
  1351             // arguments (this will also set the method symbol).
  1352             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1353             localEnv.info.varArgs = false;
  1354             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1355             if (localEnv.info.varArgs)
  1356                 assert mtype.isErroneous() || tree.varargsElement != null;
  1358             // Compute the result type.
  1359             Type restype = mtype.getReturnType();
  1360             assert restype.tag != WILDCARD : mtype;
  1362             // as a special case, array.clone() has a result that is
  1363             // the same as static type of the array being cloned
  1364             if (tree.meth.getTag() == JCTree.SELECT &&
  1365                 allowCovariantReturns &&
  1366                 methName == names.clone &&
  1367                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1368                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1370             // as a special case, x.getClass() has type Class<? extends |X|>
  1371             if (allowGenerics &&
  1372                 methName == names.getClass && tree.args.isEmpty()) {
  1373                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1374                     ? ((JCFieldAccess) tree.meth).selected.type
  1375                     : env.enclClass.sym.type;
  1376                 restype = new
  1377                     ClassType(restype.getEnclosingType(),
  1378                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1379                                                                BoundKind.EXTENDS,
  1380                                                                syms.boundClass)),
  1381                               restype.tsym);
  1384             // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
  1385             // has type <T>, and T can be a primitive type.
  1386             if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
  1387               Type selt = ((JCFieldAccess) tree.meth).selected.type;
  1388               if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) {
  1389                   assert types.isSameType(restype, typeargtypes.head) : mtype;
  1390                   typeargtypesNonRefOK = true;
  1394             if (!typeargtypesNonRefOK) {
  1395                 chk.checkRefTypes(tree.typeargs, typeargtypes);
  1398             // Check that value of resulting type is admissible in the
  1399             // current context.  Also, capture the return type
  1400             result = check(tree, capture(restype), VAL, pkind, pt);
  1402         chk.validate(tree.typeargs, localEnv);
  1404     //where
  1405         /** Check that given application node appears as first statement
  1406          *  in a constructor call.
  1407          *  @param tree   The application node
  1408          *  @param env    The environment current at the application.
  1409          */
  1410         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1411             JCMethodDecl enclMethod = env.enclMethod;
  1412             if (enclMethod != null && enclMethod.name == names.init) {
  1413                 JCBlock body = enclMethod.body;
  1414                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1415                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1416                     return true;
  1418             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1419                       TreeInfo.name(tree.meth));
  1420             return false;
  1423         /** Obtain a method type with given argument types.
  1424          */
  1425         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1426             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1427             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1430     public void visitNewClass(JCNewClass tree) {
  1431         Type owntype = types.createErrorType(tree.type);
  1433         // The local environment of a class creation is
  1434         // a new environment nested in the current one.
  1435         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1437         // The anonymous inner class definition of the new expression,
  1438         // if one is defined by it.
  1439         JCClassDecl cdef = tree.def;
  1441         // If enclosing class is given, attribute it, and
  1442         // complete class name to be fully qualified
  1443         JCExpression clazz = tree.clazz; // Class field following new
  1444         JCExpression clazzid =          // Identifier in class field
  1445             (clazz.getTag() == JCTree.TYPEAPPLY)
  1446             ? ((JCTypeApply) clazz).clazz
  1447             : clazz;
  1449         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1451         if (tree.encl != null) {
  1452             // We are seeing a qualified new, of the form
  1453             //    <expr>.new C <...> (...) ...
  1454             // In this case, we let clazz stand for the name of the
  1455             // allocated class C prefixed with the type of the qualifier
  1456             // expression, so that we can
  1457             // resolve it with standard techniques later. I.e., if
  1458             // <expr> has type T, then <expr>.new C <...> (...)
  1459             // yields a clazz T.C.
  1460             Type encltype = chk.checkRefType(tree.encl.pos(),
  1461                                              attribExpr(tree.encl, env));
  1462             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1463                                                  ((JCIdent) clazzid).name);
  1464             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1465                 clazz = make.at(tree.pos).
  1466                     TypeApply(clazzid1,
  1467                               ((JCTypeApply) clazz).arguments);
  1468             else
  1469                 clazz = clazzid1;
  1472         // Attribute clazz expression and store
  1473         // symbol + type back into the attributed tree.
  1474         Type clazztype = attribType(clazz, env);
  1475         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
  1476         if (!TreeInfo.isDiamond(tree)) {
  1477             clazztype = chk.checkClassType(
  1478                 tree.clazz.pos(), clazztype, true);
  1480         chk.validate(clazz, localEnv);
  1481         if (tree.encl != null) {
  1482             // We have to work in this case to store
  1483             // symbol + type back into the attributed tree.
  1484             tree.clazz.type = clazztype;
  1485             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1486             clazzid.type = ((JCIdent) clazzid).sym.type;
  1487             if (!clazztype.isErroneous()) {
  1488                 if (cdef != null && clazztype.tsym.isInterface()) {
  1489                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1490                 } else if (clazztype.tsym.isStatic()) {
  1491                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1494         } else if (!clazztype.tsym.isInterface() &&
  1495                    clazztype.getEnclosingType().tag == CLASS) {
  1496             // Check for the existence of an apropos outer instance
  1497             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1500         // Attribute constructor arguments.
  1501         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1502         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1504         if (TreeInfo.isDiamond(tree)) {
  1505             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes, true);
  1506             clazz.type = clazztype;
  1509         // If we have made no mistakes in the class type...
  1510         if (clazztype.tag == CLASS) {
  1511             // Enums may not be instantiated except implicitly
  1512             if (allowEnums &&
  1513                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1514                 (env.tree.getTag() != JCTree.VARDEF ||
  1515                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1516                  ((JCVariableDecl) env.tree).init != tree))
  1517                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1518             // Check that class is not abstract
  1519             if (cdef == null &&
  1520                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1521                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1522                           clazztype.tsym);
  1523             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1524                 // Check that no constructor arguments are given to
  1525                 // anonymous classes implementing an interface
  1526                 if (!argtypes.isEmpty())
  1527                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1529                 if (!typeargtypes.isEmpty())
  1530                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1532                 // Error recovery: pretend no arguments were supplied.
  1533                 argtypes = List.nil();
  1534                 typeargtypes = List.nil();
  1537             // Resolve the called constructor under the assumption
  1538             // that we are referring to a superclass instance of the
  1539             // current instance (JLS ???).
  1540             else {
  1541                 localEnv.info.selectSuper = cdef != null;
  1542                 localEnv.info.varArgs = false;
  1543                 tree.constructor = rs.resolveConstructor(
  1544                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1545                 tree.constructorType = checkMethod(clazztype,
  1546                                                 tree.constructor,
  1547                                                 localEnv,
  1548                                                 tree.args,
  1549                                                 argtypes,
  1550                                                 typeargtypes,
  1551                                                 localEnv.info.varArgs);
  1552                 if (localEnv.info.varArgs)
  1553                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
  1556             if (cdef != null) {
  1557                 // We are seeing an anonymous class instance creation.
  1558                 // In this case, the class instance creation
  1559                 // expression
  1560                 //
  1561                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1562                 //
  1563                 // is represented internally as
  1564                 //
  1565                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1566                 //
  1567                 // This expression is then *transformed* as follows:
  1568                 //
  1569                 // (1) add a STATIC flag to the class definition
  1570                 //     if the current environment is static
  1571                 // (2) add an extends or implements clause
  1572                 // (3) add a constructor.
  1573                 //
  1574                 // For instance, if C is a class, and ET is the type of E,
  1575                 // the expression
  1576                 //
  1577                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1578                 //
  1579                 // is translated to (where X is a fresh name and typarams is the
  1580                 // parameter list of the super constructor):
  1581                 //
  1582                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1583                 //     X extends C<typargs2> {
  1584                 //       <typarams> X(ET e, args) {
  1585                 //         e.<typeargs1>super(args)
  1586                 //       }
  1587                 //       ...
  1588                 //     }
  1589                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1591                 if (clazztype.tsym.isInterface()) {
  1592                     cdef.implementing = List.of(clazz);
  1593                 } else {
  1594                     cdef.extending = clazz;
  1597                 attribStat(cdef, localEnv);
  1599                 // If an outer instance is given,
  1600                 // prefix it to the constructor arguments
  1601                 // and delete it from the new expression
  1602                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1603                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1604                     argtypes = argtypes.prepend(tree.encl.type);
  1605                     tree.encl = null;
  1608                 // Reassign clazztype and recompute constructor.
  1609                 clazztype = cdef.sym.type;
  1610                 Symbol sym = rs.resolveConstructor(
  1611                     tree.pos(), localEnv, clazztype, argtypes,
  1612                     typeargtypes, true, tree.varargsElement != null);
  1613                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1614                 tree.constructor = sym;
  1615                 if (tree.constructor.kind > ERRONEOUS) {
  1616                     tree.constructorType =  syms.errType;
  1618                 else {
  1619                     tree.constructorType = checkMethod(clazztype,
  1620                             tree.constructor,
  1621                             localEnv,
  1622                             tree.args,
  1623                             argtypes,
  1624                             typeargtypes,
  1625                             localEnv.info.varArgs);
  1629             if (tree.constructor != null && tree.constructor.kind == MTH)
  1630                 owntype = clazztype;
  1632         result = check(tree, owntype, VAL, pkind, pt);
  1633         chk.validate(tree.typeargs, localEnv);
  1636     Type attribDiamond(Env<AttrContext> env,
  1637                         JCNewClass tree,
  1638                         Type clazztype,
  1639                         Pair<Scope, Scope> mapping,
  1640                         List<Type> argtypes,
  1641                         List<Type> typeargtypes,
  1642                         boolean reportErrors) {
  1643         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1644             //if the type of the instance creation expression is erroneous,
  1645             //or something prevented us to form a valid mapping, return the
  1646             //(possibly erroneous) type unchanged
  1647             return clazztype;
  1649         else if (clazztype.isInterface()) {
  1650             //if the type of the instance creation expression is an interface
  1651             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1652             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1653             clazztype = new ForAll(clazztype.tsym.type.allparams(),
  1654                     clazztype.tsym.type);
  1655         } else {
  1656             //if the type of the instance creation expression is a class type
  1657             //apply method resolution inference (JLS 15.12.2.7). The return type
  1658             //of the resolved constructor will be a partially instantiated type
  1659             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1660             Symbol constructor;
  1661             try {
  1662                 constructor = rs.resolveDiamond(tree.pos(),
  1663                         env,
  1664                         clazztype.tsym.type,
  1665                         argtypes,
  1666                         typeargtypes, reportErrors);
  1667             } finally {
  1668                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1670             if (constructor.kind == MTH) {
  1671                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1672                         clazztype.tsym.type.getTypeArguments(),
  1673                         clazztype.tsym);
  1674                 clazztype = checkMethod(ct,
  1675                         constructor,
  1676                         env,
  1677                         tree.args,
  1678                         argtypes,
  1679                         typeargtypes,
  1680                         env.info.varArgs).getReturnType();
  1681             } else {
  1682                 clazztype = syms.errType;
  1685         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1686             //if the resolved constructor's return type has some uninferred
  1687             //type-variables, infer them using the expected type and declared
  1688             //bounds (JLS 15.12.2.8).
  1689             try {
  1690                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1691                         pt.tag == NONE ? syms.objectType : pt,
  1692                         Warner.noWarnings);
  1693             } catch (Infer.InferenceException ex) {
  1694                 //an error occurred while inferring uninstantiated type-variables
  1695                 //we need to optionally report an error
  1696                 if (reportErrors) {
  1697                     log.error(tree.clazz.pos(),
  1698                             "cant.apply.diamond.1",
  1699                             diags.fragment("diamond", clazztype.tsym),
  1700                             ex.diagnostic);
  1704         if (reportErrors) {
  1705             clazztype = chk.checkClassType(tree.clazz.pos(),
  1706                     clazztype,
  1707                     true);
  1708             if (clazztype.tag == CLASS) {
  1709                 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1710                 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1711                     //one or more types inferred in the previous steps is either a
  1712                     //captured type or an intersection type --- we need to report an error.
  1713                     String subkey = invalidDiamondArgs.size() > 1 ?
  1714                         "diamond.invalid.args" :
  1715                         "diamond.invalid.arg";
  1716                     //The error message is of the kind:
  1717                     //
  1718                     //cannot infer type arguments for {clazztype}<>;
  1719                     //reason: {subkey}
  1720                     //
  1721                     //where subkey is a fragment of the kind:
  1722                     //
  1723                     //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1724                     log.error(tree.clazz.pos(),
  1725                                 "cant.apply.diamond.1",
  1726                                 diags.fragment("diamond", clazztype.tsym),
  1727                                 diags.fragment(subkey,
  1728                                                invalidDiamondArgs,
  1729                                                diags.fragment("diamond", clazztype.tsym)));
  1733         return clazztype;
  1736     /** Creates a synthetic scope containing fake generic constructors.
  1737      *  Assuming that the original scope contains a constructor of the kind:
  1738      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1739      *  the synthetic scope is added a generic constructor of the kind:
  1740      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1741      *  inference. The inferred return type of the synthetic constructor IS
  1742      *  the inferred type for the diamond operator.
  1743      */
  1744     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
  1745         if (ctype.tag != CLASS) {
  1746             return erroneousMapping;
  1748         Pair<Scope, Scope> mapping =
  1749                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1750         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1751         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1752                 e.scope != null;
  1753                 e = e.next()) {
  1754             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1755             newConstr.name = names.init;
  1756             List<Type> oldTypeargs = List.nil();
  1757             if (newConstr.type.tag == FORALL) {
  1758                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1760             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1761                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1762                     newConstr.type.getThrownTypes(),
  1763                     syms.methodClass);
  1764             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1765             mapping.snd.enter(newConstr);
  1767         return mapping;
  1770     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1772     /** Make an attributed null check tree.
  1773      */
  1774     public JCExpression makeNullCheck(JCExpression arg) {
  1775         // optimization: X.this is never null; skip null check
  1776         Name name = TreeInfo.name(arg);
  1777         if (name == names._this || name == names._super) return arg;
  1779         int optag = JCTree.NULLCHK;
  1780         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1781         tree.operator = syms.nullcheck;
  1782         tree.type = arg.type;
  1783         return tree;
  1786     public void visitNewArray(JCNewArray tree) {
  1787         Type owntype = types.createErrorType(tree.type);
  1788         Type elemtype;
  1789         if (tree.elemtype != null) {
  1790             elemtype = attribType(tree.elemtype, env);
  1791             chk.validate(tree.elemtype, env);
  1792             owntype = elemtype;
  1793             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1794                 attribExpr(l.head, env, syms.intType);
  1795                 owntype = new ArrayType(owntype, syms.arrayClass);
  1797         } else {
  1798             // we are seeing an untyped aggregate { ... }
  1799             // this is allowed only if the prototype is an array
  1800             if (pt.tag == ARRAY) {
  1801                 elemtype = types.elemtype(pt);
  1802             } else {
  1803                 if (pt.tag != ERROR) {
  1804                     log.error(tree.pos(), "illegal.initializer.for.type",
  1805                               pt);
  1807                 elemtype = types.createErrorType(pt);
  1810         if (tree.elems != null) {
  1811             attribExprs(tree.elems, env, elemtype);
  1812             owntype = new ArrayType(elemtype, syms.arrayClass);
  1814         if (!types.isReifiable(elemtype))
  1815             log.error(tree.pos(), "generic.array.creation");
  1816         result = check(tree, owntype, VAL, pkind, pt);
  1819     public void visitParens(JCParens tree) {
  1820         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1821         result = check(tree, owntype, pkind, pkind, pt);
  1822         Symbol sym = TreeInfo.symbol(tree);
  1823         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1824             log.error(tree.pos(), "illegal.start.of.type");
  1827     public void visitAssign(JCAssign tree) {
  1828         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1829         Type capturedType = capture(owntype);
  1830         attribExpr(tree.rhs, env, owntype);
  1831         result = check(tree, capturedType, VAL, pkind, pt);
  1834     public void visitAssignop(JCAssignOp tree) {
  1835         // Attribute arguments.
  1836         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1837         Type operand = attribExpr(tree.rhs, env);
  1838         // Find operator.
  1839         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1840             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1841             owntype, operand);
  1843         if (operator.kind == MTH) {
  1844             chk.checkOperator(tree.pos(),
  1845                               (OperatorSymbol)operator,
  1846                               tree.getTag() - JCTree.ASGOffset,
  1847                               owntype,
  1848                               operand);
  1849             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1850             chk.checkCastable(tree.rhs.pos(),
  1851                               operator.type.getReturnType(),
  1852                               owntype);
  1854         result = check(tree, owntype, VAL, pkind, pt);
  1857     public void visitUnary(JCUnary tree) {
  1858         // Attribute arguments.
  1859         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1860             ? attribTree(tree.arg, env, VAR, Type.noType)
  1861             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1863         // Find operator.
  1864         Symbol operator = tree.operator =
  1865             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1867         Type owntype = types.createErrorType(tree.type);
  1868         if (operator.kind == MTH) {
  1869             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1870                 ? tree.arg.type
  1871                 : operator.type.getReturnType();
  1872             int opc = ((OperatorSymbol)operator).opcode;
  1874             // If the argument is constant, fold it.
  1875             if (argtype.constValue() != null) {
  1876                 Type ctype = cfolder.fold1(opc, argtype);
  1877                 if (ctype != null) {
  1878                     owntype = cfolder.coerce(ctype, owntype);
  1880                     // Remove constant types from arguments to
  1881                     // conserve space. The parser will fold concatenations
  1882                     // of string literals; the code here also
  1883                     // gets rid of intermediate results when some of the
  1884                     // operands are constant identifiers.
  1885                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1886                         tree.arg.type = syms.stringType;
  1891         result = check(tree, owntype, VAL, pkind, pt);
  1894     public void visitBinary(JCBinary tree) {
  1895         // Attribute arguments.
  1896         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1897         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1899         // Find operator.
  1900         Symbol operator = tree.operator =
  1901             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1903         Type owntype = types.createErrorType(tree.type);
  1904         if (operator.kind == MTH) {
  1905             owntype = operator.type.getReturnType();
  1906             int opc = chk.checkOperator(tree.lhs.pos(),
  1907                                         (OperatorSymbol)operator,
  1908                                         tree.getTag(),
  1909                                         left,
  1910                                         right);
  1912             // If both arguments are constants, fold them.
  1913             if (left.constValue() != null && right.constValue() != null) {
  1914                 Type ctype = cfolder.fold2(opc, left, right);
  1915                 if (ctype != null) {
  1916                     owntype = cfolder.coerce(ctype, owntype);
  1918                     // Remove constant types from arguments to
  1919                     // conserve space. The parser will fold concatenations
  1920                     // of string literals; the code here also
  1921                     // gets rid of intermediate results when some of the
  1922                     // operands are constant identifiers.
  1923                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1924                         tree.lhs.type = syms.stringType;
  1926                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1927                         tree.rhs.type = syms.stringType;
  1932             // Check that argument types of a reference ==, != are
  1933             // castable to each other, (JLS???).
  1934             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  1935                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  1936                     log.error(tree.pos(), "incomparable.types", left, right);
  1940             chk.checkDivZero(tree.rhs.pos(), operator, right);
  1942         result = check(tree, owntype, VAL, pkind, pt);
  1945     public void visitTypeCast(JCTypeCast tree) {
  1946         Type clazztype = attribType(tree.clazz, env);
  1947         chk.validate(tree.clazz, env);
  1948         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  1949         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1950         if (exprtype.constValue() != null)
  1951             owntype = cfolder.coerce(exprtype, owntype);
  1952         result = check(tree, capture(owntype), VAL, pkind, pt);
  1955     public void visitTypeTest(JCInstanceOf tree) {
  1956         Type exprtype = chk.checkNullOrRefType(
  1957             tree.expr.pos(), attribExpr(tree.expr, env));
  1958         Type clazztype = chk.checkReifiableReferenceType(
  1959             tree.clazz.pos(), attribType(tree.clazz, env));
  1960         chk.validate(tree.clazz, env);
  1961         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  1962         result = check(tree, syms.booleanType, VAL, pkind, pt);
  1965     public void visitIndexed(JCArrayAccess tree) {
  1966         Type owntype = types.createErrorType(tree.type);
  1967         Type atype = attribExpr(tree.indexed, env);
  1968         attribExpr(tree.index, env, syms.intType);
  1969         if (types.isArray(atype))
  1970             owntype = types.elemtype(atype);
  1971         else if (atype.tag != ERROR)
  1972             log.error(tree.pos(), "array.req.but.found", atype);
  1973         if ((pkind & VAR) == 0) owntype = capture(owntype);
  1974         result = check(tree, owntype, VAR, pkind, pt);
  1977     public void visitIdent(JCIdent tree) {
  1978         Symbol sym;
  1979         boolean varArgs = false;
  1981         // Find symbol
  1982         if (pt.tag == METHOD || pt.tag == FORALL) {
  1983             // If we are looking for a method, the prototype `pt' will be a
  1984             // method type with the type of the call's arguments as parameters.
  1985             env.info.varArgs = false;
  1986             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  1987             varArgs = env.info.varArgs;
  1988         } else if (tree.sym != null && tree.sym.kind != VAR) {
  1989             sym = tree.sym;
  1990         } else {
  1991             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  1993         tree.sym = sym;
  1995         // (1) Also find the environment current for the class where
  1996         //     sym is defined (`symEnv').
  1997         // Only for pre-tiger versions (1.4 and earlier):
  1998         // (2) Also determine whether we access symbol out of an anonymous
  1999         //     class in a this or super call.  This is illegal for instance
  2000         //     members since such classes don't carry a this$n link.
  2001         //     (`noOuterThisPath').
  2002         Env<AttrContext> symEnv = env;
  2003         boolean noOuterThisPath = false;
  2004         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2005             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2006             sym.owner.kind == TYP &&
  2007             tree.name != names._this && tree.name != names._super) {
  2009             // Find environment in which identifier is defined.
  2010             while (symEnv.outer != null &&
  2011                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2012                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2013                     noOuterThisPath = !allowAnonOuterThis;
  2014                 symEnv = symEnv.outer;
  2018         // If symbol is a variable, ...
  2019         if (sym.kind == VAR) {
  2020             VarSymbol v = (VarSymbol)sym;
  2022             // ..., evaluate its initializer, if it has one, and check for
  2023             // illegal forward reference.
  2024             checkInit(tree, env, v, false);
  2026             // If symbol is a local variable accessed from an embedded
  2027             // inner class check that it is final.
  2028             if (v.owner.kind == MTH &&
  2029                 v.owner != env.info.scope.owner &&
  2030                 (v.flags_field & FINAL) == 0) {
  2031                 log.error(tree.pos(),
  2032                           "local.var.accessed.from.icls.needs.final",
  2033                           v);
  2036             // If we are expecting a variable (as opposed to a value), check
  2037             // that the variable is assignable in the current environment.
  2038             if (pkind == VAR)
  2039                 checkAssignable(tree.pos(), v, null, env);
  2042         // In a constructor body,
  2043         // if symbol is a field or instance method, check that it is
  2044         // not accessed before the supertype constructor is called.
  2045         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2046             (sym.kind & (VAR | MTH)) != 0 &&
  2047             sym.owner.kind == TYP &&
  2048             (sym.flags() & STATIC) == 0) {
  2049             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2051         Env<AttrContext> env1 = env;
  2052         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2053             // If the found symbol is inaccessible, then it is
  2054             // accessed through an enclosing instance.  Locate this
  2055             // enclosing instance:
  2056             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2057                 env1 = env1.outer;
  2059         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2062     public void visitSelect(JCFieldAccess tree) {
  2063         // Determine the expected kind of the qualifier expression.
  2064         int skind = 0;
  2065         if (tree.name == names._this || tree.name == names._super ||
  2066             tree.name == names._class)
  2068             skind = TYP;
  2069         } else {
  2070             if ((pkind & PCK) != 0) skind = skind | PCK;
  2071             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2072             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2075         // Attribute the qualifier expression, and determine its symbol (if any).
  2076         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2077         if ((pkind & (PCK | TYP)) == 0)
  2078             site = capture(site); // Capture field access
  2080         // don't allow T.class T[].class, etc
  2081         if (skind == TYP) {
  2082             Type elt = site;
  2083             while (elt.tag == ARRAY)
  2084                 elt = ((ArrayType)elt).elemtype;
  2085             if (elt.tag == TYPEVAR) {
  2086                 log.error(tree.pos(), "type.var.cant.be.deref");
  2087                 result = types.createErrorType(tree.type);
  2088                 return;
  2092         // If qualifier symbol is a type or `super', assert `selectSuper'
  2093         // for the selection. This is relevant for determining whether
  2094         // protected symbols are accessible.
  2095         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2096         boolean selectSuperPrev = env.info.selectSuper;
  2097         env.info.selectSuper =
  2098             sitesym != null &&
  2099             sitesym.name == names._super;
  2101         // If selected expression is polymorphic, strip
  2102         // type parameters and remember in env.info.tvars, so that
  2103         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2104         if (tree.selected.type.tag == FORALL) {
  2105             ForAll pstype = (ForAll)tree.selected.type;
  2106             env.info.tvars = pstype.tvars;
  2107             site = tree.selected.type = pstype.qtype;
  2110         // Determine the symbol represented by the selection.
  2111         env.info.varArgs = false;
  2112         Symbol sym = selectSym(tree, site, env, pt, pkind);
  2113         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2114             site = capture(site);
  2115             sym = selectSym(tree, site, env, pt, pkind);
  2117         boolean varArgs = env.info.varArgs;
  2118         tree.sym = sym;
  2120         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2121             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2122             site = capture(site);
  2125         // If that symbol is a variable, ...
  2126         if (sym.kind == VAR) {
  2127             VarSymbol v = (VarSymbol)sym;
  2129             // ..., evaluate its initializer, if it has one, and check for
  2130             // illegal forward reference.
  2131             checkInit(tree, env, v, true);
  2133             // If we are expecting a variable (as opposed to a value), check
  2134             // that the variable is assignable in the current environment.
  2135             if (pkind == VAR)
  2136                 checkAssignable(tree.pos(), v, tree.selected, env);
  2139         // Disallow selecting a type from an expression
  2140         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2141             tree.type = check(tree.selected, pt,
  2142                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2145         if (isType(sitesym)) {
  2146             if (sym.name == names._this) {
  2147                 // If `C' is the currently compiled class, check that
  2148                 // C.this' does not appear in a call to a super(...)
  2149                 if (env.info.isSelfCall &&
  2150                     site.tsym == env.enclClass.sym) {
  2151                     chk.earlyRefError(tree.pos(), sym);
  2153             } else {
  2154                 // Check if type-qualified fields or methods are static (JLS)
  2155                 if ((sym.flags() & STATIC) == 0 &&
  2156                     sym.name != names._super &&
  2157                     (sym.kind == VAR || sym.kind == MTH)) {
  2158                     rs.access(rs.new StaticError(sym),
  2159                               tree.pos(), site, sym.name, true);
  2162         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2163             // If the qualified item is not a type and the selected item is static, report
  2164             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2165             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2168         // If we are selecting an instance member via a `super', ...
  2169         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2171             // Check that super-qualified symbols are not abstract (JLS)
  2172             rs.checkNonAbstract(tree.pos(), sym);
  2174             if (site.isRaw()) {
  2175                 // Determine argument types for site.
  2176                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2177                 if (site1 != null) site = site1;
  2181         env.info.selectSuper = selectSuperPrev;
  2182         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2183         env.info.tvars = List.nil();
  2185     //where
  2186         /** Determine symbol referenced by a Select expression,
  2188          *  @param tree   The select tree.
  2189          *  @param site   The type of the selected expression,
  2190          *  @param env    The current environment.
  2191          *  @param pt     The current prototype.
  2192          *  @param pkind  The expected kind(s) of the Select expression.
  2193          */
  2194         private Symbol selectSym(JCFieldAccess tree,
  2195                                  Type site,
  2196                                  Env<AttrContext> env,
  2197                                  Type pt,
  2198                                  int pkind) {
  2199             DiagnosticPosition pos = tree.pos();
  2200             Name name = tree.name;
  2202             switch (site.tag) {
  2203             case PACKAGE:
  2204                 return rs.access(
  2205                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2206                     pos, site, name, true);
  2207             case ARRAY:
  2208             case CLASS:
  2209                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2210                     return rs.resolveQualifiedMethod(
  2211                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2212                 } else if (name == names._this || name == names._super) {
  2213                     return rs.resolveSelf(pos, env, site.tsym, name);
  2214                 } else if (name == names._class) {
  2215                     // In this case, we have already made sure in
  2216                     // visitSelect that qualifier expression is a type.
  2217                     Type t = syms.classType;
  2218                     List<Type> typeargs = allowGenerics
  2219                         ? List.of(types.erasure(site))
  2220                         : List.<Type>nil();
  2221                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2222                     return new VarSymbol(
  2223                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2224                 } else {
  2225                     // We are seeing a plain identifier as selector.
  2226                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2227                     if ((pkind & ERRONEOUS) == 0)
  2228                         sym = rs.access(sym, pos, site, name, true);
  2229                     return sym;
  2231             case WILDCARD:
  2232                 throw new AssertionError(tree);
  2233             case TYPEVAR:
  2234                 // Normally, site.getUpperBound() shouldn't be null.
  2235                 // It should only happen during memberEnter/attribBase
  2236                 // when determining the super type which *must* be
  2237                 // done before attributing the type variables.  In
  2238                 // other words, we are seeing this illegal program:
  2239                 // class B<T> extends A<T.foo> {}
  2240                 Symbol sym = (site.getUpperBound() != null)
  2241                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2242                     : null;
  2243                 if (sym == null) {
  2244                     log.error(pos, "type.var.cant.be.deref");
  2245                     return syms.errSymbol;
  2246                 } else {
  2247                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2248                         rs.new AccessError(env, site, sym) :
  2249                                 sym;
  2250                     rs.access(sym2, pos, site, name, true);
  2251                     return sym;
  2253             case ERROR:
  2254                 // preserve identifier names through errors
  2255                 return types.createErrorType(name, site.tsym, site).tsym;
  2256             default:
  2257                 // The qualifier expression is of a primitive type -- only
  2258                 // .class is allowed for these.
  2259                 if (name == names._class) {
  2260                     // In this case, we have already made sure in Select that
  2261                     // qualifier expression is a type.
  2262                     Type t = syms.classType;
  2263                     Type arg = types.boxedClass(site).type;
  2264                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2265                     return new VarSymbol(
  2266                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2267                 } else {
  2268                     log.error(pos, "cant.deref", site);
  2269                     return syms.errSymbol;
  2274         /** Determine type of identifier or select expression and check that
  2275          *  (1) the referenced symbol is not deprecated
  2276          *  (2) the symbol's type is safe (@see checkSafe)
  2277          *  (3) if symbol is a variable, check that its type and kind are
  2278          *      compatible with the prototype and protokind.
  2279          *  (4) if symbol is an instance field of a raw type,
  2280          *      which is being assigned to, issue an unchecked warning if its
  2281          *      type changes under erasure.
  2282          *  (5) if symbol is an instance method of a raw type, issue an
  2283          *      unchecked warning if its argument types change under erasure.
  2284          *  If checks succeed:
  2285          *    If symbol is a constant, return its constant type
  2286          *    else if symbol is a method, return its result type
  2287          *    otherwise return its type.
  2288          *  Otherwise return errType.
  2290          *  @param tree       The syntax tree representing the identifier
  2291          *  @param site       If this is a select, the type of the selected
  2292          *                    expression, otherwise the type of the current class.
  2293          *  @param sym        The symbol representing the identifier.
  2294          *  @param env        The current environment.
  2295          *  @param pkind      The set of expected kinds.
  2296          *  @param pt         The expected type.
  2297          */
  2298         Type checkId(JCTree tree,
  2299                      Type site,
  2300                      Symbol sym,
  2301                      Env<AttrContext> env,
  2302                      int pkind,
  2303                      Type pt,
  2304                      boolean useVarargs) {
  2305             if (pt.isErroneous()) return types.createErrorType(site);
  2306             Type owntype; // The computed type of this identifier occurrence.
  2307             switch (sym.kind) {
  2308             case TYP:
  2309                 // For types, the computed type equals the symbol's type,
  2310                 // except for two situations:
  2311                 owntype = sym.type;
  2312                 if (owntype.tag == CLASS) {
  2313                     Type ownOuter = owntype.getEnclosingType();
  2315                     // (a) If the symbol's type is parameterized, erase it
  2316                     // because no type parameters were given.
  2317                     // We recover generic outer type later in visitTypeApply.
  2318                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2319                         owntype = types.erasure(owntype);
  2322                     // (b) If the symbol's type is an inner class, then
  2323                     // we have to interpret its outer type as a superclass
  2324                     // of the site type. Example:
  2325                     //
  2326                     // class Tree<A> { class Visitor { ... } }
  2327                     // class PointTree extends Tree<Point> { ... }
  2328                     // ...PointTree.Visitor...
  2329                     //
  2330                     // Then the type of the last expression above is
  2331                     // Tree<Point>.Visitor.
  2332                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2333                         Type normOuter = site;
  2334                         if (normOuter.tag == CLASS)
  2335                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2336                         if (normOuter == null) // perhaps from an import
  2337                             normOuter = types.erasure(ownOuter);
  2338                         if (normOuter != ownOuter)
  2339                             owntype = new ClassType(
  2340                                 normOuter, List.<Type>nil(), owntype.tsym);
  2343                 break;
  2344             case VAR:
  2345                 VarSymbol v = (VarSymbol)sym;
  2346                 // Test (4): if symbol is an instance field of a raw type,
  2347                 // which is being assigned to, issue an unchecked warning if
  2348                 // its type changes under erasure.
  2349                 if (allowGenerics &&
  2350                     pkind == VAR &&
  2351                     v.owner.kind == TYP &&
  2352                     (v.flags() & STATIC) == 0 &&
  2353                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2354                     Type s = types.asOuterSuper(site, v.owner);
  2355                     if (s != null &&
  2356                         s.isRaw() &&
  2357                         !types.isSameType(v.type, v.erasure(types))) {
  2358                         chk.warnUnchecked(tree.pos(),
  2359                                           "unchecked.assign.to.var",
  2360                                           v, s);
  2363                 // The computed type of a variable is the type of the
  2364                 // variable symbol, taken as a member of the site type.
  2365                 owntype = (sym.owner.kind == TYP &&
  2366                            sym.name != names._this && sym.name != names._super)
  2367                     ? types.memberType(site, sym)
  2368                     : sym.type;
  2370                 if (env.info.tvars.nonEmpty()) {
  2371                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2372                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2373                         if (!owntype.contains(l.head)) {
  2374                             log.error(tree.pos(), "undetermined.type", owntype1);
  2375                             owntype1 = types.createErrorType(owntype1);
  2377                     owntype = owntype1;
  2380                 // If the variable is a constant, record constant value in
  2381                 // computed type.
  2382                 if (v.getConstValue() != null && isStaticReference(tree))
  2383                     owntype = owntype.constType(v.getConstValue());
  2385                 if (pkind == VAL) {
  2386                     owntype = capture(owntype); // capture "names as expressions"
  2388                 break;
  2389             case MTH: {
  2390                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2391                 owntype = checkMethod(site, sym, env, app.args,
  2392                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2393                                       env.info.varArgs);
  2394                 break;
  2396             case PCK: case ERR:
  2397                 owntype = sym.type;
  2398                 break;
  2399             default:
  2400                 throw new AssertionError("unexpected kind: " + sym.kind +
  2401                                          " in tree " + tree);
  2404             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2405             // (for constructors, the error was given when the constructor was
  2406             // resolved)
  2407             if (sym.name != names.init &&
  2408                 (sym.flags() & DEPRECATED) != 0 &&
  2409                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2410                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2411                 chk.warnDeprecated(tree.pos(), sym);
  2413             if ((sym.flags() & PROPRIETARY) != 0) {
  2414                 if (enableSunApiLintControl)
  2415                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
  2416                 else
  2417                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2420             // Test (3): if symbol is a variable, check that its type and
  2421             // kind are compatible with the prototype and protokind.
  2422             return check(tree, owntype, sym.kind, pkind, pt);
  2425         /** Check that variable is initialized and evaluate the variable's
  2426          *  initializer, if not yet done. Also check that variable is not
  2427          *  referenced before it is defined.
  2428          *  @param tree    The tree making up the variable reference.
  2429          *  @param env     The current environment.
  2430          *  @param v       The variable's symbol.
  2431          */
  2432         private void checkInit(JCTree tree,
  2433                                Env<AttrContext> env,
  2434                                VarSymbol v,
  2435                                boolean onlyWarning) {
  2436 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2437 //                             tree.pos + " " + v.pos + " " +
  2438 //                             Resolve.isStatic(env));//DEBUG
  2440             // A forward reference is diagnosed if the declaration position
  2441             // of the variable is greater than the current tree position
  2442             // and the tree and variable definition occur in the same class
  2443             // definition.  Note that writes don't count as references.
  2444             // This check applies only to class and instance
  2445             // variables.  Local variables follow different scope rules,
  2446             // and are subject to definite assignment checking.
  2447             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2448                 v.owner.kind == TYP &&
  2449                 canOwnInitializer(env.info.scope.owner) &&
  2450                 v.owner == env.info.scope.owner.enclClass() &&
  2451                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2452                 (env.tree.getTag() != JCTree.ASSIGN ||
  2453                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2454                 String suffix = (env.info.enclVar == v) ?
  2455                                 "self.ref" : "forward.ref";
  2456                 if (!onlyWarning || isStaticEnumField(v)) {
  2457                     log.error(tree.pos(), "illegal." + suffix);
  2458                 } else if (useBeforeDeclarationWarning) {
  2459                     log.warning(tree.pos(), suffix, v);
  2463             v.getConstValue(); // ensure initializer is evaluated
  2465             checkEnumInitializer(tree, env, v);
  2468         /**
  2469          * Check for illegal references to static members of enum.  In
  2470          * an enum type, constructors and initializers may not
  2471          * reference its static members unless they are constant.
  2473          * @param tree    The tree making up the variable reference.
  2474          * @param env     The current environment.
  2475          * @param v       The variable's symbol.
  2476          * @see JLS 3rd Ed. (8.9 Enums)
  2477          */
  2478         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2479             // JLS 3rd Ed.:
  2480             //
  2481             // "It is a compile-time error to reference a static field
  2482             // of an enum type that is not a compile-time constant
  2483             // (15.28) from constructors, instance initializer blocks,
  2484             // or instance variable initializer expressions of that
  2485             // type. It is a compile-time error for the constructors,
  2486             // instance initializer blocks, or instance variable
  2487             // initializer expressions of an enum constant e to refer
  2488             // to itself or to an enum constant of the same type that
  2489             // is declared to the right of e."
  2490             if (isStaticEnumField(v)) {
  2491                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2493                 if (enclClass == null || enclClass.owner == null)
  2494                     return;
  2496                 // See if the enclosing class is the enum (or a
  2497                 // subclass thereof) declaring v.  If not, this
  2498                 // reference is OK.
  2499                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2500                     return;
  2502                 // If the reference isn't from an initializer, then
  2503                 // the reference is OK.
  2504                 if (!Resolve.isInitializer(env))
  2505                     return;
  2507                 log.error(tree.pos(), "illegal.enum.static.ref");
  2511         /** Is the given symbol a static, non-constant field of an Enum?
  2512          *  Note: enum literals should not be regarded as such
  2513          */
  2514         private boolean isStaticEnumField(VarSymbol v) {
  2515             return Flags.isEnum(v.owner) &&
  2516                    Flags.isStatic(v) &&
  2517                    !Flags.isConstant(v) &&
  2518                    v.name != names._class;
  2521         /** Can the given symbol be the owner of code which forms part
  2522          *  if class initialization? This is the case if the symbol is
  2523          *  a type or field, or if the symbol is the synthetic method.
  2524          *  owning a block.
  2525          */
  2526         private boolean canOwnInitializer(Symbol sym) {
  2527             return
  2528                 (sym.kind & (VAR | TYP)) != 0 ||
  2529                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2532     Warner noteWarner = new Warner();
  2534     /**
  2535      * Check that method arguments conform to its instantation.
  2536      **/
  2537     public Type checkMethod(Type site,
  2538                             Symbol sym,
  2539                             Env<AttrContext> env,
  2540                             final List<JCExpression> argtrees,
  2541                             List<Type> argtypes,
  2542                             List<Type> typeargtypes,
  2543                             boolean useVarargs) {
  2544         // Test (5): if symbol is an instance method of a raw type, issue
  2545         // an unchecked warning if its argument types change under erasure.
  2546         if (allowGenerics &&
  2547             (sym.flags() & STATIC) == 0 &&
  2548             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2549             Type s = types.asOuterSuper(site, sym.owner);
  2550             if (s != null && s.isRaw() &&
  2551                 !types.isSameTypes(sym.type.getParameterTypes(),
  2552                                    sym.erasure(types).getParameterTypes())) {
  2553                 chk.warnUnchecked(env.tree.pos(),
  2554                                   "unchecked.call.mbr.of.raw.type",
  2555                                   sym, s);
  2559         // Compute the identifier's instantiated type.
  2560         // For methods, we need to compute the instance type by
  2561         // Resolve.instantiate from the symbol's type as well as
  2562         // any type arguments and value arguments.
  2563         noteWarner.warned = false;
  2564         Type owntype = rs.instantiate(env,
  2565                                       site,
  2566                                       sym,
  2567                                       argtypes,
  2568                                       typeargtypes,
  2569                                       true,
  2570                                       useVarargs,
  2571                                       noteWarner);
  2572         boolean warned = noteWarner.warned;
  2574         // If this fails, something went wrong; we should not have
  2575         // found the identifier in the first place.
  2576         if (owntype == null) {
  2577             if (!pt.isErroneous())
  2578                 log.error(env.tree.pos(),
  2579                           "internal.error.cant.instantiate",
  2580                           sym, site,
  2581                           Type.toString(pt.getParameterTypes()));
  2582             owntype = types.createErrorType(site);
  2583         } else {
  2584             // System.out.println("call   : " + env.tree);
  2585             // System.out.println("method : " + owntype);
  2586             // System.out.println("actuals: " + argtypes);
  2587             List<Type> formals = owntype.getParameterTypes();
  2588             Type last = useVarargs ? formals.last() : null;
  2589             if (sym.name==names.init &&
  2590                 sym.owner == syms.enumSym)
  2591                 formals = formals.tail.tail;
  2592             List<JCExpression> args = argtrees;
  2593             while (formals.head != last) {
  2594                 JCTree arg = args.head;
  2595                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2596                 assertConvertible(arg, arg.type, formals.head, warn);
  2597                 warned |= warn.warned;
  2598                 args = args.tail;
  2599                 formals = formals.tail;
  2601             if (useVarargs) {
  2602                 Type varArg = types.elemtype(last);
  2603                 while (args.tail != null) {
  2604                     JCTree arg = args.head;
  2605                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2606                     assertConvertible(arg, arg.type, varArg, warn);
  2607                     warned |= warn.warned;
  2608                     args = args.tail;
  2610             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2611                 // non-varargs call to varargs method
  2612                 Type varParam = owntype.getParameterTypes().last();
  2613                 Type lastArg = argtypes.last();
  2614                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2615                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2616                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2617                                 types.elemtype(varParam),
  2618                                 varParam);
  2621             if (warned && sym.type.tag == FORALL) {
  2622                 chk.warnUnchecked(env.tree.pos(),
  2623                                   "unchecked.meth.invocation.applied",
  2624                                   kindName(sym),
  2625                                   sym.name,
  2626                                   rs.methodArguments(sym.type.getParameterTypes()),
  2627                                   rs.methodArguments(argtypes),
  2628                                   kindName(sym.location()),
  2629                                   sym.location());
  2630                 owntype = new MethodType(owntype.getParameterTypes(),
  2631                                          types.erasure(owntype.getReturnType()),
  2632                                          owntype.getThrownTypes(),
  2633                                          syms.methodClass);
  2635             if (useVarargs) {
  2636                 JCTree tree = env.tree;
  2637                 if (owntype.getReturnType().tag != FORALL || warned) {
  2638                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes());
  2640                 Type elemtype = types.elemtype(owntype.getParameterTypes().last());
  2641                 switch (tree.getTag()) {
  2642                 case JCTree.APPLY:
  2643                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2644                     break;
  2645                 case JCTree.NEWCLASS:
  2646                     ((JCNewClass) tree).varargsElement = elemtype;
  2647                     break;
  2648                 default:
  2649                     throw new AssertionError(""+tree);
  2653         return owntype;
  2656     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2657         if (types.isConvertible(actual, formal, warn))
  2658             return;
  2660         if (formal.isCompound()
  2661             && types.isSubtype(actual, types.supertype(formal))
  2662             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2663             return;
  2665         if (false) {
  2666             // TODO: make assertConvertible work
  2667             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2668             throw new AssertionError("Tree: " + tree
  2669                                      + " actual:" + actual
  2670                                      + " formal: " + formal);
  2674     public void visitLiteral(JCLiteral tree) {
  2675         result = check(
  2676             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2678     //where
  2679     /** Return the type of a literal with given type tag.
  2680      */
  2681     Type litType(int tag) {
  2682         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2685     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2686         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2689     public void visitTypeArray(JCArrayTypeTree tree) {
  2690         Type etype = attribType(tree.elemtype, env);
  2691         Type type = new ArrayType(etype, syms.arrayClass);
  2692         result = check(tree, type, TYP, pkind, pt);
  2695     /** Visitor method for parameterized types.
  2696      *  Bound checking is left until later, since types are attributed
  2697      *  before supertype structure is completely known
  2698      */
  2699     public void visitTypeApply(JCTypeApply tree) {
  2700         Type owntype = types.createErrorType(tree.type);
  2702         // Attribute functor part of application and make sure it's a class.
  2703         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2705         // Attribute type parameters
  2706         List<Type> actuals = attribTypes(tree.arguments, env);
  2708         if (clazztype.tag == CLASS) {
  2709             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2711             if (actuals.length() == formals.length() || actuals.length() == 0) {
  2712                 List<Type> a = actuals;
  2713                 List<Type> f = formals;
  2714                 while (a.nonEmpty()) {
  2715                     a.head = a.head.withTypeVar(f.head);
  2716                     a = a.tail;
  2717                     f = f.tail;
  2719                 // Compute the proper generic outer
  2720                 Type clazzOuter = clazztype.getEnclosingType();
  2721                 if (clazzOuter.tag == CLASS) {
  2722                     Type site;
  2723                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2724                     if (clazz.getTag() == JCTree.IDENT) {
  2725                         site = env.enclClass.sym.type;
  2726                     } else if (clazz.getTag() == JCTree.SELECT) {
  2727                         site = ((JCFieldAccess) clazz).selected.type;
  2728                     } else throw new AssertionError(""+tree);
  2729                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2730                         if (site.tag == CLASS)
  2731                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2732                         if (site == null)
  2733                             site = types.erasure(clazzOuter);
  2734                         clazzOuter = site;
  2737                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2738             } else {
  2739                 if (formals.length() != 0) {
  2740                     log.error(tree.pos(), "wrong.number.type.args",
  2741                               Integer.toString(formals.length()));
  2742                 } else {
  2743                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2745                 owntype = types.createErrorType(tree.type);
  2748         result = check(tree, owntype, TYP, pkind, pt);
  2751     public void visitTypeDisjoint(JCTypeDisjoint tree) {
  2752         List<Type> componentTypes = attribTypes(tree.components, env);
  2753         tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
  2756     public void visitTypeParameter(JCTypeParameter tree) {
  2757         TypeVar a = (TypeVar)tree.type;
  2758         Set<Type> boundSet = new HashSet<Type>();
  2759         if (a.bound.isErroneous())
  2760             return;
  2761         List<Type> bs = types.getBounds(a);
  2762         if (tree.bounds.nonEmpty()) {
  2763             // accept class or interface or typevar as first bound.
  2764             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2765             boundSet.add(types.erasure(b));
  2766             if (b.isErroneous()) {
  2767                 a.bound = b;
  2769             else if (b.tag == TYPEVAR) {
  2770                 // if first bound was a typevar, do not accept further bounds.
  2771                 if (tree.bounds.tail.nonEmpty()) {
  2772                     log.error(tree.bounds.tail.head.pos(),
  2773                               "type.var.may.not.be.followed.by.other.bounds");
  2774                     log.unrecoverableError = true;
  2775                     tree.bounds = List.of(tree.bounds.head);
  2776                     a.bound = bs.head;
  2778             } else {
  2779                 // if first bound was a class or interface, accept only interfaces
  2780                 // as further bounds.
  2781                 for (JCExpression bound : tree.bounds.tail) {
  2782                     bs = bs.tail;
  2783                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2784                     if (i.isErroneous())
  2785                         a.bound = i;
  2786                     else if (i.tag == CLASS)
  2787                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2791         bs = types.getBounds(a);
  2793         // in case of multiple bounds ...
  2794         if (bs.length() > 1) {
  2795             // ... the variable's bound is a class type flagged COMPOUND
  2796             // (see comment for TypeVar.bound).
  2797             // In this case, generate a class tree that represents the
  2798             // bound class, ...
  2799             JCTree extending;
  2800             List<JCExpression> implementing;
  2801             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2802                 extending = tree.bounds.head;
  2803                 implementing = tree.bounds.tail;
  2804             } else {
  2805                 extending = null;
  2806                 implementing = tree.bounds;
  2808             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2809                 make.Modifiers(PUBLIC | ABSTRACT),
  2810                 tree.name, List.<JCTypeParameter>nil(),
  2811                 extending, implementing, List.<JCTree>nil());
  2813             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2814             assert (c.flags() & COMPOUND) != 0;
  2815             cd.sym = c;
  2816             c.sourcefile = env.toplevel.sourcefile;
  2818             // ... and attribute the bound class
  2819             c.flags_field |= UNATTRIBUTED;
  2820             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2821             enter.typeEnvs.put(c, cenv);
  2826     public void visitWildcard(JCWildcard tree) {
  2827         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2828         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2829             ? syms.objectType
  2830             : attribType(tree.inner, env);
  2831         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2832                                               tree.kind.kind,
  2833                                               syms.boundClass),
  2834                        TYP, pkind, pt);
  2837     public void visitAnnotation(JCAnnotation tree) {
  2838         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2839         result = tree.type = syms.errType;
  2842     public void visitAnnotatedType(JCAnnotatedType tree) {
  2843         result = tree.type = attribType(tree.getUnderlyingType(), env);
  2846     public void visitErroneous(JCErroneous tree) {
  2847         if (tree.errs != null)
  2848             for (JCTree err : tree.errs)
  2849                 attribTree(err, env, ERR, pt);
  2850         result = tree.type = syms.errType;
  2853     /** Default visitor method for all other trees.
  2854      */
  2855     public void visitTree(JCTree tree) {
  2856         throw new AssertionError();
  2859     /** Main method: attribute class definition associated with given class symbol.
  2860      *  reporting completion failures at the given position.
  2861      *  @param pos The source position at which completion errors are to be
  2862      *             reported.
  2863      *  @param c   The class symbol whose definition will be attributed.
  2864      */
  2865     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2866         try {
  2867             annotate.flush();
  2868             attribClass(c);
  2869         } catch (CompletionFailure ex) {
  2870             chk.completionError(pos, ex);
  2874     /** Attribute class definition associated with given class symbol.
  2875      *  @param c   The class symbol whose definition will be attributed.
  2876      */
  2877     void attribClass(ClassSymbol c) throws CompletionFailure {
  2878         if (c.type.tag == ERROR) return;
  2880         // Check for cycles in the inheritance graph, which can arise from
  2881         // ill-formed class files.
  2882         chk.checkNonCyclic(null, c.type);
  2884         Type st = types.supertype(c.type);
  2885         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2886             // First, attribute superclass.
  2887             if (st.tag == CLASS)
  2888                 attribClass((ClassSymbol)st.tsym);
  2890             // Next attribute owner, if it is a class.
  2891             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2892                 attribClass((ClassSymbol)c.owner);
  2895         // The previous operations might have attributed the current class
  2896         // if there was a cycle. So we test first whether the class is still
  2897         // UNATTRIBUTED.
  2898         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2899             c.flags_field &= ~UNATTRIBUTED;
  2901             // Get environment current at the point of class definition.
  2902             Env<AttrContext> env = enter.typeEnvs.get(c);
  2904             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2905             // because the annotations were not available at the time the env was created. Therefore,
  2906             // we look up the environment chain for the first enclosing environment for which the
  2907             // lint value is set. Typically, this is the parent env, but might be further if there
  2908             // are any envs created as a result of TypeParameter nodes.
  2909             Env<AttrContext> lintEnv = env;
  2910             while (lintEnv.info.lint == null)
  2911                 lintEnv = lintEnv.next;
  2913             // Having found the enclosing lint value, we can initialize the lint value for this class
  2914             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2916             Lint prevLint = chk.setLint(env.info.lint);
  2917             JavaFileObject prev = log.useSource(c.sourcefile);
  2919             try {
  2920                 // java.lang.Enum may not be subclassed by a non-enum
  2921                 if (st.tsym == syms.enumSym &&
  2922                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  2923                     log.error(env.tree.pos(), "enum.no.subclassing");
  2925                 // Enums may not be extended by source-level classes
  2926                 if (st.tsym != null &&
  2927                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  2928                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  2929                     !target.compilerBootstrap(c)) {
  2930                     log.error(env.tree.pos(), "enum.types.not.extensible");
  2932                 attribClassBody(env, c);
  2934                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  2935             } finally {
  2936                 log.useSource(prev);
  2937                 chk.setLint(prevLint);
  2943     public void visitImport(JCImport tree) {
  2944         // nothing to do
  2947     /** Finish the attribution of a class. */
  2948     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  2949         JCClassDecl tree = (JCClassDecl)env.tree;
  2950         assert c == tree.sym;
  2952         // Validate annotations
  2953         chk.validateAnnotations(tree.mods.annotations, c);
  2955         // Validate type parameters, supertype and interfaces.
  2956         attribBounds(tree.typarams);
  2957         if (!c.isAnonymous()) {
  2958             //already checked if anonymous
  2959             chk.validate(tree.typarams, env);
  2960             chk.validate(tree.extending, env);
  2961             chk.validate(tree.implementing, env);
  2964         // If this is a non-abstract class, check that it has no abstract
  2965         // methods or unimplemented methods of an implemented interface.
  2966         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  2967             if (!relax)
  2968                 chk.checkAllDefined(tree.pos(), c);
  2971         if ((c.flags() & ANNOTATION) != 0) {
  2972             if (tree.implementing.nonEmpty())
  2973                 log.error(tree.implementing.head.pos(),
  2974                           "cant.extend.intf.annotation");
  2975             if (tree.typarams.nonEmpty())
  2976                 log.error(tree.typarams.head.pos(),
  2977                           "intf.annotation.cant.have.type.params");
  2978         } else {
  2979             // Check that all extended classes and interfaces
  2980             // are compatible (i.e. no two define methods with same arguments
  2981             // yet different return types).  (JLS 8.4.6.3)
  2982             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  2985         // Check that class does not import the same parameterized interface
  2986         // with two different argument lists.
  2987         chk.checkClassBounds(tree.pos(), c.type);
  2989         tree.type = c.type;
  2991         boolean assertsEnabled = false;
  2992         assert assertsEnabled = true;
  2993         if (assertsEnabled) {
  2994             for (List<JCTypeParameter> l = tree.typarams;
  2995                  l.nonEmpty(); l = l.tail)
  2996                 assert env.info.scope.lookup(l.head.name).scope != null;
  2999         // Check that a generic class doesn't extend Throwable
  3000         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3001             log.error(tree.extending.pos(), "generic.throwable");
  3003         // Check that all methods which implement some
  3004         // method conform to the method they implement.
  3005         chk.checkImplementations(tree);
  3007         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3008             // Attribute declaration
  3009             attribStat(l.head, env);
  3010             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3011             // Make an exception for static constants.
  3012             if (c.owner.kind != PCK &&
  3013                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3014                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3015                 Symbol sym = null;
  3016                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3017                 if (sym == null ||
  3018                     sym.kind != VAR ||
  3019                     ((VarSymbol) sym).getConstValue() == null)
  3020                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  3024         // Check for cycles among non-initial constructors.
  3025         chk.checkCyclicConstructors(tree);
  3027         // Check for cycles among annotation elements.
  3028         chk.checkNonCyclicElements(tree);
  3030         // Check for proper use of serialVersionUID
  3031         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  3032             isSerializable(c) &&
  3033             (c.flags() & Flags.ENUM) == 0 &&
  3034             (c.flags() & ABSTRACT) == 0) {
  3035             checkSerialVersionUID(tree, c);
  3038         // Check type annotations applicability rules
  3039         validateTypeAnnotations(tree);
  3041         // where
  3042         /** check if a class is a subtype of Serializable, if that is available. */
  3043         private boolean isSerializable(ClassSymbol c) {
  3044             try {
  3045                 syms.serializableType.complete();
  3047             catch (CompletionFailure e) {
  3048                 return false;
  3050             return types.isSubtype(c.type, syms.serializableType);
  3053         /** Check that an appropriate serialVersionUID member is defined. */
  3054         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3056             // check for presence of serialVersionUID
  3057             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3058             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3059             if (e.scope == null) {
  3060                 log.warning(tree.pos(), "missing.SVUID", c);
  3061                 return;
  3064             // check that it is static final
  3065             VarSymbol svuid = (VarSymbol)e.sym;
  3066             if ((svuid.flags() & (STATIC | FINAL)) !=
  3067                 (STATIC | FINAL))
  3068                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3070             // check that it is long
  3071             else if (svuid.type.tag != TypeTags.LONG)
  3072                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3074             // check constant
  3075             else if (svuid.getConstValue() == null)
  3076                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3079     private Type capture(Type type) {
  3080         return types.capture(type);
  3083     private void validateTypeAnnotations(JCTree tree) {
  3084         tree.accept(typeAnnotationsValidator);
  3086     //where
  3087     private final JCTree.Visitor typeAnnotationsValidator =
  3088         new TreeScanner() {
  3089         public void visitAnnotation(JCAnnotation tree) {
  3090             if (tree instanceof JCTypeAnnotation) {
  3091                 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
  3093             super.visitAnnotation(tree);
  3095         public void visitTypeParameter(JCTypeParameter tree) {
  3096             chk.validateTypeAnnotations(tree.annotations, true);
  3097             // don't call super. skip type annotations
  3098             scan(tree.bounds);
  3100         public void visitMethodDef(JCMethodDecl tree) {
  3101             // need to check static methods
  3102             if ((tree.sym.flags() & Flags.STATIC) != 0) {
  3103                 for (JCTypeAnnotation a : tree.receiverAnnotations) {
  3104                     if (chk.isTypeAnnotation(a, false))
  3105                         log.error(a.pos(), "annotation.type.not.applicable");
  3108             super.visitMethodDef(tree);
  3110     };

mercurial