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

Mon, 06 Dec 2010 11:50:37 +0000

author
mcimadamore
date
Mon, 06 Dec 2010 11:50:37 +0000
changeset 774
56f59723fddf
parent 770
aa6605d883dc
child 780
1d625fbe6c22
permissions
-rw-r--r--

7002070: If catch clause has an incompatible type, error pointer points to first exception type in list
Summary: Attribution should check each component of a disjunctive type separately, rather than checking the corresponding lub()
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.isSet("-retrofit") ||
   123                  options.isSet("-relax"));
   124         findDiamonds = options.get("findDiamond") != null &&
   125                  source.allowDiamond();
   126         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   127         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   128     }
   130     /** Switch: relax some constraints for retrofit mode.
   131      */
   132     boolean relax;
   134     /** Switch: support generics?
   135      */
   136     boolean allowGenerics;
   138     /** Switch: allow variable-arity methods.
   139      */
   140     boolean allowVarargs;
   142     /** Switch: support enums?
   143      */
   144     boolean allowEnums;
   146     /** Switch: support boxing and unboxing?
   147      */
   148     boolean allowBoxing;
   150     /** Switch: support covariant result types?
   151      */
   152     boolean allowCovariantReturns;
   154     /** Switch: allow references to surrounding object from anonymous
   155      * objects during constructor call?
   156      */
   157     boolean allowAnonOuterThis;
   159     /** Switch: generates a warning if diamond can be safely applied
   160      *  to a given new expression
   161      */
   162     boolean findDiamonds;
   164     /**
   165      * Internally enables/disables diamond finder feature
   166      */
   167     static final boolean allowDiamondFinder = true;
   169     /**
   170      * Switch: warn about use of variable before declaration?
   171      * RFE: 6425594
   172      */
   173     boolean useBeforeDeclarationWarning;
   175     /**
   176      * Switch: allow lint infrastructure to control proprietary
   177      * API warnings.
   178      */
   179     boolean enableSunApiLintControl;
   181     /**
   182      * Switch: allow strings in switch?
   183      */
   184     boolean allowStringsInSwitch;
   186     /**
   187      * Switch: name of source level; used for error reporting.
   188      */
   189     String sourceName;
   191     /** Check kind and type of given tree against protokind and prototype.
   192      *  If check succeeds, store type in tree and return it.
   193      *  If check fails, store errType in tree and return it.
   194      *  No checks are performed if the prototype is a method type.
   195      *  It is not necessary in this case since we know that kind and type
   196      *  are correct.
   197      *
   198      *  @param tree     The tree whose kind and type is checked
   199      *  @param owntype  The computed type of the tree
   200      *  @param ownkind  The computed kind of the tree
   201      *  @param pkind    The expected kind (or: protokind) of the tree
   202      *  @param pt       The expected type (or: prototype) of the tree
   203      */
   204     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   205         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   206             if ((ownkind & ~pkind) == 0) {
   207                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
   208             } else {
   209                 log.error(tree.pos(), "unexpected.type",
   210                           kindNames(pkind),
   211                           kindName(ownkind));
   212                 owntype = types.createErrorType(owntype);
   213             }
   214         }
   215         tree.type = owntype;
   216         return owntype;
   217     }
   219     /** Is given blank final variable assignable, i.e. in a scope where it
   220      *  may be assigned to even though it is final?
   221      *  @param v      The blank final variable.
   222      *  @param env    The current environment.
   223      */
   224     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   225         Symbol owner = env.info.scope.owner;
   226            // owner refers to the innermost variable, method or
   227            // initializer block declaration at this point.
   228         return
   229             v.owner == owner
   230             ||
   231             ((owner.name == names.init ||    // i.e. we are in a constructor
   232               owner.kind == VAR ||           // i.e. we are in a variable initializer
   233               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   234              &&
   235              v.owner == owner.owner
   236              &&
   237              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   238     }
   240     /** Check that variable can be assigned to.
   241      *  @param pos    The current source code position.
   242      *  @param v      The assigned varaible
   243      *  @param base   If the variable is referred to in a Select, the part
   244      *                to the left of the `.', null otherwise.
   245      *  @param env    The current environment.
   246      */
   247     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   248         if ((v.flags() & FINAL) != 0 &&
   249             ((v.flags() & HASINIT) != 0
   250              ||
   251              !((base == null ||
   252                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   253                isAssignableAsBlankFinal(v, env)))) {
   254             if (v.isResourceVariable()) { //TWR resource
   255                 log.error(pos, "try.resource.may.not.be.assigned", v);
   256             } else {
   257                 log.error(pos, "cant.assign.val.to.final.var", v);
   258             }
   259         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
   260             v.flags_field &= ~EFFECTIVELY_FINAL;
   261         }
   262     }
   264     /** Does tree represent a static reference to an identifier?
   265      *  It is assumed that tree is either a SELECT or an IDENT.
   266      *  We have to weed out selects from non-type names here.
   267      *  @param tree    The candidate tree.
   268      */
   269     boolean isStaticReference(JCTree tree) {
   270         if (tree.getTag() == JCTree.SELECT) {
   271             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   272             if (lsym == null || lsym.kind != TYP) {
   273                 return false;
   274             }
   275         }
   276         return true;
   277     }
   279     /** Is this symbol a type?
   280      */
   281     static boolean isType(Symbol sym) {
   282         return sym != null && sym.kind == TYP;
   283     }
   285     /** The current `this' symbol.
   286      *  @param env    The current environment.
   287      */
   288     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   289         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   290     }
   292     /** Attribute a parsed identifier.
   293      * @param tree Parsed identifier name
   294      * @param topLevel The toplevel to use
   295      */
   296     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   297         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   298         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   299                                            syms.errSymbol.name,
   300                                            null, null, null, null);
   301         localEnv.enclClass.sym = syms.errSymbol;
   302         return tree.accept(identAttributer, localEnv);
   303     }
   304     // where
   305         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   306         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   307             @Override
   308             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   309                 Symbol site = visit(node.getExpression(), env);
   310                 if (site.kind == ERR)
   311                     return site;
   312                 Name name = (Name)node.getIdentifier();
   313                 if (site.kind == PCK) {
   314                     env.toplevel.packge = (PackageSymbol)site;
   315                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   316                 } else {
   317                     env.enclClass.sym = (ClassSymbol)site;
   318                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   319                 }
   320             }
   322             @Override
   323             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   324                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   325             }
   326         }
   328     public Type coerce(Type etype, Type ttype) {
   329         return cfolder.coerce(etype, ttype);
   330     }
   332     public Type attribType(JCTree node, TypeSymbol sym) {
   333         Env<AttrContext> env = enter.typeEnvs.get(sym);
   334         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   335         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   336     }
   338     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   339         breakTree = tree;
   340         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   341         try {
   342             attribExpr(expr, env);
   343         } catch (BreakAttr b) {
   344             return b.env;
   345         } catch (AssertionError ae) {
   346             if (ae.getCause() instanceof BreakAttr) {
   347                 return ((BreakAttr)(ae.getCause())).env;
   348             } else {
   349                 throw ae;
   350             }
   351         } finally {
   352             breakTree = null;
   353             log.useSource(prev);
   354         }
   355         return env;
   356     }
   358     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   359         breakTree = tree;
   360         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   361         try {
   362             attribStat(stmt, env);
   363         } catch (BreakAttr b) {
   364             return b.env;
   365         } catch (AssertionError ae) {
   366             if (ae.getCause() instanceof BreakAttr) {
   367                 return ((BreakAttr)(ae.getCause())).env;
   368             } else {
   369                 throw ae;
   370             }
   371         } finally {
   372             breakTree = null;
   373             log.useSource(prev);
   374         }
   375         return env;
   376     }
   378     private JCTree breakTree = null;
   380     private static class BreakAttr extends RuntimeException {
   381         static final long serialVersionUID = -6924771130405446405L;
   382         private Env<AttrContext> env;
   383         private BreakAttr(Env<AttrContext> env) {
   384             this.env = env;
   385         }
   386     }
   389 /* ************************************************************************
   390  * Visitor methods
   391  *************************************************************************/
   393     /** Visitor argument: the current environment.
   394      */
   395     Env<AttrContext> env;
   397     /** Visitor argument: the currently expected proto-kind.
   398      */
   399     int pkind;
   401     /** Visitor argument: the currently expected proto-type.
   402      */
   403     Type pt;
   405     /** Visitor argument: the error key to be generated when a type error occurs
   406      */
   407     String errKey;
   409     /** Visitor result: the computed type.
   410      */
   411     Type result;
   413     /** Visitor method: attribute a tree, catching any completion failure
   414      *  exceptions. Return the tree's type.
   415      *
   416      *  @param tree    The tree to be visited.
   417      *  @param env     The environment visitor argument.
   418      *  @param pkind   The protokind visitor argument.
   419      *  @param pt      The prototype visitor argument.
   420      */
   421     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   422         return attribTree(tree, env, pkind, pt, "incompatible.types");
   423     }
   425     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
   426         Env<AttrContext> prevEnv = this.env;
   427         int prevPkind = this.pkind;
   428         Type prevPt = this.pt;
   429         String prevErrKey = this.errKey;
   430         try {
   431             this.env = env;
   432             this.pkind = pkind;
   433             this.pt = pt;
   434             this.errKey = errKey;
   435             tree.accept(this);
   436             if (tree == breakTree)
   437                 throw new BreakAttr(env);
   438             return result;
   439         } catch (CompletionFailure ex) {
   440             tree.type = syms.errType;
   441             return chk.completionError(tree.pos(), ex);
   442         } finally {
   443             this.env = prevEnv;
   444             this.pkind = prevPkind;
   445             this.pt = prevPt;
   446             this.errKey = prevErrKey;
   447         }
   448     }
   450     /** Derived visitor method: attribute an expression tree.
   451      */
   452     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   453         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   454     }
   456     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
   457         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
   458     }
   460     /** Derived visitor method: attribute an expression tree with
   461      *  no constraints on the computed type.
   462      */
   463     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   464         return attribTree(tree, env, VAL, Type.noType);
   465     }
   467     /** Derived visitor method: attribute a type tree.
   468      */
   469     Type attribType(JCTree tree, Env<AttrContext> env) {
   470         Type result = attribType(tree, env, Type.noType);
   471         return result;
   472     }
   474     /** Derived visitor method: attribute a type tree.
   475      */
   476     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   477         Type result = attribTree(tree, env, TYP, pt);
   478         return result;
   479     }
   481     /** Derived visitor method: attribute a statement or definition tree.
   482      */
   483     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   484         return attribTree(tree, env, NIL, Type.noType);
   485     }
   487     /** Attribute a list of expressions, returning a list of types.
   488      */
   489     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   490         ListBuffer<Type> ts = new ListBuffer<Type>();
   491         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   492             ts.append(attribExpr(l.head, env, pt));
   493         return ts.toList();
   494     }
   496     /** Attribute a list of statements, returning nothing.
   497      */
   498     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   499         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   500             attribStat(l.head, env);
   501     }
   503     /** Attribute the arguments in a method call, returning a list of types.
   504      */
   505     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   506         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   507         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   508             argtypes.append(chk.checkNonVoid(
   509                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   510         return argtypes.toList();
   511     }
   513     /** Attribute a type argument list, returning a list of types.
   514      *  Caller is responsible for calling checkRefTypes.
   515      */
   516     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   517         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   518         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   519             argtypes.append(attribType(l.head, env));
   520         return argtypes.toList();
   521     }
   523     /** Attribute a type argument list, returning a list of types.
   524      *  Check that all the types are references.
   525      */
   526     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   527         List<Type> types = attribAnyTypes(trees, env);
   528         return chk.checkRefTypes(trees, types);
   529     }
   531     /**
   532      * Attribute type variables (of generic classes or methods).
   533      * Compound types are attributed later in attribBounds.
   534      * @param typarams the type variables to enter
   535      * @param env      the current environment
   536      */
   537     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   538         for (JCTypeParameter tvar : typarams) {
   539             TypeVar a = (TypeVar)tvar.type;
   540             a.tsym.flags_field |= UNATTRIBUTED;
   541             a.bound = Type.noType;
   542             if (!tvar.bounds.isEmpty()) {
   543                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   544                 for (JCExpression bound : tvar.bounds.tail)
   545                     bounds = bounds.prepend(attribType(bound, env));
   546                 types.setBounds(a, bounds.reverse());
   547             } else {
   548                 // if no bounds are given, assume a single bound of
   549                 // java.lang.Object.
   550                 types.setBounds(a, List.of(syms.objectType));
   551             }
   552             a.tsym.flags_field &= ~UNATTRIBUTED;
   553         }
   554         for (JCTypeParameter tvar : typarams)
   555             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   556         attribStats(typarams, env);
   557     }
   559     void attribBounds(List<JCTypeParameter> typarams) {
   560         for (JCTypeParameter typaram : typarams) {
   561             Type bound = typaram.type.getUpperBound();
   562             if (bound != null && bound.tsym instanceof ClassSymbol) {
   563                 ClassSymbol c = (ClassSymbol)bound.tsym;
   564                 if ((c.flags_field & COMPOUND) != 0) {
   565                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
   566                     attribClass(typaram.pos(), c);
   567                 }
   568             }
   569         }
   570     }
   572     /**
   573      * Attribute the type references in a list of annotations.
   574      */
   575     void attribAnnotationTypes(List<JCAnnotation> annotations,
   576                                Env<AttrContext> env) {
   577         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   578             JCAnnotation a = al.head;
   579             attribType(a.annotationType, env);
   580         }
   581     }
   583     /** Attribute type reference in an `extends' or `implements' clause.
   584      *  Supertypes of anonymous inner classes are usually already attributed.
   585      *
   586      *  @param tree              The tree making up the type reference.
   587      *  @param env               The environment current at the reference.
   588      *  @param classExpected     true if only a class is expected here.
   589      *  @param interfaceExpected true if only an interface is expected here.
   590      */
   591     Type attribBase(JCTree tree,
   592                     Env<AttrContext> env,
   593                     boolean classExpected,
   594                     boolean interfaceExpected,
   595                     boolean checkExtensible) {
   596         Type t = tree.type != null ?
   597             tree.type :
   598             attribType(tree, env);
   599         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   600     }
   601     Type checkBase(Type t,
   602                    JCTree tree,
   603                    Env<AttrContext> env,
   604                    boolean classExpected,
   605                    boolean interfaceExpected,
   606                    boolean checkExtensible) {
   607         if (t.isErroneous())
   608             return t;
   609         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   610             // check that type variable is already visible
   611             if (t.getUpperBound() == null) {
   612                 log.error(tree.pos(), "illegal.forward.ref");
   613                 return types.createErrorType(t);
   614             }
   615         } else {
   616             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   617         }
   618         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   619             log.error(tree.pos(), "intf.expected.here");
   620             // return errType is necessary since otherwise there might
   621             // be undetected cycles which cause attribution to loop
   622             return types.createErrorType(t);
   623         } else if (checkExtensible &&
   624                    classExpected &&
   625                    (t.tsym.flags() & INTERFACE) != 0) {
   626                 log.error(tree.pos(), "no.intf.expected.here");
   627             return types.createErrorType(t);
   628         }
   629         if (checkExtensible &&
   630             ((t.tsym.flags() & FINAL) != 0)) {
   631             log.error(tree.pos(),
   632                       "cant.inherit.from.final", t.tsym);
   633         }
   634         chk.checkNonCyclic(tree.pos(), t);
   635         return t;
   636     }
   638     public void visitClassDef(JCClassDecl tree) {
   639         // Local classes have not been entered yet, so we need to do it now:
   640         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   641             enter.classEnter(tree, env);
   643         ClassSymbol c = tree.sym;
   644         if (c == null) {
   645             // exit in case something drastic went wrong during enter.
   646             result = null;
   647         } else {
   648             // make sure class has been completed:
   649             c.complete();
   651             // If this class appears as an anonymous class
   652             // in a superclass constructor call where
   653             // no explicit outer instance is given,
   654             // disable implicit outer instance from being passed.
   655             // (This would be an illegal access to "this before super").
   656             if (env.info.isSelfCall &&
   657                 env.tree.getTag() == JCTree.NEWCLASS &&
   658                 ((JCNewClass) env.tree).encl == null)
   659             {
   660                 c.flags_field |= NOOUTERTHIS;
   661             }
   662             attribClass(tree.pos(), c);
   663             result = tree.type = c.type;
   664         }
   665     }
   667     public void visitMethodDef(JCMethodDecl tree) {
   668         MethodSymbol m = tree.sym;
   670         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   671         Lint prevLint = chk.setLint(lint);
   672         try {
   673             chk.checkDeprecatedAnnotation(tree.pos(), m);
   675             attribBounds(tree.typarams);
   677             // If we override any other methods, check that we do so properly.
   678             // JLS ???
   679             chk.checkOverride(tree, m);
   681             // Create a new environment with local scope
   682             // for attributing the method.
   683             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   685             localEnv.info.lint = lint;
   687             // Enter all type parameters into the local method scope.
   688             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   689                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   691             ClassSymbol owner = env.enclClass.sym;
   692             if ((owner.flags() & ANNOTATION) != 0 &&
   693                 tree.params.nonEmpty())
   694                 log.error(tree.params.head.pos(),
   695                           "intf.annotation.members.cant.have.params");
   697             // Attribute all value parameters.
   698             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   699                 attribStat(l.head, localEnv);
   700             }
   702             chk.checkVarargMethodDecl(tree);
   704             // Check that type parameters are well-formed.
   705             chk.validate(tree.typarams, localEnv);
   707             // Check that result type is well-formed.
   708             chk.validate(tree.restype, localEnv);
   710             // annotation method checks
   711             if ((owner.flags() & ANNOTATION) != 0) {
   712                 // annotation method cannot have throws clause
   713                 if (tree.thrown.nonEmpty()) {
   714                     log.error(tree.thrown.head.pos(),
   715                             "throws.not.allowed.in.intf.annotation");
   716                 }
   717                 // annotation method cannot declare type-parameters
   718                 if (tree.typarams.nonEmpty()) {
   719                     log.error(tree.typarams.head.pos(),
   720                             "intf.annotation.members.cant.have.type.params");
   721                 }
   722                 // validate annotation method's return type (could be an annotation type)
   723                 chk.validateAnnotationType(tree.restype);
   724                 // ensure that annotation method does not clash with members of Object/Annotation
   725                 chk.validateAnnotationMethod(tree.pos(), m);
   727                 if (tree.defaultValue != null) {
   728                     // if default value is an annotation, check it is a well-formed
   729                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   730                     chk.validateAnnotationTree(tree.defaultValue);
   731                 }
   732             }
   734             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   735                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   737             if (tree.body == null) {
   738                 // Empty bodies are only allowed for
   739                 // abstract, native, or interface methods, or for methods
   740                 // in a retrofit signature class.
   741                 if ((owner.flags() & INTERFACE) == 0 &&
   742                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   743                     !relax)
   744                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   745                 if (tree.defaultValue != null) {
   746                     if ((owner.flags() & ANNOTATION) == 0)
   747                         log.error(tree.pos(),
   748                                   "default.allowed.in.intf.annotation.member");
   749                 }
   750             } else if ((owner.flags() & INTERFACE) != 0) {
   751                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   752             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   753                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   754             } else if ((tree.mods.flags & NATIVE) != 0) {
   755                 log.error(tree.pos(), "native.meth.cant.have.body");
   756             } else {
   757                 // Add an implicit super() call unless an explicit call to
   758                 // super(...) or this(...) is given
   759                 // or we are compiling class java.lang.Object.
   760                 if (tree.name == names.init && owner.type != syms.objectType) {
   761                     JCBlock body = tree.body;
   762                     if (body.stats.isEmpty() ||
   763                         !TreeInfo.isSelfCall(body.stats.head)) {
   764                         body.stats = body.stats.
   765                             prepend(memberEnter.SuperCall(make.at(body.pos),
   766                                                           List.<Type>nil(),
   767                                                           List.<JCVariableDecl>nil(),
   768                                                           false));
   769                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   770                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   771                                TreeInfo.isSuperCall(body.stats.head)) {
   772                         // enum constructors are not allowed to call super
   773                         // directly, so make sure there aren't any super calls
   774                         // in enum constructors, except in the compiler
   775                         // generated one.
   776                         log.error(tree.body.stats.head.pos(),
   777                                   "call.to.super.not.allowed.in.enum.ctor",
   778                                   env.enclClass.sym);
   779                     }
   780                 }
   782                 // Attribute method body.
   783                 attribStat(tree.body, localEnv);
   784             }
   785             localEnv.info.scope.leave();
   786             result = tree.type = m.type;
   787             chk.validateAnnotations(tree.mods.annotations, m);
   788         }
   789         finally {
   790             chk.setLint(prevLint);
   791         }
   792     }
   794     public void visitVarDef(JCVariableDecl tree) {
   795         // Local variables have not been entered yet, so we need to do it now:
   796         if (env.info.scope.owner.kind == MTH) {
   797             if (tree.sym != null) {
   798                 // parameters have already been entered
   799                 env.info.scope.enter(tree.sym);
   800             } else {
   801                 memberEnter.memberEnter(tree, env);
   802                 annotate.flush();
   803             }
   804             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   805         }
   807         VarSymbol v = tree.sym;
   808         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   809         Lint prevLint = chk.setLint(lint);
   811         // Check that the variable's declared type is well-formed.
   812         chk.validate(tree.vartype, env);
   814         try {
   815             chk.checkDeprecatedAnnotation(tree.pos(), v);
   817             if (tree.init != null) {
   818                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   819                     // In this case, `v' is final.  Ensure that it's initializer is
   820                     // evaluated.
   821                     v.getConstValue(); // ensure initializer is evaluated
   822                 } else {
   823                     // Attribute initializer in a new environment
   824                     // with the declared variable as owner.
   825                     // Check that initializer conforms to variable's declared type.
   826                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   827                     initEnv.info.lint = lint;
   828                     // In order to catch self-references, we set the variable's
   829                     // declaration position to maximal possible value, effectively
   830                     // marking the variable as undefined.
   831                     initEnv.info.enclVar = v;
   832                     attribExpr(tree.init, initEnv, v.type);
   833                 }
   834             }
   835             result = tree.type = v.type;
   836             chk.validateAnnotations(tree.mods.annotations, v);
   837         }
   838         finally {
   839             chk.setLint(prevLint);
   840         }
   841     }
   843     public void visitSkip(JCSkip tree) {
   844         result = null;
   845     }
   847     public void visitBlock(JCBlock tree) {
   848         if (env.info.scope.owner.kind == TYP) {
   849             // Block is a static or instance initializer;
   850             // let the owner of the environment be a freshly
   851             // created BLOCK-method.
   852             Env<AttrContext> localEnv =
   853                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   854             localEnv.info.scope.owner =
   855                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   856                                  env.info.scope.owner);
   857             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   858             attribStats(tree.stats, localEnv);
   859         } else {
   860             // Create a new local environment with a local scope.
   861             Env<AttrContext> localEnv =
   862                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   863             attribStats(tree.stats, localEnv);
   864             localEnv.info.scope.leave();
   865         }
   866         result = null;
   867     }
   869     public void visitDoLoop(JCDoWhileLoop tree) {
   870         attribStat(tree.body, env.dup(tree));
   871         attribExpr(tree.cond, env, syms.booleanType);
   872         result = null;
   873     }
   875     public void visitWhileLoop(JCWhileLoop tree) {
   876         attribExpr(tree.cond, env, syms.booleanType);
   877         attribStat(tree.body, env.dup(tree));
   878         result = null;
   879     }
   881     public void visitForLoop(JCForLoop tree) {
   882         Env<AttrContext> loopEnv =
   883             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   884         attribStats(tree.init, loopEnv);
   885         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   886         loopEnv.tree = tree; // before, we were not in loop!
   887         attribStats(tree.step, loopEnv);
   888         attribStat(tree.body, loopEnv);
   889         loopEnv.info.scope.leave();
   890         result = null;
   891     }
   893     public void visitForeachLoop(JCEnhancedForLoop tree) {
   894         Env<AttrContext> loopEnv =
   895             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   896         attribStat(tree.var, loopEnv);
   897         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   898         chk.checkNonVoid(tree.pos(), exprType);
   899         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   900         if (elemtype == null) {
   901             // or perhaps expr implements Iterable<T>?
   902             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   903             if (base == null) {
   904                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
   905                 elemtype = types.createErrorType(exprType);
   906             } else {
   907                 List<Type> iterableParams = base.allparams();
   908                 elemtype = iterableParams.isEmpty()
   909                     ? syms.objectType
   910                     : types.upperBound(iterableParams.head);
   911             }
   912         }
   913         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   914         loopEnv.tree = tree; // before, we were not in loop!
   915         attribStat(tree.body, loopEnv);
   916         loopEnv.info.scope.leave();
   917         result = null;
   918     }
   920     public void visitLabelled(JCLabeledStatement tree) {
   921         // Check that label is not used in an enclosing statement
   922         Env<AttrContext> env1 = env;
   923         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   924             if (env1.tree.getTag() == JCTree.LABELLED &&
   925                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   926                 log.error(tree.pos(), "label.already.in.use",
   927                           tree.label);
   928                 break;
   929             }
   930             env1 = env1.next;
   931         }
   933         attribStat(tree.body, env.dup(tree));
   934         result = null;
   935     }
   937     public void visitSwitch(JCSwitch tree) {
   938         Type seltype = attribExpr(tree.selector, env);
   940         Env<AttrContext> switchEnv =
   941             env.dup(tree, env.info.dup(env.info.scope.dup()));
   943         boolean enumSwitch =
   944             allowEnums &&
   945             (seltype.tsym.flags() & Flags.ENUM) != 0;
   946         boolean stringSwitch = false;
   947         if (types.isSameType(seltype, syms.stringType)) {
   948             if (allowStringsInSwitch) {
   949                 stringSwitch = true;
   950             } else {
   951                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   952             }
   953         }
   954         if (!enumSwitch && !stringSwitch)
   955             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   957         // Attribute all cases and
   958         // check that there are no duplicate case labels or default clauses.
   959         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   960         boolean hasDefault = false;      // Is there a default label?
   961         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   962             JCCase c = l.head;
   963             Env<AttrContext> caseEnv =
   964                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   965             if (c.pat != null) {
   966                 if (enumSwitch) {
   967                     Symbol sym = enumConstant(c.pat, seltype);
   968                     if (sym == null) {
   969                         log.error(c.pat.pos(), "enum.const.req");
   970                     } else if (!labels.add(sym)) {
   971                         log.error(c.pos(), "duplicate.case.label");
   972                     }
   973                 } else {
   974                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   975                     if (pattype.tag != ERROR) {
   976                         if (pattype.constValue() == null) {
   977                             log.error(c.pat.pos(),
   978                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
   979                         } else if (labels.contains(pattype.constValue())) {
   980                             log.error(c.pos(), "duplicate.case.label");
   981                         } else {
   982                             labels.add(pattype.constValue());
   983                         }
   984                     }
   985                 }
   986             } else if (hasDefault) {
   987                 log.error(c.pos(), "duplicate.default.label");
   988             } else {
   989                 hasDefault = true;
   990             }
   991             attribStats(c.stats, caseEnv);
   992             caseEnv.info.scope.leave();
   993             addVars(c.stats, switchEnv.info.scope);
   994         }
   996         switchEnv.info.scope.leave();
   997         result = null;
   998     }
   999     // where
  1000         /** Add any variables defined in stats to the switch scope. */
  1001         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1002             for (;stats.nonEmpty(); stats = stats.tail) {
  1003                 JCTree stat = stats.head;
  1004                 if (stat.getTag() == JCTree.VARDEF)
  1005                     switchScope.enter(((JCVariableDecl) stat).sym);
  1008     // where
  1009     /** Return the selected enumeration constant symbol, or null. */
  1010     private Symbol enumConstant(JCTree tree, Type enumType) {
  1011         if (tree.getTag() != JCTree.IDENT) {
  1012             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1013             return syms.errSymbol;
  1015         JCIdent ident = (JCIdent)tree;
  1016         Name name = ident.name;
  1017         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1018              e.scope != null; e = e.next()) {
  1019             if (e.sym.kind == VAR) {
  1020                 Symbol s = ident.sym = e.sym;
  1021                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1022                 ident.type = s.type;
  1023                 return ((s.flags_field & Flags.ENUM) == 0)
  1024                     ? null : s;
  1027         return null;
  1030     public void visitSynchronized(JCSynchronized tree) {
  1031         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1032         attribStat(tree.body, env);
  1033         result = null;
  1036     public void visitTry(JCTry tree) {
  1037         // Create a new local environment with a local
  1038         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1039         boolean isTryWithResource = tree.resources.nonEmpty();
  1040         // Create a nested environment for attributing the try block if needed
  1041         Env<AttrContext> tryEnv = isTryWithResource ?
  1042             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1043             localEnv;
  1044         // Attribute resource declarations
  1045         for (JCTree resource : tree.resources) {
  1046             if (resource.getTag() == JCTree.VARDEF) {
  1047                 attribStat(resource, tryEnv);
  1048                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1049                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1050                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1051             } else {
  1052                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1055         // Attribute body
  1056         attribStat(tree.body, tryEnv);
  1057         if (isTryWithResource)
  1058             tryEnv.info.scope.leave();
  1060         // Attribute catch clauses
  1061         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1062             JCCatch c = l.head;
  1063             Env<AttrContext> catchEnv =
  1064                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1065             Type ctype = attribStat(c.param, catchEnv);
  1066             if (TreeInfo.isMultiCatch(c)) {
  1067                 //multi-catch parameter is implicitly marked as final
  1068                 c.param.sym.flags_field |= FINAL | DISJUNCTION;
  1070             if (c.param.sym.kind == Kinds.VAR) {
  1071                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1073             chk.checkType(c.param.vartype.pos(),
  1074                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1075                           syms.throwableType);
  1076             attribStat(c.body, catchEnv);
  1077             catchEnv.info.scope.leave();
  1080         // Attribute finalizer
  1081         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1083         localEnv.info.scope.leave();
  1084         result = null;
  1087     public void visitConditional(JCConditional tree) {
  1088         attribExpr(tree.cond, env, syms.booleanType);
  1089         attribExpr(tree.truepart, env);
  1090         attribExpr(tree.falsepart, env);
  1091         result = check(tree,
  1092                        capture(condType(tree.pos(), tree.cond.type,
  1093                                         tree.truepart.type, tree.falsepart.type)),
  1094                        VAL, pkind, pt);
  1096     //where
  1097         /** Compute the type of a conditional expression, after
  1098          *  checking that it exists. See Spec 15.25.
  1100          *  @param pos      The source position to be used for
  1101          *                  error diagnostics.
  1102          *  @param condtype The type of the expression's condition.
  1103          *  @param thentype The type of the expression's then-part.
  1104          *  @param elsetype The type of the expression's else-part.
  1105          */
  1106         private Type condType(DiagnosticPosition pos,
  1107                               Type condtype,
  1108                               Type thentype,
  1109                               Type elsetype) {
  1110             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1112             // If condition and both arms are numeric constants,
  1113             // evaluate at compile-time.
  1114             return ((condtype.constValue() != null) &&
  1115                     (thentype.constValue() != null) &&
  1116                     (elsetype.constValue() != null))
  1117                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1118                 : ctype;
  1120         /** Compute the type of a conditional expression, after
  1121          *  checking that it exists.  Does not take into
  1122          *  account the special case where condition and both arms
  1123          *  are constants.
  1125          *  @param pos      The source position to be used for error
  1126          *                  diagnostics.
  1127          *  @param condtype The type of the expression's condition.
  1128          *  @param thentype The type of the expression's then-part.
  1129          *  @param elsetype The type of the expression's else-part.
  1130          */
  1131         private Type condType1(DiagnosticPosition pos, Type condtype,
  1132                                Type thentype, Type elsetype) {
  1133             // If same type, that is the result
  1134             if (types.isSameType(thentype, elsetype))
  1135                 return thentype.baseType();
  1137             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1138                 ? thentype : types.unboxedType(thentype);
  1139             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1140                 ? elsetype : types.unboxedType(elsetype);
  1142             // Otherwise, if both arms can be converted to a numeric
  1143             // type, return the least numeric type that fits both arms
  1144             // (i.e. return larger of the two, or return int if one
  1145             // arm is short, the other is char).
  1146             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1147                 // If one arm has an integer subrange type (i.e., byte,
  1148                 // short, or char), and the other is an integer constant
  1149                 // that fits into the subrange, return the subrange type.
  1150                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1151                     types.isAssignable(elseUnboxed, thenUnboxed))
  1152                     return thenUnboxed.baseType();
  1153                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1154                     types.isAssignable(thenUnboxed, elseUnboxed))
  1155                     return elseUnboxed.baseType();
  1157                 for (int i = BYTE; i < VOID; i++) {
  1158                     Type candidate = syms.typeOfTag[i];
  1159                     if (types.isSubtype(thenUnboxed, candidate) &&
  1160                         types.isSubtype(elseUnboxed, candidate))
  1161                         return candidate;
  1165             // Those were all the cases that could result in a primitive
  1166             if (allowBoxing) {
  1167                 if (thentype.isPrimitive())
  1168                     thentype = types.boxedClass(thentype).type;
  1169                 if (elsetype.isPrimitive())
  1170                     elsetype = types.boxedClass(elsetype).type;
  1173             if (types.isSubtype(thentype, elsetype))
  1174                 return elsetype.baseType();
  1175             if (types.isSubtype(elsetype, thentype))
  1176                 return thentype.baseType();
  1178             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1179                 log.error(pos, "neither.conditional.subtype",
  1180                           thentype, elsetype);
  1181                 return thentype.baseType();
  1184             // both are known to be reference types.  The result is
  1185             // lub(thentype,elsetype). This cannot fail, as it will
  1186             // always be possible to infer "Object" if nothing better.
  1187             return types.lub(thentype.baseType(), elsetype.baseType());
  1190     public void visitIf(JCIf tree) {
  1191         attribExpr(tree.cond, env, syms.booleanType);
  1192         attribStat(tree.thenpart, env);
  1193         if (tree.elsepart != null)
  1194             attribStat(tree.elsepart, env);
  1195         chk.checkEmptyIf(tree);
  1196         result = null;
  1199     public void visitExec(JCExpressionStatement tree) {
  1200         //a fresh environment is required for 292 inference to work properly ---
  1201         //see Infer.instantiatePolymorphicSignatureInstance()
  1202         Env<AttrContext> localEnv = env.dup(tree);
  1203         attribExpr(tree.expr, localEnv);
  1204         result = null;
  1207     public void visitBreak(JCBreak tree) {
  1208         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1209         result = null;
  1212     public void visitContinue(JCContinue tree) {
  1213         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1214         result = null;
  1216     //where
  1217         /** Return the target of a break or continue statement, if it exists,
  1218          *  report an error if not.
  1219          *  Note: The target of a labelled break or continue is the
  1220          *  (non-labelled) statement tree referred to by the label,
  1221          *  not the tree representing the labelled statement itself.
  1223          *  @param pos     The position to be used for error diagnostics
  1224          *  @param tag     The tag of the jump statement. This is either
  1225          *                 Tree.BREAK or Tree.CONTINUE.
  1226          *  @param label   The label of the jump statement, or null if no
  1227          *                 label is given.
  1228          *  @param env     The environment current at the jump statement.
  1229          */
  1230         private JCTree findJumpTarget(DiagnosticPosition pos,
  1231                                     int tag,
  1232                                     Name label,
  1233                                     Env<AttrContext> env) {
  1234             // Search environments outwards from the point of jump.
  1235             Env<AttrContext> env1 = env;
  1236             LOOP:
  1237             while (env1 != null) {
  1238                 switch (env1.tree.getTag()) {
  1239                 case JCTree.LABELLED:
  1240                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1241                     if (label == labelled.label) {
  1242                         // If jump is a continue, check that target is a loop.
  1243                         if (tag == JCTree.CONTINUE) {
  1244                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1245                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1246                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1247                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1248                                 log.error(pos, "not.loop.label", label);
  1249                             // Found labelled statement target, now go inwards
  1250                             // to next non-labelled tree.
  1251                             return TreeInfo.referencedStatement(labelled);
  1252                         } else {
  1253                             return labelled;
  1256                     break;
  1257                 case JCTree.DOLOOP:
  1258                 case JCTree.WHILELOOP:
  1259                 case JCTree.FORLOOP:
  1260                 case JCTree.FOREACHLOOP:
  1261                     if (label == null) return env1.tree;
  1262                     break;
  1263                 case JCTree.SWITCH:
  1264                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1265                     break;
  1266                 case JCTree.METHODDEF:
  1267                 case JCTree.CLASSDEF:
  1268                     break LOOP;
  1269                 default:
  1271                 env1 = env1.next;
  1273             if (label != null)
  1274                 log.error(pos, "undef.label", label);
  1275             else if (tag == JCTree.CONTINUE)
  1276                 log.error(pos, "cont.outside.loop");
  1277             else
  1278                 log.error(pos, "break.outside.switch.loop");
  1279             return null;
  1282     public void visitReturn(JCReturn tree) {
  1283         // Check that there is an enclosing method which is
  1284         // nested within than the enclosing class.
  1285         if (env.enclMethod == null ||
  1286             env.enclMethod.sym.owner != env.enclClass.sym) {
  1287             log.error(tree.pos(), "ret.outside.meth");
  1289         } else {
  1290             // Attribute return expression, if it exists, and check that
  1291             // it conforms to result type of enclosing method.
  1292             Symbol m = env.enclMethod.sym;
  1293             if (m.type.getReturnType().tag == VOID) {
  1294                 if (tree.expr != null)
  1295                     log.error(tree.expr.pos(),
  1296                               "cant.ret.val.from.meth.decl.void");
  1297             } else if (tree.expr == null) {
  1298                 log.error(tree.pos(), "missing.ret.val");
  1299             } else {
  1300                 attribExpr(tree.expr, env, m.type.getReturnType());
  1303         result = null;
  1306     public void visitThrow(JCThrow tree) {
  1307         attribExpr(tree.expr, env, syms.throwableType);
  1308         result = null;
  1311     public void visitAssert(JCAssert tree) {
  1312         attribExpr(tree.cond, env, syms.booleanType);
  1313         if (tree.detail != null) {
  1314             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1316         result = null;
  1319      /** Visitor method for method invocations.
  1320      *  NOTE: The method part of an application will have in its type field
  1321      *        the return type of the method, not the method's type itself!
  1322      */
  1323     public void visitApply(JCMethodInvocation tree) {
  1324         // The local environment of a method application is
  1325         // a new environment nested in the current one.
  1326         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1328         // The types of the actual method arguments.
  1329         List<Type> argtypes;
  1331         // The types of the actual method type arguments.
  1332         List<Type> typeargtypes = null;
  1333         boolean typeargtypesNonRefOK = false;
  1335         Name methName = TreeInfo.name(tree.meth);
  1337         boolean isConstructorCall =
  1338             methName == names._this || methName == names._super;
  1340         if (isConstructorCall) {
  1341             // We are seeing a ...this(...) or ...super(...) call.
  1342             // Check that this is the first statement in a constructor.
  1343             if (checkFirstConstructorStat(tree, env)) {
  1345                 // Record the fact
  1346                 // that this is a constructor call (using isSelfCall).
  1347                 localEnv.info.isSelfCall = true;
  1349                 // Attribute arguments, yielding list of argument types.
  1350                 argtypes = attribArgs(tree.args, localEnv);
  1351                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1353                 // Variable `site' points to the class in which the called
  1354                 // constructor is defined.
  1355                 Type site = env.enclClass.sym.type;
  1356                 if (methName == names._super) {
  1357                     if (site == syms.objectType) {
  1358                         log.error(tree.meth.pos(), "no.superclass", site);
  1359                         site = types.createErrorType(syms.objectType);
  1360                     } else {
  1361                         site = types.supertype(site);
  1365                 if (site.tag == CLASS) {
  1366                     Type encl = site.getEnclosingType();
  1367                     while (encl != null && encl.tag == TYPEVAR)
  1368                         encl = encl.getUpperBound();
  1369                     if (encl.tag == CLASS) {
  1370                         // we are calling a nested class
  1372                         if (tree.meth.getTag() == JCTree.SELECT) {
  1373                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1375                             // We are seeing a prefixed call, of the form
  1376                             //     <expr>.super(...).
  1377                             // Check that the prefix expression conforms
  1378                             // to the outer instance type of the class.
  1379                             chk.checkRefType(qualifier.pos(),
  1380                                              attribExpr(qualifier, localEnv,
  1381                                                         encl));
  1382                         } else if (methName == names._super) {
  1383                             // qualifier omitted; check for existence
  1384                             // of an appropriate implicit qualifier.
  1385                             rs.resolveImplicitThis(tree.meth.pos(),
  1386                                                    localEnv, site);
  1388                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1389                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1390                                   site.tsym);
  1393                     // if we're calling a java.lang.Enum constructor,
  1394                     // prefix the implicit String and int parameters
  1395                     if (site.tsym == syms.enumSym && allowEnums)
  1396                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1398                     // Resolve the called constructor under the assumption
  1399                     // that we are referring to a superclass instance of the
  1400                     // current instance (JLS ???).
  1401                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1402                     localEnv.info.selectSuper = true;
  1403                     localEnv.info.varArgs = false;
  1404                     Symbol sym = rs.resolveConstructor(
  1405                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1406                     localEnv.info.selectSuper = selectSuperPrev;
  1408                     // Set method symbol to resolved constructor...
  1409                     TreeInfo.setSymbol(tree.meth, sym);
  1411                     // ...and check that it is legal in the current context.
  1412                     // (this will also set the tree's type)
  1413                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1414                     checkId(tree.meth, site, sym, localEnv, MTH,
  1415                             mpt, tree.varargsElement != null);
  1417                 // Otherwise, `site' is an error type and we do nothing
  1419             result = tree.type = syms.voidType;
  1420         } else {
  1421             // Otherwise, we are seeing a regular method call.
  1422             // Attribute the arguments, yielding list of argument types, ...
  1423             argtypes = attribArgs(tree.args, localEnv);
  1424             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1426             // ... and attribute the method using as a prototype a methodtype
  1427             // whose formal argument types is exactly the list of actual
  1428             // arguments (this will also set the method symbol).
  1429             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1430             localEnv.info.varArgs = false;
  1431             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1432             if (localEnv.info.varArgs)
  1433                 assert mtype.isErroneous() || tree.varargsElement != null;
  1435             // Compute the result type.
  1436             Type restype = mtype.getReturnType();
  1437             if (restype.tag == WILDCARD)
  1438                 throw new AssertionError(mtype);
  1440             // as a special case, array.clone() has a result that is
  1441             // the same as static type of the array being cloned
  1442             if (tree.meth.getTag() == JCTree.SELECT &&
  1443                 allowCovariantReturns &&
  1444                 methName == names.clone &&
  1445                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1446                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1448             // as a special case, x.getClass() has type Class<? extends |X|>
  1449             if (allowGenerics &&
  1450                 methName == names.getClass && tree.args.isEmpty()) {
  1451                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1452                     ? ((JCFieldAccess) tree.meth).selected.type
  1453                     : env.enclClass.sym.type;
  1454                 restype = new
  1455                     ClassType(restype.getEnclosingType(),
  1456                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1457                                                                BoundKind.EXTENDS,
  1458                                                                syms.boundClass)),
  1459                               restype.tsym);
  1462             // Special case logic for JSR 292 types.
  1463             if (rs.allowTransitionalJSR292 &&
  1464                     tree.meth.getTag() == JCTree.SELECT &&
  1465                     !typeargtypes.isEmpty()) {
  1466                 JCFieldAccess mfield = (JCFieldAccess) tree.meth;
  1467                 // MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
  1468                 // has type <T>, and T can be a primitive type.
  1469                 if (mfield.sym != null &&
  1470                         mfield.sym.isPolymorphicSignatureInstance())
  1471                     typeargtypesNonRefOK = true;
  1474             if (!(rs.allowTransitionalJSR292 && typeargtypesNonRefOK)) {
  1475                 chk.checkRefTypes(tree.typeargs, typeargtypes);
  1478             // Check that value of resulting type is admissible in the
  1479             // current context.  Also, capture the return type
  1480             result = check(tree, capture(restype), VAL, pkind, pt);
  1482         chk.validate(tree.typeargs, localEnv);
  1484     //where
  1485         /** Check that given application node appears as first statement
  1486          *  in a constructor call.
  1487          *  @param tree   The application node
  1488          *  @param env    The environment current at the application.
  1489          */
  1490         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1491             JCMethodDecl enclMethod = env.enclMethod;
  1492             if (enclMethod != null && enclMethod.name == names.init) {
  1493                 JCBlock body = enclMethod.body;
  1494                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1495                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1496                     return true;
  1498             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1499                       TreeInfo.name(tree.meth));
  1500             return false;
  1503         /** Obtain a method type with given argument types.
  1504          */
  1505         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1506             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1507             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1510     public void visitNewClass(JCNewClass tree) {
  1511         Type owntype = types.createErrorType(tree.type);
  1513         // The local environment of a class creation is
  1514         // a new environment nested in the current one.
  1515         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1517         // The anonymous inner class definition of the new expression,
  1518         // if one is defined by it.
  1519         JCClassDecl cdef = tree.def;
  1521         // If enclosing class is given, attribute it, and
  1522         // complete class name to be fully qualified
  1523         JCExpression clazz = tree.clazz; // Class field following new
  1524         JCExpression clazzid =          // Identifier in class field
  1525             (clazz.getTag() == JCTree.TYPEAPPLY)
  1526             ? ((JCTypeApply) clazz).clazz
  1527             : clazz;
  1529         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1531         if (tree.encl != null) {
  1532             // We are seeing a qualified new, of the form
  1533             //    <expr>.new C <...> (...) ...
  1534             // In this case, we let clazz stand for the name of the
  1535             // allocated class C prefixed with the type of the qualifier
  1536             // expression, so that we can
  1537             // resolve it with standard techniques later. I.e., if
  1538             // <expr> has type T, then <expr>.new C <...> (...)
  1539             // yields a clazz T.C.
  1540             Type encltype = chk.checkRefType(tree.encl.pos(),
  1541                                              attribExpr(tree.encl, env));
  1542             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1543                                                  ((JCIdent) clazzid).name);
  1544             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1545                 clazz = make.at(tree.pos).
  1546                     TypeApply(clazzid1,
  1547                               ((JCTypeApply) clazz).arguments);
  1548             else
  1549                 clazz = clazzid1;
  1552         // Attribute clazz expression and store
  1553         // symbol + type back into the attributed tree.
  1554         Type clazztype = attribType(clazz, env);
  1555         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype, cdef != null);
  1556         if (!TreeInfo.isDiamond(tree)) {
  1557             clazztype = chk.checkClassType(
  1558                 tree.clazz.pos(), clazztype, true);
  1560         chk.validate(clazz, localEnv);
  1561         if (tree.encl != null) {
  1562             // We have to work in this case to store
  1563             // symbol + type back into the attributed tree.
  1564             tree.clazz.type = clazztype;
  1565             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1566             clazzid.type = ((JCIdent) clazzid).sym.type;
  1567             if (!clazztype.isErroneous()) {
  1568                 if (cdef != null && clazztype.tsym.isInterface()) {
  1569                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1570                 } else if (clazztype.tsym.isStatic()) {
  1571                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1574         } else if (!clazztype.tsym.isInterface() &&
  1575                    clazztype.getEnclosingType().tag == CLASS) {
  1576             // Check for the existence of an apropos outer instance
  1577             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1580         // Attribute constructor arguments.
  1581         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1582         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1584         if (TreeInfo.isDiamond(tree)) {
  1585             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1586             clazz.type = clazztype;
  1587         } else if (allowDiamondFinder &&
  1588                 clazztype.getTypeArguments().nonEmpty() &&
  1589                 findDiamonds) {
  1590             boolean prevDeferDiags = log.deferDiagnostics;
  1591             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1592             Type inferred = null;
  1593             try {
  1594                 //disable diamond-related diagnostics
  1595                 log.deferDiagnostics = true;
  1596                 log.deferredDiagnostics = ListBuffer.lb();
  1597                 inferred = attribDiamond(localEnv,
  1598                         tree,
  1599                         clazztype,
  1600                         mapping,
  1601                         argtypes,
  1602                         typeargtypes);
  1604             finally {
  1605                 log.deferDiagnostics = prevDeferDiags;
  1606                 log.deferredDiagnostics = prevDeferredDiags;
  1608             if (inferred != null &&
  1609                     !inferred.isErroneous() &&
  1610                     inferred.tag == CLASS &&
  1611                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
  1612                     chk.checkDiamond((ClassType)inferred).isEmpty()) {
  1613                 String key = types.isSameType(clazztype, inferred) ?
  1614                     "diamond.redundant.args" :
  1615                     "diamond.redundant.args.1";
  1616                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1620         // If we have made no mistakes in the class type...
  1621         if (clazztype.tag == CLASS) {
  1622             // Enums may not be instantiated except implicitly
  1623             if (allowEnums &&
  1624                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1625                 (env.tree.getTag() != JCTree.VARDEF ||
  1626                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1627                  ((JCVariableDecl) env.tree).init != tree))
  1628                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1629             // Check that class is not abstract
  1630             if (cdef == null &&
  1631                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1632                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1633                           clazztype.tsym);
  1634             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1635                 // Check that no constructor arguments are given to
  1636                 // anonymous classes implementing an interface
  1637                 if (!argtypes.isEmpty())
  1638                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1640                 if (!typeargtypes.isEmpty())
  1641                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1643                 // Error recovery: pretend no arguments were supplied.
  1644                 argtypes = List.nil();
  1645                 typeargtypes = List.nil();
  1648             // Resolve the called constructor under the assumption
  1649             // that we are referring to a superclass instance of the
  1650             // current instance (JLS ???).
  1651             else {
  1652                 localEnv.info.selectSuper = cdef != null;
  1653                 localEnv.info.varArgs = false;
  1654                 tree.constructor = rs.resolveConstructor(
  1655                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1656                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1657                     syms.errType :
  1658                     checkMethod(clazztype,
  1659                         tree.constructor,
  1660                         localEnv,
  1661                         tree.args,
  1662                         argtypes,
  1663                         typeargtypes,
  1664                         localEnv.info.varArgs);
  1665                 if (localEnv.info.varArgs)
  1666                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
  1669             if (cdef != null) {
  1670                 // We are seeing an anonymous class instance creation.
  1671                 // In this case, the class instance creation
  1672                 // expression
  1673                 //
  1674                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1675                 //
  1676                 // is represented internally as
  1677                 //
  1678                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1679                 //
  1680                 // This expression is then *transformed* as follows:
  1681                 //
  1682                 // (1) add a STATIC flag to the class definition
  1683                 //     if the current environment is static
  1684                 // (2) add an extends or implements clause
  1685                 // (3) add a constructor.
  1686                 //
  1687                 // For instance, if C is a class, and ET is the type of E,
  1688                 // the expression
  1689                 //
  1690                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1691                 //
  1692                 // is translated to (where X is a fresh name and typarams is the
  1693                 // parameter list of the super constructor):
  1694                 //
  1695                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1696                 //     X extends C<typargs2> {
  1697                 //       <typarams> X(ET e, args) {
  1698                 //         e.<typeargs1>super(args)
  1699                 //       }
  1700                 //       ...
  1701                 //     }
  1702                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1704                 if (clazztype.tsym.isInterface()) {
  1705                     cdef.implementing = List.of(clazz);
  1706                 } else {
  1707                     cdef.extending = clazz;
  1710                 attribStat(cdef, localEnv);
  1712                 // If an outer instance is given,
  1713                 // prefix it to the constructor arguments
  1714                 // and delete it from the new expression
  1715                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1716                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1717                     argtypes = argtypes.prepend(tree.encl.type);
  1718                     tree.encl = null;
  1721                 // Reassign clazztype and recompute constructor.
  1722                 clazztype = cdef.sym.type;
  1723                 Symbol sym = rs.resolveConstructor(
  1724                     tree.pos(), localEnv, clazztype, argtypes,
  1725                     typeargtypes, true, tree.varargsElement != null);
  1726                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
  1727                 tree.constructor = sym;
  1728                 if (tree.constructor.kind > ERRONEOUS) {
  1729                     tree.constructorType =  syms.errType;
  1731                 else {
  1732                     tree.constructorType = checkMethod(clazztype,
  1733                             tree.constructor,
  1734                             localEnv,
  1735                             tree.args,
  1736                             argtypes,
  1737                             typeargtypes,
  1738                             localEnv.info.varArgs);
  1742             if (tree.constructor != null && tree.constructor.kind == MTH)
  1743                 owntype = clazztype;
  1745         result = check(tree, owntype, VAL, pkind, pt);
  1746         chk.validate(tree.typeargs, localEnv);
  1749     Type attribDiamond(Env<AttrContext> env,
  1750                         JCNewClass tree,
  1751                         Type clazztype,
  1752                         Pair<Scope, Scope> mapping,
  1753                         List<Type> argtypes,
  1754                         List<Type> typeargtypes) {
  1755         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1756             //if the type of the instance creation expression is erroneous,
  1757             //or something prevented us to form a valid mapping, return the
  1758             //(possibly erroneous) type unchanged
  1759             return clazztype;
  1761         else if (clazztype.isInterface()) {
  1762             //if the type of the instance creation expression is an interface
  1763             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1764             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1765             clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
  1766                 @Override
  1767                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
  1768                     switch (ck) {
  1769                         case EXTENDS: return types.getBounds(tv);
  1770                         default: return List.nil();
  1773                 @Override
  1774                 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
  1775                     // check that inferred bounds conform to their bounds
  1776                     infer.checkWithinBounds(tvars,
  1777                            types.subst(tvars, tvars, inferred), Warner.noWarnings);
  1778                     return super.inst(inferred, types);
  1780             };
  1781         } else {
  1782             //if the type of the instance creation expression is a class type
  1783             //apply method resolution inference (JLS 15.12.2.7). The return type
  1784             //of the resolved constructor will be a partially instantiated type
  1785             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1786             Symbol constructor;
  1787             try {
  1788                 constructor = rs.resolveDiamond(tree.pos(),
  1789                         env,
  1790                         clazztype.tsym.type,
  1791                         argtypes,
  1792                         typeargtypes);
  1793             } finally {
  1794                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1796             if (constructor.kind == MTH) {
  1797                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1798                         clazztype.tsym.type.getTypeArguments(),
  1799                         clazztype.tsym);
  1800                 clazztype = checkMethod(ct,
  1801                         constructor,
  1802                         env,
  1803                         tree.args,
  1804                         argtypes,
  1805                         typeargtypes,
  1806                         env.info.varArgs).getReturnType();
  1807             } else {
  1808                 clazztype = syms.errType;
  1811         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1812             //if the resolved constructor's return type has some uninferred
  1813             //type-variables, infer them using the expected type and declared
  1814             //bounds (JLS 15.12.2.8).
  1815             try {
  1816                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1817                         pt.tag == NONE ? syms.objectType : pt,
  1818                         Warner.noWarnings);
  1819             } catch (Infer.InferenceException ex) {
  1820                 //an error occurred while inferring uninstantiated type-variables
  1821                 log.error(tree.clazz.pos(),
  1822                         "cant.apply.diamond.1",
  1823                         diags.fragment("diamond", clazztype.tsym),
  1824                         ex.diagnostic);
  1827         clazztype = chk.checkClassType(tree.clazz.pos(),
  1828                 clazztype,
  1829                 true);
  1830         if (clazztype.tag == CLASS) {
  1831             List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1832             if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1833                 //one or more types inferred in the previous steps is either a
  1834                 //captured type or an intersection type --- we need to report an error.
  1835                 String subkey = invalidDiamondArgs.size() > 1 ?
  1836                     "diamond.invalid.args" :
  1837                     "diamond.invalid.arg";
  1838                 //The error message is of the kind:
  1839                 //
  1840                 //cannot infer type arguments for {clazztype}<>;
  1841                 //reason: {subkey}
  1842                 //
  1843                 //where subkey is a fragment of the kind:
  1844                 //
  1845                 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1846                 log.error(tree.clazz.pos(),
  1847                             "cant.apply.diamond.1",
  1848                             diags.fragment("diamond", clazztype.tsym),
  1849                             diags.fragment(subkey,
  1850                                            invalidDiamondArgs,
  1851                                            diags.fragment("diamond", clazztype.tsym)));
  1854         return clazztype;
  1857     /** Creates a synthetic scope containing fake generic constructors.
  1858      *  Assuming that the original scope contains a constructor of the kind:
  1859      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1860      *  the synthetic scope is added a generic constructor of the kind:
  1861      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1862      *  inference. The inferred return type of the synthetic constructor IS
  1863      *  the inferred type for the diamond operator.
  1864      */
  1865     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype, boolean overrideProtectedAccess) {
  1866         if (ctype.tag != CLASS) {
  1867             return erroneousMapping;
  1869         Pair<Scope, Scope> mapping =
  1870                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1871         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1872         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1873                 e.scope != null;
  1874                 e = e.next()) {
  1875             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1876             if (overrideProtectedAccess && (newConstr.flags() & PROTECTED) != 0) {
  1877                 //make protected constructor public (this is required for
  1878                 //anonymous inner class creation expressions using diamond)
  1879                 newConstr.flags_field |= PUBLIC;
  1880                 newConstr.flags_field &= ~PROTECTED;
  1882             newConstr.name = names.init;
  1883             List<Type> oldTypeargs = List.nil();
  1884             if (newConstr.type.tag == FORALL) {
  1885                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1887             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1888                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1889                     newConstr.type.getThrownTypes(),
  1890                     syms.methodClass);
  1891             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1892             mapping.snd.enter(newConstr);
  1894         return mapping;
  1897     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1899     /** Make an attributed null check tree.
  1900      */
  1901     public JCExpression makeNullCheck(JCExpression arg) {
  1902         // optimization: X.this is never null; skip null check
  1903         Name name = TreeInfo.name(arg);
  1904         if (name == names._this || name == names._super) return arg;
  1906         int optag = JCTree.NULLCHK;
  1907         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1908         tree.operator = syms.nullcheck;
  1909         tree.type = arg.type;
  1910         return tree;
  1913     public void visitNewArray(JCNewArray tree) {
  1914         Type owntype = types.createErrorType(tree.type);
  1915         Type elemtype;
  1916         if (tree.elemtype != null) {
  1917             elemtype = attribType(tree.elemtype, env);
  1918             chk.validate(tree.elemtype, env);
  1919             owntype = elemtype;
  1920             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1921                 attribExpr(l.head, env, syms.intType);
  1922                 owntype = new ArrayType(owntype, syms.arrayClass);
  1924         } else {
  1925             // we are seeing an untyped aggregate { ... }
  1926             // this is allowed only if the prototype is an array
  1927             if (pt.tag == ARRAY) {
  1928                 elemtype = types.elemtype(pt);
  1929             } else {
  1930                 if (pt.tag != ERROR) {
  1931                     log.error(tree.pos(), "illegal.initializer.for.type",
  1932                               pt);
  1934                 elemtype = types.createErrorType(pt);
  1937         if (tree.elems != null) {
  1938             attribExprs(tree.elems, env, elemtype);
  1939             owntype = new ArrayType(elemtype, syms.arrayClass);
  1941         if (!types.isReifiable(elemtype))
  1942             log.error(tree.pos(), "generic.array.creation");
  1943         result = check(tree, owntype, VAL, pkind, pt);
  1946     public void visitParens(JCParens tree) {
  1947         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1948         result = check(tree, owntype, pkind, pkind, pt);
  1949         Symbol sym = TreeInfo.symbol(tree);
  1950         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1951             log.error(tree.pos(), "illegal.start.of.type");
  1954     public void visitAssign(JCAssign tree) {
  1955         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1956         Type capturedType = capture(owntype);
  1957         attribExpr(tree.rhs, env, owntype);
  1958         result = check(tree, capturedType, VAL, pkind, pt);
  1961     public void visitAssignop(JCAssignOp tree) {
  1962         // Attribute arguments.
  1963         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1964         Type operand = attribExpr(tree.rhs, env);
  1965         // Find operator.
  1966         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1967             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1968             owntype, operand);
  1970         if (operator.kind == MTH) {
  1971             chk.checkOperator(tree.pos(),
  1972                               (OperatorSymbol)operator,
  1973                               tree.getTag() - JCTree.ASGOffset,
  1974                               owntype,
  1975                               operand);
  1976             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1977             chk.checkCastable(tree.rhs.pos(),
  1978                               operator.type.getReturnType(),
  1979                               owntype);
  1981         result = check(tree, owntype, VAL, pkind, pt);
  1984     public void visitUnary(JCUnary tree) {
  1985         // Attribute arguments.
  1986         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1987             ? attribTree(tree.arg, env, VAR, Type.noType)
  1988             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1990         // Find operator.
  1991         Symbol operator = tree.operator =
  1992             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1994         Type owntype = types.createErrorType(tree.type);
  1995         if (operator.kind == MTH) {
  1996             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1997                 ? tree.arg.type
  1998                 : operator.type.getReturnType();
  1999             int opc = ((OperatorSymbol)operator).opcode;
  2001             // If the argument is constant, fold it.
  2002             if (argtype.constValue() != null) {
  2003                 Type ctype = cfolder.fold1(opc, argtype);
  2004                 if (ctype != null) {
  2005                     owntype = cfolder.coerce(ctype, owntype);
  2007                     // Remove constant types from arguments to
  2008                     // conserve space. The parser will fold concatenations
  2009                     // of string literals; the code here also
  2010                     // gets rid of intermediate results when some of the
  2011                     // operands are constant identifiers.
  2012                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2013                         tree.arg.type = syms.stringType;
  2018         result = check(tree, owntype, VAL, pkind, pt);
  2021     public void visitBinary(JCBinary tree) {
  2022         // Attribute arguments.
  2023         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2024         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2026         // Find operator.
  2027         Symbol operator = tree.operator =
  2028             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2030         Type owntype = types.createErrorType(tree.type);
  2031         if (operator.kind == MTH) {
  2032             owntype = operator.type.getReturnType();
  2033             int opc = chk.checkOperator(tree.lhs.pos(),
  2034                                         (OperatorSymbol)operator,
  2035                                         tree.getTag(),
  2036                                         left,
  2037                                         right);
  2039             // If both arguments are constants, fold them.
  2040             if (left.constValue() != null && right.constValue() != null) {
  2041                 Type ctype = cfolder.fold2(opc, left, right);
  2042                 if (ctype != null) {
  2043                     owntype = cfolder.coerce(ctype, owntype);
  2045                     // Remove constant types from arguments to
  2046                     // conserve space. The parser will fold concatenations
  2047                     // of string literals; the code here also
  2048                     // gets rid of intermediate results when some of the
  2049                     // operands are constant identifiers.
  2050                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2051                         tree.lhs.type = syms.stringType;
  2053                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2054                         tree.rhs.type = syms.stringType;
  2059             // Check that argument types of a reference ==, != are
  2060             // castable to each other, (JLS???).
  2061             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2062                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2063                     log.error(tree.pos(), "incomparable.types", left, right);
  2067             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2069         result = check(tree, owntype, VAL, pkind, pt);
  2072     public void visitTypeCast(JCTypeCast tree) {
  2073         Type clazztype = attribType(tree.clazz, env);
  2074         chk.validate(tree.clazz, env, false);
  2075         //a fresh environment is required for 292 inference to work properly ---
  2076         //see Infer.instantiatePolymorphicSignatureInstance()
  2077         Env<AttrContext> localEnv = env.dup(tree);
  2078         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2079         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2080         if (exprtype.constValue() != null)
  2081             owntype = cfolder.coerce(exprtype, owntype);
  2082         result = check(tree, capture(owntype), VAL, pkind, pt);
  2085     public void visitTypeTest(JCInstanceOf tree) {
  2086         Type exprtype = chk.checkNullOrRefType(
  2087             tree.expr.pos(), attribExpr(tree.expr, env));
  2088         Type clazztype = chk.checkReifiableReferenceType(
  2089             tree.clazz.pos(), attribType(tree.clazz, env));
  2090         chk.validate(tree.clazz, env, false);
  2091         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2092         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2095     public void visitIndexed(JCArrayAccess tree) {
  2096         Type owntype = types.createErrorType(tree.type);
  2097         Type atype = attribExpr(tree.indexed, env);
  2098         attribExpr(tree.index, env, syms.intType);
  2099         if (types.isArray(atype))
  2100             owntype = types.elemtype(atype);
  2101         else if (atype.tag != ERROR)
  2102             log.error(tree.pos(), "array.req.but.found", atype);
  2103         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2104         result = check(tree, owntype, VAR, pkind, pt);
  2107     public void visitIdent(JCIdent tree) {
  2108         Symbol sym;
  2109         boolean varArgs = false;
  2111         // Find symbol
  2112         if (pt.tag == METHOD || pt.tag == FORALL) {
  2113             // If we are looking for a method, the prototype `pt' will be a
  2114             // method type with the type of the call's arguments as parameters.
  2115             env.info.varArgs = false;
  2116             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2117             varArgs = env.info.varArgs;
  2118         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2119             sym = tree.sym;
  2120         } else {
  2121             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2123         tree.sym = sym;
  2125         // (1) Also find the environment current for the class where
  2126         //     sym is defined (`symEnv').
  2127         // Only for pre-tiger versions (1.4 and earlier):
  2128         // (2) Also determine whether we access symbol out of an anonymous
  2129         //     class in a this or super call.  This is illegal for instance
  2130         //     members since such classes don't carry a this$n link.
  2131         //     (`noOuterThisPath').
  2132         Env<AttrContext> symEnv = env;
  2133         boolean noOuterThisPath = false;
  2134         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2135             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2136             sym.owner.kind == TYP &&
  2137             tree.name != names._this && tree.name != names._super) {
  2139             // Find environment in which identifier is defined.
  2140             while (symEnv.outer != null &&
  2141                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2142                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2143                     noOuterThisPath = !allowAnonOuterThis;
  2144                 symEnv = symEnv.outer;
  2148         // If symbol is a variable, ...
  2149         if (sym.kind == VAR) {
  2150             VarSymbol v = (VarSymbol)sym;
  2152             // ..., evaluate its initializer, if it has one, and check for
  2153             // illegal forward reference.
  2154             checkInit(tree, env, v, false);
  2156             // If symbol is a local variable accessed from an embedded
  2157             // inner class check that it is final.
  2158             if (v.owner.kind == MTH &&
  2159                 v.owner != env.info.scope.owner &&
  2160                 (v.flags_field & FINAL) == 0) {
  2161                 log.error(tree.pos(),
  2162                           "local.var.accessed.from.icls.needs.final",
  2163                           v);
  2166             // If we are expecting a variable (as opposed to a value), check
  2167             // that the variable is assignable in the current environment.
  2168             if (pkind == VAR)
  2169                 checkAssignable(tree.pos(), v, null, env);
  2172         // In a constructor body,
  2173         // if symbol is a field or instance method, check that it is
  2174         // not accessed before the supertype constructor is called.
  2175         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2176             (sym.kind & (VAR | MTH)) != 0 &&
  2177             sym.owner.kind == TYP &&
  2178             (sym.flags() & STATIC) == 0) {
  2179             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2181         Env<AttrContext> env1 = env;
  2182         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2183             // If the found symbol is inaccessible, then it is
  2184             // accessed through an enclosing instance.  Locate this
  2185             // enclosing instance:
  2186             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2187                 env1 = env1.outer;
  2189         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2192     public void visitSelect(JCFieldAccess tree) {
  2193         // Determine the expected kind of the qualifier expression.
  2194         int skind = 0;
  2195         if (tree.name == names._this || tree.name == names._super ||
  2196             tree.name == names._class)
  2198             skind = TYP;
  2199         } else {
  2200             if ((pkind & PCK) != 0) skind = skind | PCK;
  2201             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2202             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2205         // Attribute the qualifier expression, and determine its symbol (if any).
  2206         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2207         if ((pkind & (PCK | TYP)) == 0)
  2208             site = capture(site); // Capture field access
  2210         // don't allow T.class T[].class, etc
  2211         if (skind == TYP) {
  2212             Type elt = site;
  2213             while (elt.tag == ARRAY)
  2214                 elt = ((ArrayType)elt).elemtype;
  2215             if (elt.tag == TYPEVAR) {
  2216                 log.error(tree.pos(), "type.var.cant.be.deref");
  2217                 result = types.createErrorType(tree.type);
  2218                 return;
  2222         // If qualifier symbol is a type or `super', assert `selectSuper'
  2223         // for the selection. This is relevant for determining whether
  2224         // protected symbols are accessible.
  2225         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2226         boolean selectSuperPrev = env.info.selectSuper;
  2227         env.info.selectSuper =
  2228             sitesym != null &&
  2229             sitesym.name == names._super;
  2231         // If selected expression is polymorphic, strip
  2232         // type parameters and remember in env.info.tvars, so that
  2233         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2234         if (tree.selected.type.tag == FORALL) {
  2235             ForAll pstype = (ForAll)tree.selected.type;
  2236             env.info.tvars = pstype.tvars;
  2237             site = tree.selected.type = pstype.qtype;
  2240         // Determine the symbol represented by the selection.
  2241         env.info.varArgs = false;
  2242         Symbol sym = selectSym(tree, site, env, pt, pkind);
  2243         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2244             site = capture(site);
  2245             sym = selectSym(tree, site, env, pt, pkind);
  2247         boolean varArgs = env.info.varArgs;
  2248         tree.sym = sym;
  2250         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2251             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2252             site = capture(site);
  2255         // If that symbol is a variable, ...
  2256         if (sym.kind == VAR) {
  2257             VarSymbol v = (VarSymbol)sym;
  2259             // ..., evaluate its initializer, if it has one, and check for
  2260             // illegal forward reference.
  2261             checkInit(tree, env, v, true);
  2263             // If we are expecting a variable (as opposed to a value), check
  2264             // that the variable is assignable in the current environment.
  2265             if (pkind == VAR)
  2266                 checkAssignable(tree.pos(), v, tree.selected, env);
  2269         if (sitesym != null &&
  2270                 sitesym.kind == VAR &&
  2271                 ((VarSymbol)sitesym).isResourceVariable() &&
  2272                 sym.kind == MTH &&
  2273                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2274                 env.info.lint.isEnabled(Lint.LintCategory.TRY)) {
  2275             log.warning(Lint.LintCategory.TRY, tree, "try.explicit.close.call");
  2278         // Disallow selecting a type from an expression
  2279         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2280             tree.type = check(tree.selected, pt,
  2281                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2284         if (isType(sitesym)) {
  2285             if (sym.name == names._this) {
  2286                 // If `C' is the currently compiled class, check that
  2287                 // C.this' does not appear in a call to a super(...)
  2288                 if (env.info.isSelfCall &&
  2289                     site.tsym == env.enclClass.sym) {
  2290                     chk.earlyRefError(tree.pos(), sym);
  2292             } else {
  2293                 // Check if type-qualified fields or methods are static (JLS)
  2294                 if ((sym.flags() & STATIC) == 0 &&
  2295                     sym.name != names._super &&
  2296                     (sym.kind == VAR || sym.kind == MTH)) {
  2297                     rs.access(rs.new StaticError(sym),
  2298                               tree.pos(), site, sym.name, true);
  2301         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2302             // If the qualified item is not a type and the selected item is static, report
  2303             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2304             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2307         // If we are selecting an instance member via a `super', ...
  2308         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2310             // Check that super-qualified symbols are not abstract (JLS)
  2311             rs.checkNonAbstract(tree.pos(), sym);
  2313             if (site.isRaw()) {
  2314                 // Determine argument types for site.
  2315                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2316                 if (site1 != null) site = site1;
  2320         env.info.selectSuper = selectSuperPrev;
  2321         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2322         env.info.tvars = List.nil();
  2324     //where
  2325         /** Determine symbol referenced by a Select expression,
  2327          *  @param tree   The select tree.
  2328          *  @param site   The type of the selected expression,
  2329          *  @param env    The current environment.
  2330          *  @param pt     The current prototype.
  2331          *  @param pkind  The expected kind(s) of the Select expression.
  2332          */
  2333         private Symbol selectSym(JCFieldAccess tree,
  2334                                  Type site,
  2335                                  Env<AttrContext> env,
  2336                                  Type pt,
  2337                                  int pkind) {
  2338             DiagnosticPosition pos = tree.pos();
  2339             Name name = tree.name;
  2341             switch (site.tag) {
  2342             case PACKAGE:
  2343                 return rs.access(
  2344                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2345                     pos, site, name, true);
  2346             case ARRAY:
  2347             case CLASS:
  2348                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2349                     return rs.resolveQualifiedMethod(
  2350                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2351                 } else if (name == names._this || name == names._super) {
  2352                     return rs.resolveSelf(pos, env, site.tsym, name);
  2353                 } else if (name == names._class) {
  2354                     // In this case, we have already made sure in
  2355                     // visitSelect that qualifier expression is a type.
  2356                     Type t = syms.classType;
  2357                     List<Type> typeargs = allowGenerics
  2358                         ? List.of(types.erasure(site))
  2359                         : List.<Type>nil();
  2360                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2361                     return new VarSymbol(
  2362                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2363                 } else {
  2364                     // We are seeing a plain identifier as selector.
  2365                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2366                     if ((pkind & ERRONEOUS) == 0)
  2367                         sym = rs.access(sym, pos, site, name, true);
  2368                     return sym;
  2370             case WILDCARD:
  2371                 throw new AssertionError(tree);
  2372             case TYPEVAR:
  2373                 // Normally, site.getUpperBound() shouldn't be null.
  2374                 // It should only happen during memberEnter/attribBase
  2375                 // when determining the super type which *must* be
  2376                 // done before attributing the type variables.  In
  2377                 // other words, we are seeing this illegal program:
  2378                 // class B<T> extends A<T.foo> {}
  2379                 Symbol sym = (site.getUpperBound() != null)
  2380                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
  2381                     : null;
  2382                 if (sym == null) {
  2383                     log.error(pos, "type.var.cant.be.deref");
  2384                     return syms.errSymbol;
  2385                 } else {
  2386                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2387                         rs.new AccessError(env, site, sym) :
  2388                                 sym;
  2389                     rs.access(sym2, pos, site, name, true);
  2390                     return sym;
  2392             case ERROR:
  2393                 // preserve identifier names through errors
  2394                 return types.createErrorType(name, site.tsym, site).tsym;
  2395             default:
  2396                 // The qualifier expression is of a primitive type -- only
  2397                 // .class is allowed for these.
  2398                 if (name == names._class) {
  2399                     // In this case, we have already made sure in Select that
  2400                     // qualifier expression is a type.
  2401                     Type t = syms.classType;
  2402                     Type arg = types.boxedClass(site).type;
  2403                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2404                     return new VarSymbol(
  2405                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2406                 } else {
  2407                     log.error(pos, "cant.deref", site);
  2408                     return syms.errSymbol;
  2413         /** Determine type of identifier or select expression and check that
  2414          *  (1) the referenced symbol is not deprecated
  2415          *  (2) the symbol's type is safe (@see checkSafe)
  2416          *  (3) if symbol is a variable, check that its type and kind are
  2417          *      compatible with the prototype and protokind.
  2418          *  (4) if symbol is an instance field of a raw type,
  2419          *      which is being assigned to, issue an unchecked warning if its
  2420          *      type changes under erasure.
  2421          *  (5) if symbol is an instance method of a raw type, issue an
  2422          *      unchecked warning if its argument types change under erasure.
  2423          *  If checks succeed:
  2424          *    If symbol is a constant, return its constant type
  2425          *    else if symbol is a method, return its result type
  2426          *    otherwise return its type.
  2427          *  Otherwise return errType.
  2429          *  @param tree       The syntax tree representing the identifier
  2430          *  @param site       If this is a select, the type of the selected
  2431          *                    expression, otherwise the type of the current class.
  2432          *  @param sym        The symbol representing the identifier.
  2433          *  @param env        The current environment.
  2434          *  @param pkind      The set of expected kinds.
  2435          *  @param pt         The expected type.
  2436          */
  2437         Type checkId(JCTree tree,
  2438                      Type site,
  2439                      Symbol sym,
  2440                      Env<AttrContext> env,
  2441                      int pkind,
  2442                      Type pt,
  2443                      boolean useVarargs) {
  2444             if (pt.isErroneous()) return types.createErrorType(site);
  2445             Type owntype; // The computed type of this identifier occurrence.
  2446             switch (sym.kind) {
  2447             case TYP:
  2448                 // For types, the computed type equals the symbol's type,
  2449                 // except for two situations:
  2450                 owntype = sym.type;
  2451                 if (owntype.tag == CLASS) {
  2452                     Type ownOuter = owntype.getEnclosingType();
  2454                     // (a) If the symbol's type is parameterized, erase it
  2455                     // because no type parameters were given.
  2456                     // We recover generic outer type later in visitTypeApply.
  2457                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2458                         owntype = types.erasure(owntype);
  2461                     // (b) If the symbol's type is an inner class, then
  2462                     // we have to interpret its outer type as a superclass
  2463                     // of the site type. Example:
  2464                     //
  2465                     // class Tree<A> { class Visitor { ... } }
  2466                     // class PointTree extends Tree<Point> { ... }
  2467                     // ...PointTree.Visitor...
  2468                     //
  2469                     // Then the type of the last expression above is
  2470                     // Tree<Point>.Visitor.
  2471                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2472                         Type normOuter = site;
  2473                         if (normOuter.tag == CLASS)
  2474                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2475                         if (normOuter == null) // perhaps from an import
  2476                             normOuter = types.erasure(ownOuter);
  2477                         if (normOuter != ownOuter)
  2478                             owntype = new ClassType(
  2479                                 normOuter, List.<Type>nil(), owntype.tsym);
  2482                 break;
  2483             case VAR:
  2484                 VarSymbol v = (VarSymbol)sym;
  2485                 // Test (4): if symbol is an instance field of a raw type,
  2486                 // which is being assigned to, issue an unchecked warning if
  2487                 // its type changes under erasure.
  2488                 if (allowGenerics &&
  2489                     pkind == VAR &&
  2490                     v.owner.kind == TYP &&
  2491                     (v.flags() & STATIC) == 0 &&
  2492                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2493                     Type s = types.asOuterSuper(site, v.owner);
  2494                     if (s != null &&
  2495                         s.isRaw() &&
  2496                         !types.isSameType(v.type, v.erasure(types))) {
  2497                         chk.warnUnchecked(tree.pos(),
  2498                                           "unchecked.assign.to.var",
  2499                                           v, s);
  2502                 // The computed type of a variable is the type of the
  2503                 // variable symbol, taken as a member of the site type.
  2504                 owntype = (sym.owner.kind == TYP &&
  2505                            sym.name != names._this && sym.name != names._super)
  2506                     ? types.memberType(site, sym)
  2507                     : sym.type;
  2509                 if (env.info.tvars.nonEmpty()) {
  2510                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2511                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2512                         if (!owntype.contains(l.head)) {
  2513                             log.error(tree.pos(), "undetermined.type", owntype1);
  2514                             owntype1 = types.createErrorType(owntype1);
  2516                     owntype = owntype1;
  2519                 // If the variable is a constant, record constant value in
  2520                 // computed type.
  2521                 if (v.getConstValue() != null && isStaticReference(tree))
  2522                     owntype = owntype.constType(v.getConstValue());
  2524                 if (pkind == VAL) {
  2525                     owntype = capture(owntype); // capture "names as expressions"
  2527                 break;
  2528             case MTH: {
  2529                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2530                 owntype = checkMethod(site, sym, env, app.args,
  2531                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2532                                       env.info.varArgs);
  2533                 break;
  2535             case PCK: case ERR:
  2536                 owntype = sym.type;
  2537                 break;
  2538             default:
  2539                 throw new AssertionError("unexpected kind: " + sym.kind +
  2540                                          " in tree " + tree);
  2543             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2544             // (for constructors, the error was given when the constructor was
  2545             // resolved)
  2546             if (sym.name != names.init &&
  2547                 (sym.flags() & DEPRECATED) != 0 &&
  2548                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2549                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2550                 chk.warnDeprecated(tree.pos(), sym);
  2552             if ((sym.flags() & PROPRIETARY) != 0) {
  2553                 if (enableSunApiLintControl)
  2554                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
  2555                 else
  2556                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2559             // Test (3): if symbol is a variable, check that its type and
  2560             // kind are compatible with the prototype and protokind.
  2561             return check(tree, owntype, sym.kind, pkind, pt);
  2564         /** Check that variable is initialized and evaluate the variable's
  2565          *  initializer, if not yet done. Also check that variable is not
  2566          *  referenced before it is defined.
  2567          *  @param tree    The tree making up the variable reference.
  2568          *  @param env     The current environment.
  2569          *  @param v       The variable's symbol.
  2570          */
  2571         private void checkInit(JCTree tree,
  2572                                Env<AttrContext> env,
  2573                                VarSymbol v,
  2574                                boolean onlyWarning) {
  2575 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2576 //                             tree.pos + " " + v.pos + " " +
  2577 //                             Resolve.isStatic(env));//DEBUG
  2579             // A forward reference is diagnosed if the declaration position
  2580             // of the variable is greater than the current tree position
  2581             // and the tree and variable definition occur in the same class
  2582             // definition.  Note that writes don't count as references.
  2583             // This check applies only to class and instance
  2584             // variables.  Local variables follow different scope rules,
  2585             // and are subject to definite assignment checking.
  2586             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2587                 v.owner.kind == TYP &&
  2588                 canOwnInitializer(env.info.scope.owner) &&
  2589                 v.owner == env.info.scope.owner.enclClass() &&
  2590                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2591                 (env.tree.getTag() != JCTree.ASSIGN ||
  2592                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2593                 String suffix = (env.info.enclVar == v) ?
  2594                                 "self.ref" : "forward.ref";
  2595                 if (!onlyWarning || isStaticEnumField(v)) {
  2596                     log.error(tree.pos(), "illegal." + suffix);
  2597                 } else if (useBeforeDeclarationWarning) {
  2598                     log.warning(tree.pos(), suffix, v);
  2602             v.getConstValue(); // ensure initializer is evaluated
  2604             checkEnumInitializer(tree, env, v);
  2607         /**
  2608          * Check for illegal references to static members of enum.  In
  2609          * an enum type, constructors and initializers may not
  2610          * reference its static members unless they are constant.
  2612          * @param tree    The tree making up the variable reference.
  2613          * @param env     The current environment.
  2614          * @param v       The variable's symbol.
  2615          * @see JLS 3rd Ed. (8.9 Enums)
  2616          */
  2617         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2618             // JLS 3rd Ed.:
  2619             //
  2620             // "It is a compile-time error to reference a static field
  2621             // of an enum type that is not a compile-time constant
  2622             // (15.28) from constructors, instance initializer blocks,
  2623             // or instance variable initializer expressions of that
  2624             // type. It is a compile-time error for the constructors,
  2625             // instance initializer blocks, or instance variable
  2626             // initializer expressions of an enum constant e to refer
  2627             // to itself or to an enum constant of the same type that
  2628             // is declared to the right of e."
  2629             if (isStaticEnumField(v)) {
  2630                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2632                 if (enclClass == null || enclClass.owner == null)
  2633                     return;
  2635                 // See if the enclosing class is the enum (or a
  2636                 // subclass thereof) declaring v.  If not, this
  2637                 // reference is OK.
  2638                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2639                     return;
  2641                 // If the reference isn't from an initializer, then
  2642                 // the reference is OK.
  2643                 if (!Resolve.isInitializer(env))
  2644                     return;
  2646                 log.error(tree.pos(), "illegal.enum.static.ref");
  2650         /** Is the given symbol a static, non-constant field of an Enum?
  2651          *  Note: enum literals should not be regarded as such
  2652          */
  2653         private boolean isStaticEnumField(VarSymbol v) {
  2654             return Flags.isEnum(v.owner) &&
  2655                    Flags.isStatic(v) &&
  2656                    !Flags.isConstant(v) &&
  2657                    v.name != names._class;
  2660         /** Can the given symbol be the owner of code which forms part
  2661          *  if class initialization? This is the case if the symbol is
  2662          *  a type or field, or if the symbol is the synthetic method.
  2663          *  owning a block.
  2664          */
  2665         private boolean canOwnInitializer(Symbol sym) {
  2666             return
  2667                 (sym.kind & (VAR | TYP)) != 0 ||
  2668                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2671     Warner noteWarner = new Warner();
  2673     /**
  2674      * Check that method arguments conform to its instantation.
  2675      **/
  2676     public Type checkMethod(Type site,
  2677                             Symbol sym,
  2678                             Env<AttrContext> env,
  2679                             final List<JCExpression> argtrees,
  2680                             List<Type> argtypes,
  2681                             List<Type> typeargtypes,
  2682                             boolean useVarargs) {
  2683         // Test (5): if symbol is an instance method of a raw type, issue
  2684         // an unchecked warning if its argument types change under erasure.
  2685         if (allowGenerics &&
  2686             (sym.flags() & STATIC) == 0 &&
  2687             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2688             Type s = types.asOuterSuper(site, sym.owner);
  2689             if (s != null && s.isRaw() &&
  2690                 !types.isSameTypes(sym.type.getParameterTypes(),
  2691                                    sym.erasure(types).getParameterTypes())) {
  2692                 chk.warnUnchecked(env.tree.pos(),
  2693                                   "unchecked.call.mbr.of.raw.type",
  2694                                   sym, s);
  2698         // Compute the identifier's instantiated type.
  2699         // For methods, we need to compute the instance type by
  2700         // Resolve.instantiate from the symbol's type as well as
  2701         // any type arguments and value arguments.
  2702         noteWarner.warned = false;
  2703         Type owntype = rs.instantiate(env,
  2704                                       site,
  2705                                       sym,
  2706                                       argtypes,
  2707                                       typeargtypes,
  2708                                       true,
  2709                                       useVarargs,
  2710                                       noteWarner);
  2711         boolean warned = noteWarner.warned;
  2713         // If this fails, something went wrong; we should not have
  2714         // found the identifier in the first place.
  2715         if (owntype == null) {
  2716             if (!pt.isErroneous())
  2717                 log.error(env.tree.pos(),
  2718                           "internal.error.cant.instantiate",
  2719                           sym, site,
  2720                           Type.toString(pt.getParameterTypes()));
  2721             owntype = types.createErrorType(site);
  2722         } else {
  2723             // System.out.println("call   : " + env.tree);
  2724             // System.out.println("method : " + owntype);
  2725             // System.out.println("actuals: " + argtypes);
  2726             List<Type> formals = owntype.getParameterTypes();
  2727             Type last = useVarargs ? formals.last() : null;
  2728             if (sym.name==names.init &&
  2729                 sym.owner == syms.enumSym)
  2730                 formals = formals.tail.tail;
  2731             List<JCExpression> args = argtrees;
  2732             while (formals.head != last) {
  2733                 JCTree arg = args.head;
  2734                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2735                 assertConvertible(arg, arg.type, formals.head, warn);
  2736                 warned |= warn.warned;
  2737                 args = args.tail;
  2738                 formals = formals.tail;
  2740             if (useVarargs) {
  2741                 Type varArg = types.elemtype(last);
  2742                 while (args.tail != null) {
  2743                     JCTree arg = args.head;
  2744                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2745                     assertConvertible(arg, arg.type, varArg, warn);
  2746                     warned |= warn.warned;
  2747                     args = args.tail;
  2749             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2750                 // non-varargs call to varargs method
  2751                 Type varParam = owntype.getParameterTypes().last();
  2752                 Type lastArg = argtypes.last();
  2753                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2754                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2755                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2756                                 types.elemtype(varParam),
  2757                                 varParam);
  2760             if (warned && sym.type.tag == FORALL) {
  2761                 chk.warnUnchecked(env.tree.pos(),
  2762                                   "unchecked.meth.invocation.applied",
  2763                                   kindName(sym),
  2764                                   sym.name,
  2765                                   rs.methodArguments(sym.type.getParameterTypes()),
  2766                                   rs.methodArguments(argtypes),
  2767                                   kindName(sym.location()),
  2768                                   sym.location());
  2769                 owntype = new MethodType(owntype.getParameterTypes(),
  2770                                          types.erasure(owntype.getReturnType()),
  2771                                          owntype.getThrownTypes(),
  2772                                          syms.methodClass);
  2774             if (useVarargs) {
  2775                 JCTree tree = env.tree;
  2776                 Type argtype = owntype.getParameterTypes().last();
  2777                 if (owntype.getReturnType().tag != FORALL || warned) {
  2778                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym, env);
  2780                 Type elemtype = types.elemtype(argtype);
  2781                 switch (tree.getTag()) {
  2782                 case JCTree.APPLY:
  2783                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2784                     break;
  2785                 case JCTree.NEWCLASS:
  2786                     ((JCNewClass) tree).varargsElement = elemtype;
  2787                     break;
  2788                 default:
  2789                     throw new AssertionError(""+tree);
  2793         return owntype;
  2796     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2797         if (types.isConvertible(actual, formal, warn))
  2798             return;
  2800         if (formal.isCompound()
  2801             && types.isSubtype(actual, types.supertype(formal))
  2802             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2803             return;
  2805         if (false) {
  2806             // TODO: make assertConvertible work
  2807             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2808             throw new AssertionError("Tree: " + tree
  2809                                      + " actual:" + actual
  2810                                      + " formal: " + formal);
  2814     public void visitLiteral(JCLiteral tree) {
  2815         result = check(
  2816             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2818     //where
  2819     /** Return the type of a literal with given type tag.
  2820      */
  2821     Type litType(int tag) {
  2822         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2825     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2826         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2829     public void visitTypeArray(JCArrayTypeTree tree) {
  2830         Type etype = attribType(tree.elemtype, env);
  2831         Type type = new ArrayType(etype, syms.arrayClass);
  2832         result = check(tree, type, TYP, pkind, pt);
  2835     /** Visitor method for parameterized types.
  2836      *  Bound checking is left until later, since types are attributed
  2837      *  before supertype structure is completely known
  2838      */
  2839     public void visitTypeApply(JCTypeApply tree) {
  2840         Type owntype = types.createErrorType(tree.type);
  2842         // Attribute functor part of application and make sure it's a class.
  2843         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2845         // Attribute type parameters
  2846         List<Type> actuals = attribTypes(tree.arguments, env);
  2848         if (clazztype.tag == CLASS) {
  2849             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2851             if (actuals.length() == formals.length() || actuals.length() == 0) {
  2852                 List<Type> a = actuals;
  2853                 List<Type> f = formals;
  2854                 while (a.nonEmpty()) {
  2855                     a.head = a.head.withTypeVar(f.head);
  2856                     a = a.tail;
  2857                     f = f.tail;
  2859                 // Compute the proper generic outer
  2860                 Type clazzOuter = clazztype.getEnclosingType();
  2861                 if (clazzOuter.tag == CLASS) {
  2862                     Type site;
  2863                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2864                     if (clazz.getTag() == JCTree.IDENT) {
  2865                         site = env.enclClass.sym.type;
  2866                     } else if (clazz.getTag() == JCTree.SELECT) {
  2867                         site = ((JCFieldAccess) clazz).selected.type;
  2868                     } else throw new AssertionError(""+tree);
  2869                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2870                         if (site.tag == CLASS)
  2871                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2872                         if (site == null)
  2873                             site = types.erasure(clazzOuter);
  2874                         clazzOuter = site;
  2877                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2878             } else {
  2879                 if (formals.length() != 0) {
  2880                     log.error(tree.pos(), "wrong.number.type.args",
  2881                               Integer.toString(formals.length()));
  2882                 } else {
  2883                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2885                 owntype = types.createErrorType(tree.type);
  2888         result = check(tree, owntype, TYP, pkind, pt);
  2891     public void visitTypeDisjunction(JCTypeDisjunction tree) {
  2892         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2893         for (JCExpression typeTree : tree.alternatives) {
  2894             Type ctype = attribType(typeTree, env);
  2895             ctype = chk.checkType(typeTree.pos(),
  2896                           chk.checkClassType(typeTree.pos(), ctype),
  2897                           syms.throwableType);
  2898             multicatchTypes.append(ctype);
  2900         tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2903     public void visitTypeParameter(JCTypeParameter tree) {
  2904         TypeVar a = (TypeVar)tree.type;
  2905         Set<Type> boundSet = new HashSet<Type>();
  2906         if (a.bound.isErroneous())
  2907             return;
  2908         List<Type> bs = types.getBounds(a);
  2909         if (tree.bounds.nonEmpty()) {
  2910             // accept class or interface or typevar as first bound.
  2911             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2912             boundSet.add(types.erasure(b));
  2913             if (b.isErroneous()) {
  2914                 a.bound = b;
  2916             else if (b.tag == TYPEVAR) {
  2917                 // if first bound was a typevar, do not accept further bounds.
  2918                 if (tree.bounds.tail.nonEmpty()) {
  2919                     log.error(tree.bounds.tail.head.pos(),
  2920                               "type.var.may.not.be.followed.by.other.bounds");
  2921                     tree.bounds = List.of(tree.bounds.head);
  2922                     a.bound = bs.head;
  2924             } else {
  2925                 // if first bound was a class or interface, accept only interfaces
  2926                 // as further bounds.
  2927                 for (JCExpression bound : tree.bounds.tail) {
  2928                     bs = bs.tail;
  2929                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2930                     if (i.isErroneous())
  2931                         a.bound = i;
  2932                     else if (i.tag == CLASS)
  2933                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2937         bs = types.getBounds(a);
  2939         // in case of multiple bounds ...
  2940         if (bs.length() > 1) {
  2941             // ... the variable's bound is a class type flagged COMPOUND
  2942             // (see comment for TypeVar.bound).
  2943             // In this case, generate a class tree that represents the
  2944             // bound class, ...
  2945             JCTree extending;
  2946             List<JCExpression> implementing;
  2947             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2948                 extending = tree.bounds.head;
  2949                 implementing = tree.bounds.tail;
  2950             } else {
  2951                 extending = null;
  2952                 implementing = tree.bounds;
  2954             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2955                 make.Modifiers(PUBLIC | ABSTRACT),
  2956                 tree.name, List.<JCTypeParameter>nil(),
  2957                 extending, implementing, List.<JCTree>nil());
  2959             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2960             assert (c.flags() & COMPOUND) != 0;
  2961             cd.sym = c;
  2962             c.sourcefile = env.toplevel.sourcefile;
  2964             // ... and attribute the bound class
  2965             c.flags_field |= UNATTRIBUTED;
  2966             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2967             enter.typeEnvs.put(c, cenv);
  2972     public void visitWildcard(JCWildcard tree) {
  2973         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2974         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2975             ? syms.objectType
  2976             : attribType(tree.inner, env);
  2977         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2978                                               tree.kind.kind,
  2979                                               syms.boundClass),
  2980                        TYP, pkind, pt);
  2983     public void visitAnnotation(JCAnnotation tree) {
  2984         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2985         result = tree.type = syms.errType;
  2988     public void visitAnnotatedType(JCAnnotatedType tree) {
  2989         result = tree.type = attribType(tree.getUnderlyingType(), env);
  2992     public void visitErroneous(JCErroneous tree) {
  2993         if (tree.errs != null)
  2994             for (JCTree err : tree.errs)
  2995                 attribTree(err, env, ERR, pt);
  2996         result = tree.type = syms.errType;
  2999     /** Default visitor method for all other trees.
  3000      */
  3001     public void visitTree(JCTree tree) {
  3002         throw new AssertionError();
  3005     /** Main method: attribute class definition associated with given class symbol.
  3006      *  reporting completion failures at the given position.
  3007      *  @param pos The source position at which completion errors are to be
  3008      *             reported.
  3009      *  @param c   The class symbol whose definition will be attributed.
  3010      */
  3011     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3012         try {
  3013             annotate.flush();
  3014             attribClass(c);
  3015         } catch (CompletionFailure ex) {
  3016             chk.completionError(pos, ex);
  3020     /** Attribute class definition associated with given class symbol.
  3021      *  @param c   The class symbol whose definition will be attributed.
  3022      */
  3023     void attribClass(ClassSymbol c) throws CompletionFailure {
  3024         if (c.type.tag == ERROR) return;
  3026         // Check for cycles in the inheritance graph, which can arise from
  3027         // ill-formed class files.
  3028         chk.checkNonCyclic(null, c.type);
  3030         Type st = types.supertype(c.type);
  3031         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3032             // First, attribute superclass.
  3033             if (st.tag == CLASS)
  3034                 attribClass((ClassSymbol)st.tsym);
  3036             // Next attribute owner, if it is a class.
  3037             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3038                 attribClass((ClassSymbol)c.owner);
  3041         // The previous operations might have attributed the current class
  3042         // if there was a cycle. So we test first whether the class is still
  3043         // UNATTRIBUTED.
  3044         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3045             c.flags_field &= ~UNATTRIBUTED;
  3047             // Get environment current at the point of class definition.
  3048             Env<AttrContext> env = enter.typeEnvs.get(c);
  3050             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3051             // because the annotations were not available at the time the env was created. Therefore,
  3052             // we look up the environment chain for the first enclosing environment for which the
  3053             // lint value is set. Typically, this is the parent env, but might be further if there
  3054             // are any envs created as a result of TypeParameter nodes.
  3055             Env<AttrContext> lintEnv = env;
  3056             while (lintEnv.info.lint == null)
  3057                 lintEnv = lintEnv.next;
  3059             // Having found the enclosing lint value, we can initialize the lint value for this class
  3060             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3062             Lint prevLint = chk.setLint(env.info.lint);
  3063             JavaFileObject prev = log.useSource(c.sourcefile);
  3065             try {
  3066                 // java.lang.Enum may not be subclassed by a non-enum
  3067                 if (st.tsym == syms.enumSym &&
  3068                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3069                     log.error(env.tree.pos(), "enum.no.subclassing");
  3071                 // Enums may not be extended by source-level classes
  3072                 if (st.tsym != null &&
  3073                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3074                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3075                     !target.compilerBootstrap(c)) {
  3076                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3078                 attribClassBody(env, c);
  3080                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3081             } finally {
  3082                 log.useSource(prev);
  3083                 chk.setLint(prevLint);
  3089     public void visitImport(JCImport tree) {
  3090         // nothing to do
  3093     /** Finish the attribution of a class. */
  3094     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3095         JCClassDecl tree = (JCClassDecl)env.tree;
  3096         assert c == tree.sym;
  3098         // Validate annotations
  3099         chk.validateAnnotations(tree.mods.annotations, c);
  3101         // Validate type parameters, supertype and interfaces.
  3102         attribBounds(tree.typarams);
  3103         if (!c.isAnonymous()) {
  3104             //already checked if anonymous
  3105             chk.validate(tree.typarams, env);
  3106             chk.validate(tree.extending, env);
  3107             chk.validate(tree.implementing, env);
  3110         // If this is a non-abstract class, check that it has no abstract
  3111         // methods or unimplemented methods of an implemented interface.
  3112         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3113             if (!relax)
  3114                 chk.checkAllDefined(tree.pos(), c);
  3117         if ((c.flags() & ANNOTATION) != 0) {
  3118             if (tree.implementing.nonEmpty())
  3119                 log.error(tree.implementing.head.pos(),
  3120                           "cant.extend.intf.annotation");
  3121             if (tree.typarams.nonEmpty())
  3122                 log.error(tree.typarams.head.pos(),
  3123                           "intf.annotation.cant.have.type.params");
  3124         } else {
  3125             // Check that all extended classes and interfaces
  3126             // are compatible (i.e. no two define methods with same arguments
  3127             // yet different return types).  (JLS 8.4.6.3)
  3128             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3131         // Check that class does not import the same parameterized interface
  3132         // with two different argument lists.
  3133         chk.checkClassBounds(tree.pos(), c.type);
  3135         tree.type = c.type;
  3137         boolean assertsEnabled = false;
  3138         assert assertsEnabled = true;
  3139         if (assertsEnabled) {
  3140             for (List<JCTypeParameter> l = tree.typarams;
  3141                  l.nonEmpty(); l = l.tail)
  3142                 assert env.info.scope.lookup(l.head.name).scope != null;
  3145         // Check that a generic class doesn't extend Throwable
  3146         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3147             log.error(tree.extending.pos(), "generic.throwable");
  3149         // Check that all methods which implement some
  3150         // method conform to the method they implement.
  3151         chk.checkImplementations(tree);
  3153         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3154             // Attribute declaration
  3155             attribStat(l.head, env);
  3156             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3157             // Make an exception for static constants.
  3158             if (c.owner.kind != PCK &&
  3159                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3160                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3161                 Symbol sym = null;
  3162                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3163                 if (sym == null ||
  3164                     sym.kind != VAR ||
  3165                     ((VarSymbol) sym).getConstValue() == null)
  3166                     log.error(l.head.pos(), "icls.cant.have.static.decl");
  3170         // Check for cycles among non-initial constructors.
  3171         chk.checkCyclicConstructors(tree);
  3173         // Check for cycles among annotation elements.
  3174         chk.checkNonCyclicElements(tree);
  3176         // Check for proper use of serialVersionUID
  3177         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
  3178             isSerializable(c) &&
  3179             (c.flags() & Flags.ENUM) == 0 &&
  3180             (c.flags() & ABSTRACT) == 0) {
  3181             checkSerialVersionUID(tree, c);
  3184         // Check type annotations applicability rules
  3185         validateTypeAnnotations(tree);
  3187         // where
  3188         /** check if a class is a subtype of Serializable, if that is available. */
  3189         private boolean isSerializable(ClassSymbol c) {
  3190             try {
  3191                 syms.serializableType.complete();
  3193             catch (CompletionFailure e) {
  3194                 return false;
  3196             return types.isSubtype(c.type, syms.serializableType);
  3199         /** Check that an appropriate serialVersionUID member is defined. */
  3200         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3202             // check for presence of serialVersionUID
  3203             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3204             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3205             if (e.scope == null) {
  3206                 log.warning(Lint.LintCategory.SERIAL,
  3207                         tree.pos(), "missing.SVUID", c);
  3208                 return;
  3211             // check that it is static final
  3212             VarSymbol svuid = (VarSymbol)e.sym;
  3213             if ((svuid.flags() & (STATIC | FINAL)) !=
  3214                 (STATIC | FINAL))
  3215                 log.warning(Lint.LintCategory.SERIAL,
  3216                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3218             // check that it is long
  3219             else if (svuid.type.tag != TypeTags.LONG)
  3220                 log.warning(Lint.LintCategory.SERIAL,
  3221                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3223             // check constant
  3224             else if (svuid.getConstValue() == null)
  3225                 log.warning(Lint.LintCategory.SERIAL,
  3226                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3229     private Type capture(Type type) {
  3230         return types.capture(type);
  3233     private void validateTypeAnnotations(JCTree tree) {
  3234         tree.accept(typeAnnotationsValidator);
  3236     //where
  3237     private final JCTree.Visitor typeAnnotationsValidator =
  3238         new TreeScanner() {
  3239         public void visitAnnotation(JCAnnotation tree) {
  3240             if (tree instanceof JCTypeAnnotation) {
  3241                 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
  3243             super.visitAnnotation(tree);
  3245         public void visitTypeParameter(JCTypeParameter tree) {
  3246             chk.validateTypeAnnotations(tree.annotations, true);
  3247             // don't call super. skip type annotations
  3248             scan(tree.bounds);
  3250         public void visitMethodDef(JCMethodDecl tree) {
  3251             // need to check static methods
  3252             if ((tree.sym.flags() & Flags.STATIC) != 0) {
  3253                 for (JCTypeAnnotation a : tree.receiverAnnotations) {
  3254                     if (chk.isTypeAnnotation(a, false))
  3255                         log.error(a.pos(), "annotation.type.not.applicable");
  3258             super.visitMethodDef(tree);
  3260     };
  3262     // <editor-fold desc="post-attribution visitor">
  3264     /**
  3265      * Handle missing types/symbols in an AST. This routine is useful when
  3266      * the compiler has encountered some errors (which might have ended up
  3267      * terminating attribution abruptly); if the compiler is used in fail-over
  3268      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3269      * prevents NPE to be progagated during subsequent compilation steps.
  3270      */
  3271     public void postAttr(Env<AttrContext> env) {
  3272         new PostAttrAnalyzer().scan(env.tree);
  3275     class PostAttrAnalyzer extends TreeScanner {
  3277         private void initTypeIfNeeded(JCTree that) {
  3278             if (that.type == null) {
  3279                 that.type = syms.unknownType;
  3283         @Override
  3284         public void scan(JCTree tree) {
  3285             if (tree == null) return;
  3286             if (tree instanceof JCExpression) {
  3287                 initTypeIfNeeded(tree);
  3289             super.scan(tree);
  3292         @Override
  3293         public void visitIdent(JCIdent that) {
  3294             if (that.sym == null) {
  3295                 that.sym = syms.unknownSymbol;
  3299         @Override
  3300         public void visitSelect(JCFieldAccess that) {
  3301             if (that.sym == null) {
  3302                 that.sym = syms.unknownSymbol;
  3304             super.visitSelect(that);
  3307         @Override
  3308         public void visitClassDef(JCClassDecl that) {
  3309             initTypeIfNeeded(that);
  3310             if (that.sym == null) {
  3311                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3313             super.visitClassDef(that);
  3316         @Override
  3317         public void visitMethodDef(JCMethodDecl that) {
  3318             initTypeIfNeeded(that);
  3319             if (that.sym == null) {
  3320                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3322             super.visitMethodDef(that);
  3325         @Override
  3326         public void visitVarDef(JCVariableDecl that) {
  3327             initTypeIfNeeded(that);
  3328             if (that.sym == null) {
  3329                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3330                 that.sym.adr = 0;
  3332             super.visitVarDef(that);
  3335         @Override
  3336         public void visitNewClass(JCNewClass that) {
  3337             if (that.constructor == null) {
  3338                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3340             if (that.constructorType == null) {
  3341                 that.constructorType = syms.unknownType;
  3343             super.visitNewClass(that);
  3346         @Override
  3347         public void visitBinary(JCBinary that) {
  3348             if (that.operator == null)
  3349                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3350             super.visitBinary(that);
  3353         @Override
  3354         public void visitUnary(JCUnary that) {
  3355             if (that.operator == null)
  3356                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3357             super.visitUnary(that);
  3360     // </editor-fold>

mercurial