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

Mon, 07 Feb 2011 18:10:13 +0000

author
mcimadamore
date
Mon, 07 Feb 2011 18:10:13 +0000
changeset 858
96d4226bdd60
parent 855
afe226180744
child 881
4ce95dc0b908
permissions
-rw-r--r--

7007615: java_util/generics/phase2/NameClashTest02 fails since jdk7/pit/b123.
Summary: override clash algorithm is not implemented correctly
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, 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.Lint.LintCategory;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.tree.JCTree.*;
    44 import com.sun.tools.javac.code.Type.*;
    46 import com.sun.source.tree.IdentifierTree;
    47 import com.sun.source.tree.MemberSelectTree;
    48 import com.sun.source.tree.TreeVisitor;
    49 import com.sun.source.util.SimpleTreeVisitor;
    51 import static com.sun.tools.javac.code.Flags.*;
    52 import static com.sun.tools.javac.code.Kinds.*;
    53 import static com.sun.tools.javac.code.TypeTags.*;
    55 /** This is the main context-dependent analysis phase in GJC. It
    56  *  encompasses name resolution, type checking and constant folding as
    57  *  subtasks. Some subtasks involve auxiliary classes.
    58  *  @see Check
    59  *  @see Resolve
    60  *  @see ConstFold
    61  *  @see Infer
    62  *
    63  *  <p><b>This is NOT part of any supported API.
    64  *  If you write code that depends on this, you do so at your own risk.
    65  *  This code and its internal interfaces are subject to change or
    66  *  deletion without notice.</b>
    67  */
    68 public class Attr extends JCTree.Visitor {
    69     protected static final Context.Key<Attr> attrKey =
    70         new Context.Key<Attr>();
    72     final Names names;
    73     final Log log;
    74     final Symtab syms;
    75     final Resolve rs;
    76     final Infer infer;
    77     final Check chk;
    78     final MemberEnter memberEnter;
    79     final TreeMaker make;
    80     final ConstFold cfolder;
    81     final Enter enter;
    82     final Target target;
    83     final Types types;
    84     final JCDiagnostic.Factory diags;
    85     final Annotate annotate;
    86     final DeferredLintHandler deferredLintHandler;
    88     public static Attr instance(Context context) {
    89         Attr instance = context.get(attrKey);
    90         if (instance == null)
    91             instance = new Attr(context);
    92         return instance;
    93     }
    95     protected Attr(Context context) {
    96         context.put(attrKey, this);
    98         names = Names.instance(context);
    99         log = Log.instance(context);
   100         syms = Symtab.instance(context);
   101         rs = Resolve.instance(context);
   102         chk = Check.instance(context);
   103         memberEnter = MemberEnter.instance(context);
   104         make = TreeMaker.instance(context);
   105         enter = Enter.instance(context);
   106         infer = Infer.instance(context);
   107         cfolder = ConstFold.instance(context);
   108         target = Target.instance(context);
   109         types = Types.instance(context);
   110         diags = JCDiagnostic.Factory.instance(context);
   111         annotate = Annotate.instance(context);
   112         deferredLintHandler = DeferredLintHandler.instance(context);
   114         Options options = Options.instance(context);
   116         Source source = Source.instance(context);
   117         allowGenerics = source.allowGenerics();
   118         allowVarargs = source.allowVarargs();
   119         allowEnums = source.allowEnums();
   120         allowBoxing = source.allowBoxing();
   121         allowCovariantReturns = source.allowCovariantReturns();
   122         allowAnonOuterThis = source.allowAnonOuterThis();
   123         allowStringsInSwitch = source.allowStringsInSwitch();
   124         sourceName = source.name;
   125         relax = (options.isSet("-retrofit") ||
   126                  options.isSet("-relax"));
   127         findDiamonds = options.get("findDiamond") != null &&
   128                  source.allowDiamond();
   129         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   130     }
   132     /** Switch: relax some constraints for retrofit mode.
   133      */
   134     boolean relax;
   136     /** Switch: support generics?
   137      */
   138     boolean allowGenerics;
   140     /** Switch: allow variable-arity methods.
   141      */
   142     boolean allowVarargs;
   144     /** Switch: support enums?
   145      */
   146     boolean allowEnums;
   148     /** Switch: support boxing and unboxing?
   149      */
   150     boolean allowBoxing;
   152     /** Switch: support covariant result types?
   153      */
   154     boolean allowCovariantReturns;
   156     /** Switch: allow references to surrounding object from anonymous
   157      * objects during constructor call?
   158      */
   159     boolean allowAnonOuterThis;
   161     /** Switch: generates a warning if diamond can be safely applied
   162      *  to a given new expression
   163      */
   164     boolean findDiamonds;
   166     /**
   167      * Internally enables/disables diamond finder feature
   168      */
   169     static final boolean allowDiamondFinder = true;
   171     /**
   172      * Switch: warn about use of variable before declaration?
   173      * RFE: 6425594
   174      */
   175     boolean useBeforeDeclarationWarning;
   177     /**
   178      * Switch: allow strings in switch?
   179      */
   180     boolean allowStringsInSwitch;
   182     /**
   183      * Switch: name of source level; used for error reporting.
   184      */
   185     String sourceName;
   187     /** Check kind and type of given tree against protokind and prototype.
   188      *  If check succeeds, store type in tree and return it.
   189      *  If check fails, store errType in tree and return it.
   190      *  No checks are performed if the prototype is a method type.
   191      *  It is not necessary in this case since we know that kind and type
   192      *  are correct.
   193      *
   194      *  @param tree     The tree whose kind and type is checked
   195      *  @param owntype  The computed type of the tree
   196      *  @param ownkind  The computed kind of the tree
   197      *  @param pkind    The expected kind (or: protokind) of the tree
   198      *  @param pt       The expected type (or: prototype) of the tree
   199      */
   200     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   201         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   202             if ((ownkind & ~pkind) == 0) {
   203                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
   204             } else {
   205                 log.error(tree.pos(), "unexpected.type",
   206                           kindNames(pkind),
   207                           kindName(ownkind));
   208                 owntype = types.createErrorType(owntype);
   209             }
   210         }
   211         tree.type = owntype;
   212         return owntype;
   213     }
   215     /** Is given blank final variable assignable, i.e. in a scope where it
   216      *  may be assigned to even though it is final?
   217      *  @param v      The blank final variable.
   218      *  @param env    The current environment.
   219      */
   220     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   221         Symbol owner = env.info.scope.owner;
   222            // owner refers to the innermost variable, method or
   223            // initializer block declaration at this point.
   224         return
   225             v.owner == owner
   226             ||
   227             ((owner.name == names.init ||    // i.e. we are in a constructor
   228               owner.kind == VAR ||           // i.e. we are in a variable initializer
   229               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   230              &&
   231              v.owner == owner.owner
   232              &&
   233              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   234     }
   236     /** Check that variable can be assigned to.
   237      *  @param pos    The current source code position.
   238      *  @param v      The assigned varaible
   239      *  @param base   If the variable is referred to in a Select, the part
   240      *                to the left of the `.', null otherwise.
   241      *  @param env    The current environment.
   242      */
   243     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   244         if ((v.flags() & FINAL) != 0 &&
   245             ((v.flags() & HASINIT) != 0
   246              ||
   247              !((base == null ||
   248                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   249                isAssignableAsBlankFinal(v, env)))) {
   250             if (v.isResourceVariable()) { //TWR resource
   251                 log.error(pos, "try.resource.may.not.be.assigned", v);
   252             } else {
   253                 log.error(pos, "cant.assign.val.to.final.var", v);
   254             }
   255         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
   256             v.flags_field &= ~EFFECTIVELY_FINAL;
   257         }
   258     }
   260     /** Does tree represent a static reference to an identifier?
   261      *  It is assumed that tree is either a SELECT or an IDENT.
   262      *  We have to weed out selects from non-type names here.
   263      *  @param tree    The candidate tree.
   264      */
   265     boolean isStaticReference(JCTree tree) {
   266         if (tree.getTag() == JCTree.SELECT) {
   267             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   268             if (lsym == null || lsym.kind != TYP) {
   269                 return false;
   270             }
   271         }
   272         return true;
   273     }
   275     /** Is this symbol a type?
   276      */
   277     static boolean isType(Symbol sym) {
   278         return sym != null && sym.kind == TYP;
   279     }
   281     /** The current `this' symbol.
   282      *  @param env    The current environment.
   283      */
   284     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   285         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   286     }
   288     /** Attribute a parsed identifier.
   289      * @param tree Parsed identifier name
   290      * @param topLevel The toplevel to use
   291      */
   292     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   293         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   294         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   295                                            syms.errSymbol.name,
   296                                            null, null, null, null);
   297         localEnv.enclClass.sym = syms.errSymbol;
   298         return tree.accept(identAttributer, localEnv);
   299     }
   300     // where
   301         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   302         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   303             @Override
   304             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   305                 Symbol site = visit(node.getExpression(), env);
   306                 if (site.kind == ERR)
   307                     return site;
   308                 Name name = (Name)node.getIdentifier();
   309                 if (site.kind == PCK) {
   310                     env.toplevel.packge = (PackageSymbol)site;
   311                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   312                 } else {
   313                     env.enclClass.sym = (ClassSymbol)site;
   314                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   315                 }
   316             }
   318             @Override
   319             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   320                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   321             }
   322         }
   324     public Type coerce(Type etype, Type ttype) {
   325         return cfolder.coerce(etype, ttype);
   326     }
   328     public Type attribType(JCTree node, TypeSymbol sym) {
   329         Env<AttrContext> env = enter.typeEnvs.get(sym);
   330         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   331         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   332     }
   334     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   335         breakTree = tree;
   336         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   337         try {
   338             attribExpr(expr, env);
   339         } catch (BreakAttr b) {
   340             return b.env;
   341         } catch (AssertionError ae) {
   342             if (ae.getCause() instanceof BreakAttr) {
   343                 return ((BreakAttr)(ae.getCause())).env;
   344             } else {
   345                 throw ae;
   346             }
   347         } finally {
   348             breakTree = null;
   349             log.useSource(prev);
   350         }
   351         return env;
   352     }
   354     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   355         breakTree = tree;
   356         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   357         try {
   358             attribStat(stmt, env);
   359         } catch (BreakAttr b) {
   360             return b.env;
   361         } catch (AssertionError ae) {
   362             if (ae.getCause() instanceof BreakAttr) {
   363                 return ((BreakAttr)(ae.getCause())).env;
   364             } else {
   365                 throw ae;
   366             }
   367         } finally {
   368             breakTree = null;
   369             log.useSource(prev);
   370         }
   371         return env;
   372     }
   374     private JCTree breakTree = null;
   376     private static class BreakAttr extends RuntimeException {
   377         static final long serialVersionUID = -6924771130405446405L;
   378         private Env<AttrContext> env;
   379         private BreakAttr(Env<AttrContext> env) {
   380             this.env = env;
   381         }
   382     }
   385 /* ************************************************************************
   386  * Visitor methods
   387  *************************************************************************/
   389     /** Visitor argument: the current environment.
   390      */
   391     Env<AttrContext> env;
   393     /** Visitor argument: the currently expected proto-kind.
   394      */
   395     int pkind;
   397     /** Visitor argument: the currently expected proto-type.
   398      */
   399     Type pt;
   401     /** Visitor argument: the error key to be generated when a type error occurs
   402      */
   403     String errKey;
   405     /** Visitor result: the computed type.
   406      */
   407     Type result;
   409     /** Visitor method: attribute a tree, catching any completion failure
   410      *  exceptions. Return the tree's type.
   411      *
   412      *  @param tree    The tree to be visited.
   413      *  @param env     The environment visitor argument.
   414      *  @param pkind   The protokind visitor argument.
   415      *  @param pt      The prototype visitor argument.
   416      */
   417     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   418         return attribTree(tree, env, pkind, pt, "incompatible.types");
   419     }
   421     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
   422         Env<AttrContext> prevEnv = this.env;
   423         int prevPkind = this.pkind;
   424         Type prevPt = this.pt;
   425         String prevErrKey = this.errKey;
   426         try {
   427             this.env = env;
   428             this.pkind = pkind;
   429             this.pt = pt;
   430             this.errKey = errKey;
   431             tree.accept(this);
   432             if (tree == breakTree)
   433                 throw new BreakAttr(env);
   434             return result;
   435         } catch (CompletionFailure ex) {
   436             tree.type = syms.errType;
   437             return chk.completionError(tree.pos(), ex);
   438         } finally {
   439             this.env = prevEnv;
   440             this.pkind = prevPkind;
   441             this.pt = prevPt;
   442             this.errKey = prevErrKey;
   443         }
   444     }
   446     /** Derived visitor method: attribute an expression tree.
   447      */
   448     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   449         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   450     }
   452     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
   453         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
   454     }
   456     /** Derived visitor method: attribute an expression tree with
   457      *  no constraints on the computed type.
   458      */
   459     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   460         return attribTree(tree, env, VAL, Type.noType);
   461     }
   463     /** Derived visitor method: attribute a type tree.
   464      */
   465     Type attribType(JCTree tree, Env<AttrContext> env) {
   466         Type result = attribType(tree, env, Type.noType);
   467         return result;
   468     }
   470     /** Derived visitor method: attribute a type tree.
   471      */
   472     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   473         Type result = attribTree(tree, env, TYP, pt);
   474         return result;
   475     }
   477     /** Derived visitor method: attribute a statement or definition tree.
   478      */
   479     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   480         return attribTree(tree, env, NIL, Type.noType);
   481     }
   483     /** Attribute a list of expressions, returning a list of types.
   484      */
   485     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   486         ListBuffer<Type> ts = new ListBuffer<Type>();
   487         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   488             ts.append(attribExpr(l.head, env, pt));
   489         return ts.toList();
   490     }
   492     /** Attribute a list of statements, returning nothing.
   493      */
   494     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   495         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   496             attribStat(l.head, env);
   497     }
   499     /** Attribute the arguments in a method call, returning a list of types.
   500      */
   501     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   502         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   503         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   504             argtypes.append(chk.checkNonVoid(
   505                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   506         return argtypes.toList();
   507     }
   509     /** Attribute a type argument list, returning a list of types.
   510      *  Caller is responsible for calling checkRefTypes.
   511      */
   512     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   513         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   514         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   515             argtypes.append(attribType(l.head, env));
   516         return argtypes.toList();
   517     }
   519     /** Attribute a type argument list, returning a list of types.
   520      *  Check that all the types are references.
   521      */
   522     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   523         List<Type> types = attribAnyTypes(trees, env);
   524         return chk.checkRefTypes(trees, types);
   525     }
   527     /**
   528      * Attribute type variables (of generic classes or methods).
   529      * Compound types are attributed later in attribBounds.
   530      * @param typarams the type variables to enter
   531      * @param env      the current environment
   532      */
   533     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   534         for (JCTypeParameter tvar : typarams) {
   535             TypeVar a = (TypeVar)tvar.type;
   536             a.tsym.flags_field |= UNATTRIBUTED;
   537             a.bound = Type.noType;
   538             if (!tvar.bounds.isEmpty()) {
   539                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   540                 for (JCExpression bound : tvar.bounds.tail)
   541                     bounds = bounds.prepend(attribType(bound, env));
   542                 types.setBounds(a, bounds.reverse());
   543             } else {
   544                 // if no bounds are given, assume a single bound of
   545                 // java.lang.Object.
   546                 types.setBounds(a, List.of(syms.objectType));
   547             }
   548             a.tsym.flags_field &= ~UNATTRIBUTED;
   549         }
   550         for (JCTypeParameter tvar : typarams)
   551             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   552         attribStats(typarams, env);
   553     }
   555     void attribBounds(List<JCTypeParameter> typarams) {
   556         for (JCTypeParameter typaram : typarams) {
   557             Type bound = typaram.type.getUpperBound();
   558             if (bound != null && bound.tsym instanceof ClassSymbol) {
   559                 ClassSymbol c = (ClassSymbol)bound.tsym;
   560                 if ((c.flags_field & COMPOUND) != 0) {
   561                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   562                     attribClass(typaram.pos(), c);
   563                 }
   564             }
   565         }
   566     }
   568     /**
   569      * Attribute the type references in a list of annotations.
   570      */
   571     void attribAnnotationTypes(List<JCAnnotation> annotations,
   572                                Env<AttrContext> env) {
   573         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   574             JCAnnotation a = al.head;
   575             attribType(a.annotationType, env);
   576         }
   577     }
   579     /**
   580      * Attribute a "lazy constant value".
   581      *  @param env         The env for the const value
   582      *  @param initializer The initializer for the const value
   583      *  @param type        The expected type, or null
   584      *  @see VarSymbol#setlazyConstValue
   585      */
   586     public Object attribLazyConstantValue(Env<AttrContext> env,
   587                                       JCTree.JCExpression initializer,
   588                                       Type type) {
   590         // in case no lint value has been set up for this env, scan up
   591         // env stack looking for smallest enclosing env for which it is set.
   592         Env<AttrContext> lintEnv = env;
   593         while (lintEnv.info.lint == null)
   594             lintEnv = lintEnv.next;
   596         // Having found the enclosing lint value, we can initialize the lint value for this class
   597         env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.attributes_field, env.info.enclVar.flags());
   599         Lint prevLint = chk.setLint(env.info.lint);
   600         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   602         try {
   603             Type itype = attribExpr(initializer, env, type);
   604             if (itype.constValue() != null)
   605                 return coerce(itype, type).constValue();
   606             else
   607                 return null;
   608         } finally {
   609             env.info.lint = prevLint;
   610             log.useSource(prevSource);
   611         }
   612     }
   614     /** Attribute type reference in an `extends' or `implements' clause.
   615      *  Supertypes of anonymous inner classes are usually already attributed.
   616      *
   617      *  @param tree              The tree making up the type reference.
   618      *  @param env               The environment current at the reference.
   619      *  @param classExpected     true if only a class is expected here.
   620      *  @param interfaceExpected true if only an interface is expected here.
   621      */
   622     Type attribBase(JCTree tree,
   623                     Env<AttrContext> env,
   624                     boolean classExpected,
   625                     boolean interfaceExpected,
   626                     boolean checkExtensible) {
   627         Type t = tree.type != null ?
   628             tree.type :
   629             attribType(tree, env);
   630         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   631     }
   632     Type checkBase(Type t,
   633                    JCTree tree,
   634                    Env<AttrContext> env,
   635                    boolean classExpected,
   636                    boolean interfaceExpected,
   637                    boolean checkExtensible) {
   638         if (t.isErroneous())
   639             return t;
   640         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   641             // check that type variable is already visible
   642             if (t.getUpperBound() == null) {
   643                 log.error(tree.pos(), "illegal.forward.ref");
   644                 return types.createErrorType(t);
   645             }
   646         } else {
   647             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   648         }
   649         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   650             log.error(tree.pos(), "intf.expected.here");
   651             // return errType is necessary since otherwise there might
   652             // be undetected cycles which cause attribution to loop
   653             return types.createErrorType(t);
   654         } else if (checkExtensible &&
   655                    classExpected &&
   656                    (t.tsym.flags() & INTERFACE) != 0) {
   657                 log.error(tree.pos(), "no.intf.expected.here");
   658             return types.createErrorType(t);
   659         }
   660         if (checkExtensible &&
   661             ((t.tsym.flags() & FINAL) != 0)) {
   662             log.error(tree.pos(),
   663                       "cant.inherit.from.final", t.tsym);
   664         }
   665         chk.checkNonCyclic(tree.pos(), t);
   666         return t;
   667     }
   669     public void visitClassDef(JCClassDecl tree) {
   670         // Local classes have not been entered yet, so we need to do it now:
   671         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   672             enter.classEnter(tree, env);
   674         ClassSymbol c = tree.sym;
   675         if (c == null) {
   676             // exit in case something drastic went wrong during enter.
   677             result = null;
   678         } else {
   679             // make sure class has been completed:
   680             c.complete();
   682             // If this class appears as an anonymous class
   683             // in a superclass constructor call where
   684             // no explicit outer instance is given,
   685             // disable implicit outer instance from being passed.
   686             // (This would be an illegal access to "this before super").
   687             if (env.info.isSelfCall &&
   688                 env.tree.getTag() == JCTree.NEWCLASS &&
   689                 ((JCNewClass) env.tree).encl == null)
   690             {
   691                 c.flags_field |= NOOUTERTHIS;
   692             }
   693             attribClass(tree.pos(), c);
   694             result = tree.type = c.type;
   695         }
   696     }
   698     public void visitMethodDef(JCMethodDecl tree) {
   699         MethodSymbol m = tree.sym;
   701         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   702         Lint prevLint = chk.setLint(lint);
   703         MethodSymbol prevMethod = chk.setMethod(m);
   704         try {
   705             deferredLintHandler.flush(tree.pos());
   706             chk.checkDeprecatedAnnotation(tree.pos(), m);
   708             attribBounds(tree.typarams);
   710             // If we override any other methods, check that we do so properly.
   711             // JLS ???
   712             if (m.isStatic()) {
   713                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   714             } else {
   715                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   716             }
   717             chk.checkOverride(tree, m);
   719             // Create a new environment with local scope
   720             // for attributing the method.
   721             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   723             localEnv.info.lint = lint;
   725             // Enter all type parameters into the local method scope.
   726             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   727                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   729             ClassSymbol owner = env.enclClass.sym;
   730             if ((owner.flags() & ANNOTATION) != 0 &&
   731                 tree.params.nonEmpty())
   732                 log.error(tree.params.head.pos(),
   733                           "intf.annotation.members.cant.have.params");
   735             // Attribute all value parameters.
   736             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   737                 attribStat(l.head, localEnv);
   738             }
   740             chk.checkVarargsMethodDecl(localEnv, tree);
   742             // Check that type parameters are well-formed.
   743             chk.validate(tree.typarams, localEnv);
   745             // Check that result type is well-formed.
   746             chk.validate(tree.restype, localEnv);
   748             // annotation method checks
   749             if ((owner.flags() & ANNOTATION) != 0) {
   750                 // annotation method cannot have throws clause
   751                 if (tree.thrown.nonEmpty()) {
   752                     log.error(tree.thrown.head.pos(),
   753                             "throws.not.allowed.in.intf.annotation");
   754                 }
   755                 // annotation method cannot declare type-parameters
   756                 if (tree.typarams.nonEmpty()) {
   757                     log.error(tree.typarams.head.pos(),
   758                             "intf.annotation.members.cant.have.type.params");
   759                 }
   760                 // validate annotation method's return type (could be an annotation type)
   761                 chk.validateAnnotationType(tree.restype);
   762                 // ensure that annotation method does not clash with members of Object/Annotation
   763                 chk.validateAnnotationMethod(tree.pos(), m);
   765                 if (tree.defaultValue != null) {
   766                     // if default value is an annotation, check it is a well-formed
   767                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   768                     chk.validateAnnotationTree(tree.defaultValue);
   769                 }
   770             }
   772             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   773                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   775             if (tree.body == null) {
   776                 // Empty bodies are only allowed for
   777                 // abstract, native, or interface methods, or for methods
   778                 // in a retrofit signature class.
   779                 if ((owner.flags() & INTERFACE) == 0 &&
   780                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   781                     !relax)
   782                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   783                 if (tree.defaultValue != null) {
   784                     if ((owner.flags() & ANNOTATION) == 0)
   785                         log.error(tree.pos(),
   786                                   "default.allowed.in.intf.annotation.member");
   787                 }
   788             } else if ((owner.flags() & INTERFACE) != 0) {
   789                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   790             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   791                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   792             } else if ((tree.mods.flags & NATIVE) != 0) {
   793                 log.error(tree.pos(), "native.meth.cant.have.body");
   794             } else {
   795                 // Add an implicit super() call unless an explicit call to
   796                 // super(...) or this(...) is given
   797                 // or we are compiling class java.lang.Object.
   798                 if (tree.name == names.init && owner.type != syms.objectType) {
   799                     JCBlock body = tree.body;
   800                     if (body.stats.isEmpty() ||
   801                         !TreeInfo.isSelfCall(body.stats.head)) {
   802                         body.stats = body.stats.
   803                             prepend(memberEnter.SuperCall(make.at(body.pos),
   804                                                           List.<Type>nil(),
   805                                                           List.<JCVariableDecl>nil(),
   806                                                           false));
   807                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   808                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   809                                TreeInfo.isSuperCall(body.stats.head)) {
   810                         // enum constructors are not allowed to call super
   811                         // directly, so make sure there aren't any super calls
   812                         // in enum constructors, except in the compiler
   813                         // generated one.
   814                         log.error(tree.body.stats.head.pos(),
   815                                   "call.to.super.not.allowed.in.enum.ctor",
   816                                   env.enclClass.sym);
   817                     }
   818                 }
   820                 // Attribute method body.
   821                 attribStat(tree.body, localEnv);
   822             }
   823             localEnv.info.scope.leave();
   824             result = tree.type = m.type;
   825             chk.validateAnnotations(tree.mods.annotations, m);
   826         }
   827         finally {
   828             chk.setLint(prevLint);
   829             chk.setMethod(prevMethod);
   830         }
   831     }
   833     public void visitVarDef(JCVariableDecl tree) {
   834         // Local variables have not been entered yet, so we need to do it now:
   835         if (env.info.scope.owner.kind == MTH) {
   836             if (tree.sym != null) {
   837                 // parameters have already been entered
   838                 env.info.scope.enter(tree.sym);
   839             } else {
   840                 memberEnter.memberEnter(tree, env);
   841                 annotate.flush();
   842             }
   843             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   844         }
   846         VarSymbol v = tree.sym;
   847         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   848         Lint prevLint = chk.setLint(lint);
   850         // Check that the variable's declared type is well-formed.
   851         chk.validate(tree.vartype, env);
   852         deferredLintHandler.flush(tree.pos());
   854         try {
   855             chk.checkDeprecatedAnnotation(tree.pos(), v);
   857             if (tree.init != null) {
   858                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   859                     // In this case, `v' is final.  Ensure that it's initializer is
   860                     // evaluated.
   861                     v.getConstValue(); // ensure initializer is evaluated
   862                 } else {
   863                     // Attribute initializer in a new environment
   864                     // with the declared variable as owner.
   865                     // Check that initializer conforms to variable's declared type.
   866                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   867                     initEnv.info.lint = lint;
   868                     // In order to catch self-references, we set the variable's
   869                     // declaration position to maximal possible value, effectively
   870                     // marking the variable as undefined.
   871                     initEnv.info.enclVar = v;
   872                     attribExpr(tree.init, initEnv, v.type);
   873                 }
   874             }
   875             result = tree.type = v.type;
   876             chk.validateAnnotations(tree.mods.annotations, v);
   877         }
   878         finally {
   879             chk.setLint(prevLint);
   880         }
   881     }
   883     public void visitSkip(JCSkip tree) {
   884         result = null;
   885     }
   887     public void visitBlock(JCBlock tree) {
   888         if (env.info.scope.owner.kind == TYP) {
   889             // Block is a static or instance initializer;
   890             // let the owner of the environment be a freshly
   891             // created BLOCK-method.
   892             Env<AttrContext> localEnv =
   893                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   894             localEnv.info.scope.owner =
   895                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   896                                  env.info.scope.owner);
   897             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   898             attribStats(tree.stats, localEnv);
   899         } else {
   900             // Create a new local environment with a local scope.
   901             Env<AttrContext> localEnv =
   902                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   903             attribStats(tree.stats, localEnv);
   904             localEnv.info.scope.leave();
   905         }
   906         result = null;
   907     }
   909     public void visitDoLoop(JCDoWhileLoop tree) {
   910         attribStat(tree.body, env.dup(tree));
   911         attribExpr(tree.cond, env, syms.booleanType);
   912         result = null;
   913     }
   915     public void visitWhileLoop(JCWhileLoop tree) {
   916         attribExpr(tree.cond, env, syms.booleanType);
   917         attribStat(tree.body, env.dup(tree));
   918         result = null;
   919     }
   921     public void visitForLoop(JCForLoop tree) {
   922         Env<AttrContext> loopEnv =
   923             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   924         attribStats(tree.init, loopEnv);
   925         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   926         loopEnv.tree = tree; // before, we were not in loop!
   927         attribStats(tree.step, loopEnv);
   928         attribStat(tree.body, loopEnv);
   929         loopEnv.info.scope.leave();
   930         result = null;
   931     }
   933     public void visitForeachLoop(JCEnhancedForLoop tree) {
   934         Env<AttrContext> loopEnv =
   935             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   936         attribStat(tree.var, loopEnv);
   937         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   938         chk.checkNonVoid(tree.pos(), exprType);
   939         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   940         if (elemtype == null) {
   941             // or perhaps expr implements Iterable<T>?
   942             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   943             if (base == null) {
   944                 log.error(tree.expr.pos(),
   945                         "foreach.not.applicable.to.type",
   946                         exprType,
   947                         diags.fragment("type.req.array.or.iterable"));
   948                 elemtype = types.createErrorType(exprType);
   949             } else {
   950                 List<Type> iterableParams = base.allparams();
   951                 elemtype = iterableParams.isEmpty()
   952                     ? syms.objectType
   953                     : types.upperBound(iterableParams.head);
   954             }
   955         }
   956         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   957         loopEnv.tree = tree; // before, we were not in loop!
   958         attribStat(tree.body, loopEnv);
   959         loopEnv.info.scope.leave();
   960         result = null;
   961     }
   963     public void visitLabelled(JCLabeledStatement tree) {
   964         // Check that label is not used in an enclosing statement
   965         Env<AttrContext> env1 = env;
   966         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   967             if (env1.tree.getTag() == JCTree.LABELLED &&
   968                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   969                 log.error(tree.pos(), "label.already.in.use",
   970                           tree.label);
   971                 break;
   972             }
   973             env1 = env1.next;
   974         }
   976         attribStat(tree.body, env.dup(tree));
   977         result = null;
   978     }
   980     public void visitSwitch(JCSwitch tree) {
   981         Type seltype = attribExpr(tree.selector, env);
   983         Env<AttrContext> switchEnv =
   984             env.dup(tree, env.info.dup(env.info.scope.dup()));
   986         boolean enumSwitch =
   987             allowEnums &&
   988             (seltype.tsym.flags() & Flags.ENUM) != 0;
   989         boolean stringSwitch = false;
   990         if (types.isSameType(seltype, syms.stringType)) {
   991             if (allowStringsInSwitch) {
   992                 stringSwitch = true;
   993             } else {
   994                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   995             }
   996         }
   997         if (!enumSwitch && !stringSwitch)
   998             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1000         // Attribute all cases and
  1001         // check that there are no duplicate case labels or default clauses.
  1002         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1003         boolean hasDefault = false;      // Is there a default label?
  1004         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1005             JCCase c = l.head;
  1006             Env<AttrContext> caseEnv =
  1007                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1008             if (c.pat != null) {
  1009                 if (enumSwitch) {
  1010                     Symbol sym = enumConstant(c.pat, seltype);
  1011                     if (sym == null) {
  1012                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1013                     } else if (!labels.add(sym)) {
  1014                         log.error(c.pos(), "duplicate.case.label");
  1016                 } else {
  1017                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1018                     if (pattype.tag != ERROR) {
  1019                         if (pattype.constValue() == null) {
  1020                             log.error(c.pat.pos(),
  1021                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
  1022                         } else if (labels.contains(pattype.constValue())) {
  1023                             log.error(c.pos(), "duplicate.case.label");
  1024                         } else {
  1025                             labels.add(pattype.constValue());
  1029             } else if (hasDefault) {
  1030                 log.error(c.pos(), "duplicate.default.label");
  1031             } else {
  1032                 hasDefault = true;
  1034             attribStats(c.stats, caseEnv);
  1035             caseEnv.info.scope.leave();
  1036             addVars(c.stats, switchEnv.info.scope);
  1039         switchEnv.info.scope.leave();
  1040         result = null;
  1042     // where
  1043         /** Add any variables defined in stats to the switch scope. */
  1044         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1045             for (;stats.nonEmpty(); stats = stats.tail) {
  1046                 JCTree stat = stats.head;
  1047                 if (stat.getTag() == JCTree.VARDEF)
  1048                     switchScope.enter(((JCVariableDecl) stat).sym);
  1051     // where
  1052     /** Return the selected enumeration constant symbol, or null. */
  1053     private Symbol enumConstant(JCTree tree, Type enumType) {
  1054         if (tree.getTag() != JCTree.IDENT) {
  1055             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1056             return syms.errSymbol;
  1058         JCIdent ident = (JCIdent)tree;
  1059         Name name = ident.name;
  1060         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1061              e.scope != null; e = e.next()) {
  1062             if (e.sym.kind == VAR) {
  1063                 Symbol s = ident.sym = e.sym;
  1064                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1065                 ident.type = s.type;
  1066                 return ((s.flags_field & Flags.ENUM) == 0)
  1067                     ? null : s;
  1070         return null;
  1073     public void visitSynchronized(JCSynchronized tree) {
  1074         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1075         attribStat(tree.body, env);
  1076         result = null;
  1079     public void visitTry(JCTry tree) {
  1080         // Create a new local environment with a local
  1081         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1082         boolean isTryWithResource = tree.resources.nonEmpty();
  1083         // Create a nested environment for attributing the try block if needed
  1084         Env<AttrContext> tryEnv = isTryWithResource ?
  1085             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1086             localEnv;
  1087         // Attribute resource declarations
  1088         for (JCTree resource : tree.resources) {
  1089             if (resource.getTag() == JCTree.VARDEF) {
  1090                 attribStat(resource, tryEnv);
  1091                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1092                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1093                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1094             } else {
  1095                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1098         // Attribute body
  1099         attribStat(tree.body, tryEnv);
  1100         if (isTryWithResource)
  1101             tryEnv.info.scope.leave();
  1103         // Attribute catch clauses
  1104         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1105             JCCatch c = l.head;
  1106             Env<AttrContext> catchEnv =
  1107                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1108             Type ctype = attribStat(c.param, catchEnv);
  1109             if (TreeInfo.isMultiCatch(c)) {
  1110                 //multi-catch parameter is implicitly marked as final
  1111                 c.param.sym.flags_field |= FINAL | DISJUNCTION;
  1113             if (c.param.sym.kind == Kinds.VAR) {
  1114                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1116             chk.checkType(c.param.vartype.pos(),
  1117                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1118                           syms.throwableType);
  1119             attribStat(c.body, catchEnv);
  1120             catchEnv.info.scope.leave();
  1123         // Attribute finalizer
  1124         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1126         localEnv.info.scope.leave();
  1127         result = null;
  1130     public void visitConditional(JCConditional tree) {
  1131         attribExpr(tree.cond, env, syms.booleanType);
  1132         attribExpr(tree.truepart, env);
  1133         attribExpr(tree.falsepart, env);
  1134         result = check(tree,
  1135                        capture(condType(tree.pos(), tree.cond.type,
  1136                                         tree.truepart.type, tree.falsepart.type)),
  1137                        VAL, pkind, pt);
  1139     //where
  1140         /** Compute the type of a conditional expression, after
  1141          *  checking that it exists. See Spec 15.25.
  1143          *  @param pos      The source position to be used for
  1144          *                  error diagnostics.
  1145          *  @param condtype The type of the expression's condition.
  1146          *  @param thentype The type of the expression's then-part.
  1147          *  @param elsetype The type of the expression's else-part.
  1148          */
  1149         private Type condType(DiagnosticPosition pos,
  1150                               Type condtype,
  1151                               Type thentype,
  1152                               Type elsetype) {
  1153             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1155             // If condition and both arms are numeric constants,
  1156             // evaluate at compile-time.
  1157             return ((condtype.constValue() != null) &&
  1158                     (thentype.constValue() != null) &&
  1159                     (elsetype.constValue() != null))
  1160                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1161                 : ctype;
  1163         /** Compute the type of a conditional expression, after
  1164          *  checking that it exists.  Does not take into
  1165          *  account the special case where condition and both arms
  1166          *  are constants.
  1168          *  @param pos      The source position to be used for error
  1169          *                  diagnostics.
  1170          *  @param condtype The type of the expression's condition.
  1171          *  @param thentype The type of the expression's then-part.
  1172          *  @param elsetype The type of the expression's else-part.
  1173          */
  1174         private Type condType1(DiagnosticPosition pos, Type condtype,
  1175                                Type thentype, Type elsetype) {
  1176             // If same type, that is the result
  1177             if (types.isSameType(thentype, elsetype))
  1178                 return thentype.baseType();
  1180             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1181                 ? thentype : types.unboxedType(thentype);
  1182             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1183                 ? elsetype : types.unboxedType(elsetype);
  1185             // Otherwise, if both arms can be converted to a numeric
  1186             // type, return the least numeric type that fits both arms
  1187             // (i.e. return larger of the two, or return int if one
  1188             // arm is short, the other is char).
  1189             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1190                 // If one arm has an integer subrange type (i.e., byte,
  1191                 // short, or char), and the other is an integer constant
  1192                 // that fits into the subrange, return the subrange type.
  1193                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1194                     types.isAssignable(elseUnboxed, thenUnboxed))
  1195                     return thenUnboxed.baseType();
  1196                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1197                     types.isAssignable(thenUnboxed, elseUnboxed))
  1198                     return elseUnboxed.baseType();
  1200                 for (int i = BYTE; i < VOID; i++) {
  1201                     Type candidate = syms.typeOfTag[i];
  1202                     if (types.isSubtype(thenUnboxed, candidate) &&
  1203                         types.isSubtype(elseUnboxed, candidate))
  1204                         return candidate;
  1208             // Those were all the cases that could result in a primitive
  1209             if (allowBoxing) {
  1210                 if (thentype.isPrimitive())
  1211                     thentype = types.boxedClass(thentype).type;
  1212                 if (elsetype.isPrimitive())
  1213                     elsetype = types.boxedClass(elsetype).type;
  1216             if (types.isSubtype(thentype, elsetype))
  1217                 return elsetype.baseType();
  1218             if (types.isSubtype(elsetype, thentype))
  1219                 return thentype.baseType();
  1221             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1222                 log.error(pos, "neither.conditional.subtype",
  1223                           thentype, elsetype);
  1224                 return thentype.baseType();
  1227             // both are known to be reference types.  The result is
  1228             // lub(thentype,elsetype). This cannot fail, as it will
  1229             // always be possible to infer "Object" if nothing better.
  1230             return types.lub(thentype.baseType(), elsetype.baseType());
  1233     public void visitIf(JCIf tree) {
  1234         attribExpr(tree.cond, env, syms.booleanType);
  1235         attribStat(tree.thenpart, env);
  1236         if (tree.elsepart != null)
  1237             attribStat(tree.elsepart, env);
  1238         chk.checkEmptyIf(tree);
  1239         result = null;
  1242     public void visitExec(JCExpressionStatement tree) {
  1243         //a fresh environment is required for 292 inference to work properly ---
  1244         //see Infer.instantiatePolymorphicSignatureInstance()
  1245         Env<AttrContext> localEnv = env.dup(tree);
  1246         attribExpr(tree.expr, localEnv);
  1247         result = null;
  1250     public void visitBreak(JCBreak tree) {
  1251         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1252         result = null;
  1255     public void visitContinue(JCContinue tree) {
  1256         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1257         result = null;
  1259     //where
  1260         /** Return the target of a break or continue statement, if it exists,
  1261          *  report an error if not.
  1262          *  Note: The target of a labelled break or continue is the
  1263          *  (non-labelled) statement tree referred to by the label,
  1264          *  not the tree representing the labelled statement itself.
  1266          *  @param pos     The position to be used for error diagnostics
  1267          *  @param tag     The tag of the jump statement. This is either
  1268          *                 Tree.BREAK or Tree.CONTINUE.
  1269          *  @param label   The label of the jump statement, or null if no
  1270          *                 label is given.
  1271          *  @param env     The environment current at the jump statement.
  1272          */
  1273         private JCTree findJumpTarget(DiagnosticPosition pos,
  1274                                     int tag,
  1275                                     Name label,
  1276                                     Env<AttrContext> env) {
  1277             // Search environments outwards from the point of jump.
  1278             Env<AttrContext> env1 = env;
  1279             LOOP:
  1280             while (env1 != null) {
  1281                 switch (env1.tree.getTag()) {
  1282                 case JCTree.LABELLED:
  1283                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1284                     if (label == labelled.label) {
  1285                         // If jump is a continue, check that target is a loop.
  1286                         if (tag == JCTree.CONTINUE) {
  1287                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1288                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1289                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1290                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1291                                 log.error(pos, "not.loop.label", label);
  1292                             // Found labelled statement target, now go inwards
  1293                             // to next non-labelled tree.
  1294                             return TreeInfo.referencedStatement(labelled);
  1295                         } else {
  1296                             return labelled;
  1299                     break;
  1300                 case JCTree.DOLOOP:
  1301                 case JCTree.WHILELOOP:
  1302                 case JCTree.FORLOOP:
  1303                 case JCTree.FOREACHLOOP:
  1304                     if (label == null) return env1.tree;
  1305                     break;
  1306                 case JCTree.SWITCH:
  1307                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1308                     break;
  1309                 case JCTree.METHODDEF:
  1310                 case JCTree.CLASSDEF:
  1311                     break LOOP;
  1312                 default:
  1314                 env1 = env1.next;
  1316             if (label != null)
  1317                 log.error(pos, "undef.label", label);
  1318             else if (tag == JCTree.CONTINUE)
  1319                 log.error(pos, "cont.outside.loop");
  1320             else
  1321                 log.error(pos, "break.outside.switch.loop");
  1322             return null;
  1325     public void visitReturn(JCReturn tree) {
  1326         // Check that there is an enclosing method which is
  1327         // nested within than the enclosing class.
  1328         if (env.enclMethod == null ||
  1329             env.enclMethod.sym.owner != env.enclClass.sym) {
  1330             log.error(tree.pos(), "ret.outside.meth");
  1332         } else {
  1333             // Attribute return expression, if it exists, and check that
  1334             // it conforms to result type of enclosing method.
  1335             Symbol m = env.enclMethod.sym;
  1336             if (m.type.getReturnType().tag == VOID) {
  1337                 if (tree.expr != null)
  1338                     log.error(tree.expr.pos(),
  1339                               "cant.ret.val.from.meth.decl.void");
  1340             } else if (tree.expr == null) {
  1341                 log.error(tree.pos(), "missing.ret.val");
  1342             } else {
  1343                 attribExpr(tree.expr, env, m.type.getReturnType());
  1346         result = null;
  1349     public void visitThrow(JCThrow tree) {
  1350         attribExpr(tree.expr, env, syms.throwableType);
  1351         result = null;
  1354     public void visitAssert(JCAssert tree) {
  1355         attribExpr(tree.cond, env, syms.booleanType);
  1356         if (tree.detail != null) {
  1357             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1359         result = null;
  1362      /** Visitor method for method invocations.
  1363      *  NOTE: The method part of an application will have in its type field
  1364      *        the return type of the method, not the method's type itself!
  1365      */
  1366     public void visitApply(JCMethodInvocation tree) {
  1367         // The local environment of a method application is
  1368         // a new environment nested in the current one.
  1369         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1371         // The types of the actual method arguments.
  1372         List<Type> argtypes;
  1374         // The types of the actual method type arguments.
  1375         List<Type> typeargtypes = null;
  1377         Name methName = TreeInfo.name(tree.meth);
  1379         boolean isConstructorCall =
  1380             methName == names._this || methName == names._super;
  1382         if (isConstructorCall) {
  1383             // We are seeing a ...this(...) or ...super(...) call.
  1384             // Check that this is the first statement in a constructor.
  1385             if (checkFirstConstructorStat(tree, env)) {
  1387                 // Record the fact
  1388                 // that this is a constructor call (using isSelfCall).
  1389                 localEnv.info.isSelfCall = true;
  1391                 // Attribute arguments, yielding list of argument types.
  1392                 argtypes = attribArgs(tree.args, localEnv);
  1393                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1395                 // Variable `site' points to the class in which the called
  1396                 // constructor is defined.
  1397                 Type site = env.enclClass.sym.type;
  1398                 if (methName == names._super) {
  1399                     if (site == syms.objectType) {
  1400                         log.error(tree.meth.pos(), "no.superclass", site);
  1401                         site = types.createErrorType(syms.objectType);
  1402                     } else {
  1403                         site = types.supertype(site);
  1407                 if (site.tag == CLASS) {
  1408                     Type encl = site.getEnclosingType();
  1409                     while (encl != null && encl.tag == TYPEVAR)
  1410                         encl = encl.getUpperBound();
  1411                     if (encl.tag == CLASS) {
  1412                         // we are calling a nested class
  1414                         if (tree.meth.getTag() == JCTree.SELECT) {
  1415                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1417                             // We are seeing a prefixed call, of the form
  1418                             //     <expr>.super(...).
  1419                             // Check that the prefix expression conforms
  1420                             // to the outer instance type of the class.
  1421                             chk.checkRefType(qualifier.pos(),
  1422                                              attribExpr(qualifier, localEnv,
  1423                                                         encl));
  1424                         } else if (methName == names._super) {
  1425                             // qualifier omitted; check for existence
  1426                             // of an appropriate implicit qualifier.
  1427                             rs.resolveImplicitThis(tree.meth.pos(),
  1428                                                    localEnv, site);
  1430                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1431                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1432                                   site.tsym);
  1435                     // if we're calling a java.lang.Enum constructor,
  1436                     // prefix the implicit String and int parameters
  1437                     if (site.tsym == syms.enumSym && allowEnums)
  1438                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1440                     // Resolve the called constructor under the assumption
  1441                     // that we are referring to a superclass instance of the
  1442                     // current instance (JLS ???).
  1443                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1444                     localEnv.info.selectSuper = true;
  1445                     localEnv.info.varArgs = false;
  1446                     Symbol sym = rs.resolveConstructor(
  1447                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1448                     localEnv.info.selectSuper = selectSuperPrev;
  1450                     // Set method symbol to resolved constructor...
  1451                     TreeInfo.setSymbol(tree.meth, sym);
  1453                     // ...and check that it is legal in the current context.
  1454                     // (this will also set the tree's type)
  1455                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1456                     checkId(tree.meth, site, sym, localEnv, MTH,
  1457                             mpt, tree.varargsElement != null);
  1459                 // Otherwise, `site' is an error type and we do nothing
  1461             result = tree.type = syms.voidType;
  1462         } else {
  1463             // Otherwise, we are seeing a regular method call.
  1464             // Attribute the arguments, yielding list of argument types, ...
  1465             argtypes = attribArgs(tree.args, localEnv);
  1466             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1468             // ... and attribute the method using as a prototype a methodtype
  1469             // whose formal argument types is exactly the list of actual
  1470             // arguments (this will also set the method symbol).
  1471             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1472             localEnv.info.varArgs = false;
  1473             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1474             if (localEnv.info.varArgs)
  1475                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
  1477             // Compute the result type.
  1478             Type restype = mtype.getReturnType();
  1479             if (restype.tag == WILDCARD)
  1480                 throw new AssertionError(mtype);
  1482             // as a special case, array.clone() has a result that is
  1483             // the same as static type of the array being cloned
  1484             if (tree.meth.getTag() == JCTree.SELECT &&
  1485                 allowCovariantReturns &&
  1486                 methName == names.clone &&
  1487                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1488                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1490             // as a special case, x.getClass() has type Class<? extends |X|>
  1491             if (allowGenerics &&
  1492                 methName == names.getClass && tree.args.isEmpty()) {
  1493                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1494                     ? ((JCFieldAccess) tree.meth).selected.type
  1495                     : env.enclClass.sym.type;
  1496                 restype = new
  1497                     ClassType(restype.getEnclosingType(),
  1498                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1499                                                                BoundKind.EXTENDS,
  1500                                                                syms.boundClass)),
  1501                               restype.tsym);
  1504             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1506             // Check that value of resulting type is admissible in the
  1507             // current context.  Also, capture the return type
  1508             result = check(tree, capture(restype), VAL, pkind, pt);
  1510         chk.validate(tree.typeargs, localEnv);
  1512     //where
  1513         /** Check that given application node appears as first statement
  1514          *  in a constructor call.
  1515          *  @param tree   The application node
  1516          *  @param env    The environment current at the application.
  1517          */
  1518         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1519             JCMethodDecl enclMethod = env.enclMethod;
  1520             if (enclMethod != null && enclMethod.name == names.init) {
  1521                 JCBlock body = enclMethod.body;
  1522                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1523                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1524                     return true;
  1526             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1527                       TreeInfo.name(tree.meth));
  1528             return false;
  1531         /** Obtain a method type with given argument types.
  1532          */
  1533         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1534             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1535             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1538     public void visitNewClass(JCNewClass tree) {
  1539         Type owntype = types.createErrorType(tree.type);
  1541         // The local environment of a class creation is
  1542         // a new environment nested in the current one.
  1543         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1545         // The anonymous inner class definition of the new expression,
  1546         // if one is defined by it.
  1547         JCClassDecl cdef = tree.def;
  1549         // If enclosing class is given, attribute it, and
  1550         // complete class name to be fully qualified
  1551         JCExpression clazz = tree.clazz; // Class field following new
  1552         JCExpression clazzid =          // Identifier in class field
  1553             (clazz.getTag() == JCTree.TYPEAPPLY)
  1554             ? ((JCTypeApply) clazz).clazz
  1555             : clazz;
  1557         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1559         if (tree.encl != null) {
  1560             // We are seeing a qualified new, of the form
  1561             //    <expr>.new C <...> (...) ...
  1562             // In this case, we let clazz stand for the name of the
  1563             // allocated class C prefixed with the type of the qualifier
  1564             // expression, so that we can
  1565             // resolve it with standard techniques later. I.e., if
  1566             // <expr> has type T, then <expr>.new C <...> (...)
  1567             // yields a clazz T.C.
  1568             Type encltype = chk.checkRefType(tree.encl.pos(),
  1569                                              attribExpr(tree.encl, env));
  1570             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1571                                                  ((JCIdent) clazzid).name);
  1572             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1573                 clazz = make.at(tree.pos).
  1574                     TypeApply(clazzid1,
  1575                               ((JCTypeApply) clazz).arguments);
  1576             else
  1577                 clazz = clazzid1;
  1580         // Attribute clazz expression and store
  1581         // symbol + type back into the attributed tree.
  1582         Type clazztype = attribType(clazz, env);
  1583         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype, cdef != null);
  1584         if (!TreeInfo.isDiamond(tree)) {
  1585             clazztype = chk.checkClassType(
  1586                 tree.clazz.pos(), clazztype, true);
  1588         chk.validate(clazz, localEnv);
  1589         if (tree.encl != null) {
  1590             // We have to work in this case to store
  1591             // symbol + type back into the attributed tree.
  1592             tree.clazz.type = clazztype;
  1593             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1594             clazzid.type = ((JCIdent) clazzid).sym.type;
  1595             if (!clazztype.isErroneous()) {
  1596                 if (cdef != null && clazztype.tsym.isInterface()) {
  1597                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1598                 } else if (clazztype.tsym.isStatic()) {
  1599                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1602         } else if (!clazztype.tsym.isInterface() &&
  1603                    clazztype.getEnclosingType().tag == CLASS) {
  1604             // Check for the existence of an apropos outer instance
  1605             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1608         // Attribute constructor arguments.
  1609         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1610         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1612         if (TreeInfo.isDiamond(tree)) {
  1613             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1614             clazz.type = clazztype;
  1615         } else if (allowDiamondFinder &&
  1616                 clazztype.getTypeArguments().nonEmpty() &&
  1617                 findDiamonds) {
  1618             boolean prevDeferDiags = log.deferDiagnostics;
  1619             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1620             Type inferred = null;
  1621             try {
  1622                 //disable diamond-related diagnostics
  1623                 log.deferDiagnostics = true;
  1624                 log.deferredDiagnostics = ListBuffer.lb();
  1625                 inferred = attribDiamond(localEnv,
  1626                         tree,
  1627                         clazztype,
  1628                         mapping,
  1629                         argtypes,
  1630                         typeargtypes);
  1632             finally {
  1633                 log.deferDiagnostics = prevDeferDiags;
  1634                 log.deferredDiagnostics = prevDeferredDiags;
  1636             if (inferred != null &&
  1637                     !inferred.isErroneous() &&
  1638                     inferred.tag == CLASS &&
  1639                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
  1640                     chk.checkDiamond((ClassType)inferred).isEmpty()) {
  1641                 String key = types.isSameType(clazztype, inferred) ?
  1642                     "diamond.redundant.args" :
  1643                     "diamond.redundant.args.1";
  1644                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1648         // If we have made no mistakes in the class type...
  1649         if (clazztype.tag == CLASS) {
  1650             // Enums may not be instantiated except implicitly
  1651             if (allowEnums &&
  1652                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1653                 (env.tree.getTag() != JCTree.VARDEF ||
  1654                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1655                  ((JCVariableDecl) env.tree).init != tree))
  1656                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1657             // Check that class is not abstract
  1658             if (cdef == null &&
  1659                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1660                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1661                           clazztype.tsym);
  1662             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1663                 // Check that no constructor arguments are given to
  1664                 // anonymous classes implementing an interface
  1665                 if (!argtypes.isEmpty())
  1666                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1668                 if (!typeargtypes.isEmpty())
  1669                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1671                 // Error recovery: pretend no arguments were supplied.
  1672                 argtypes = List.nil();
  1673                 typeargtypes = List.nil();
  1676             // Resolve the called constructor under the assumption
  1677             // that we are referring to a superclass instance of the
  1678             // current instance (JLS ???).
  1679             else {
  1680                 localEnv.info.selectSuper = cdef != null;
  1681                 localEnv.info.varArgs = false;
  1682                 tree.constructor = rs.resolveConstructor(
  1683                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1684                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1685                     syms.errType :
  1686                     checkMethod(clazztype,
  1687                         tree.constructor,
  1688                         localEnv,
  1689                         tree.args,
  1690                         argtypes,
  1691                         typeargtypes,
  1692                         localEnv.info.varArgs);
  1693                 if (localEnv.info.varArgs)
  1694                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1697             if (cdef != null) {
  1698                 // We are seeing an anonymous class instance creation.
  1699                 // In this case, the class instance creation
  1700                 // expression
  1701                 //
  1702                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1703                 //
  1704                 // is represented internally as
  1705                 //
  1706                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1707                 //
  1708                 // This expression is then *transformed* as follows:
  1709                 //
  1710                 // (1) add a STATIC flag to the class definition
  1711                 //     if the current environment is static
  1712                 // (2) add an extends or implements clause
  1713                 // (3) add a constructor.
  1714                 //
  1715                 // For instance, if C is a class, and ET is the type of E,
  1716                 // the expression
  1717                 //
  1718                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1719                 //
  1720                 // is translated to (where X is a fresh name and typarams is the
  1721                 // parameter list of the super constructor):
  1722                 //
  1723                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1724                 //     X extends C<typargs2> {
  1725                 //       <typarams> X(ET e, args) {
  1726                 //         e.<typeargs1>super(args)
  1727                 //       }
  1728                 //       ...
  1729                 //     }
  1730                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1732                 if (clazztype.tsym.isInterface()) {
  1733                     cdef.implementing = List.of(clazz);
  1734                 } else {
  1735                     cdef.extending = clazz;
  1738                 attribStat(cdef, localEnv);
  1740                 // If an outer instance is given,
  1741                 // prefix it to the constructor arguments
  1742                 // and delete it from the new expression
  1743                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1744                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1745                     argtypes = argtypes.prepend(tree.encl.type);
  1746                     tree.encl = null;
  1749                 // Reassign clazztype and recompute constructor.
  1750                 clazztype = cdef.sym.type;
  1751                 Symbol sym = rs.resolveConstructor(
  1752                     tree.pos(), localEnv, clazztype, argtypes,
  1753                     typeargtypes, true, tree.varargsElement != null);
  1754                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
  1755                 tree.constructor = sym;
  1756                 if (tree.constructor.kind > ERRONEOUS) {
  1757                     tree.constructorType =  syms.errType;
  1759                 else {
  1760                     tree.constructorType = checkMethod(clazztype,
  1761                             tree.constructor,
  1762                             localEnv,
  1763                             tree.args,
  1764                             argtypes,
  1765                             typeargtypes,
  1766                             localEnv.info.varArgs);
  1770             if (tree.constructor != null && tree.constructor.kind == MTH)
  1771                 owntype = clazztype;
  1773         result = check(tree, owntype, VAL, pkind, pt);
  1774         chk.validate(tree.typeargs, localEnv);
  1777     Type attribDiamond(Env<AttrContext> env,
  1778                         JCNewClass tree,
  1779                         Type clazztype,
  1780                         Pair<Scope, Scope> mapping,
  1781                         List<Type> argtypes,
  1782                         List<Type> typeargtypes) {
  1783         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1784             //if the type of the instance creation expression is erroneous,
  1785             //or something prevented us to form a valid mapping, return the
  1786             //(possibly erroneous) type unchanged
  1787             return clazztype;
  1789         else if (clazztype.isInterface()) {
  1790             //if the type of the instance creation expression is an interface
  1791             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1792             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1793             clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
  1794                 @Override
  1795                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
  1796                     switch (ck) {
  1797                         case EXTENDS: return types.getBounds(tv);
  1798                         default: return List.nil();
  1801                 @Override
  1802                 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
  1803                     // check that inferred bounds conform to their bounds
  1804                     infer.checkWithinBounds(tvars,
  1805                            types.subst(tvars, tvars, inferred), Warner.noWarnings);
  1806                     return super.inst(inferred, types);
  1808             };
  1809         } else {
  1810             //if the type of the instance creation expression is a class type
  1811             //apply method resolution inference (JLS 15.12.2.7). The return type
  1812             //of the resolved constructor will be a partially instantiated type
  1813             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1814             Symbol constructor;
  1815             try {
  1816                 constructor = rs.resolveDiamond(tree.pos(),
  1817                         env,
  1818                         clazztype.tsym.type,
  1819                         argtypes,
  1820                         typeargtypes);
  1821             } finally {
  1822                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1824             if (constructor.kind == MTH) {
  1825                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1826                         clazztype.tsym.type.getTypeArguments(),
  1827                         clazztype.tsym);
  1828                 clazztype = checkMethod(ct,
  1829                         constructor,
  1830                         env,
  1831                         tree.args,
  1832                         argtypes,
  1833                         typeargtypes,
  1834                         env.info.varArgs).getReturnType();
  1835             } else {
  1836                 clazztype = syms.errType;
  1839         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1840             //if the resolved constructor's return type has some uninferred
  1841             //type-variables, infer them using the expected type and declared
  1842             //bounds (JLS 15.12.2.8).
  1843             try {
  1844                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1845                         pt.tag == NONE ? syms.objectType : pt,
  1846                         Warner.noWarnings);
  1847             } catch (Infer.InferenceException ex) {
  1848                 //an error occurred while inferring uninstantiated type-variables
  1849                 log.error(tree.clazz.pos(),
  1850                         "cant.apply.diamond.1",
  1851                         diags.fragment("diamond", clazztype.tsym),
  1852                         ex.diagnostic);
  1855         clazztype = chk.checkClassType(tree.clazz.pos(),
  1856                 clazztype,
  1857                 true);
  1858         if (clazztype.tag == CLASS) {
  1859             List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1860             if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1861                 //one or more types inferred in the previous steps is either a
  1862                 //captured type or an intersection type --- we need to report an error.
  1863                 String subkey = invalidDiamondArgs.size() > 1 ?
  1864                     "diamond.invalid.args" :
  1865                     "diamond.invalid.arg";
  1866                 //The error message is of the kind:
  1867                 //
  1868                 //cannot infer type arguments for {clazztype}<>;
  1869                 //reason: {subkey}
  1870                 //
  1871                 //where subkey is a fragment of the kind:
  1872                 //
  1873                 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1874                 log.error(tree.clazz.pos(),
  1875                             "cant.apply.diamond.1",
  1876                             diags.fragment("diamond", clazztype.tsym),
  1877                             diags.fragment(subkey,
  1878                                            invalidDiamondArgs,
  1879                                            diags.fragment("diamond", clazztype.tsym)));
  1882         return clazztype;
  1885     /** Creates a synthetic scope containing fake generic constructors.
  1886      *  Assuming that the original scope contains a constructor of the kind:
  1887      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1888      *  the synthetic scope is added a generic constructor of the kind:
  1889      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1890      *  inference. The inferred return type of the synthetic constructor IS
  1891      *  the inferred type for the diamond operator.
  1892      */
  1893     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype, boolean overrideProtectedAccess) {
  1894         if (ctype.tag != CLASS) {
  1895             return erroneousMapping;
  1897         Pair<Scope, Scope> mapping =
  1898                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1899         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1900         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1901                 e.scope != null;
  1902                 e = e.next()) {
  1903             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1904             if (overrideProtectedAccess && (newConstr.flags() & PROTECTED) != 0) {
  1905                 //make protected constructor public (this is required for
  1906                 //anonymous inner class creation expressions using diamond)
  1907                 newConstr.flags_field |= PUBLIC;
  1908                 newConstr.flags_field &= ~PROTECTED;
  1910             newConstr.name = names.init;
  1911             List<Type> oldTypeargs = List.nil();
  1912             if (newConstr.type.tag == FORALL) {
  1913                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1915             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1916                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1917                     newConstr.type.getThrownTypes(),
  1918                     syms.methodClass);
  1919             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1920             mapping.snd.enter(newConstr);
  1922         return mapping;
  1925     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1927     /** Make an attributed null check tree.
  1928      */
  1929     public JCExpression makeNullCheck(JCExpression arg) {
  1930         // optimization: X.this is never null; skip null check
  1931         Name name = TreeInfo.name(arg);
  1932         if (name == names._this || name == names._super) return arg;
  1934         int optag = JCTree.NULLCHK;
  1935         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1936         tree.operator = syms.nullcheck;
  1937         tree.type = arg.type;
  1938         return tree;
  1941     public void visitNewArray(JCNewArray tree) {
  1942         Type owntype = types.createErrorType(tree.type);
  1943         Type elemtype;
  1944         if (tree.elemtype != null) {
  1945             elemtype = attribType(tree.elemtype, env);
  1946             chk.validate(tree.elemtype, env);
  1947             owntype = elemtype;
  1948             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1949                 attribExpr(l.head, env, syms.intType);
  1950                 owntype = new ArrayType(owntype, syms.arrayClass);
  1952         } else {
  1953             // we are seeing an untyped aggregate { ... }
  1954             // this is allowed only if the prototype is an array
  1955             if (pt.tag == ARRAY) {
  1956                 elemtype = types.elemtype(pt);
  1957             } else {
  1958                 if (pt.tag != ERROR) {
  1959                     log.error(tree.pos(), "illegal.initializer.for.type",
  1960                               pt);
  1962                 elemtype = types.createErrorType(pt);
  1965         if (tree.elems != null) {
  1966             attribExprs(tree.elems, env, elemtype);
  1967             owntype = new ArrayType(elemtype, syms.arrayClass);
  1969         if (!types.isReifiable(elemtype))
  1970             log.error(tree.pos(), "generic.array.creation");
  1971         result = check(tree, owntype, VAL, pkind, pt);
  1974     public void visitParens(JCParens tree) {
  1975         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1976         result = check(tree, owntype, pkind, pkind, pt);
  1977         Symbol sym = TreeInfo.symbol(tree);
  1978         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1979             log.error(tree.pos(), "illegal.start.of.type");
  1982     public void visitAssign(JCAssign tree) {
  1983         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1984         Type capturedType = capture(owntype);
  1985         attribExpr(tree.rhs, env, owntype);
  1986         result = check(tree, capturedType, VAL, pkind, pt);
  1989     public void visitAssignop(JCAssignOp tree) {
  1990         // Attribute arguments.
  1991         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1992         Type operand = attribExpr(tree.rhs, env);
  1993         // Find operator.
  1994         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1995             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1996             owntype, operand);
  1998         if (operator.kind == MTH &&
  1999                 !owntype.isErroneous() &&
  2000                 !operand.isErroneous()) {
  2001             chk.checkOperator(tree.pos(),
  2002                               (OperatorSymbol)operator,
  2003                               tree.getTag() - JCTree.ASGOffset,
  2004                               owntype,
  2005                               operand);
  2006             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2007             chk.checkCastable(tree.rhs.pos(),
  2008                               operator.type.getReturnType(),
  2009                               owntype);
  2011         result = check(tree, owntype, VAL, pkind, pt);
  2014     public void visitUnary(JCUnary tree) {
  2015         // Attribute arguments.
  2016         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2017             ? attribTree(tree.arg, env, VAR, Type.noType)
  2018             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2020         // Find operator.
  2021         Symbol operator = tree.operator =
  2022             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2024         Type owntype = types.createErrorType(tree.type);
  2025         if (operator.kind == MTH &&
  2026                 !argtype.isErroneous()) {
  2027             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2028                 ? tree.arg.type
  2029                 : operator.type.getReturnType();
  2030             int opc = ((OperatorSymbol)operator).opcode;
  2032             // If the argument is constant, fold it.
  2033             if (argtype.constValue() != null) {
  2034                 Type ctype = cfolder.fold1(opc, argtype);
  2035                 if (ctype != null) {
  2036                     owntype = cfolder.coerce(ctype, owntype);
  2038                     // Remove constant types from arguments to
  2039                     // conserve space. The parser will fold concatenations
  2040                     // of string literals; the code here also
  2041                     // gets rid of intermediate results when some of the
  2042                     // operands are constant identifiers.
  2043                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2044                         tree.arg.type = syms.stringType;
  2049         result = check(tree, owntype, VAL, pkind, pt);
  2052     public void visitBinary(JCBinary tree) {
  2053         // Attribute arguments.
  2054         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2055         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2057         // Find operator.
  2058         Symbol operator = tree.operator =
  2059             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2061         Type owntype = types.createErrorType(tree.type);
  2062         if (operator.kind == MTH &&
  2063                 !left.isErroneous() &&
  2064                 !right.isErroneous()) {
  2065             owntype = operator.type.getReturnType();
  2066             int opc = chk.checkOperator(tree.lhs.pos(),
  2067                                         (OperatorSymbol)operator,
  2068                                         tree.getTag(),
  2069                                         left,
  2070                                         right);
  2072             // If both arguments are constants, fold them.
  2073             if (left.constValue() != null && right.constValue() != null) {
  2074                 Type ctype = cfolder.fold2(opc, left, right);
  2075                 if (ctype != null) {
  2076                     owntype = cfolder.coerce(ctype, owntype);
  2078                     // Remove constant types from arguments to
  2079                     // conserve space. The parser will fold concatenations
  2080                     // of string literals; the code here also
  2081                     // gets rid of intermediate results when some of the
  2082                     // operands are constant identifiers.
  2083                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2084                         tree.lhs.type = syms.stringType;
  2086                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2087                         tree.rhs.type = syms.stringType;
  2092             // Check that argument types of a reference ==, != are
  2093             // castable to each other, (JLS???).
  2094             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2095                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2096                     log.error(tree.pos(), "incomparable.types", left, right);
  2100             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2102         result = check(tree, owntype, VAL, pkind, pt);
  2105     public void visitTypeCast(JCTypeCast tree) {
  2106         Type clazztype = attribType(tree.clazz, env);
  2107         chk.validate(tree.clazz, env, false);
  2108         //a fresh environment is required for 292 inference to work properly ---
  2109         //see Infer.instantiatePolymorphicSignatureInstance()
  2110         Env<AttrContext> localEnv = env.dup(tree);
  2111         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2112         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2113         if (exprtype.constValue() != null)
  2114             owntype = cfolder.coerce(exprtype, owntype);
  2115         result = check(tree, capture(owntype), VAL, pkind, pt);
  2118     public void visitTypeTest(JCInstanceOf tree) {
  2119         Type exprtype = chk.checkNullOrRefType(
  2120             tree.expr.pos(), attribExpr(tree.expr, env));
  2121         Type clazztype = chk.checkReifiableReferenceType(
  2122             tree.clazz.pos(), attribType(tree.clazz, env));
  2123         chk.validate(tree.clazz, env, false);
  2124         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2125         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2128     public void visitIndexed(JCArrayAccess tree) {
  2129         Type owntype = types.createErrorType(tree.type);
  2130         Type atype = attribExpr(tree.indexed, env);
  2131         attribExpr(tree.index, env, syms.intType);
  2132         if (types.isArray(atype))
  2133             owntype = types.elemtype(atype);
  2134         else if (atype.tag != ERROR)
  2135             log.error(tree.pos(), "array.req.but.found", atype);
  2136         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2137         result = check(tree, owntype, VAR, pkind, pt);
  2140     public void visitIdent(JCIdent tree) {
  2141         Symbol sym;
  2142         boolean varArgs = false;
  2144         // Find symbol
  2145         if (pt.tag == METHOD || pt.tag == FORALL) {
  2146             // If we are looking for a method, the prototype `pt' will be a
  2147             // method type with the type of the call's arguments as parameters.
  2148             env.info.varArgs = false;
  2149             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2150             varArgs = env.info.varArgs;
  2151         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2152             sym = tree.sym;
  2153         } else {
  2154             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2156         tree.sym = sym;
  2158         // (1) Also find the environment current for the class where
  2159         //     sym is defined (`symEnv').
  2160         // Only for pre-tiger versions (1.4 and earlier):
  2161         // (2) Also determine whether we access symbol out of an anonymous
  2162         //     class in a this or super call.  This is illegal for instance
  2163         //     members since such classes don't carry a this$n link.
  2164         //     (`noOuterThisPath').
  2165         Env<AttrContext> symEnv = env;
  2166         boolean noOuterThisPath = false;
  2167         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2168             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2169             sym.owner.kind == TYP &&
  2170             tree.name != names._this && tree.name != names._super) {
  2172             // Find environment in which identifier is defined.
  2173             while (symEnv.outer != null &&
  2174                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2175                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2176                     noOuterThisPath = !allowAnonOuterThis;
  2177                 symEnv = symEnv.outer;
  2181         // If symbol is a variable, ...
  2182         if (sym.kind == VAR) {
  2183             VarSymbol v = (VarSymbol)sym;
  2185             // ..., evaluate its initializer, if it has one, and check for
  2186             // illegal forward reference.
  2187             checkInit(tree, env, v, false);
  2189             // If symbol is a local variable accessed from an embedded
  2190             // inner class check that it is final.
  2191             if (v.owner.kind == MTH &&
  2192                 v.owner != env.info.scope.owner &&
  2193                 (v.flags_field & FINAL) == 0) {
  2194                 log.error(tree.pos(),
  2195                           "local.var.accessed.from.icls.needs.final",
  2196                           v);
  2199             // If we are expecting a variable (as opposed to a value), check
  2200             // that the variable is assignable in the current environment.
  2201             if (pkind == VAR)
  2202                 checkAssignable(tree.pos(), v, null, env);
  2205         // In a constructor body,
  2206         // if symbol is a field or instance method, check that it is
  2207         // not accessed before the supertype constructor is called.
  2208         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2209             (sym.kind & (VAR | MTH)) != 0 &&
  2210             sym.owner.kind == TYP &&
  2211             (sym.flags() & STATIC) == 0) {
  2212             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2214         Env<AttrContext> env1 = env;
  2215         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2216             // If the found symbol is inaccessible, then it is
  2217             // accessed through an enclosing instance.  Locate this
  2218             // enclosing instance:
  2219             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2220                 env1 = env1.outer;
  2222         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2225     public void visitSelect(JCFieldAccess tree) {
  2226         // Determine the expected kind of the qualifier expression.
  2227         int skind = 0;
  2228         if (tree.name == names._this || tree.name == names._super ||
  2229             tree.name == names._class)
  2231             skind = TYP;
  2232         } else {
  2233             if ((pkind & PCK) != 0) skind = skind | PCK;
  2234             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2235             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2238         // Attribute the qualifier expression, and determine its symbol (if any).
  2239         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2240         if ((pkind & (PCK | TYP)) == 0)
  2241             site = capture(site); // Capture field access
  2243         // don't allow T.class T[].class, etc
  2244         if (skind == TYP) {
  2245             Type elt = site;
  2246             while (elt.tag == ARRAY)
  2247                 elt = ((ArrayType)elt).elemtype;
  2248             if (elt.tag == TYPEVAR) {
  2249                 log.error(tree.pos(), "type.var.cant.be.deref");
  2250                 result = types.createErrorType(tree.type);
  2251                 return;
  2255         // If qualifier symbol is a type or `super', assert `selectSuper'
  2256         // for the selection. This is relevant for determining whether
  2257         // protected symbols are accessible.
  2258         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2259         boolean selectSuperPrev = env.info.selectSuper;
  2260         env.info.selectSuper =
  2261             sitesym != null &&
  2262             sitesym.name == names._super;
  2264         // If selected expression is polymorphic, strip
  2265         // type parameters and remember in env.info.tvars, so that
  2266         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2267         if (tree.selected.type.tag == FORALL) {
  2268             ForAll pstype = (ForAll)tree.selected.type;
  2269             env.info.tvars = pstype.tvars;
  2270             site = tree.selected.type = pstype.qtype;
  2273         // Determine the symbol represented by the selection.
  2274         env.info.varArgs = false;
  2275         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2276         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2277             site = capture(site);
  2278             sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2280         boolean varArgs = env.info.varArgs;
  2281         tree.sym = sym;
  2283         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2284             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2285             site = capture(site);
  2288         // If that symbol is a variable, ...
  2289         if (sym.kind == VAR) {
  2290             VarSymbol v = (VarSymbol)sym;
  2292             // ..., evaluate its initializer, if it has one, and check for
  2293             // illegal forward reference.
  2294             checkInit(tree, env, v, true);
  2296             // If we are expecting a variable (as opposed to a value), check
  2297             // that the variable is assignable in the current environment.
  2298             if (pkind == VAR)
  2299                 checkAssignable(tree.pos(), v, tree.selected, env);
  2302         if (sitesym != null &&
  2303                 sitesym.kind == VAR &&
  2304                 ((VarSymbol)sitesym).isResourceVariable() &&
  2305                 sym.kind == MTH &&
  2306                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2307                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2308             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2311         // Disallow selecting a type from an expression
  2312         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2313             tree.type = check(tree.selected, pt,
  2314                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2317         if (isType(sitesym)) {
  2318             if (sym.name == names._this) {
  2319                 // If `C' is the currently compiled class, check that
  2320                 // C.this' does not appear in a call to a super(...)
  2321                 if (env.info.isSelfCall &&
  2322                     site.tsym == env.enclClass.sym) {
  2323                     chk.earlyRefError(tree.pos(), sym);
  2325             } else {
  2326                 // Check if type-qualified fields or methods are static (JLS)
  2327                 if ((sym.flags() & STATIC) == 0 &&
  2328                     sym.name != names._super &&
  2329                     (sym.kind == VAR || sym.kind == MTH)) {
  2330                     rs.access(rs.new StaticError(sym),
  2331                               tree.pos(), site, sym.name, true);
  2334         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2335             // If the qualified item is not a type and the selected item is static, report
  2336             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2337             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2340         // If we are selecting an instance member via a `super', ...
  2341         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2343             // Check that super-qualified symbols are not abstract (JLS)
  2344             rs.checkNonAbstract(tree.pos(), sym);
  2346             if (site.isRaw()) {
  2347                 // Determine argument types for site.
  2348                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2349                 if (site1 != null) site = site1;
  2353         env.info.selectSuper = selectSuperPrev;
  2354         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2355         env.info.tvars = List.nil();
  2357     //where
  2358         /** Determine symbol referenced by a Select expression,
  2360          *  @param tree   The select tree.
  2361          *  @param site   The type of the selected expression,
  2362          *  @param env    The current environment.
  2363          *  @param pt     The current prototype.
  2364          *  @param pkind  The expected kind(s) of the Select expression.
  2365          */
  2366         private Symbol selectSym(JCFieldAccess tree,
  2367                                      Type site,
  2368                                      Env<AttrContext> env,
  2369                                      Type pt,
  2370                                      int pkind) {
  2371             return selectSym(tree, site.tsym, site, env, pt, pkind);
  2373         private Symbol selectSym(JCFieldAccess tree,
  2374                                  Symbol location,
  2375                                  Type site,
  2376                                  Env<AttrContext> env,
  2377                                  Type pt,
  2378                                  int pkind) {
  2379             DiagnosticPosition pos = tree.pos();
  2380             Name name = tree.name;
  2381             switch (site.tag) {
  2382             case PACKAGE:
  2383                 return rs.access(
  2384                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2385                     pos, location, site, name, true);
  2386             case ARRAY:
  2387             case CLASS:
  2388                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2389                     return rs.resolveQualifiedMethod(
  2390                         pos, env, location, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2391                 } else if (name == names._this || name == names._super) {
  2392                     return rs.resolveSelf(pos, env, site.tsym, name);
  2393                 } else if (name == names._class) {
  2394                     // In this case, we have already made sure in
  2395                     // visitSelect that qualifier expression is a type.
  2396                     Type t = syms.classType;
  2397                     List<Type> typeargs = allowGenerics
  2398                         ? List.of(types.erasure(site))
  2399                         : List.<Type>nil();
  2400                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2401                     return new VarSymbol(
  2402                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2403                 } else {
  2404                     // We are seeing a plain identifier as selector.
  2405                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2406                     if ((pkind & ERRONEOUS) == 0)
  2407                         sym = rs.access(sym, pos, location, site, name, true);
  2408                     return sym;
  2410             case WILDCARD:
  2411                 throw new AssertionError(tree);
  2412             case TYPEVAR:
  2413                 // Normally, site.getUpperBound() shouldn't be null.
  2414                 // It should only happen during memberEnter/attribBase
  2415                 // when determining the super type which *must* beac
  2416                 // done before attributing the type variables.  In
  2417                 // other words, we are seeing this illegal program:
  2418                 // class B<T> extends A<T.foo> {}
  2419                 Symbol sym = (site.getUpperBound() != null)
  2420                     ? selectSym(tree, location, capture(site.getUpperBound()), env, pt, pkind)
  2421                     : null;
  2422                 if (sym == null) {
  2423                     log.error(pos, "type.var.cant.be.deref");
  2424                     return syms.errSymbol;
  2425                 } else {
  2426                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2427                         rs.new AccessError(env, site, sym) :
  2428                                 sym;
  2429                     rs.access(sym2, pos, location, site, name, true);
  2430                     return sym;
  2432             case ERROR:
  2433                 // preserve identifier names through errors
  2434                 return types.createErrorType(name, site.tsym, site).tsym;
  2435             default:
  2436                 // The qualifier expression is of a primitive type -- only
  2437                 // .class is allowed for these.
  2438                 if (name == names._class) {
  2439                     // In this case, we have already made sure in Select that
  2440                     // qualifier expression is a type.
  2441                     Type t = syms.classType;
  2442                     Type arg = types.boxedClass(site).type;
  2443                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2444                     return new VarSymbol(
  2445                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2446                 } else {
  2447                     log.error(pos, "cant.deref", site);
  2448                     return syms.errSymbol;
  2453         /** Determine type of identifier or select expression and check that
  2454          *  (1) the referenced symbol is not deprecated
  2455          *  (2) the symbol's type is safe (@see checkSafe)
  2456          *  (3) if symbol is a variable, check that its type and kind are
  2457          *      compatible with the prototype and protokind.
  2458          *  (4) if symbol is an instance field of a raw type,
  2459          *      which is being assigned to, issue an unchecked warning if its
  2460          *      type changes under erasure.
  2461          *  (5) if symbol is an instance method of a raw type, issue an
  2462          *      unchecked warning if its argument types change under erasure.
  2463          *  If checks succeed:
  2464          *    If symbol is a constant, return its constant type
  2465          *    else if symbol is a method, return its result type
  2466          *    otherwise return its type.
  2467          *  Otherwise return errType.
  2469          *  @param tree       The syntax tree representing the identifier
  2470          *  @param site       If this is a select, the type of the selected
  2471          *                    expression, otherwise the type of the current class.
  2472          *  @param sym        The symbol representing the identifier.
  2473          *  @param env        The current environment.
  2474          *  @param pkind      The set of expected kinds.
  2475          *  @param pt         The expected type.
  2476          */
  2477         Type checkId(JCTree tree,
  2478                      Type site,
  2479                      Symbol sym,
  2480                      Env<AttrContext> env,
  2481                      int pkind,
  2482                      Type pt,
  2483                      boolean useVarargs) {
  2484             if (pt.isErroneous()) return types.createErrorType(site);
  2485             Type owntype; // The computed type of this identifier occurrence.
  2486             switch (sym.kind) {
  2487             case TYP:
  2488                 // For types, the computed type equals the symbol's type,
  2489                 // except for two situations:
  2490                 owntype = sym.type;
  2491                 if (owntype.tag == CLASS) {
  2492                     Type ownOuter = owntype.getEnclosingType();
  2494                     // (a) If the symbol's type is parameterized, erase it
  2495                     // because no type parameters were given.
  2496                     // We recover generic outer type later in visitTypeApply.
  2497                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2498                         owntype = types.erasure(owntype);
  2501                     // (b) If the symbol's type is an inner class, then
  2502                     // we have to interpret its outer type as a superclass
  2503                     // of the site type. Example:
  2504                     //
  2505                     // class Tree<A> { class Visitor { ... } }
  2506                     // class PointTree extends Tree<Point> { ... }
  2507                     // ...PointTree.Visitor...
  2508                     //
  2509                     // Then the type of the last expression above is
  2510                     // Tree<Point>.Visitor.
  2511                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2512                         Type normOuter = site;
  2513                         if (normOuter.tag == CLASS)
  2514                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2515                         if (normOuter == null) // perhaps from an import
  2516                             normOuter = types.erasure(ownOuter);
  2517                         if (normOuter != ownOuter)
  2518                             owntype = new ClassType(
  2519                                 normOuter, List.<Type>nil(), owntype.tsym);
  2522                 break;
  2523             case VAR:
  2524                 VarSymbol v = (VarSymbol)sym;
  2525                 // Test (4): if symbol is an instance field of a raw type,
  2526                 // which is being assigned to, issue an unchecked warning if
  2527                 // its type changes under erasure.
  2528                 if (allowGenerics &&
  2529                     pkind == VAR &&
  2530                     v.owner.kind == TYP &&
  2531                     (v.flags() & STATIC) == 0 &&
  2532                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2533                     Type s = types.asOuterSuper(site, v.owner);
  2534                     if (s != null &&
  2535                         s.isRaw() &&
  2536                         !types.isSameType(v.type, v.erasure(types))) {
  2537                         chk.warnUnchecked(tree.pos(),
  2538                                           "unchecked.assign.to.var",
  2539                                           v, s);
  2542                 // The computed type of a variable is the type of the
  2543                 // variable symbol, taken as a member of the site type.
  2544                 owntype = (sym.owner.kind == TYP &&
  2545                            sym.name != names._this && sym.name != names._super)
  2546                     ? types.memberType(site, sym)
  2547                     : sym.type;
  2549                 if (env.info.tvars.nonEmpty()) {
  2550                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2551                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2552                         if (!owntype.contains(l.head)) {
  2553                             log.error(tree.pos(), "undetermined.type", owntype1);
  2554                             owntype1 = types.createErrorType(owntype1);
  2556                     owntype = owntype1;
  2559                 // If the variable is a constant, record constant value in
  2560                 // computed type.
  2561                 if (v.getConstValue() != null && isStaticReference(tree))
  2562                     owntype = owntype.constType(v.getConstValue());
  2564                 if (pkind == VAL) {
  2565                     owntype = capture(owntype); // capture "names as expressions"
  2567                 break;
  2568             case MTH: {
  2569                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2570                 owntype = checkMethod(site, sym, env, app.args,
  2571                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2572                                       env.info.varArgs);
  2573                 break;
  2575             case PCK: case ERR:
  2576                 owntype = sym.type;
  2577                 break;
  2578             default:
  2579                 throw new AssertionError("unexpected kind: " + sym.kind +
  2580                                          " in tree " + tree);
  2583             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2584             // (for constructors, the error was given when the constructor was
  2585             // resolved)
  2587             if (sym.name != names.init) {
  2588                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  2589                 chk.checkSunAPI(tree.pos(), sym);
  2592             // Test (3): if symbol is a variable, check that its type and
  2593             // kind are compatible with the prototype and protokind.
  2594             return check(tree, owntype, sym.kind, pkind, pt);
  2597         /** Check that variable is initialized and evaluate the variable's
  2598          *  initializer, if not yet done. Also check that variable is not
  2599          *  referenced before it is defined.
  2600          *  @param tree    The tree making up the variable reference.
  2601          *  @param env     The current environment.
  2602          *  @param v       The variable's symbol.
  2603          */
  2604         private void checkInit(JCTree tree,
  2605                                Env<AttrContext> env,
  2606                                VarSymbol v,
  2607                                boolean onlyWarning) {
  2608 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2609 //                             tree.pos + " " + v.pos + " " +
  2610 //                             Resolve.isStatic(env));//DEBUG
  2612             // A forward reference is diagnosed if the declaration position
  2613             // of the variable is greater than the current tree position
  2614             // and the tree and variable definition occur in the same class
  2615             // definition.  Note that writes don't count as references.
  2616             // This check applies only to class and instance
  2617             // variables.  Local variables follow different scope rules,
  2618             // and are subject to definite assignment checking.
  2619             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2620                 v.owner.kind == TYP &&
  2621                 canOwnInitializer(env.info.scope.owner) &&
  2622                 v.owner == env.info.scope.owner.enclClass() &&
  2623                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2624                 (env.tree.getTag() != JCTree.ASSIGN ||
  2625                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2626                 String suffix = (env.info.enclVar == v) ?
  2627                                 "self.ref" : "forward.ref";
  2628                 if (!onlyWarning || isStaticEnumField(v)) {
  2629                     log.error(tree.pos(), "illegal." + suffix);
  2630                 } else if (useBeforeDeclarationWarning) {
  2631                     log.warning(tree.pos(), suffix, v);
  2635             v.getConstValue(); // ensure initializer is evaluated
  2637             checkEnumInitializer(tree, env, v);
  2640         /**
  2641          * Check for illegal references to static members of enum.  In
  2642          * an enum type, constructors and initializers may not
  2643          * reference its static members unless they are constant.
  2645          * @param tree    The tree making up the variable reference.
  2646          * @param env     The current environment.
  2647          * @param v       The variable's symbol.
  2648          * @see JLS 3rd Ed. (8.9 Enums)
  2649          */
  2650         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2651             // JLS 3rd Ed.:
  2652             //
  2653             // "It is a compile-time error to reference a static field
  2654             // of an enum type that is not a compile-time constant
  2655             // (15.28) from constructors, instance initializer blocks,
  2656             // or instance variable initializer expressions of that
  2657             // type. It is a compile-time error for the constructors,
  2658             // instance initializer blocks, or instance variable
  2659             // initializer expressions of an enum constant e to refer
  2660             // to itself or to an enum constant of the same type that
  2661             // is declared to the right of e."
  2662             if (isStaticEnumField(v)) {
  2663                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2665                 if (enclClass == null || enclClass.owner == null)
  2666                     return;
  2668                 // See if the enclosing class is the enum (or a
  2669                 // subclass thereof) declaring v.  If not, this
  2670                 // reference is OK.
  2671                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2672                     return;
  2674                 // If the reference isn't from an initializer, then
  2675                 // the reference is OK.
  2676                 if (!Resolve.isInitializer(env))
  2677                     return;
  2679                 log.error(tree.pos(), "illegal.enum.static.ref");
  2683         /** Is the given symbol a static, non-constant field of an Enum?
  2684          *  Note: enum literals should not be regarded as such
  2685          */
  2686         private boolean isStaticEnumField(VarSymbol v) {
  2687             return Flags.isEnum(v.owner) &&
  2688                    Flags.isStatic(v) &&
  2689                    !Flags.isConstant(v) &&
  2690                    v.name != names._class;
  2693         /** Can the given symbol be the owner of code which forms part
  2694          *  if class initialization? This is the case if the symbol is
  2695          *  a type or field, or if the symbol is the synthetic method.
  2696          *  owning a block.
  2697          */
  2698         private boolean canOwnInitializer(Symbol sym) {
  2699             return
  2700                 (sym.kind & (VAR | TYP)) != 0 ||
  2701                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2704     Warner noteWarner = new Warner();
  2706     /**
  2707      * Check that method arguments conform to its instantation.
  2708      **/
  2709     public Type checkMethod(Type site,
  2710                             Symbol sym,
  2711                             Env<AttrContext> env,
  2712                             final List<JCExpression> argtrees,
  2713                             List<Type> argtypes,
  2714                             List<Type> typeargtypes,
  2715                             boolean useVarargs) {
  2716         // Test (5): if symbol is an instance method of a raw type, issue
  2717         // an unchecked warning if its argument types change under erasure.
  2718         if (allowGenerics &&
  2719             (sym.flags() & STATIC) == 0 &&
  2720             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2721             Type s = types.asOuterSuper(site, sym.owner);
  2722             if (s != null && s.isRaw() &&
  2723                 !types.isSameTypes(sym.type.getParameterTypes(),
  2724                                    sym.erasure(types).getParameterTypes())) {
  2725                 chk.warnUnchecked(env.tree.pos(),
  2726                                   "unchecked.call.mbr.of.raw.type",
  2727                                   sym, s);
  2731         // Compute the identifier's instantiated type.
  2732         // For methods, we need to compute the instance type by
  2733         // Resolve.instantiate from the symbol's type as well as
  2734         // any type arguments and value arguments.
  2735         noteWarner.clear();
  2736         Type owntype = rs.instantiate(env,
  2737                                       site,
  2738                                       sym,
  2739                                       argtypes,
  2740                                       typeargtypes,
  2741                                       true,
  2742                                       useVarargs,
  2743                                       noteWarner);
  2744         boolean warned = noteWarner.hasNonSilentLint(LintCategory.UNCHECKED);
  2746         // If this fails, something went wrong; we should not have
  2747         // found the identifier in the first place.
  2748         if (owntype == null) {
  2749             if (!pt.isErroneous())
  2750                 log.error(env.tree.pos(),
  2751                           "internal.error.cant.instantiate",
  2752                           sym, site,
  2753                           Type.toString(pt.getParameterTypes()));
  2754             owntype = types.createErrorType(site);
  2755         } else {
  2756             // System.out.println("call   : " + env.tree);
  2757             // System.out.println("method : " + owntype);
  2758             // System.out.println("actuals: " + argtypes);
  2759             List<Type> formals = owntype.getParameterTypes();
  2760             Type last = useVarargs ? formals.last() : null;
  2761             if (sym.name==names.init &&
  2762                 sym.owner == syms.enumSym)
  2763                 formals = formals.tail.tail;
  2764             List<JCExpression> args = argtrees;
  2765             while (formals.head != last) {
  2766                 JCTree arg = args.head;
  2767                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2768                 assertConvertible(arg, arg.type, formals.head, warn);
  2769                 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2770                 args = args.tail;
  2771                 formals = formals.tail;
  2773             if (useVarargs) {
  2774                 Type varArg = types.elemtype(last);
  2775                 while (args.tail != null) {
  2776                     JCTree arg = args.head;
  2777                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2778                     assertConvertible(arg, arg.type, varArg, warn);
  2779                     warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2780                     args = args.tail;
  2782             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2783                 // non-varargs call to varargs method
  2784                 Type varParam = owntype.getParameterTypes().last();
  2785                 Type lastArg = argtypes.last();
  2786                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2787                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2788                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2789                                 types.elemtype(varParam),
  2790                                 varParam);
  2793             if (warned && sym.type.tag == FORALL) {
  2794                 chk.warnUnchecked(env.tree.pos(),
  2795                                   "unchecked.meth.invocation.applied",
  2796                                   kindName(sym),
  2797                                   sym.name,
  2798                                   rs.methodArguments(sym.type.getParameterTypes()),
  2799                                   rs.methodArguments(argtypes),
  2800                                   kindName(sym.location()),
  2801                                   sym.location());
  2802                 owntype = new MethodType(owntype.getParameterTypes(),
  2803                                          types.erasure(owntype.getReturnType()),
  2804                                          owntype.getThrownTypes(),
  2805                                          syms.methodClass);
  2807             if (useVarargs) {
  2808                 JCTree tree = env.tree;
  2809                 Type argtype = owntype.getParameterTypes().last();
  2810                 if (owntype.getReturnType().tag != FORALL || warned) {
  2811                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym);
  2813                 Type elemtype = types.elemtype(argtype);
  2814                 switch (tree.getTag()) {
  2815                 case JCTree.APPLY:
  2816                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2817                     break;
  2818                 case JCTree.NEWCLASS:
  2819                     ((JCNewClass) tree).varargsElement = elemtype;
  2820                     break;
  2821                 default:
  2822                     throw new AssertionError(""+tree);
  2826         return owntype;
  2829     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2830         if (types.isConvertible(actual, formal, warn))
  2831             return;
  2833         if (formal.isCompound()
  2834             && types.isSubtype(actual, types.supertype(formal))
  2835             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2836             return;
  2838         if (false) {
  2839             // TODO: make assertConvertible work
  2840             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2841             throw new AssertionError("Tree: " + tree
  2842                                      + " actual:" + actual
  2843                                      + " formal: " + formal);
  2847     public void visitLiteral(JCLiteral tree) {
  2848         result = check(
  2849             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2851     //where
  2852     /** Return the type of a literal with given type tag.
  2853      */
  2854     Type litType(int tag) {
  2855         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2858     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2859         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2862     public void visitTypeArray(JCArrayTypeTree tree) {
  2863         Type etype = attribType(tree.elemtype, env);
  2864         Type type = new ArrayType(etype, syms.arrayClass);
  2865         result = check(tree, type, TYP, pkind, pt);
  2868     /** Visitor method for parameterized types.
  2869      *  Bound checking is left until later, since types are attributed
  2870      *  before supertype structure is completely known
  2871      */
  2872     public void visitTypeApply(JCTypeApply tree) {
  2873         Type owntype = types.createErrorType(tree.type);
  2875         // Attribute functor part of application and make sure it's a class.
  2876         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2878         // Attribute type parameters
  2879         List<Type> actuals = attribTypes(tree.arguments, env);
  2881         if (clazztype.tag == CLASS) {
  2882             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2884             if (actuals.length() == formals.length() || actuals.length() == 0) {
  2885                 List<Type> a = actuals;
  2886                 List<Type> f = formals;
  2887                 while (a.nonEmpty()) {
  2888                     a.head = a.head.withTypeVar(f.head);
  2889                     a = a.tail;
  2890                     f = f.tail;
  2892                 // Compute the proper generic outer
  2893                 Type clazzOuter = clazztype.getEnclosingType();
  2894                 if (clazzOuter.tag == CLASS) {
  2895                     Type site;
  2896                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2897                     if (clazz.getTag() == JCTree.IDENT) {
  2898                         site = env.enclClass.sym.type;
  2899                     } else if (clazz.getTag() == JCTree.SELECT) {
  2900                         site = ((JCFieldAccess) clazz).selected.type;
  2901                     } else throw new AssertionError(""+tree);
  2902                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2903                         if (site.tag == CLASS)
  2904                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2905                         if (site == null)
  2906                             site = types.erasure(clazzOuter);
  2907                         clazzOuter = site;
  2910                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2911             } else {
  2912                 if (formals.length() != 0) {
  2913                     log.error(tree.pos(), "wrong.number.type.args",
  2914                               Integer.toString(formals.length()));
  2915                 } else {
  2916                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2918                 owntype = types.createErrorType(tree.type);
  2921         result = check(tree, owntype, TYP, pkind, pt);
  2924     public void visitTypeDisjunction(JCTypeDisjunction tree) {
  2925         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2926         for (JCExpression typeTree : tree.alternatives) {
  2927             Type ctype = attribType(typeTree, env);
  2928             ctype = chk.checkType(typeTree.pos(),
  2929                           chk.checkClassType(typeTree.pos(), ctype),
  2930                           syms.throwableType);
  2931             multicatchTypes.append(ctype);
  2933         tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2936     public void visitTypeParameter(JCTypeParameter tree) {
  2937         TypeVar a = (TypeVar)tree.type;
  2938         Set<Type> boundSet = new HashSet<Type>();
  2939         if (a.bound.isErroneous())
  2940             return;
  2941         List<Type> bs = types.getBounds(a);
  2942         if (tree.bounds.nonEmpty()) {
  2943             // accept class or interface or typevar as first bound.
  2944             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2945             boundSet.add(types.erasure(b));
  2946             if (b.isErroneous()) {
  2947                 a.bound = b;
  2949             else if (b.tag == TYPEVAR) {
  2950                 // if first bound was a typevar, do not accept further bounds.
  2951                 if (tree.bounds.tail.nonEmpty()) {
  2952                     log.error(tree.bounds.tail.head.pos(),
  2953                               "type.var.may.not.be.followed.by.other.bounds");
  2954                     tree.bounds = List.of(tree.bounds.head);
  2955                     a.bound = bs.head;
  2957             } else {
  2958                 // if first bound was a class or interface, accept only interfaces
  2959                 // as further bounds.
  2960                 for (JCExpression bound : tree.bounds.tail) {
  2961                     bs = bs.tail;
  2962                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2963                     if (i.isErroneous())
  2964                         a.bound = i;
  2965                     else if (i.tag == CLASS)
  2966                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2970         bs = types.getBounds(a);
  2972         // in case of multiple bounds ...
  2973         if (bs.length() > 1) {
  2974             // ... the variable's bound is a class type flagged COMPOUND
  2975             // (see comment for TypeVar.bound).
  2976             // In this case, generate a class tree that represents the
  2977             // bound class, ...
  2978             JCTree extending;
  2979             List<JCExpression> implementing;
  2980             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2981                 extending = tree.bounds.head;
  2982                 implementing = tree.bounds.tail;
  2983             } else {
  2984                 extending = null;
  2985                 implementing = tree.bounds;
  2987             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2988                 make.Modifiers(PUBLIC | ABSTRACT),
  2989                 tree.name, List.<JCTypeParameter>nil(),
  2990                 extending, implementing, List.<JCTree>nil());
  2992             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2993             Assert.check((c.flags() & COMPOUND) != 0);
  2994             cd.sym = c;
  2995             c.sourcefile = env.toplevel.sourcefile;
  2997             // ... and attribute the bound class
  2998             c.flags_field |= UNATTRIBUTED;
  2999             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3000             enter.typeEnvs.put(c, cenv);
  3005     public void visitWildcard(JCWildcard tree) {
  3006         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3007         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3008             ? syms.objectType
  3009             : attribType(tree.inner, env);
  3010         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3011                                               tree.kind.kind,
  3012                                               syms.boundClass),
  3013                        TYP, pkind, pt);
  3016     public void visitAnnotation(JCAnnotation tree) {
  3017         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  3018         result = tree.type = syms.errType;
  3021     public void visitErroneous(JCErroneous tree) {
  3022         if (tree.errs != null)
  3023             for (JCTree err : tree.errs)
  3024                 attribTree(err, env, ERR, pt);
  3025         result = tree.type = syms.errType;
  3028     /** Default visitor method for all other trees.
  3029      */
  3030     public void visitTree(JCTree tree) {
  3031         throw new AssertionError();
  3034     /** Main method: attribute class definition associated with given class symbol.
  3035      *  reporting completion failures at the given position.
  3036      *  @param pos The source position at which completion errors are to be
  3037      *             reported.
  3038      *  @param c   The class symbol whose definition will be attributed.
  3039      */
  3040     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3041         try {
  3042             annotate.flush();
  3043             attribClass(c);
  3044         } catch (CompletionFailure ex) {
  3045             chk.completionError(pos, ex);
  3049     /** Attribute class definition associated with given class symbol.
  3050      *  @param c   The class symbol whose definition will be attributed.
  3051      */
  3052     void attribClass(ClassSymbol c) throws CompletionFailure {
  3053         if (c.type.tag == ERROR) return;
  3055         // Check for cycles in the inheritance graph, which can arise from
  3056         // ill-formed class files.
  3057         chk.checkNonCyclic(null, c.type);
  3059         Type st = types.supertype(c.type);
  3060         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3061             // First, attribute superclass.
  3062             if (st.tag == CLASS)
  3063                 attribClass((ClassSymbol)st.tsym);
  3065             // Next attribute owner, if it is a class.
  3066             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3067                 attribClass((ClassSymbol)c.owner);
  3070         // The previous operations might have attributed the current class
  3071         // if there was a cycle. So we test first whether the class is still
  3072         // UNATTRIBUTED.
  3073         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3074             c.flags_field &= ~UNATTRIBUTED;
  3076             // Get environment current at the point of class definition.
  3077             Env<AttrContext> env = enter.typeEnvs.get(c);
  3079             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3080             // because the annotations were not available at the time the env was created. Therefore,
  3081             // we look up the environment chain for the first enclosing environment for which the
  3082             // lint value is set. Typically, this is the parent env, but might be further if there
  3083             // are any envs created as a result of TypeParameter nodes.
  3084             Env<AttrContext> lintEnv = env;
  3085             while (lintEnv.info.lint == null)
  3086                 lintEnv = lintEnv.next;
  3088             // Having found the enclosing lint value, we can initialize the lint value for this class
  3089             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3091             Lint prevLint = chk.setLint(env.info.lint);
  3092             JavaFileObject prev = log.useSource(c.sourcefile);
  3094             try {
  3095                 // java.lang.Enum may not be subclassed by a non-enum
  3096                 if (st.tsym == syms.enumSym &&
  3097                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3098                     log.error(env.tree.pos(), "enum.no.subclassing");
  3100                 // Enums may not be extended by source-level classes
  3101                 if (st.tsym != null &&
  3102                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3103                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3104                     !target.compilerBootstrap(c)) {
  3105                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3107                 attribClassBody(env, c);
  3109                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3110             } finally {
  3111                 log.useSource(prev);
  3112                 chk.setLint(prevLint);
  3118     public void visitImport(JCImport tree) {
  3119         // nothing to do
  3122     /** Finish the attribution of a class. */
  3123     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3124         JCClassDecl tree = (JCClassDecl)env.tree;
  3125         Assert.check(c == tree.sym);
  3127         // Validate annotations
  3128         chk.validateAnnotations(tree.mods.annotations, c);
  3130         // Validate type parameters, supertype and interfaces.
  3131         attribBounds(tree.typarams);
  3132         if (!c.isAnonymous()) {
  3133             //already checked if anonymous
  3134             chk.validate(tree.typarams, env);
  3135             chk.validate(tree.extending, env);
  3136             chk.validate(tree.implementing, env);
  3139         // If this is a non-abstract class, check that it has no abstract
  3140         // methods or unimplemented methods of an implemented interface.
  3141         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3142             if (!relax)
  3143                 chk.checkAllDefined(tree.pos(), c);
  3146         if ((c.flags() & ANNOTATION) != 0) {
  3147             if (tree.implementing.nonEmpty())
  3148                 log.error(tree.implementing.head.pos(),
  3149                           "cant.extend.intf.annotation");
  3150             if (tree.typarams.nonEmpty())
  3151                 log.error(tree.typarams.head.pos(),
  3152                           "intf.annotation.cant.have.type.params");
  3153         } else {
  3154             // Check that all extended classes and interfaces
  3155             // are compatible (i.e. no two define methods with same arguments
  3156             // yet different return types).  (JLS 8.4.6.3)
  3157             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3160         // Check that class does not import the same parameterized interface
  3161         // with two different argument lists.
  3162         chk.checkClassBounds(tree.pos(), c.type);
  3164         tree.type = c.type;
  3166         for (List<JCTypeParameter> l = tree.typarams;
  3167              l.nonEmpty(); l = l.tail) {
  3168              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3171         // Check that a generic class doesn't extend Throwable
  3172         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3173             log.error(tree.extending.pos(), "generic.throwable");
  3175         // Check that all methods which implement some
  3176         // method conform to the method they implement.
  3177         chk.checkImplementations(tree);
  3179         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3180             // Attribute declaration
  3181             attribStat(l.head, env);
  3182             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3183             // Make an exception for static constants.
  3184             if (c.owner.kind != PCK &&
  3185                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3186                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3187                 Symbol sym = null;
  3188                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3189                 if (sym == null ||
  3190                     sym.kind != VAR ||
  3191                     ((VarSymbol) sym).getConstValue() == null)
  3192                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3196         // Check for cycles among non-initial constructors.
  3197         chk.checkCyclicConstructors(tree);
  3199         // Check for cycles among annotation elements.
  3200         chk.checkNonCyclicElements(tree);
  3202         // Check for proper use of serialVersionUID
  3203         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3204             isSerializable(c) &&
  3205             (c.flags() & Flags.ENUM) == 0 &&
  3206             (c.flags() & ABSTRACT) == 0) {
  3207             checkSerialVersionUID(tree, c);
  3210         // where
  3211         /** check if a class is a subtype of Serializable, if that is available. */
  3212         private boolean isSerializable(ClassSymbol c) {
  3213             try {
  3214                 syms.serializableType.complete();
  3216             catch (CompletionFailure e) {
  3217                 return false;
  3219             return types.isSubtype(c.type, syms.serializableType);
  3222         /** Check that an appropriate serialVersionUID member is defined. */
  3223         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3225             // check for presence of serialVersionUID
  3226             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3227             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3228             if (e.scope == null) {
  3229                 log.warning(LintCategory.SERIAL,
  3230                         tree.pos(), "missing.SVUID", c);
  3231                 return;
  3234             // check that it is static final
  3235             VarSymbol svuid = (VarSymbol)e.sym;
  3236             if ((svuid.flags() & (STATIC | FINAL)) !=
  3237                 (STATIC | FINAL))
  3238                 log.warning(LintCategory.SERIAL,
  3239                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3241             // check that it is long
  3242             else if (svuid.type.tag != TypeTags.LONG)
  3243                 log.warning(LintCategory.SERIAL,
  3244                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3246             // check constant
  3247             else if (svuid.getConstValue() == null)
  3248                 log.warning(LintCategory.SERIAL,
  3249                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3252     private Type capture(Type type) {
  3253         return types.capture(type);
  3256     // <editor-fold desc="post-attribution visitor">
  3258     /**
  3259      * Handle missing types/symbols in an AST. This routine is useful when
  3260      * the compiler has encountered some errors (which might have ended up
  3261      * terminating attribution abruptly); if the compiler is used in fail-over
  3262      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3263      * prevents NPE to be progagated during subsequent compilation steps.
  3264      */
  3265     public void postAttr(Env<AttrContext> env) {
  3266         new PostAttrAnalyzer().scan(env.tree);
  3269     class PostAttrAnalyzer extends TreeScanner {
  3271         private void initTypeIfNeeded(JCTree that) {
  3272             if (that.type == null) {
  3273                 that.type = syms.unknownType;
  3277         @Override
  3278         public void scan(JCTree tree) {
  3279             if (tree == null) return;
  3280             if (tree instanceof JCExpression) {
  3281                 initTypeIfNeeded(tree);
  3283             super.scan(tree);
  3286         @Override
  3287         public void visitIdent(JCIdent that) {
  3288             if (that.sym == null) {
  3289                 that.sym = syms.unknownSymbol;
  3293         @Override
  3294         public void visitSelect(JCFieldAccess that) {
  3295             if (that.sym == null) {
  3296                 that.sym = syms.unknownSymbol;
  3298             super.visitSelect(that);
  3301         @Override
  3302         public void visitClassDef(JCClassDecl that) {
  3303             initTypeIfNeeded(that);
  3304             if (that.sym == null) {
  3305                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3307             super.visitClassDef(that);
  3310         @Override
  3311         public void visitMethodDef(JCMethodDecl that) {
  3312             initTypeIfNeeded(that);
  3313             if (that.sym == null) {
  3314                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3316             super.visitMethodDef(that);
  3319         @Override
  3320         public void visitVarDef(JCVariableDecl that) {
  3321             initTypeIfNeeded(that);
  3322             if (that.sym == null) {
  3323                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3324                 that.sym.adr = 0;
  3326             super.visitVarDef(that);
  3329         @Override
  3330         public void visitNewClass(JCNewClass that) {
  3331             if (that.constructor == null) {
  3332                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3334             if (that.constructorType == null) {
  3335                 that.constructorType = syms.unknownType;
  3337             super.visitNewClass(that);
  3340         @Override
  3341         public void visitBinary(JCBinary that) {
  3342             if (that.operator == null)
  3343                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3344             super.visitBinary(that);
  3347         @Override
  3348         public void visitUnary(JCUnary that) {
  3349             if (that.operator == null)
  3350                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3351             super.visitUnary(that);
  3354     // </editor-fold>

mercurial