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

Thu, 05 Aug 2010 09:45:25 +0100

author
mcimadamore
date
Thu, 05 Aug 2010 09:45:25 +0100
changeset 630
237f3bd52242
parent 629
0fe472f4a332
child 631
a2d8c7071f24
permissions
-rw-r--r--

6857948: Calling a constructor with a doubly bogus argument causes an internal error
Summary: problem when constructor resolution returns an erroneous symbol
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2009, Oracle and/or its affiliates. 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.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * 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 supported API.
    63  *  If 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         enableSunApiLintControl = options.get("enableSunApiLintControl") != null;
   126     }
   128     /** Switch: relax some constraints for retrofit mode.
   129      */
   130     boolean relax;
   132     /** Switch: support generics?
   133      */
   134     boolean allowGenerics;
   136     /** Switch: allow variable-arity methods.
   137      */
   138     boolean allowVarargs;
   140     /** Switch: support enums?
   141      */
   142     boolean allowEnums;
   144     /** Switch: support boxing and unboxing?
   145      */
   146     boolean allowBoxing;
   148     /** Switch: support covariant result types?
   149      */
   150     boolean allowCovariantReturns;
   152     /** Switch: allow references to surrounding object from anonymous
   153      * objects during constructor call?
   154      */
   155     boolean allowAnonOuterThis;
   157     /**
   158      * Switch: warn about use of variable before declaration?
   159      * RFE: 6425594
   160      */
   161     boolean useBeforeDeclarationWarning;
   163     /**
   164      * Switch: allow lint infrastructure to control proprietary
   165      * API warnings.
   166      */
   167     boolean enableSunApiLintControl;
   169     /**
   170      * Switch: allow strings in switch?
   171      */
   172     boolean allowStringsInSwitch;
   174     /**
   175      * Switch: name of source level; used for error reporting.
   176      */
   177     String sourceName;
   179     /** Check kind and type of given tree against protokind and prototype.
   180      *  If check succeeds, store type in tree and return it.
   181      *  If check fails, store errType in tree and return it.
   182      *  No checks are performed if the prototype is a method type.
   183      *  It is not necessary in this case since we know that kind and type
   184      *  are correct.
   185      *
   186      *  @param tree     The tree whose kind and type is checked
   187      *  @param owntype  The computed type of the tree
   188      *  @param ownkind  The computed kind of the tree
   189      *  @param pkind    The expected kind (or: protokind) of the tree
   190      *  @param pt       The expected type (or: prototype) of the tree
   191      */
   192     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   193         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   194             if ((ownkind & ~pkind) == 0) {
   195                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
   196             } else {
   197                 log.error(tree.pos(), "unexpected.type",
   198                           kindNames(pkind),
   199                           kindName(ownkind));
   200                 owntype = types.createErrorType(owntype);
   201             }
   202         }
   203         tree.type = owntype;
   204         return owntype;
   205     }
   207     /** Is given blank final variable assignable, i.e. in a scope where it
   208      *  may be assigned to even though it is final?
   209      *  @param v      The blank final variable.
   210      *  @param env    The current environment.
   211      */
   212     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   213         Symbol owner = env.info.scope.owner;
   214            // owner refers to the innermost variable, method or
   215            // initializer block declaration at this point.
   216         return
   217             v.owner == owner
   218             ||
   219             ((owner.name == names.init ||    // i.e. we are in a constructor
   220               owner.kind == VAR ||           // i.e. we are in a variable initializer
   221               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   222              &&
   223              v.owner == owner.owner
   224              &&
   225              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   226     }
   228     /** Check that variable can be assigned to.
   229      *  @param pos    The current source code position.
   230      *  @param v      The assigned varaible
   231      *  @param base   If the variable is referred to in a Select, the part
   232      *                to the left of the `.', null otherwise.
   233      *  @param env    The current environment.
   234      */
   235     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   236         if ((v.flags() & FINAL) != 0 &&
   237             ((v.flags() & HASINIT) != 0
   238              ||
   239              !((base == null ||
   240                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   241                isAssignableAsBlankFinal(v, env)))) {
   242             if (v.isResourceVariable()) { //TWR resource
   243                 log.error(pos, "twr.resource.may.not.be.assigned", v);
   244             } else {
   245                 log.error(pos, "cant.assign.val.to.final.var", v);
   246             }
   247         }
   248     }
   250     /** Does tree represent a static reference to an identifier?
   251      *  It is assumed that tree is either a SELECT or an IDENT.
   252      *  We have to weed out selects from non-type names here.
   253      *  @param tree    The candidate tree.
   254      */
   255     boolean isStaticReference(JCTree tree) {
   256         if (tree.getTag() == JCTree.SELECT) {
   257             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   258             if (lsym == null || lsym.kind != TYP) {
   259                 return false;
   260             }
   261         }
   262         return true;
   263     }
   265     /** Is this symbol a type?
   266      */
   267     static boolean isType(Symbol sym) {
   268         return sym != null && sym.kind == TYP;
   269     }
   271     /** The current `this' symbol.
   272      *  @param env    The current environment.
   273      */
   274     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   275         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   276     }
   278     /** Attribute a parsed identifier.
   279      * @param tree Parsed identifier name
   280      * @param topLevel The toplevel to use
   281      */
   282     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   283         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   284         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   285                                            syms.errSymbol.name,
   286                                            null, null, null, null);
   287         localEnv.enclClass.sym = syms.errSymbol;
   288         return tree.accept(identAttributer, localEnv);
   289     }
   290     // where
   291         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   292         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   293             @Override
   294             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   295                 Symbol site = visit(node.getExpression(), env);
   296                 if (site.kind == ERR)
   297                     return site;
   298                 Name name = (Name)node.getIdentifier();
   299                 if (site.kind == PCK) {
   300                     env.toplevel.packge = (PackageSymbol)site;
   301                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   302                 } else {
   303                     env.enclClass.sym = (ClassSymbol)site;
   304                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   305                 }
   306             }
   308             @Override
   309             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   310                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   311             }
   312         }
   314     public Type coerce(Type etype, Type ttype) {
   315         return cfolder.coerce(etype, ttype);
   316     }
   318     public Type attribType(JCTree node, TypeSymbol sym) {
   319         Env<AttrContext> env = enter.typeEnvs.get(sym);
   320         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   321         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   322     }
   324     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   325         breakTree = tree;
   326         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   327         try {
   328             attribExpr(expr, env);
   329         } catch (BreakAttr b) {
   330             return b.env;
   331         } finally {
   332             breakTree = null;
   333             log.useSource(prev);
   334         }
   335         return env;
   336     }
   338     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   339         breakTree = tree;
   340         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   341         try {
   342             attribStat(stmt, env);
   343         } catch (BreakAttr b) {
   344             return b.env;
   345         } finally {
   346             breakTree = null;
   347             log.useSource(prev);
   348         }
   349         return env;
   350     }
   352     private JCTree breakTree = null;
   354     private static class BreakAttr extends RuntimeException {
   355         static final long serialVersionUID = -6924771130405446405L;
   356         private Env<AttrContext> env;
   357         private BreakAttr(Env<AttrContext> env) {
   358             this.env = env;
   359         }
   360     }
   363 /* ************************************************************************
   364  * Visitor methods
   365  *************************************************************************/
   367     /** Visitor argument: the current environment.
   368      */
   369     Env<AttrContext> env;
   371     /** Visitor argument: the currently expected proto-kind.
   372      */
   373     int pkind;
   375     /** Visitor argument: the currently expected proto-type.
   376      */
   377     Type pt;
   379     /** Visitor argument: the error key to be generated when a type error occurs
   380      */
   381     String errKey;
   383     /** Visitor result: the computed type.
   384      */
   385     Type result;
   387     /** Visitor method: attribute a tree, catching any completion failure
   388      *  exceptions. Return the tree's type.
   389      *
   390      *  @param tree    The tree to be visited.
   391      *  @param env     The environment visitor argument.
   392      *  @param pkind   The protokind visitor argument.
   393      *  @param pt      The prototype visitor argument.
   394      */
   395     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   396         return attribTree(tree, env, pkind, pt, "incompatible.types");
   397     }
   399     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
   400         Env<AttrContext> prevEnv = this.env;
   401         int prevPkind = this.pkind;
   402         Type prevPt = this.pt;
   403         String prevErrKey = this.errKey;
   404         try {
   405             this.env = env;
   406             this.pkind = pkind;
   407             this.pt = pt;
   408             this.errKey = errKey;
   409             tree.accept(this);
   410             if (tree == breakTree)
   411                 throw new BreakAttr(env);
   412             return result;
   413         } catch (CompletionFailure ex) {
   414             tree.type = syms.errType;
   415             return chk.completionError(tree.pos(), ex);
   416         } finally {
   417             this.env = prevEnv;
   418             this.pkind = prevPkind;
   419             this.pt = prevPt;
   420             this.errKey = prevErrKey;
   421         }
   422     }
   424     /** Derived visitor method: attribute an expression tree.
   425      */
   426     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   427         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   428     }
   430     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
   431         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
   432     }
   434     /** Derived visitor method: attribute an expression tree with
   435      *  no constraints on the computed type.
   436      */
   437     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   438         return attribTree(tree, env, VAL, Type.noType);
   439     }
   441     /** Derived visitor method: attribute a type tree.
   442      */
   443     Type attribType(JCTree tree, Env<AttrContext> env) {
   444         Type result = attribType(tree, env, Type.noType);
   445         return result;
   446     }
   448     /** Derived visitor method: attribute a type tree.
   449      */
   450     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   451         Type result = attribTree(tree, env, TYP, pt);
   452         return result;
   453     }
   455     /** Derived visitor method: attribute a statement or definition tree.
   456      */
   457     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   458         return attribTree(tree, env, NIL, Type.noType);
   459     }
   461     /** Attribute a list of expressions, returning a list of types.
   462      */
   463     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   464         ListBuffer<Type> ts = new ListBuffer<Type>();
   465         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   466             ts.append(attribExpr(l.head, env, pt));
   467         return ts.toList();
   468     }
   470     /** Attribute a list of statements, returning nothing.
   471      */
   472     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   473         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   474             attribStat(l.head, env);
   475     }
   477     /** Attribute the arguments in a method call, returning a list of types.
   478      */
   479     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   480         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   481         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   482             argtypes.append(chk.checkNonVoid(
   483                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   484         return argtypes.toList();
   485     }
   487     /** Attribute a type argument list, returning a list of types.
   488      *  Caller is responsible for calling checkRefTypes.
   489      */
   490     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   491         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   492         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   493             argtypes.append(attribType(l.head, env));
   494         return argtypes.toList();
   495     }
   497     /** Attribute a type argument list, returning a list of types.
   498      *  Check that all the types are references.
   499      */
   500     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   501         List<Type> types = attribAnyTypes(trees, env);
   502         return chk.checkRefTypes(trees, types);
   503     }
   505     /**
   506      * Attribute type variables (of generic classes or methods).
   507      * Compound types are attributed later in attribBounds.
   508      * @param typarams the type variables to enter
   509      * @param env      the current environment
   510      */
   511     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   512         for (JCTypeParameter tvar : typarams) {
   513             TypeVar a = (TypeVar)tvar.type;
   514             a.tsym.flags_field |= UNATTRIBUTED;
   515             a.bound = Type.noType;
   516             if (!tvar.bounds.isEmpty()) {
   517                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   518                 for (JCExpression bound : tvar.bounds.tail)
   519                     bounds = bounds.prepend(attribType(bound, env));
   520                 types.setBounds(a, bounds.reverse());
   521             } else {
   522                 // if no bounds are given, assume a single bound of
   523                 // java.lang.Object.
   524                 types.setBounds(a, List.of(syms.objectType));
   525             }
   526             a.tsym.flags_field &= ~UNATTRIBUTED;
   527         }
   528         for (JCTypeParameter tvar : typarams)
   529             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   530         attribStats(typarams, env);
   531     }
   533     void attribBounds(List<JCTypeParameter> typarams) {
   534         for (JCTypeParameter typaram : typarams) {
   535             Type bound = typaram.type.getUpperBound();
   536             if (bound != null && bound.tsym instanceof ClassSymbol) {
   537                 ClassSymbol c = (ClassSymbol)bound.tsym;
   538                 if ((c.flags_field & COMPOUND) != 0) {
   539                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   540                     attribClass(typaram.pos(), c);
   541                 }
   542             }
   543         }
   544     }
   546     /**
   547      * Attribute the type references in a list of annotations.
   548      */
   549     void attribAnnotationTypes(List<JCAnnotation> annotations,
   550                                Env<AttrContext> env) {
   551         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   552             JCAnnotation a = al.head;
   553             attribType(a.annotationType, env);
   554         }
   555     }
   557     /** Attribute type reference in an `extends' or `implements' clause.
   558      *  Supertypes of anonymous inner classes are usually already attributed.
   559      *
   560      *  @param tree              The tree making up the type reference.
   561      *  @param env               The environment current at the reference.
   562      *  @param classExpected     true if only a class is expected here.
   563      *  @param interfaceExpected true if only an interface is expected here.
   564      */
   565     Type attribBase(JCTree tree,
   566                     Env<AttrContext> env,
   567                     boolean classExpected,
   568                     boolean interfaceExpected,
   569                     boolean checkExtensible) {
   570         Type t = tree.type != null ?
   571             tree.type :
   572             attribType(tree, env);
   573         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   574     }
   575     Type checkBase(Type t,
   576                    JCTree tree,
   577                    Env<AttrContext> env,
   578                    boolean classExpected,
   579                    boolean interfaceExpected,
   580                    boolean checkExtensible) {
   581         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   582             // check that type variable is already visible
   583             if (t.getUpperBound() == null) {
   584                 log.error(tree.pos(), "illegal.forward.ref");
   585                 return types.createErrorType(t);
   586             }
   587         } else {
   588             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   589         }
   590         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   591             log.error(tree.pos(), "intf.expected.here");
   592             // return errType is necessary since otherwise there might
   593             // be undetected cycles which cause attribution to loop
   594             return types.createErrorType(t);
   595         } else if (checkExtensible &&
   596                    classExpected &&
   597                    (t.tsym.flags() & INTERFACE) != 0) {
   598             log.error(tree.pos(), "no.intf.expected.here");
   599             return types.createErrorType(t);
   600         }
   601         if (checkExtensible &&
   602             ((t.tsym.flags() & FINAL) != 0)) {
   603             log.error(tree.pos(),
   604                       "cant.inherit.from.final", t.tsym);
   605         }
   606         chk.checkNonCyclic(tree.pos(), t);
   607         return t;
   608     }
   610     public void visitClassDef(JCClassDecl tree) {
   611         // Local classes have not been entered yet, so we need to do it now:
   612         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   613             enter.classEnter(tree, env);
   615         ClassSymbol c = tree.sym;
   616         if (c == null) {
   617             // exit in case something drastic went wrong during enter.
   618             result = null;
   619         } else {
   620             // make sure class has been completed:
   621             c.complete();
   623             // If this class appears as an anonymous class
   624             // in a superclass constructor call where
   625             // no explicit outer instance is given,
   626             // disable implicit outer instance from being passed.
   627             // (This would be an illegal access to "this before super").
   628             if (env.info.isSelfCall &&
   629                 env.tree.getTag() == JCTree.NEWCLASS &&
   630                 ((JCNewClass) env.tree).encl == null)
   631             {
   632                 c.flags_field |= NOOUTERTHIS;
   633             }
   634             attribClass(tree.pos(), c);
   635             result = tree.type = c.type;
   636         }
   637     }
   639     public void visitMethodDef(JCMethodDecl tree) {
   640         MethodSymbol m = tree.sym;
   642         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   643         Lint prevLint = chk.setLint(lint);
   644         try {
   645             chk.checkDeprecatedAnnotation(tree.pos(), m);
   647             attribBounds(tree.typarams);
   649             // If we override any other methods, check that we do so properly.
   650             // JLS ???
   651             chk.checkOverride(tree, m);
   653             // Create a new environment with local scope
   654             // for attributing the method.
   655             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   657             localEnv.info.lint = lint;
   659             // Enter all type parameters into the local method scope.
   660             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   661                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   663             ClassSymbol owner = env.enclClass.sym;
   664             if ((owner.flags() & ANNOTATION) != 0 &&
   665                 tree.params.nonEmpty())
   666                 log.error(tree.params.head.pos(),
   667                           "intf.annotation.members.cant.have.params");
   669             // Attribute all value parameters.
   670             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   671                 attribStat(l.head, localEnv);
   672             }
   674             chk.checkVarargMethodDecl(tree);
   676             // Check that type parameters are well-formed.
   677             chk.validate(tree.typarams, localEnv);
   679             // Check that result type is well-formed.
   680             chk.validate(tree.restype, localEnv);
   682             // annotation method checks
   683             if ((owner.flags() & ANNOTATION) != 0) {
   684                 // annotation method cannot have throws clause
   685                 if (tree.thrown.nonEmpty()) {
   686                     log.error(tree.thrown.head.pos(),
   687                             "throws.not.allowed.in.intf.annotation");
   688                 }
   689                 // annotation method cannot declare type-parameters
   690                 if (tree.typarams.nonEmpty()) {
   691                     log.error(tree.typarams.head.pos(),
   692                             "intf.annotation.members.cant.have.type.params");
   693                 }
   694                 // validate annotation method's return type (could be an annotation type)
   695                 chk.validateAnnotationType(tree.restype);
   696                 // ensure that annotation method does not clash with members of Object/Annotation
   697                 chk.validateAnnotationMethod(tree.pos(), m);
   699                 // if default value is an annotation, check it is a well-formed
   700                 // annotation value (e.g. no duplicate values, no missing values, etc.)
   701                 chk.validateAnnotationDefaultValue(tree.defaultValue);
   702             }
   704             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   705                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   707             if (tree.body == null) {
   708                 // Empty bodies are only allowed for
   709                 // abstract, native, or interface methods, or for methods
   710                 // in a retrofit signature class.
   711                 if ((owner.flags() & INTERFACE) == 0 &&
   712                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   713                     !relax)
   714                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   715                 if (tree.defaultValue != null) {
   716                     if ((owner.flags() & ANNOTATION) == 0)
   717                         log.error(tree.pos(),
   718                                   "default.allowed.in.intf.annotation.member");
   719                 }
   720             } else if ((owner.flags() & INTERFACE) != 0) {
   721                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   722             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   723                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   724             } else if ((tree.mods.flags & NATIVE) != 0) {
   725                 log.error(tree.pos(), "native.meth.cant.have.body");
   726             } else {
   727                 // Add an implicit super() call unless an explicit call to
   728                 // super(...) or this(...) is given
   729                 // or we are compiling class java.lang.Object.
   730                 if (tree.name == names.init && owner.type != syms.objectType) {
   731                     JCBlock body = tree.body;
   732                     if (body.stats.isEmpty() ||
   733                         !TreeInfo.isSelfCall(body.stats.head)) {
   734                         body.stats = body.stats.
   735                             prepend(memberEnter.SuperCall(make.at(body.pos),
   736                                                           List.<Type>nil(),
   737                                                           List.<JCVariableDecl>nil(),
   738                                                           false));
   739                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   740                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   741                                TreeInfo.isSuperCall(body.stats.head)) {
   742                         // enum constructors are not allowed to call super
   743                         // directly, so make sure there aren't any super calls
   744                         // in enum constructors, except in the compiler
   745                         // generated one.
   746                         log.error(tree.body.stats.head.pos(),
   747                                   "call.to.super.not.allowed.in.enum.ctor",
   748                                   env.enclClass.sym);
   749                     }
   750                 }
   752                 // Attribute method body.
   753                 attribStat(tree.body, localEnv);
   754             }
   755             localEnv.info.scope.leave();
   756             result = tree.type = m.type;
   757             chk.validateAnnotations(tree.mods.annotations, m);
   758         }
   759         finally {
   760             chk.setLint(prevLint);
   761         }
   762     }
   764     public void visitVarDef(JCVariableDecl tree) {
   765         // Local variables have not been entered yet, so we need to do it now:
   766         if (env.info.scope.owner.kind == MTH) {
   767             if (tree.sym != null) {
   768                 // parameters have already been entered
   769                 env.info.scope.enter(tree.sym);
   770             } else {
   771                 memberEnter.memberEnter(tree, env);
   772                 annotate.flush();
   773             }
   774         }
   776         VarSymbol v = tree.sym;
   777         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   778         Lint prevLint = chk.setLint(lint);
   780         // Check that the variable's declared type is well-formed.
   781         chk.validate(tree.vartype, env);
   783         try {
   784             chk.checkDeprecatedAnnotation(tree.pos(), v);
   786             if (tree.init != null) {
   787                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   788                     // In this case, `v' is final.  Ensure that it's initializer is
   789                     // evaluated.
   790                     v.getConstValue(); // ensure initializer is evaluated
   791                 } else {
   792                     // Attribute initializer in a new environment
   793                     // with the declared variable as owner.
   794                     // Check that initializer conforms to variable's declared type.
   795                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   796                     initEnv.info.lint = lint;
   797                     // In order to catch self-references, we set the variable's
   798                     // declaration position to maximal possible value, effectively
   799                     // marking the variable as undefined.
   800                     initEnv.info.enclVar = v;
   801                     attribExpr(tree.init, initEnv, v.type);
   802                 }
   803             }
   804             result = tree.type = v.type;
   805             chk.validateAnnotations(tree.mods.annotations, v);
   806         }
   807         finally {
   808             chk.setLint(prevLint);
   809         }
   810     }
   812     public void visitSkip(JCSkip tree) {
   813         result = null;
   814     }
   816     public void visitBlock(JCBlock tree) {
   817         if (env.info.scope.owner.kind == TYP) {
   818             // Block is a static or instance initializer;
   819             // let the owner of the environment be a freshly
   820             // created BLOCK-method.
   821             Env<AttrContext> localEnv =
   822                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   823             localEnv.info.scope.owner =
   824                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   825                                  env.info.scope.owner);
   826             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   827             attribStats(tree.stats, localEnv);
   828         } else {
   829             // Create a new local environment with a local scope.
   830             Env<AttrContext> localEnv =
   831                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   832             attribStats(tree.stats, localEnv);
   833             localEnv.info.scope.leave();
   834         }
   835         result = null;
   836     }
   838     public void visitDoLoop(JCDoWhileLoop tree) {
   839         attribStat(tree.body, env.dup(tree));
   840         attribExpr(tree.cond, env, syms.booleanType);
   841         result = null;
   842     }
   844     public void visitWhileLoop(JCWhileLoop tree) {
   845         attribExpr(tree.cond, env, syms.booleanType);
   846         attribStat(tree.body, env.dup(tree));
   847         result = null;
   848     }
   850     public void visitForLoop(JCForLoop tree) {
   851         Env<AttrContext> loopEnv =
   852             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   853         attribStats(tree.init, loopEnv);
   854         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   855         loopEnv.tree = tree; // before, we were not in loop!
   856         attribStats(tree.step, loopEnv);
   857         attribStat(tree.body, loopEnv);
   858         loopEnv.info.scope.leave();
   859         result = null;
   860     }
   862     public void visitForeachLoop(JCEnhancedForLoop tree) {
   863         Env<AttrContext> loopEnv =
   864             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   865         attribStat(tree.var, loopEnv);
   866         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   867         chk.checkNonVoid(tree.pos(), exprType);
   868         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   869         if (elemtype == null) {
   870             // or perhaps expr implements Iterable<T>?
   871             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   872             if (base == null) {
   873                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   874                 elemtype = types.createErrorType(exprType);
   875             } else {
   876                 List<Type> iterableParams = base.allparams();
   877                 elemtype = iterableParams.isEmpty()
   878                     ? syms.objectType
   879                     : types.upperBound(iterableParams.head);
   880             }
   881         }
   882         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   883         loopEnv.tree = tree; // before, we were not in loop!
   884         attribStat(tree.body, loopEnv);
   885         loopEnv.info.scope.leave();
   886         result = null;
   887     }
   889     public void visitLabelled(JCLabeledStatement tree) {
   890         // Check that label is not used in an enclosing statement
   891         Env<AttrContext> env1 = env;
   892         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   893             if (env1.tree.getTag() == JCTree.LABELLED &&
   894                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   895                 log.error(tree.pos(), "label.already.in.use",
   896                           tree.label);
   897                 break;
   898             }
   899             env1 = env1.next;
   900         }
   902         attribStat(tree.body, env.dup(tree));
   903         result = null;
   904     }
   906     public void visitSwitch(JCSwitch tree) {
   907         Type seltype = attribExpr(tree.selector, env);
   909         Env<AttrContext> switchEnv =
   910             env.dup(tree, env.info.dup(env.info.scope.dup()));
   912         boolean enumSwitch =
   913             allowEnums &&
   914             (seltype.tsym.flags() & Flags.ENUM) != 0;
   915         boolean stringSwitch = false;
   916         if (types.isSameType(seltype, syms.stringType)) {
   917             if (allowStringsInSwitch) {
   918                 stringSwitch = true;
   919             } else {
   920                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   921             }
   922         }
   923         if (!enumSwitch && !stringSwitch)
   924             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   926         // Attribute all cases and
   927         // check that there are no duplicate case labels or default clauses.
   928         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   929         boolean hasDefault = false;      // Is there a default label?
   930         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   931             JCCase c = l.head;
   932             Env<AttrContext> caseEnv =
   933                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   934             if (c.pat != null) {
   935                 if (enumSwitch) {
   936                     Symbol sym = enumConstant(c.pat, seltype);
   937                     if (sym == null) {
   938                         log.error(c.pat.pos(), "enum.const.req");
   939                     } else if (!labels.add(sym)) {
   940                         log.error(c.pos(), "duplicate.case.label");
   941                     }
   942                 } else {
   943                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   944                     if (pattype.tag != ERROR) {
   945                         if (pattype.constValue() == null) {
   946                             log.error(c.pat.pos(),
   947                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
   948                         } else if (labels.contains(pattype.constValue())) {
   949                             log.error(c.pos(), "duplicate.case.label");
   950                         } else {
   951                             labels.add(pattype.constValue());
   952                         }
   953                     }
   954                 }
   955             } else if (hasDefault) {
   956                 log.error(c.pos(), "duplicate.default.label");
   957             } else {
   958                 hasDefault = true;
   959             }
   960             attribStats(c.stats, caseEnv);
   961             caseEnv.info.scope.leave();
   962             addVars(c.stats, switchEnv.info.scope);
   963         }
   965         switchEnv.info.scope.leave();
   966         result = null;
   967     }
   968     // where
   969         /** Add any variables defined in stats to the switch scope. */
   970         private static void addVars(List<JCStatement> stats, Scope switchScope) {
   971             for (;stats.nonEmpty(); stats = stats.tail) {
   972                 JCTree stat = stats.head;
   973                 if (stat.getTag() == JCTree.VARDEF)
   974                     switchScope.enter(((JCVariableDecl) stat).sym);
   975             }
   976         }
   977     // where
   978     /** Return the selected enumeration constant symbol, or null. */
   979     private Symbol enumConstant(JCTree tree, Type enumType) {
   980         if (tree.getTag() != JCTree.IDENT) {
   981             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
   982             return syms.errSymbol;
   983         }
   984         JCIdent ident = (JCIdent)tree;
   985         Name name = ident.name;
   986         for (Scope.Entry e = enumType.tsym.members().lookup(name);
   987              e.scope != null; e = e.next()) {
   988             if (e.sym.kind == VAR) {
   989                 Symbol s = ident.sym = e.sym;
   990                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
   991                 ident.type = s.type;
   992                 return ((s.flags_field & Flags.ENUM) == 0)
   993                     ? null : s;
   994             }
   995         }
   996         return null;
   997     }
   999     public void visitSynchronized(JCSynchronized tree) {
  1000         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1001         attribStat(tree.body, env);
  1002         result = null;
  1005     public void visitTry(JCTry tree) {
  1006         // Create a new local environment with a local
  1007         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1008         boolean isTryWithResource = tree.resources.nonEmpty();
  1009         // Create a nested environment for attributing the try block if needed
  1010         Env<AttrContext> tryEnv = isTryWithResource ?
  1011             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1012             localEnv;
  1013         // Attribute resource declarations
  1014         for (JCTree resource : tree.resources) {
  1015             if (resource.getTag() == JCTree.VARDEF) {
  1016                 attribStat(resource, tryEnv);
  1017                 chk.checkType(resource, resource.type, syms.autoCloseableType, "twr.not.applicable.to.type");
  1018                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1019                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1020             } else {
  1021                 attribExpr(resource, tryEnv, syms.autoCloseableType, "twr.not.applicable.to.type");
  1024         // Attribute body
  1025         attribStat(tree.body, tryEnv);
  1026         if (isTryWithResource)
  1027             tryEnv.info.scope.leave();
  1029         // Attribute catch clauses
  1030         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1031             JCCatch c = l.head;
  1032             Env<AttrContext> catchEnv =
  1033                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1034             Type ctype = attribStat(c.param, catchEnv);
  1035             if (TreeInfo.isMultiCatch(c)) {
  1036                 //check that multi-catch parameter is marked as final
  1037                 if ((c.param.sym.flags() & FINAL) == 0) {
  1038                     log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
  1040                 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
  1042             if (c.param.type.tsym.kind == Kinds.VAR) {
  1043                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1045             chk.checkType(c.param.vartype.pos(),
  1046                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1047                           syms.throwableType);
  1048             attribStat(c.body, catchEnv);
  1049             catchEnv.info.scope.leave();
  1052         // Attribute finalizer
  1053         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1055         localEnv.info.scope.leave();
  1056         result = null;
  1059     public void visitConditional(JCConditional tree) {
  1060         attribExpr(tree.cond, env, syms.booleanType);
  1061         attribExpr(tree.truepart, env);
  1062         attribExpr(tree.falsepart, env);
  1063         result = check(tree,
  1064                        capture(condType(tree.pos(), tree.cond.type,
  1065                                         tree.truepart.type, tree.falsepart.type)),
  1066                        VAL, pkind, pt);
  1068     //where
  1069         /** Compute the type of a conditional expression, after
  1070          *  checking that it exists. See Spec 15.25.
  1072          *  @param pos      The source position to be used for
  1073          *                  error diagnostics.
  1074          *  @param condtype The type of the expression's condition.
  1075          *  @param thentype The type of the expression's then-part.
  1076          *  @param elsetype The type of the expression's else-part.
  1077          */
  1078         private Type condType(DiagnosticPosition pos,
  1079                               Type condtype,
  1080                               Type thentype,
  1081                               Type elsetype) {
  1082             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1084             // If condition and both arms are numeric constants,
  1085             // evaluate at compile-time.
  1086             return ((condtype.constValue() != null) &&
  1087                     (thentype.constValue() != null) &&
  1088                     (elsetype.constValue() != null))
  1089                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1090                 : ctype;
  1092         /** Compute the type of a conditional expression, after
  1093          *  checking that it exists.  Does not take into
  1094          *  account the special case where condition and both arms
  1095          *  are constants.
  1097          *  @param pos      The source position to be used for error
  1098          *                  diagnostics.
  1099          *  @param condtype The type of the expression's condition.
  1100          *  @param thentype The type of the expression's then-part.
  1101          *  @param elsetype The type of the expression's else-part.
  1102          */
  1103         private Type condType1(DiagnosticPosition pos, Type condtype,
  1104                                Type thentype, Type elsetype) {
  1105             // If same type, that is the result
  1106             if (types.isSameType(thentype, elsetype))
  1107                 return thentype.baseType();
  1109             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1110                 ? thentype : types.unboxedType(thentype);
  1111             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1112                 ? elsetype : types.unboxedType(elsetype);
  1114             // Otherwise, if both arms can be converted to a numeric
  1115             // type, return the least numeric type that fits both arms
  1116             // (i.e. return larger of the two, or return int if one
  1117             // arm is short, the other is char).
  1118             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1119                 // If one arm has an integer subrange type (i.e., byte,
  1120                 // short, or char), and the other is an integer constant
  1121                 // that fits into the subrange, return the subrange type.
  1122                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1123                     types.isAssignable(elseUnboxed, thenUnboxed))
  1124                     return thenUnboxed.baseType();
  1125                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1126                     types.isAssignable(thenUnboxed, elseUnboxed))
  1127                     return elseUnboxed.baseType();
  1129                 for (int i = BYTE; i < VOID; i++) {
  1130                     Type candidate = syms.typeOfTag[i];
  1131                     if (types.isSubtype(thenUnboxed, candidate) &&
  1132                         types.isSubtype(elseUnboxed, candidate))
  1133                         return candidate;
  1137             // Those were all the cases that could result in a primitive
  1138             if (allowBoxing) {
  1139                 if (thentype.isPrimitive())
  1140                     thentype = types.boxedClass(thentype).type;
  1141                 if (elsetype.isPrimitive())
  1142                     elsetype = types.boxedClass(elsetype).type;
  1145             if (types.isSubtype(thentype, elsetype))
  1146                 return elsetype.baseType();
  1147             if (types.isSubtype(elsetype, thentype))
  1148                 return thentype.baseType();
  1150             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1151                 log.error(pos, "neither.conditional.subtype",
  1152                           thentype, elsetype);
  1153                 return thentype.baseType();
  1156             // both are known to be reference types.  The result is
  1157             // lub(thentype,elsetype). This cannot fail, as it will
  1158             // always be possible to infer "Object" if nothing better.
  1159             return types.lub(thentype.baseType(), elsetype.baseType());
  1162     public void visitIf(JCIf tree) {
  1163         attribExpr(tree.cond, env, syms.booleanType);
  1164         attribStat(tree.thenpart, env);
  1165         if (tree.elsepart != null)
  1166             attribStat(tree.elsepart, env);
  1167         chk.checkEmptyIf(tree);
  1168         result = null;
  1171     public void visitExec(JCExpressionStatement tree) {
  1172         attribExpr(tree.expr, env);
  1173         result = null;
  1176     public void visitBreak(JCBreak tree) {
  1177         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1178         result = null;
  1181     public void visitContinue(JCContinue tree) {
  1182         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1183         result = null;
  1185     //where
  1186         /** Return the target of a break or continue statement, if it exists,
  1187          *  report an error if not.
  1188          *  Note: The target of a labelled break or continue is the
  1189          *  (non-labelled) statement tree referred to by the label,
  1190          *  not the tree representing the labelled statement itself.
  1192          *  @param pos     The position to be used for error diagnostics
  1193          *  @param tag     The tag of the jump statement. This is either
  1194          *                 Tree.BREAK or Tree.CONTINUE.
  1195          *  @param label   The label of the jump statement, or null if no
  1196          *                 label is given.
  1197          *  @param env     The environment current at the jump statement.
  1198          */
  1199         private JCTree findJumpTarget(DiagnosticPosition pos,
  1200                                     int tag,
  1201                                     Name label,
  1202                                     Env<AttrContext> env) {
  1203             // Search environments outwards from the point of jump.
  1204             Env<AttrContext> env1 = env;
  1205             LOOP:
  1206             while (env1 != null) {
  1207                 switch (env1.tree.getTag()) {
  1208                 case JCTree.LABELLED:
  1209                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1210                     if (label == labelled.label) {
  1211                         // If jump is a continue, check that target is a loop.
  1212                         if (tag == JCTree.CONTINUE) {
  1213                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1214                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1215                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1216                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1217                                 log.error(pos, "not.loop.label", label);
  1218                             // Found labelled statement target, now go inwards
  1219                             // to next non-labelled tree.
  1220                             return TreeInfo.referencedStatement(labelled);
  1221                         } else {
  1222                             return labelled;
  1225                     break;
  1226                 case JCTree.DOLOOP:
  1227                 case JCTree.WHILELOOP:
  1228                 case JCTree.FORLOOP:
  1229                 case JCTree.FOREACHLOOP:
  1230                     if (label == null) return env1.tree;
  1231                     break;
  1232                 case JCTree.SWITCH:
  1233                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1234                     break;
  1235                 case JCTree.METHODDEF:
  1236                 case JCTree.CLASSDEF:
  1237                     break LOOP;
  1238                 default:
  1240                 env1 = env1.next;
  1242             if (label != null)
  1243                 log.error(pos, "undef.label", label);
  1244             else if (tag == JCTree.CONTINUE)
  1245                 log.error(pos, "cont.outside.loop");
  1246             else
  1247                 log.error(pos, "break.outside.switch.loop");
  1248             return null;
  1251     public void visitReturn(JCReturn tree) {
  1252         // Check that there is an enclosing method which is
  1253         // nested within than the enclosing class.
  1254         if (env.enclMethod == null ||
  1255             env.enclMethod.sym.owner != env.enclClass.sym) {
  1256             log.error(tree.pos(), "ret.outside.meth");
  1258         } else {
  1259             // Attribute return expression, if it exists, and check that
  1260             // it conforms to result type of enclosing method.
  1261             Symbol m = env.enclMethod.sym;
  1262             if (m.type.getReturnType().tag == VOID) {
  1263                 if (tree.expr != null)
  1264                     log.error(tree.expr.pos(),
  1265                               "cant.ret.val.from.meth.decl.void");
  1266             } else if (tree.expr == null) {
  1267                 log.error(tree.pos(), "missing.ret.val");
  1268             } else {
  1269                 attribExpr(tree.expr, env, m.type.getReturnType());
  1272         result = null;
  1275     public void visitThrow(JCThrow tree) {
  1276         attribExpr(tree.expr, env, syms.throwableType);
  1277         result = null;
  1280     public void visitAssert(JCAssert tree) {
  1281         attribExpr(tree.cond, env, syms.booleanType);
  1282         if (tree.detail != null) {
  1283             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1285         result = null;
  1288      /** Visitor method for method invocations.
  1289      *  NOTE: The method part of an application will have in its type field
  1290      *        the return type of the method, not the method's type itself!
  1291      */
  1292     public void visitApply(JCMethodInvocation tree) {
  1293         // The local environment of a method application is
  1294         // a new environment nested in the current one.
  1295         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1297         // The types of the actual method arguments.
  1298         List<Type> argtypes;
  1300         // The types of the actual method type arguments.
  1301         List<Type> typeargtypes = null;
  1302         boolean typeargtypesNonRefOK = false;
  1304         Name methName = TreeInfo.name(tree.meth);
  1306         boolean isConstructorCall =
  1307             methName == names._this || methName == names._super;
  1309         if (isConstructorCall) {
  1310             // We are seeing a ...this(...) or ...super(...) call.
  1311             // Check that this is the first statement in a constructor.
  1312             if (checkFirstConstructorStat(tree, env)) {
  1314                 // Record the fact
  1315                 // that this is a constructor call (using isSelfCall).
  1316                 localEnv.info.isSelfCall = true;
  1318                 // Attribute arguments, yielding list of argument types.
  1319                 argtypes = attribArgs(tree.args, localEnv);
  1320                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1322                 // Variable `site' points to the class in which the called
  1323                 // constructor is defined.
  1324                 Type site = env.enclClass.sym.type;
  1325                 if (methName == names._super) {
  1326                     if (site == syms.objectType) {
  1327                         log.error(tree.meth.pos(), "no.superclass", site);
  1328                         site = types.createErrorType(syms.objectType);
  1329                     } else {
  1330                         site = types.supertype(site);
  1334                 if (site.tag == CLASS) {
  1335                     Type encl = site.getEnclosingType();
  1336                     while (encl != null && encl.tag == TYPEVAR)
  1337                         encl = encl.getUpperBound();
  1338                     if (encl.tag == CLASS) {
  1339                         // we are calling a nested class
  1341                         if (tree.meth.getTag() == JCTree.SELECT) {
  1342                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1344                             // We are seeing a prefixed call, of the form
  1345                             //     <expr>.super(...).
  1346                             // Check that the prefix expression conforms
  1347                             // to the outer instance type of the class.
  1348                             chk.checkRefType(qualifier.pos(),
  1349                                              attribExpr(qualifier, localEnv,
  1350                                                         encl));
  1351                         } else if (methName == names._super) {
  1352                             // qualifier omitted; check for existence
  1353                             // of an appropriate implicit qualifier.
  1354                             rs.resolveImplicitThis(tree.meth.pos(),
  1355                                                    localEnv, site);
  1357                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1358                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1359                                   site.tsym);
  1362                     // if we're calling a java.lang.Enum constructor,
  1363                     // prefix the implicit String and int parameters
  1364                     if (site.tsym == syms.enumSym && allowEnums)
  1365                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1367                     // Resolve the called constructor under the assumption
  1368                     // that we are referring to a superclass instance of the
  1369                     // current instance (JLS ???).
  1370                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1371                     localEnv.info.selectSuper = true;
  1372                     localEnv.info.varArgs = false;
  1373                     Symbol sym = rs.resolveConstructor(
  1374                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1375                     localEnv.info.selectSuper = selectSuperPrev;
  1377                     // Set method symbol to resolved constructor...
  1378                     TreeInfo.setSymbol(tree.meth, sym);
  1380                     // ...and check that it is legal in the current context.
  1381                     // (this will also set the tree's type)
  1382                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1383                     checkId(tree.meth, site, sym, localEnv, MTH,
  1384                             mpt, tree.varargsElement != null);
  1386                 // Otherwise, `site' is an error type and we do nothing
  1388             result = tree.type = syms.voidType;
  1389         } else {
  1390             // Otherwise, we are seeing a regular method call.
  1391             // Attribute the arguments, yielding list of argument types, ...
  1392             argtypes = attribArgs(tree.args, localEnv);
  1393             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1395             // ... and attribute the method using as a prototype a methodtype
  1396             // whose formal argument types is exactly the list of actual
  1397             // arguments (this will also set the method symbol).
  1398             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1399             localEnv.info.varArgs = false;
  1400             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1401             if (localEnv.info.varArgs)
  1402                 assert mtype.isErroneous() || tree.varargsElement != null;
  1404             // Compute the result type.
  1405             Type restype = mtype.getReturnType();
  1406             assert restype.tag != WILDCARD : mtype;
  1408             // as a special case, array.clone() has a result that is
  1409             // the same as static type of the array being cloned
  1410             if (tree.meth.getTag() == JCTree.SELECT &&
  1411                 allowCovariantReturns &&
  1412                 methName == names.clone &&
  1413                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1414                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1416             // as a special case, x.getClass() has type Class<? extends |X|>
  1417             if (allowGenerics &&
  1418                 methName == names.getClass && tree.args.isEmpty()) {
  1419                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1420                     ? ((JCFieldAccess) tree.meth).selected.type
  1421                     : env.enclClass.sym.type;
  1422                 restype = new
  1423                     ClassType(restype.getEnclosingType(),
  1424                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1425                                                                BoundKind.EXTENDS,
  1426                                                                syms.boundClass)),
  1427                               restype.tsym);
  1430             // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
  1431             // has type <T>, and T can be a primitive type.
  1432             if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
  1433               JCFieldAccess mfield = (JCFieldAccess) tree.meth;
  1434               if ((mfield.selected.type.tsym != null &&
  1435                    (mfield.selected.type.tsym.flags() & POLYMORPHIC_SIGNATURE) != 0)
  1436                   ||
  1437                   (mfield.sym != null &&
  1438                    (mfield.sym.flags() & POLYMORPHIC_SIGNATURE) != 0)) {
  1439                   assert types.isSameType(restype, typeargtypes.head) : mtype;
  1440                   assert mfield.selected.type == syms.methodHandleType
  1441                       || mfield.selected.type == syms.invokeDynamicType;
  1442                   typeargtypesNonRefOK = true;
  1446             if (!typeargtypesNonRefOK) {
  1447                 chk.checkRefTypes(tree.typeargs, typeargtypes);
  1450             // Check that value of resulting type is admissible in the
  1451             // current context.  Also, capture the return type
  1452             result = check(tree, capture(restype), VAL, pkind, pt);
  1454         chk.validate(tree.typeargs, localEnv);
  1456     //where
  1457         /** Check that given application node appears as first statement
  1458          *  in a constructor call.
  1459          *  @param tree   The application node
  1460          *  @param env    The environment current at the application.
  1461          */
  1462         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1463             JCMethodDecl enclMethod = env.enclMethod;
  1464             if (enclMethod != null && enclMethod.name == names.init) {
  1465                 JCBlock body = enclMethod.body;
  1466                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1467                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1468                     return true;
  1470             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1471                       TreeInfo.name(tree.meth));
  1472             return false;
  1475         /** Obtain a method type with given argument types.
  1476          */
  1477         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1478             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1479             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1482     public void visitNewClass(JCNewClass tree) {
  1483         Type owntype = types.createErrorType(tree.type);
  1485         // The local environment of a class creation is
  1486         // a new environment nested in the current one.
  1487         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1489         // The anonymous inner class definition of the new expression,
  1490         // if one is defined by it.
  1491         JCClassDecl cdef = tree.def;
  1493         // If enclosing class is given, attribute it, and
  1494         // complete class name to be fully qualified
  1495         JCExpression clazz = tree.clazz; // Class field following new
  1496         JCExpression clazzid =          // Identifier in class field
  1497             (clazz.getTag() == JCTree.TYPEAPPLY)
  1498             ? ((JCTypeApply) clazz).clazz
  1499             : clazz;
  1501         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1503         if (tree.encl != null) {
  1504             // We are seeing a qualified new, of the form
  1505             //    <expr>.new C <...> (...) ...
  1506             // In this case, we let clazz stand for the name of the
  1507             // allocated class C prefixed with the type of the qualifier
  1508             // expression, so that we can
  1509             // resolve it with standard techniques later. I.e., if
  1510             // <expr> has type T, then <expr>.new C <...> (...)
  1511             // yields a clazz T.C.
  1512             Type encltype = chk.checkRefType(tree.encl.pos(),
  1513                                              attribExpr(tree.encl, env));
  1514             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1515                                                  ((JCIdent) clazzid).name);
  1516             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1517                 clazz = make.at(tree.pos).
  1518                     TypeApply(clazzid1,
  1519                               ((JCTypeApply) clazz).arguments);
  1520             else
  1521                 clazz = clazzid1;
  1524         // Attribute clazz expression and store
  1525         // symbol + type back into the attributed tree.
  1526         Type clazztype = attribType(clazz, env);
  1527         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
  1528         if (!TreeInfo.isDiamond(tree)) {
  1529             clazztype = chk.checkClassType(
  1530                 tree.clazz.pos(), clazztype, true);
  1532         chk.validate(clazz, localEnv);
  1533         if (tree.encl != null) {
  1534             // We have to work in this case to store
  1535             // symbol + type back into the attributed tree.
  1536             tree.clazz.type = clazztype;
  1537             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1538             clazzid.type = ((JCIdent) clazzid).sym.type;
  1539             if (!clazztype.isErroneous()) {
  1540                 if (cdef != null && clazztype.tsym.isInterface()) {
  1541                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1542                 } else if (clazztype.tsym.isStatic()) {
  1543                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1546         } else if (!clazztype.tsym.isInterface() &&
  1547                    clazztype.getEnclosingType().tag == CLASS) {
  1548             // Check for the existence of an apropos outer instance
  1549             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1552         // Attribute constructor arguments.
  1553         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1554         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1556         if (TreeInfo.isDiamond(tree)) {
  1557             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes, true);
  1558             clazz.type = clazztype;
  1561         // If we have made no mistakes in the class type...
  1562         if (clazztype.tag == CLASS) {
  1563             // Enums may not be instantiated except implicitly
  1564             if (allowEnums &&
  1565                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1566                 (env.tree.getTag() != JCTree.VARDEF ||
  1567                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1568                  ((JCVariableDecl) env.tree).init != tree))
  1569                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1570             // Check that class is not abstract
  1571             if (cdef == null &&
  1572                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1573                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1574                           clazztype.tsym);
  1575             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1576                 // Check that no constructor arguments are given to
  1577                 // anonymous classes implementing an interface
  1578                 if (!argtypes.isEmpty())
  1579                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1581                 if (!typeargtypes.isEmpty())
  1582                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1584                 // Error recovery: pretend no arguments were supplied.
  1585                 argtypes = List.nil();
  1586                 typeargtypes = List.nil();
  1589             // Resolve the called constructor under the assumption
  1590             // that we are referring to a superclass instance of the
  1591             // current instance (JLS ???).
  1592             else {
  1593                 localEnv.info.selectSuper = cdef != null;
  1594                 localEnv.info.varArgs = false;
  1595                 tree.constructor = rs.resolveConstructor(
  1596                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1597                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1598                     syms.errType :
  1599                     checkMethod(clazztype,
  1600                         tree.constructor,
  1601                         localEnv,
  1602                         tree.args,
  1603                         argtypes,
  1604                         typeargtypes,
  1605                         localEnv.info.varArgs);
  1606                 if (localEnv.info.varArgs)
  1607                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
  1610             if (cdef != null) {
  1611                 // We are seeing an anonymous class instance creation.
  1612                 // In this case, the class instance creation
  1613                 // expression
  1614                 //
  1615                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1616                 //
  1617                 // is represented internally as
  1618                 //
  1619                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1620                 //
  1621                 // This expression is then *transformed* as follows:
  1622                 //
  1623                 // (1) add a STATIC flag to the class definition
  1624                 //     if the current environment is static
  1625                 // (2) add an extends or implements clause
  1626                 // (3) add a constructor.
  1627                 //
  1628                 // For instance, if C is a class, and ET is the type of E,
  1629                 // the expression
  1630                 //
  1631                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1632                 //
  1633                 // is translated to (where X is a fresh name and typarams is the
  1634                 // parameter list of the super constructor):
  1635                 //
  1636                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1637                 //     X extends C<typargs2> {
  1638                 //       <typarams> X(ET e, args) {
  1639                 //         e.<typeargs1>super(args)
  1640                 //       }
  1641                 //       ...
  1642                 //     }
  1643                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1645                 if (clazztype.tsym.isInterface()) {
  1646                     cdef.implementing = List.of(clazz);
  1647                 } else {
  1648                     cdef.extending = clazz;
  1651                 attribStat(cdef, localEnv);
  1653                 // If an outer instance is given,
  1654                 // prefix it to the constructor arguments
  1655                 // and delete it from the new expression
  1656                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1657                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1658                     argtypes = argtypes.prepend(tree.encl.type);
  1659                     tree.encl = null;
  1662                 // Reassign clazztype and recompute constructor.
  1663                 clazztype = cdef.sym.type;
  1664                 Symbol sym = rs.resolveConstructor(
  1665                     tree.pos(), localEnv, clazztype, argtypes,
  1666                     typeargtypes, true, tree.varargsElement != null);
  1667                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1668                 tree.constructor = sym;
  1669                 if (tree.constructor.kind > ERRONEOUS) {
  1670                     tree.constructorType =  syms.errType;
  1672                 else {
  1673                     tree.constructorType = checkMethod(clazztype,
  1674                             tree.constructor,
  1675                             localEnv,
  1676                             tree.args,
  1677                             argtypes,
  1678                             typeargtypes,
  1679                             localEnv.info.varArgs);
  1683             if (tree.constructor != null && tree.constructor.kind == MTH)
  1684                 owntype = clazztype;
  1686         result = check(tree, owntype, VAL, pkind, pt);
  1687         chk.validate(tree.typeargs, localEnv);
  1690     Type attribDiamond(Env<AttrContext> env,
  1691                         JCNewClass tree,
  1692                         Type clazztype,
  1693                         Pair<Scope, Scope> mapping,
  1694                         List<Type> argtypes,
  1695                         List<Type> typeargtypes,
  1696                         boolean reportErrors) {
  1697         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1698             //if the type of the instance creation expression is erroneous,
  1699             //or something prevented us to form a valid mapping, return the
  1700             //(possibly erroneous) type unchanged
  1701             return clazztype;
  1703         else if (clazztype.isInterface()) {
  1704             //if the type of the instance creation expression is an interface
  1705             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1706             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1707             clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
  1708                 @Override
  1709                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
  1710                     switch (ck) {
  1711                         case EXTENDS: return types.getBounds(tv);
  1712                         default: return List.nil();
  1715                 @Override
  1716                 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
  1717                     // check that inferred bounds conform to their bounds
  1718                     infer.checkWithinBounds(tvars,
  1719                            types.subst(tvars, tvars, inferred), Warner.noWarnings);
  1720                     return super.inst(inferred, types);
  1722             };
  1723         } else {
  1724             //if the type of the instance creation expression is a class type
  1725             //apply method resolution inference (JLS 15.12.2.7). The return type
  1726             //of the resolved constructor will be a partially instantiated type
  1727             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1728             Symbol constructor;
  1729             try {
  1730                 constructor = rs.resolveDiamond(tree.pos(),
  1731                         env,
  1732                         clazztype.tsym.type,
  1733                         argtypes,
  1734                         typeargtypes, reportErrors);
  1735             } finally {
  1736                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1738             if (constructor.kind == MTH) {
  1739                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1740                         clazztype.tsym.type.getTypeArguments(),
  1741                         clazztype.tsym);
  1742                 clazztype = checkMethod(ct,
  1743                         constructor,
  1744                         env,
  1745                         tree.args,
  1746                         argtypes,
  1747                         typeargtypes,
  1748                         env.info.varArgs).getReturnType();
  1749             } else {
  1750                 clazztype = syms.errType;
  1753         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1754             //if the resolved constructor's return type has some uninferred
  1755             //type-variables, infer them using the expected type and declared
  1756             //bounds (JLS 15.12.2.8).
  1757             try {
  1758                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1759                         pt.tag == NONE ? syms.objectType : pt,
  1760                         Warner.noWarnings);
  1761             } catch (Infer.InferenceException ex) {
  1762                 //an error occurred while inferring uninstantiated type-variables
  1763                 //we need to optionally report an error
  1764                 if (reportErrors) {
  1765                     log.error(tree.clazz.pos(),
  1766                             "cant.apply.diamond.1",
  1767                             diags.fragment("diamond", clazztype.tsym),
  1768                             ex.diagnostic);
  1772         if (reportErrors) {
  1773             clazztype = chk.checkClassType(tree.clazz.pos(),
  1774                     clazztype,
  1775                     true);
  1776             if (clazztype.tag == CLASS) {
  1777                 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1778                 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1779                     //one or more types inferred in the previous steps is either a
  1780                     //captured type or an intersection type --- we need to report an error.
  1781                     String subkey = invalidDiamondArgs.size() > 1 ?
  1782                         "diamond.invalid.args" :
  1783                         "diamond.invalid.arg";
  1784                     //The error message is of the kind:
  1785                     //
  1786                     //cannot infer type arguments for {clazztype}<>;
  1787                     //reason: {subkey}
  1788                     //
  1789                     //where subkey is a fragment of the kind:
  1790                     //
  1791                     //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1792                     log.error(tree.clazz.pos(),
  1793                                 "cant.apply.diamond.1",
  1794                                 diags.fragment("diamond", clazztype.tsym),
  1795                                 diags.fragment(subkey,
  1796                                                invalidDiamondArgs,
  1797                                                diags.fragment("diamond", clazztype.tsym)));
  1801         return clazztype;
  1804     /** Creates a synthetic scope containing fake generic constructors.
  1805      *  Assuming that the original scope contains a constructor of the kind:
  1806      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1807      *  the synthetic scope is added a generic constructor of the kind:
  1808      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1809      *  inference. The inferred return type of the synthetic constructor IS
  1810      *  the inferred type for the diamond operator.
  1811      */
  1812     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
  1813         if (ctype.tag != CLASS) {
  1814             return erroneousMapping;
  1816         Pair<Scope, Scope> mapping =
  1817                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1818         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1819         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1820                 e.scope != null;
  1821                 e = e.next()) {
  1822             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1823             newConstr.name = names.init;
  1824             List<Type> oldTypeargs = List.nil();
  1825             if (newConstr.type.tag == FORALL) {
  1826                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1828             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1829                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1830                     newConstr.type.getThrownTypes(),
  1831                     syms.methodClass);
  1832             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1833             mapping.snd.enter(newConstr);
  1835         return mapping;
  1838     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1840     /** Make an attributed null check tree.
  1841      */
  1842     public JCExpression makeNullCheck(JCExpression arg) {
  1843         // optimization: X.this is never null; skip null check
  1844         Name name = TreeInfo.name(arg);
  1845         if (name == names._this || name == names._super) return arg;
  1847         int optag = JCTree.NULLCHK;
  1848         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1849         tree.operator = syms.nullcheck;
  1850         tree.type = arg.type;
  1851         return tree;
  1854     public void visitNewArray(JCNewArray tree) {
  1855         Type owntype = types.createErrorType(tree.type);
  1856         Type elemtype;
  1857         if (tree.elemtype != null) {
  1858             elemtype = attribType(tree.elemtype, env);
  1859             chk.validate(tree.elemtype, env);
  1860             owntype = elemtype;
  1861             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1862                 attribExpr(l.head, env, syms.intType);
  1863                 owntype = new ArrayType(owntype, syms.arrayClass);
  1865         } else {
  1866             // we are seeing an untyped aggregate { ... }
  1867             // this is allowed only if the prototype is an array
  1868             if (pt.tag == ARRAY) {
  1869                 elemtype = types.elemtype(pt);
  1870             } else {
  1871                 if (pt.tag != ERROR) {
  1872                     log.error(tree.pos(), "illegal.initializer.for.type",
  1873                               pt);
  1875                 elemtype = types.createErrorType(pt);
  1878         if (tree.elems != null) {
  1879             attribExprs(tree.elems, env, elemtype);
  1880             owntype = new ArrayType(elemtype, syms.arrayClass);
  1882         if (!types.isReifiable(elemtype))
  1883             log.error(tree.pos(), "generic.array.creation");
  1884         result = check(tree, owntype, VAL, pkind, pt);
  1887     public void visitParens(JCParens tree) {
  1888         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1889         result = check(tree, owntype, pkind, pkind, pt);
  1890         Symbol sym = TreeInfo.symbol(tree);
  1891         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1892             log.error(tree.pos(), "illegal.start.of.type");
  1895     public void visitAssign(JCAssign tree) {
  1896         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1897         Type capturedType = capture(owntype);
  1898         attribExpr(tree.rhs, env, owntype);
  1899         result = check(tree, capturedType, VAL, pkind, pt);
  1902     public void visitAssignop(JCAssignOp tree) {
  1903         // Attribute arguments.
  1904         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1905         Type operand = attribExpr(tree.rhs, env);
  1906         // Find operator.
  1907         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1908             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1909             owntype, operand);
  1911         if (operator.kind == MTH) {
  1912             chk.checkOperator(tree.pos(),
  1913                               (OperatorSymbol)operator,
  1914                               tree.getTag() - JCTree.ASGOffset,
  1915                               owntype,
  1916                               operand);
  1917             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1918             chk.checkCastable(tree.rhs.pos(),
  1919                               operator.type.getReturnType(),
  1920                               owntype);
  1922         result = check(tree, owntype, VAL, pkind, pt);
  1925     public void visitUnary(JCUnary tree) {
  1926         // Attribute arguments.
  1927         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1928             ? attribTree(tree.arg, env, VAR, Type.noType)
  1929             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1931         // Find operator.
  1932         Symbol operator = tree.operator =
  1933             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1935         Type owntype = types.createErrorType(tree.type);
  1936         if (operator.kind == MTH) {
  1937             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1938                 ? tree.arg.type
  1939                 : operator.type.getReturnType();
  1940             int opc = ((OperatorSymbol)operator).opcode;
  1942             // If the argument is constant, fold it.
  1943             if (argtype.constValue() != null) {
  1944                 Type ctype = cfolder.fold1(opc, argtype);
  1945                 if (ctype != null) {
  1946                     owntype = cfolder.coerce(ctype, owntype);
  1948                     // Remove constant types from arguments to
  1949                     // conserve space. The parser will fold concatenations
  1950                     // of string literals; the code here also
  1951                     // gets rid of intermediate results when some of the
  1952                     // operands are constant identifiers.
  1953                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  1954                         tree.arg.type = syms.stringType;
  1959         result = check(tree, owntype, VAL, pkind, pt);
  1962     public void visitBinary(JCBinary tree) {
  1963         // Attribute arguments.
  1964         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  1965         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  1967         // Find operator.
  1968         Symbol operator = tree.operator =
  1969             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  1971         Type owntype = types.createErrorType(tree.type);
  1972         if (operator.kind == MTH) {
  1973             owntype = operator.type.getReturnType();
  1974             int opc = chk.checkOperator(tree.lhs.pos(),
  1975                                         (OperatorSymbol)operator,
  1976                                         tree.getTag(),
  1977                                         left,
  1978                                         right);
  1980             // If both arguments are constants, fold them.
  1981             if (left.constValue() != null && right.constValue() != null) {
  1982                 Type ctype = cfolder.fold2(opc, left, right);
  1983                 if (ctype != null) {
  1984                     owntype = cfolder.coerce(ctype, owntype);
  1986                     // Remove constant types from arguments to
  1987                     // conserve space. The parser will fold concatenations
  1988                     // of string literals; the code here also
  1989                     // gets rid of intermediate results when some of the
  1990                     // operands are constant identifiers.
  1991                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  1992                         tree.lhs.type = syms.stringType;
  1994                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  1995                         tree.rhs.type = syms.stringType;
  2000             // Check that argument types of a reference ==, != are
  2001             // castable to each other, (JLS???).
  2002             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2003                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2004                     log.error(tree.pos(), "incomparable.types", left, right);
  2008             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2010         result = check(tree, owntype, VAL, pkind, pt);
  2013     public void visitTypeCast(JCTypeCast tree) {
  2014         Type clazztype = attribType(tree.clazz, env);
  2015         chk.validate(tree.clazz, env);
  2016         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
  2017         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2018         if (exprtype.constValue() != null)
  2019             owntype = cfolder.coerce(exprtype, owntype);
  2020         result = check(tree, capture(owntype), VAL, pkind, pt);
  2023     public void visitTypeTest(JCInstanceOf tree) {
  2024         Type exprtype = chk.checkNullOrRefType(
  2025             tree.expr.pos(), attribExpr(tree.expr, env));
  2026         Type clazztype = chk.checkReifiableReferenceType(
  2027             tree.clazz.pos(), attribType(tree.clazz, env));
  2028         chk.validate(tree.clazz, env);
  2029         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2030         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2033     public void visitIndexed(JCArrayAccess tree) {
  2034         Type owntype = types.createErrorType(tree.type);
  2035         Type atype = attribExpr(tree.indexed, env);
  2036         attribExpr(tree.index, env, syms.intType);
  2037         if (types.isArray(atype))
  2038             owntype = types.elemtype(atype);
  2039         else if (atype.tag != ERROR)
  2040             log.error(tree.pos(), "array.req.but.found", atype);
  2041         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2042         result = check(tree, owntype, VAR, pkind, pt);
  2045     public void visitIdent(JCIdent tree) {
  2046         Symbol sym;
  2047         boolean varArgs = false;
  2049         // Find symbol
  2050         if (pt.tag == METHOD || pt.tag == FORALL) {
  2051             // If we are looking for a method, the prototype `pt' will be a
  2052             // method type with the type of the call's arguments as parameters.
  2053             env.info.varArgs = false;
  2054             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2055             varArgs = env.info.varArgs;
  2056         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2057             sym = tree.sym;
  2058         } else {
  2059             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2061         tree.sym = sym;
  2063         // (1) Also find the environment current for the class where
  2064         //     sym is defined (`symEnv').
  2065         // Only for pre-tiger versions (1.4 and earlier):
  2066         // (2) Also determine whether we access symbol out of an anonymous
  2067         //     class in a this or super call.  This is illegal for instance
  2068         //     members since such classes don't carry a this$n link.
  2069         //     (`noOuterThisPath').
  2070         Env<AttrContext> symEnv = env;
  2071         boolean noOuterThisPath = false;
  2072         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2073             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2074             sym.owner.kind == TYP &&
  2075             tree.name != names._this && tree.name != names._super) {
  2077             // Find environment in which identifier is defined.
  2078             while (symEnv.outer != null &&
  2079                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2080                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2081                     noOuterThisPath = !allowAnonOuterThis;
  2082                 symEnv = symEnv.outer;
  2086         // If symbol is a variable, ...
  2087         if (sym.kind == VAR) {
  2088             VarSymbol v = (VarSymbol)sym;
  2090             // ..., evaluate its initializer, if it has one, and check for
  2091             // illegal forward reference.
  2092             checkInit(tree, env, v, false);
  2094             // If symbol is a local variable accessed from an embedded
  2095             // inner class check that it is final.
  2096             if (v.owner.kind == MTH &&
  2097                 v.owner != env.info.scope.owner &&
  2098                 (v.flags_field & FINAL) == 0) {
  2099                 log.error(tree.pos(),
  2100                           "local.var.accessed.from.icls.needs.final",
  2101                           v);
  2104             // If we are expecting a variable (as opposed to a value), check
  2105             // that the variable is assignable in the current environment.
  2106             if (pkind == VAR)
  2107                 checkAssignable(tree.pos(), v, null, env);
  2110         // In a constructor body,
  2111         // if symbol is a field or instance method, check that it is
  2112         // not accessed before the supertype constructor is called.
  2113         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2114             (sym.kind & (VAR | MTH)) != 0 &&
  2115             sym.owner.kind == TYP &&
  2116             (sym.flags() & STATIC) == 0) {
  2117             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2119         Env<AttrContext> env1 = env;
  2120         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2121             // If the found symbol is inaccessible, then it is
  2122             // accessed through an enclosing instance.  Locate this
  2123             // enclosing instance:
  2124             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2125                 env1 = env1.outer;
  2127         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2130     public void visitSelect(JCFieldAccess tree) {
  2131         // Determine the expected kind of the qualifier expression.
  2132         int skind = 0;
  2133         if (tree.name == names._this || tree.name == names._super ||
  2134             tree.name == names._class)
  2136             skind = TYP;
  2137         } else {
  2138             if ((pkind & PCK) != 0) skind = skind | PCK;
  2139             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2140             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2143         // Attribute the qualifier expression, and determine its symbol (if any).
  2144         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2145         if ((pkind & (PCK | TYP)) == 0)
  2146             site = capture(site); // Capture field access
  2148         // don't allow T.class T[].class, etc
  2149         if (skind == TYP) {
  2150             Type elt = site;
  2151             while (elt.tag == ARRAY)
  2152                 elt = ((ArrayType)elt).elemtype;
  2153             if (elt.tag == TYPEVAR) {
  2154                 log.error(tree.pos(), "type.var.cant.be.deref");
  2155                 result = types.createErrorType(tree.type);
  2156                 return;
  2160         // If qualifier symbol is a type or `super', assert `selectSuper'
  2161         // for the selection. This is relevant for determining whether
  2162         // protected symbols are accessible.
  2163         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2164         boolean selectSuperPrev = env.info.selectSuper;
  2165         env.info.selectSuper =
  2166             sitesym != null &&
  2167             sitesym.name == names._super;
  2169         // If selected expression is polymorphic, strip
  2170         // type parameters and remember in env.info.tvars, so that
  2171         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2172         if (tree.selected.type.tag == FORALL) {
  2173             ForAll pstype = (ForAll)tree.selected.type;
  2174             env.info.tvars = pstype.tvars;
  2175             site = tree.selected.type = pstype.qtype;
  2178         // Determine the symbol represented by the selection.
  2179         env.info.varArgs = false;
  2180         Symbol sym = selectSym(tree, site, env, pt, pkind);
  2181         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2182             site = capture(site);
  2183             sym = selectSym(tree, site, env, pt, pkind);
  2185         boolean varArgs = env.info.varArgs;
  2186         tree.sym = sym;
  2188         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2189             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2190             site = capture(site);
  2193         // If that symbol is a variable, ...
  2194         if (sym.kind == VAR) {
  2195             VarSymbol v = (VarSymbol)sym;
  2197             // ..., evaluate its initializer, if it has one, and check for
  2198             // illegal forward reference.
  2199             checkInit(tree, env, v, true);
  2201             // If we are expecting a variable (as opposed to a value), check
  2202             // that the variable is assignable in the current environment.
  2203             if (pkind == VAR)
  2204                 checkAssignable(tree.pos(), v, tree.selected, env);
  2207         if (sitesym != null &&
  2208                 sitesym.kind == VAR &&
  2209                 ((VarSymbol)sitesym).isResourceVariable() &&
  2210                 sym.kind == MTH &&
  2211                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2212                 env.info.lint.isEnabled(Lint.LintCategory.ARM)) {
  2213             log.warning(tree, "twr.explicit.close.call");
  2216         // Disallow selecting a type from an expression
  2217         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2218             tree.type = check(tree.selected, pt,
  2219                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2222         if (isType(sitesym)) {
  2223             if (sym.name == names._this) {
  2224                 // If `C' is the currently compiled class, check that
  2225                 // C.this' does not appear in a call to a super(...)
  2226                 if (env.info.isSelfCall &&
  2227                     site.tsym == env.enclClass.sym) {
  2228                     chk.earlyRefError(tree.pos(), sym);
  2230             } else {
  2231                 // Check if type-qualified fields or methods are static (JLS)
  2232                 if ((sym.flags() & STATIC) == 0 &&
  2233                     sym.name != names._super &&
  2234                     (sym.kind == VAR || sym.kind == MTH)) {
  2235                     rs.access(rs.new StaticError(sym),
  2236                               tree.pos(), site, sym.name, true);
  2239         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2240             // If the qualified item is not a type and the selected item is static, report
  2241             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2242             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2245         // If we are selecting an instance member via a `super', ...
  2246         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2248             // Check that super-qualified symbols are not abstract (JLS)
  2249             rs.checkNonAbstract(tree.pos(), sym);
  2251             if (site.isRaw()) {
  2252                 // Determine argument types for site.
  2253                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2254                 if (site1 != null) site = site1;
  2258         env.info.selectSuper = selectSuperPrev;
  2259         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2260         env.info.tvars = List.nil();
  2262     //where
  2263         /** Determine symbol referenced by a Select expression,
  2265          *  @param tree   The select tree.
  2266          *  @param site   The type of the selected expression,
  2267          *  @param env    The current environment.
  2268          *  @param pt     The current prototype.
  2269          *  @param pkind  The expected kind(s) of the Select expression.
  2270          */
  2271         private Symbol selectSym(JCFieldAccess tree,
  2272                                  Type site,
  2273                                  Env<AttrContext> env,
  2274                                  Type pt,
  2275                                  int pkind) {
  2276             DiagnosticPosition pos = tree.pos();
  2277             Name name = tree.name;
  2279             switch (site.tag) {
  2280             case PACKAGE:
  2281                 return rs.access(
  2282                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2283                     pos, site, name, true);
  2284             case ARRAY:
  2285             case CLASS:
  2286                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2287                     return rs.resolveQualifiedMethod(
  2288                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2289                 } else if (name == names._this || name == names._super) {
  2290                     return rs.resolveSelf(pos, env, site.tsym, name);
  2291                 } else if (name == names._class) {
  2292                     // In this case, we have already made sure in
  2293                     // visitSelect that qualifier expression is a type.
  2294                     Type t = syms.classType;
  2295                     List<Type> typeargs = allowGenerics
  2296                         ? List.of(types.erasure(site))
  2297                         : List.<Type>nil();
  2298                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2299                     return new VarSymbol(
  2300                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2301                 } else {
  2302                     // We are seeing a plain identifier as selector.
  2303                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2304                     if ((pkind & ERRONEOUS) == 0)
  2305                         sym = rs.access(sym, pos, site, name, true);
  2306                     return sym;
  2308             case WILDCARD:
  2309                 throw new AssertionError(tree);
  2310             case TYPEVAR:
  2311                 // Normally, site.getUpperBound() shouldn't be null.
  2312                 // It should only happen during memberEnter/attribBase
  2313                 // when determining the super type which *must* be
  2314                 // done before attributing the type variables.  In
  2315                 // other words, we are seeing this illegal program:
  2316                 // class B<T> extends A<T.foo> {}
  2317                 Symbol sym = (site.getUpperBound() != null)
  2318                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2319                     : null;
  2320                 if (sym == null) {
  2321                     log.error(pos, "type.var.cant.be.deref");
  2322                     return syms.errSymbol;
  2323                 } else {
  2324                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2325                         rs.new AccessError(env, site, sym) :
  2326                                 sym;
  2327                     rs.access(sym2, pos, site, name, true);
  2328                     return sym;
  2330             case ERROR:
  2331                 // preserve identifier names through errors
  2332                 return types.createErrorType(name, site.tsym, site).tsym;
  2333             default:
  2334                 // The qualifier expression is of a primitive type -- only
  2335                 // .class is allowed for these.
  2336                 if (name == names._class) {
  2337                     // In this case, we have already made sure in Select that
  2338                     // qualifier expression is a type.
  2339                     Type t = syms.classType;
  2340                     Type arg = types.boxedClass(site).type;
  2341                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2342                     return new VarSymbol(
  2343                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2344                 } else {
  2345                     log.error(pos, "cant.deref", site);
  2346                     return syms.errSymbol;
  2351         /** Determine type of identifier or select expression and check that
  2352          *  (1) the referenced symbol is not deprecated
  2353          *  (2) the symbol's type is safe (@see checkSafe)
  2354          *  (3) if symbol is a variable, check that its type and kind are
  2355          *      compatible with the prototype and protokind.
  2356          *  (4) if symbol is an instance field of a raw type,
  2357          *      which is being assigned to, issue an unchecked warning if its
  2358          *      type changes under erasure.
  2359          *  (5) if symbol is an instance method of a raw type, issue an
  2360          *      unchecked warning if its argument types change under erasure.
  2361          *  If checks succeed:
  2362          *    If symbol is a constant, return its constant type
  2363          *    else if symbol is a method, return its result type
  2364          *    otherwise return its type.
  2365          *  Otherwise return errType.
  2367          *  @param tree       The syntax tree representing the identifier
  2368          *  @param site       If this is a select, the type of the selected
  2369          *                    expression, otherwise the type of the current class.
  2370          *  @param sym        The symbol representing the identifier.
  2371          *  @param env        The current environment.
  2372          *  @param pkind      The set of expected kinds.
  2373          *  @param pt         The expected type.
  2374          */
  2375         Type checkId(JCTree tree,
  2376                      Type site,
  2377                      Symbol sym,
  2378                      Env<AttrContext> env,
  2379                      int pkind,
  2380                      Type pt,
  2381                      boolean useVarargs) {
  2382             if (pt.isErroneous()) return types.createErrorType(site);
  2383             Type owntype; // The computed type of this identifier occurrence.
  2384             switch (sym.kind) {
  2385             case TYP:
  2386                 // For types, the computed type equals the symbol's type,
  2387                 // except for two situations:
  2388                 owntype = sym.type;
  2389                 if (owntype.tag == CLASS) {
  2390                     Type ownOuter = owntype.getEnclosingType();
  2392                     // (a) If the symbol's type is parameterized, erase it
  2393                     // because no type parameters were given.
  2394                     // We recover generic outer type later in visitTypeApply.
  2395                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2396                         owntype = types.erasure(owntype);
  2399                     // (b) If the symbol's type is an inner class, then
  2400                     // we have to interpret its outer type as a superclass
  2401                     // of the site type. Example:
  2402                     //
  2403                     // class Tree<A> { class Visitor { ... } }
  2404                     // class PointTree extends Tree<Point> { ... }
  2405                     // ...PointTree.Visitor...
  2406                     //
  2407                     // Then the type of the last expression above is
  2408                     // Tree<Point>.Visitor.
  2409                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2410                         Type normOuter = site;
  2411                         if (normOuter.tag == CLASS)
  2412                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2413                         if (normOuter == null) // perhaps from an import
  2414                             normOuter = types.erasure(ownOuter);
  2415                         if (normOuter != ownOuter)
  2416                             owntype = new ClassType(
  2417                                 normOuter, List.<Type>nil(), owntype.tsym);
  2420                 break;
  2421             case VAR:
  2422                 VarSymbol v = (VarSymbol)sym;
  2423                 // Test (4): if symbol is an instance field of a raw type,
  2424                 // which is being assigned to, issue an unchecked warning if
  2425                 // its type changes under erasure.
  2426                 if (allowGenerics &&
  2427                     pkind == VAR &&
  2428                     v.owner.kind == TYP &&
  2429                     (v.flags() & STATIC) == 0 &&
  2430                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2431                     Type s = types.asOuterSuper(site, v.owner);
  2432                     if (s != null &&
  2433                         s.isRaw() &&
  2434                         !types.isSameType(v.type, v.erasure(types))) {
  2435                         chk.warnUnchecked(tree.pos(),
  2436                                           "unchecked.assign.to.var",
  2437                                           v, s);
  2440                 // The computed type of a variable is the type of the
  2441                 // variable symbol, taken as a member of the site type.
  2442                 owntype = (sym.owner.kind == TYP &&
  2443                            sym.name != names._this && sym.name != names._super)
  2444                     ? types.memberType(site, sym)
  2445                     : sym.type;
  2447                 if (env.info.tvars.nonEmpty()) {
  2448                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2449                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2450                         if (!owntype.contains(l.head)) {
  2451                             log.error(tree.pos(), "undetermined.type", owntype1);
  2452                             owntype1 = types.createErrorType(owntype1);
  2454                     owntype = owntype1;
  2457                 // If the variable is a constant, record constant value in
  2458                 // computed type.
  2459                 if (v.getConstValue() != null && isStaticReference(tree))
  2460                     owntype = owntype.constType(v.getConstValue());
  2462                 if (pkind == VAL) {
  2463                     owntype = capture(owntype); // capture "names as expressions"
  2465                 break;
  2466             case MTH: {
  2467                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2468                 owntype = checkMethod(site, sym, env, app.args,
  2469                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2470                                       env.info.varArgs);
  2471                 break;
  2473             case PCK: case ERR:
  2474                 owntype = sym.type;
  2475                 break;
  2476             default:
  2477                 throw new AssertionError("unexpected kind: " + sym.kind +
  2478                                          " in tree " + tree);
  2481             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2482             // (for constructors, the error was given when the constructor was
  2483             // resolved)
  2484             if (sym.name != names.init &&
  2485                 (sym.flags() & DEPRECATED) != 0 &&
  2486                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2487                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2488                 chk.warnDeprecated(tree.pos(), sym);
  2490             if ((sym.flags() & PROPRIETARY) != 0) {
  2491                 if (enableSunApiLintControl)
  2492                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
  2493                 else
  2494                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2497             // Test (3): if symbol is a variable, check that its type and
  2498             // kind are compatible with the prototype and protokind.
  2499             return check(tree, owntype, sym.kind, pkind, pt);
  2502         /** Check that variable is initialized and evaluate the variable's
  2503          *  initializer, if not yet done. Also check that variable is not
  2504          *  referenced before it is defined.
  2505          *  @param tree    The tree making up the variable reference.
  2506          *  @param env     The current environment.
  2507          *  @param v       The variable's symbol.
  2508          */
  2509         private void checkInit(JCTree tree,
  2510                                Env<AttrContext> env,
  2511                                VarSymbol v,
  2512                                boolean onlyWarning) {
  2513 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2514 //                             tree.pos + " " + v.pos + " " +
  2515 //                             Resolve.isStatic(env));//DEBUG
  2517             // A forward reference is diagnosed if the declaration position
  2518             // of the variable is greater than the current tree position
  2519             // and the tree and variable definition occur in the same class
  2520             // definition.  Note that writes don't count as references.
  2521             // This check applies only to class and instance
  2522             // variables.  Local variables follow different scope rules,
  2523             // and are subject to definite assignment checking.
  2524             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2525                 v.owner.kind == TYP &&
  2526                 canOwnInitializer(env.info.scope.owner) &&
  2527                 v.owner == env.info.scope.owner.enclClass() &&
  2528                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2529                 (env.tree.getTag() != JCTree.ASSIGN ||
  2530                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2531                 String suffix = (env.info.enclVar == v) ?
  2532                                 "self.ref" : "forward.ref";
  2533                 if (!onlyWarning || isStaticEnumField(v)) {
  2534                     log.error(tree.pos(), "illegal." + suffix);
  2535                 } else if (useBeforeDeclarationWarning) {
  2536                     log.warning(tree.pos(), suffix, v);
  2540             v.getConstValue(); // ensure initializer is evaluated
  2542             checkEnumInitializer(tree, env, v);
  2545         /**
  2546          * Check for illegal references to static members of enum.  In
  2547          * an enum type, constructors and initializers may not
  2548          * reference its static members unless they are constant.
  2550          * @param tree    The tree making up the variable reference.
  2551          * @param env     The current environment.
  2552          * @param v       The variable's symbol.
  2553          * @see JLS 3rd Ed. (8.9 Enums)
  2554          */
  2555         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2556             // JLS 3rd Ed.:
  2557             //
  2558             // "It is a compile-time error to reference a static field
  2559             // of an enum type that is not a compile-time constant
  2560             // (15.28) from constructors, instance initializer blocks,
  2561             // or instance variable initializer expressions of that
  2562             // type. It is a compile-time error for the constructors,
  2563             // instance initializer blocks, or instance variable
  2564             // initializer expressions of an enum constant e to refer
  2565             // to itself or to an enum constant of the same type that
  2566             // is declared to the right of e."
  2567             if (isStaticEnumField(v)) {
  2568                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2570                 if (enclClass == null || enclClass.owner == null)
  2571                     return;
  2573                 // See if the enclosing class is the enum (or a
  2574                 // subclass thereof) declaring v.  If not, this
  2575                 // reference is OK.
  2576                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2577                     return;
  2579                 // If the reference isn't from an initializer, then
  2580                 // the reference is OK.
  2581                 if (!Resolve.isInitializer(env))
  2582                     return;
  2584                 log.error(tree.pos(), "illegal.enum.static.ref");
  2588         /** Is the given symbol a static, non-constant field of an Enum?
  2589          *  Note: enum literals should not be regarded as such
  2590          */
  2591         private boolean isStaticEnumField(VarSymbol v) {
  2592             return Flags.isEnum(v.owner) &&
  2593                    Flags.isStatic(v) &&
  2594                    !Flags.isConstant(v) &&
  2595                    v.name != names._class;
  2598         /** Can the given symbol be the owner of code which forms part
  2599          *  if class initialization? This is the case if the symbol is
  2600          *  a type or field, or if the symbol is the synthetic method.
  2601          *  owning a block.
  2602          */
  2603         private boolean canOwnInitializer(Symbol sym) {
  2604             return
  2605                 (sym.kind & (VAR | TYP)) != 0 ||
  2606                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2609     Warner noteWarner = new Warner();
  2611     /**
  2612      * Check that method arguments conform to its instantation.
  2613      **/
  2614     public Type checkMethod(Type site,
  2615                             Symbol sym,
  2616                             Env<AttrContext> env,
  2617                             final List<JCExpression> argtrees,
  2618                             List<Type> argtypes,
  2619                             List<Type> typeargtypes,
  2620                             boolean useVarargs) {
  2621         // Test (5): if symbol is an instance method of a raw type, issue
  2622         // an unchecked warning if its argument types change under erasure.
  2623         if (allowGenerics &&
  2624             (sym.flags() & STATIC) == 0 &&
  2625             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2626             Type s = types.asOuterSuper(site, sym.owner);
  2627             if (s != null && s.isRaw() &&
  2628                 !types.isSameTypes(sym.type.getParameterTypes(),
  2629                                    sym.erasure(types).getParameterTypes())) {
  2630                 chk.warnUnchecked(env.tree.pos(),
  2631                                   "unchecked.call.mbr.of.raw.type",
  2632                                   sym, s);
  2636         // Compute the identifier's instantiated type.
  2637         // For methods, we need to compute the instance type by
  2638         // Resolve.instantiate from the symbol's type as well as
  2639         // any type arguments and value arguments.
  2640         noteWarner.warned = false;
  2641         Type owntype = rs.instantiate(env,
  2642                                       site,
  2643                                       sym,
  2644                                       argtypes,
  2645                                       typeargtypes,
  2646                                       true,
  2647                                       useVarargs,
  2648                                       noteWarner);
  2649         boolean warned = noteWarner.warned;
  2651         // If this fails, something went wrong; we should not have
  2652         // found the identifier in the first place.
  2653         if (owntype == null) {
  2654             if (!pt.isErroneous())
  2655                 log.error(env.tree.pos(),
  2656                           "internal.error.cant.instantiate",
  2657                           sym, site,
  2658                           Type.toString(pt.getParameterTypes()));
  2659             owntype = types.createErrorType(site);
  2660         } else {
  2661             // System.out.println("call   : " + env.tree);
  2662             // System.out.println("method : " + owntype);
  2663             // System.out.println("actuals: " + argtypes);
  2664             List<Type> formals = owntype.getParameterTypes();
  2665             Type last = useVarargs ? formals.last() : null;
  2666             if (sym.name==names.init &&
  2667                 sym.owner == syms.enumSym)
  2668                 formals = formals.tail.tail;
  2669             List<JCExpression> args = argtrees;
  2670             while (formals.head != last) {
  2671                 JCTree arg = args.head;
  2672                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2673                 assertConvertible(arg, arg.type, formals.head, warn);
  2674                 warned |= warn.warned;
  2675                 args = args.tail;
  2676                 formals = formals.tail;
  2678             if (useVarargs) {
  2679                 Type varArg = types.elemtype(last);
  2680                 while (args.tail != null) {
  2681                     JCTree arg = args.head;
  2682                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2683                     assertConvertible(arg, arg.type, varArg, warn);
  2684                     warned |= warn.warned;
  2685                     args = args.tail;
  2687             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2688                 // non-varargs call to varargs method
  2689                 Type varParam = owntype.getParameterTypes().last();
  2690                 Type lastArg = argtypes.last();
  2691                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2692                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2693                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2694                                 types.elemtype(varParam),
  2695                                 varParam);
  2698             if (warned && sym.type.tag == FORALL) {
  2699                 chk.warnUnchecked(env.tree.pos(),
  2700                                   "unchecked.meth.invocation.applied",
  2701                                   kindName(sym),
  2702                                   sym.name,
  2703                                   rs.methodArguments(sym.type.getParameterTypes()),
  2704                                   rs.methodArguments(argtypes),
  2705                                   kindName(sym.location()),
  2706                                   sym.location());
  2707                 owntype = new MethodType(owntype.getParameterTypes(),
  2708                                          types.erasure(owntype.getReturnType()),
  2709                                          owntype.getThrownTypes(),
  2710                                          syms.methodClass);
  2712             if (useVarargs) {
  2713                 JCTree tree = env.tree;
  2714                 Type argtype = owntype.getParameterTypes().last();
  2715                 if (owntype.getReturnType().tag != FORALL || warned) {
  2716                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym, env);
  2718                 Type elemtype = types.elemtype(argtype);
  2719                 switch (tree.getTag()) {
  2720                 case JCTree.APPLY:
  2721                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2722                     break;
  2723                 case JCTree.NEWCLASS:
  2724                     ((JCNewClass) tree).varargsElement = elemtype;
  2725                     break;
  2726                 default:
  2727                     throw new AssertionError(""+tree);
  2731         return owntype;
  2734     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2735         if (types.isConvertible(actual, formal, warn))
  2736             return;
  2738         if (formal.isCompound()
  2739             && types.isSubtype(actual, types.supertype(formal))
  2740             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2741             return;
  2743         if (false) {
  2744             // TODO: make assertConvertible work
  2745             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2746             throw new AssertionError("Tree: " + tree
  2747                                      + " actual:" + actual
  2748                                      + " formal: " + formal);
  2752     public void visitLiteral(JCLiteral tree) {
  2753         result = check(
  2754             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2756     //where
  2757     /** Return the type of a literal with given type tag.
  2758      */
  2759     Type litType(int tag) {
  2760         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2763     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2764         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2767     public void visitTypeArray(JCArrayTypeTree tree) {
  2768         Type etype = attribType(tree.elemtype, env);
  2769         Type type = new ArrayType(etype, syms.arrayClass);
  2770         result = check(tree, type, TYP, pkind, pt);
  2773     /** Visitor method for parameterized types.
  2774      *  Bound checking is left until later, since types are attributed
  2775      *  before supertype structure is completely known
  2776      */
  2777     public void visitTypeApply(JCTypeApply tree) {
  2778         Type owntype = types.createErrorType(tree.type);
  2780         // Attribute functor part of application and make sure it's a class.
  2781         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2783         // Attribute type parameters
  2784         List<Type> actuals = attribTypes(tree.arguments, env);
  2786         if (clazztype.tag == CLASS) {
  2787             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2789             if (actuals.length() == formals.length() || actuals.length() == 0) {
  2790                 List<Type> a = actuals;
  2791                 List<Type> f = formals;
  2792                 while (a.nonEmpty()) {
  2793                     a.head = a.head.withTypeVar(f.head);
  2794                     a = a.tail;
  2795                     f = f.tail;
  2797                 // Compute the proper generic outer
  2798                 Type clazzOuter = clazztype.getEnclosingType();
  2799                 if (clazzOuter.tag == CLASS) {
  2800                     Type site;
  2801                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2802                     if (clazz.getTag() == JCTree.IDENT) {
  2803                         site = env.enclClass.sym.type;
  2804                     } else if (clazz.getTag() == JCTree.SELECT) {
  2805                         site = ((JCFieldAccess) clazz).selected.type;
  2806                     } else throw new AssertionError(""+tree);
  2807                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2808                         if (site.tag == CLASS)
  2809                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2810                         if (site == null)
  2811                             site = types.erasure(clazzOuter);
  2812                         clazzOuter = site;
  2815                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2816             } else {
  2817                 if (formals.length() != 0) {
  2818                     log.error(tree.pos(), "wrong.number.type.args",
  2819                               Integer.toString(formals.length()));
  2820                 } else {
  2821                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2823                 owntype = types.createErrorType(tree.type);
  2826         result = check(tree, owntype, TYP, pkind, pt);
  2829     public void visitTypeDisjoint(JCTypeDisjoint tree) {
  2830         List<Type> componentTypes = attribTypes(tree.components, env);
  2831         tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
  2834     public void visitTypeParameter(JCTypeParameter tree) {
  2835         TypeVar a = (TypeVar)tree.type;
  2836         Set<Type> boundSet = new HashSet<Type>();
  2837         if (a.bound.isErroneous())
  2838             return;
  2839         List<Type> bs = types.getBounds(a);
  2840         if (tree.bounds.nonEmpty()) {
  2841             // accept class or interface or typevar as first bound.
  2842             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2843             boundSet.add(types.erasure(b));
  2844             if (b.isErroneous()) {
  2845                 a.bound = b;
  2847             else if (b.tag == TYPEVAR) {
  2848                 // if first bound was a typevar, do not accept further bounds.
  2849                 if (tree.bounds.tail.nonEmpty()) {
  2850                     log.error(tree.bounds.tail.head.pos(),
  2851                               "type.var.may.not.be.followed.by.other.bounds");
  2852                     log.unrecoverableError = true;
  2853                     tree.bounds = List.of(tree.bounds.head);
  2854                     a.bound = bs.head;
  2856             } else {
  2857                 // if first bound was a class or interface, accept only interfaces
  2858                 // as further bounds.
  2859                 for (JCExpression bound : tree.bounds.tail) {
  2860                     bs = bs.tail;
  2861                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2862                     if (i.isErroneous())
  2863                         a.bound = i;
  2864                     else if (i.tag == CLASS)
  2865                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2869         bs = types.getBounds(a);
  2871         // in case of multiple bounds ...
  2872         if (bs.length() > 1) {
  2873             // ... the variable's bound is a class type flagged COMPOUND
  2874             // (see comment for TypeVar.bound).
  2875             // In this case, generate a class tree that represents the
  2876             // bound class, ...
  2877             JCTree extending;
  2878             List<JCExpression> implementing;
  2879             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2880                 extending = tree.bounds.head;
  2881                 implementing = tree.bounds.tail;
  2882             } else {
  2883                 extending = null;
  2884                 implementing = tree.bounds;
  2886             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2887                 make.Modifiers(PUBLIC | ABSTRACT),
  2888                 tree.name, List.<JCTypeParameter>nil(),
  2889                 extending, implementing, List.<JCTree>nil());
  2891             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2892             assert (c.flags() & COMPOUND) != 0;
  2893             cd.sym = c;
  2894             c.sourcefile = env.toplevel.sourcefile;
  2896             // ... and attribute the bound class
  2897             c.flags_field |= UNATTRIBUTED;
  2898             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2899             enter.typeEnvs.put(c, cenv);
  2904     public void visitWildcard(JCWildcard tree) {
  2905         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2906         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2907             ? syms.objectType
  2908             : attribType(tree.inner, env);
  2909         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2910                                               tree.kind.kind,
  2911                                               syms.boundClass),
  2912                        TYP, pkind, pt);
  2915     public void visitAnnotation(JCAnnotation tree) {
  2916         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2917         result = tree.type = syms.errType;
  2920     public void visitAnnotatedType(JCAnnotatedType tree) {
  2921         result = tree.type = attribType(tree.getUnderlyingType(), env);
  2924     public void visitErroneous(JCErroneous tree) {
  2925         if (tree.errs != null)
  2926             for (JCTree err : tree.errs)
  2927                 attribTree(err, env, ERR, pt);
  2928         result = tree.type = syms.errType;
  2931     /** Default visitor method for all other trees.
  2932      */
  2933     public void visitTree(JCTree tree) {
  2934         throw new AssertionError();
  2937     /** Main method: attribute class definition associated with given class symbol.
  2938      *  reporting completion failures at the given position.
  2939      *  @param pos The source position at which completion errors are to be
  2940      *             reported.
  2941      *  @param c   The class symbol whose definition will be attributed.
  2942      */
  2943     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  2944         try {
  2945             annotate.flush();
  2946             attribClass(c);
  2947         } catch (CompletionFailure ex) {
  2948             chk.completionError(pos, ex);
  2952     /** Attribute class definition associated with given class symbol.
  2953      *  @param c   The class symbol whose definition will be attributed.
  2954      */
  2955     void attribClass(ClassSymbol c) throws CompletionFailure {
  2956         if (c.type.tag == ERROR) return;
  2958         // Check for cycles in the inheritance graph, which can arise from
  2959         // ill-formed class files.
  2960         chk.checkNonCyclic(null, c.type);
  2962         Type st = types.supertype(c.type);
  2963         if ((c.flags_field & Flags.COMPOUND) == 0) {
  2964             // First, attribute superclass.
  2965             if (st.tag == CLASS)
  2966                 attribClass((ClassSymbol)st.tsym);
  2968             // Next attribute owner, if it is a class.
  2969             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  2970                 attribClass((ClassSymbol)c.owner);
  2973         // The previous operations might have attributed the current class
  2974         // if there was a cycle. So we test first whether the class is still
  2975         // UNATTRIBUTED.
  2976         if ((c.flags_field & UNATTRIBUTED) != 0) {
  2977             c.flags_field &= ~UNATTRIBUTED;
  2979             // Get environment current at the point of class definition.
  2980             Env<AttrContext> env = enter.typeEnvs.get(c);
  2982             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  2983             // because the annotations were not available at the time the env was created. Therefore,
  2984             // we look up the environment chain for the first enclosing environment for which the
  2985             // lint value is set. Typically, this is the parent env, but might be further if there
  2986             // are any envs created as a result of TypeParameter nodes.
  2987             Env<AttrContext> lintEnv = env;
  2988             while (lintEnv.info.lint == null)
  2989                 lintEnv = lintEnv.next;
  2991             // Having found the enclosing lint value, we can initialize the lint value for this class
  2992             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  2994             Lint prevLint = chk.setLint(env.info.lint);
  2995             JavaFileObject prev = log.useSource(c.sourcefile);
  2997             try {
  2998                 // java.lang.Enum may not be subclassed by a non-enum
  2999                 if (st.tsym == syms.enumSym &&
  3000                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3001                     log.error(env.tree.pos(), "enum.no.subclassing");
  3003                 // Enums may not be extended by source-level classes
  3004                 if (st.tsym != null &&
  3005                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3006                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3007                     !target.compilerBootstrap(c)) {
  3008                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3010                 attribClassBody(env, c);
  3012                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3013             } finally {
  3014                 log.useSource(prev);
  3015                 chk.setLint(prevLint);
  3021     public void visitImport(JCImport tree) {
  3022         // nothing to do
  3025     /** Finish the attribution of a class. */
  3026     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3027         JCClassDecl tree = (JCClassDecl)env.tree;
  3028         assert c == tree.sym;
  3030         // Validate annotations
  3031         chk.validateAnnotations(tree.mods.annotations, c);
  3033         // Validate type parameters, supertype and interfaces.
  3034         attribBounds(tree.typarams);
  3035         if (!c.isAnonymous()) {
  3036             //already checked if anonymous
  3037             chk.validate(tree.typarams, env);
  3038             chk.validate(tree.extending, env);
  3039             chk.validate(tree.implementing, env);
  3042         // If this is a non-abstract class, check that it has no abstract
  3043         // methods or unimplemented methods of an implemented interface.
  3044         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3045             if (!relax)
  3046                 chk.checkAllDefined(tree.pos(), c);
  3049         if ((c.flags() & ANNOTATION) != 0) {
  3050             if (tree.implementing.nonEmpty())
  3051                 log.error(tree.implementing.head.pos(),
  3052                           "cant.extend.intf.annotation");
  3053             if (tree.typarams.nonEmpty())
  3054                 log.error(tree.typarams.head.pos(),
  3055                           "intf.annotation.cant.have.type.params");
  3056         } else {
  3057             // Check that all extended classes and interfaces
  3058             // are compatible (i.e. no two define methods with same arguments
  3059             // yet different return types).  (JLS 8.4.6.3)
  3060             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3063         // Check that class does not import the same parameterized interface
  3064         // with two different argument lists.
  3065         chk.checkClassBounds(tree.pos(), c.type);
  3067         tree.type = c.type;
  3069         boolean assertsEnabled = false;
  3070         assert assertsEnabled = true;
  3071         if (assertsEnabled) {
  3072             for (List<JCTypeParameter> l = tree.typarams;
  3073                  l.nonEmpty(); l = l.tail)
  3074                 assert env.info.scope.lookup(l.head.name).scope != null;
  3077         // Check that a generic class doesn't extend Throwable
  3078         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3079             log.error(tree.extending.pos(), "generic.throwable");
  3081         // Check that all methods which implement some
  3082         // method conform to the method they implement.
  3083         chk.checkImplementations(tree);
  3085         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3086             // Attribute declaration
  3087             attribStat(l.head, env);
  3088             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3089             // Make an exception for static constants.
  3090             if (c.owner.kind != PCK &&
  3091                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3092                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3093                 Symbol sym = null;
  3094                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3095                 if (sym == null ||
  3096                     sym.kind != VAR ||
  3097                     ((VarSymbol) sym).getConstValue() == null)
  3098                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  3102         // Check for cycles among non-initial constructors.
  3103         chk.checkCyclicConstructors(tree);
  3105         // Check for cycles among annotation elements.
  3106         chk.checkNonCyclicElements(tree);
  3108         // Check for proper use of serialVersionUID
  3109         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  3110             isSerializable(c) &&
  3111             (c.flags() & Flags.ENUM) == 0 &&
  3112             (c.flags() & ABSTRACT) == 0) {
  3113             checkSerialVersionUID(tree, c);
  3116         // Check type annotations applicability rules
  3117         validateTypeAnnotations(tree);
  3119         // where
  3120         /** check if a class is a subtype of Serializable, if that is available. */
  3121         private boolean isSerializable(ClassSymbol c) {
  3122             try {
  3123                 syms.serializableType.complete();
  3125             catch (CompletionFailure e) {
  3126                 return false;
  3128             return types.isSubtype(c.type, syms.serializableType);
  3131         /** Check that an appropriate serialVersionUID member is defined. */
  3132         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3134             // check for presence of serialVersionUID
  3135             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3136             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3137             if (e.scope == null) {
  3138                 log.warning(Lint.LintCategory.SERIAL,
  3139                         tree.pos(), "missing.SVUID", c);
  3140                 return;
  3143             // check that it is static final
  3144             VarSymbol svuid = (VarSymbol)e.sym;
  3145             if ((svuid.flags() & (STATIC | FINAL)) !=
  3146                 (STATIC | FINAL))
  3147                 log.warning(Lint.LintCategory.SERIAL,
  3148                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3150             // check that it is long
  3151             else if (svuid.type.tag != TypeTags.LONG)
  3152                 log.warning(Lint.LintCategory.SERIAL,
  3153                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3155             // check constant
  3156             else if (svuid.getConstValue() == null)
  3157                 log.warning(Lint.LintCategory.SERIAL,
  3158                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3161     private Type capture(Type type) {
  3162         return types.capture(type);
  3165     private void validateTypeAnnotations(JCTree tree) {
  3166         tree.accept(typeAnnotationsValidator);
  3168     //where
  3169     private final JCTree.Visitor typeAnnotationsValidator =
  3170         new TreeScanner() {
  3171         public void visitAnnotation(JCAnnotation tree) {
  3172             if (tree instanceof JCTypeAnnotation) {
  3173                 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
  3175             super.visitAnnotation(tree);
  3177         public void visitTypeParameter(JCTypeParameter tree) {
  3178             chk.validateTypeAnnotations(tree.annotations, true);
  3179             // don't call super. skip type annotations
  3180             scan(tree.bounds);
  3182         public void visitMethodDef(JCMethodDecl tree) {
  3183             // need to check static methods
  3184             if ((tree.sym.flags() & Flags.STATIC) != 0) {
  3185                 for (JCTypeAnnotation a : tree.receiverAnnotations) {
  3186                     if (chk.isTypeAnnotation(a, false))
  3187                         log.error(a.pos(), "annotation.type.not.applicable");
  3190             super.visitMethodDef(tree);
  3192     };

mercurial