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

Wed, 21 Sep 2011 21:56:53 -0700

author
jjg
date
Wed, 21 Sep 2011 21:56:53 -0700
changeset 1096
b0d5f00e69f7
parent 1078
1ee9f9a91e9c
child 1127
ca49d50318dc
permissions
-rw-r--r--

7092965: javac should not close processorClassLoader before end of compilation
Reviewed-by: darcy

     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         // ... but ...
   598         // There's a problem with evaluating annotations in the right order, such that
   599         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   600         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   601         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   602         if (env.info.enclVar.attributes_field == null)
   603             env.info.lint = lintEnv.info.lint;
   604         else
   605             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.attributes_field, env.info.enclVar.flags());
   607         Lint prevLint = chk.setLint(env.info.lint);
   608         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   610         try {
   611             Type itype = attribExpr(initializer, env, type);
   612             if (itype.constValue() != null)
   613                 return coerce(itype, type).constValue();
   614             else
   615                 return null;
   616         } finally {
   617             env.info.lint = prevLint;
   618             log.useSource(prevSource);
   619         }
   620     }
   622     /** Attribute type reference in an `extends' or `implements' clause.
   623      *  Supertypes of anonymous inner classes are usually already attributed.
   624      *
   625      *  @param tree              The tree making up the type reference.
   626      *  @param env               The environment current at the reference.
   627      *  @param classExpected     true if only a class is expected here.
   628      *  @param interfaceExpected true if only an interface is expected here.
   629      */
   630     Type attribBase(JCTree tree,
   631                     Env<AttrContext> env,
   632                     boolean classExpected,
   633                     boolean interfaceExpected,
   634                     boolean checkExtensible) {
   635         Type t = tree.type != null ?
   636             tree.type :
   637             attribType(tree, env);
   638         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   639     }
   640     Type checkBase(Type t,
   641                    JCTree tree,
   642                    Env<AttrContext> env,
   643                    boolean classExpected,
   644                    boolean interfaceExpected,
   645                    boolean checkExtensible) {
   646         if (t.isErroneous())
   647             return t;
   648         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   649             // check that type variable is already visible
   650             if (t.getUpperBound() == null) {
   651                 log.error(tree.pos(), "illegal.forward.ref");
   652                 return types.createErrorType(t);
   653             }
   654         } else {
   655             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   656         }
   657         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   658             log.error(tree.pos(), "intf.expected.here");
   659             // return errType is necessary since otherwise there might
   660             // be undetected cycles which cause attribution to loop
   661             return types.createErrorType(t);
   662         } else if (checkExtensible &&
   663                    classExpected &&
   664                    (t.tsym.flags() & INTERFACE) != 0) {
   665                 log.error(tree.pos(), "no.intf.expected.here");
   666             return types.createErrorType(t);
   667         }
   668         if (checkExtensible &&
   669             ((t.tsym.flags() & FINAL) != 0)) {
   670             log.error(tree.pos(),
   671                       "cant.inherit.from.final", t.tsym);
   672         }
   673         chk.checkNonCyclic(tree.pos(), t);
   674         return t;
   675     }
   677     public void visitClassDef(JCClassDecl tree) {
   678         // Local classes have not been entered yet, so we need to do it now:
   679         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   680             enter.classEnter(tree, env);
   682         ClassSymbol c = tree.sym;
   683         if (c == null) {
   684             // exit in case something drastic went wrong during enter.
   685             result = null;
   686         } else {
   687             // make sure class has been completed:
   688             c.complete();
   690             // If this class appears as an anonymous class
   691             // in a superclass constructor call where
   692             // no explicit outer instance is given,
   693             // disable implicit outer instance from being passed.
   694             // (This would be an illegal access to "this before super").
   695             if (env.info.isSelfCall &&
   696                 env.tree.getTag() == JCTree.NEWCLASS &&
   697                 ((JCNewClass) env.tree).encl == null)
   698             {
   699                 c.flags_field |= NOOUTERTHIS;
   700             }
   701             attribClass(tree.pos(), c);
   702             result = tree.type = c.type;
   703         }
   704     }
   706     public void visitMethodDef(JCMethodDecl tree) {
   707         MethodSymbol m = tree.sym;
   709         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   710         Lint prevLint = chk.setLint(lint);
   711         MethodSymbol prevMethod = chk.setMethod(m);
   712         try {
   713             deferredLintHandler.flush(tree.pos());
   714             chk.checkDeprecatedAnnotation(tree.pos(), m);
   716             attribBounds(tree.typarams);
   718             // If we override any other methods, check that we do so properly.
   719             // JLS ???
   720             if (m.isStatic()) {
   721                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   722             } else {
   723                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   724             }
   725             chk.checkOverride(tree, m);
   727             // Create a new environment with local scope
   728             // for attributing the method.
   729             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   731             localEnv.info.lint = lint;
   733             // Enter all type parameters into the local method scope.
   734             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   735                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   737             ClassSymbol owner = env.enclClass.sym;
   738             if ((owner.flags() & ANNOTATION) != 0 &&
   739                 tree.params.nonEmpty())
   740                 log.error(tree.params.head.pos(),
   741                           "intf.annotation.members.cant.have.params");
   743             // Attribute all value parameters.
   744             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   745                 attribStat(l.head, localEnv);
   746             }
   748             chk.checkVarargsMethodDecl(localEnv, tree);
   750             // Check that type parameters are well-formed.
   751             chk.validate(tree.typarams, localEnv);
   753             // Check that result type is well-formed.
   754             chk.validate(tree.restype, localEnv);
   756             // annotation method checks
   757             if ((owner.flags() & ANNOTATION) != 0) {
   758                 // annotation method cannot have throws clause
   759                 if (tree.thrown.nonEmpty()) {
   760                     log.error(tree.thrown.head.pos(),
   761                             "throws.not.allowed.in.intf.annotation");
   762                 }
   763                 // annotation method cannot declare type-parameters
   764                 if (tree.typarams.nonEmpty()) {
   765                     log.error(tree.typarams.head.pos(),
   766                             "intf.annotation.members.cant.have.type.params");
   767                 }
   768                 // validate annotation method's return type (could be an annotation type)
   769                 chk.validateAnnotationType(tree.restype);
   770                 // ensure that annotation method does not clash with members of Object/Annotation
   771                 chk.validateAnnotationMethod(tree.pos(), m);
   773                 if (tree.defaultValue != null) {
   774                     // if default value is an annotation, check it is a well-formed
   775                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   776                     chk.validateAnnotationTree(tree.defaultValue);
   777                 }
   778             }
   780             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   781                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   783             if (tree.body == null) {
   784                 // Empty bodies are only allowed for
   785                 // abstract, native, or interface methods, or for methods
   786                 // in a retrofit signature class.
   787                 if ((owner.flags() & INTERFACE) == 0 &&
   788                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   789                     !relax)
   790                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   791                 if (tree.defaultValue != null) {
   792                     if ((owner.flags() & ANNOTATION) == 0)
   793                         log.error(tree.pos(),
   794                                   "default.allowed.in.intf.annotation.member");
   795                 }
   796             } else if ((owner.flags() & INTERFACE) != 0) {
   797                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   798             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   799                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   800             } else if ((tree.mods.flags & NATIVE) != 0) {
   801                 log.error(tree.pos(), "native.meth.cant.have.body");
   802             } else {
   803                 // Add an implicit super() call unless an explicit call to
   804                 // super(...) or this(...) is given
   805                 // or we are compiling class java.lang.Object.
   806                 if (tree.name == names.init && owner.type != syms.objectType) {
   807                     JCBlock body = tree.body;
   808                     if (body.stats.isEmpty() ||
   809                         !TreeInfo.isSelfCall(body.stats.head)) {
   810                         body.stats = body.stats.
   811                             prepend(memberEnter.SuperCall(make.at(body.pos),
   812                                                           List.<Type>nil(),
   813                                                           List.<JCVariableDecl>nil(),
   814                                                           false));
   815                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   816                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   817                                TreeInfo.isSuperCall(body.stats.head)) {
   818                         // enum constructors are not allowed to call super
   819                         // directly, so make sure there aren't any super calls
   820                         // in enum constructors, except in the compiler
   821                         // generated one.
   822                         log.error(tree.body.stats.head.pos(),
   823                                   "call.to.super.not.allowed.in.enum.ctor",
   824                                   env.enclClass.sym);
   825                     }
   826                 }
   828                 // Attribute method body.
   829                 attribStat(tree.body, localEnv);
   830             }
   831             localEnv.info.scope.leave();
   832             result = tree.type = m.type;
   833             chk.validateAnnotations(tree.mods.annotations, m);
   834         }
   835         finally {
   836             chk.setLint(prevLint);
   837             chk.setMethod(prevMethod);
   838         }
   839     }
   841     public void visitVarDef(JCVariableDecl tree) {
   842         // Local variables have not been entered yet, so we need to do it now:
   843         if (env.info.scope.owner.kind == MTH) {
   844             if (tree.sym != null) {
   845                 // parameters have already been entered
   846                 env.info.scope.enter(tree.sym);
   847             } else {
   848                 memberEnter.memberEnter(tree, env);
   849                 annotate.flush();
   850             }
   851             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   852         }
   854         VarSymbol v = tree.sym;
   855         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   856         Lint prevLint = chk.setLint(lint);
   858         // Check that the variable's declared type is well-formed.
   859         chk.validate(tree.vartype, env);
   860         deferredLintHandler.flush(tree.pos());
   862         try {
   863             chk.checkDeprecatedAnnotation(tree.pos(), v);
   865             if (tree.init != null) {
   866                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   867                     // In this case, `v' is final.  Ensure that it's initializer is
   868                     // evaluated.
   869                     v.getConstValue(); // ensure initializer is evaluated
   870                 } else {
   871                     // Attribute initializer in a new environment
   872                     // with the declared variable as owner.
   873                     // Check that initializer conforms to variable's declared type.
   874                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   875                     initEnv.info.lint = lint;
   876                     // In order to catch self-references, we set the variable's
   877                     // declaration position to maximal possible value, effectively
   878                     // marking the variable as undefined.
   879                     initEnv.info.enclVar = v;
   880                     attribExpr(tree.init, initEnv, v.type);
   881                 }
   882             }
   883             result = tree.type = v.type;
   884             chk.validateAnnotations(tree.mods.annotations, v);
   885         }
   886         finally {
   887             chk.setLint(prevLint);
   888         }
   889     }
   891     public void visitSkip(JCSkip tree) {
   892         result = null;
   893     }
   895     public void visitBlock(JCBlock tree) {
   896         if (env.info.scope.owner.kind == TYP) {
   897             // Block is a static or instance initializer;
   898             // let the owner of the environment be a freshly
   899             // created BLOCK-method.
   900             Env<AttrContext> localEnv =
   901                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   902             localEnv.info.scope.owner =
   903                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   904                                  env.info.scope.owner);
   905             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   906             attribStats(tree.stats, localEnv);
   907         } else {
   908             // Create a new local environment with a local scope.
   909             Env<AttrContext> localEnv =
   910                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   911             attribStats(tree.stats, localEnv);
   912             localEnv.info.scope.leave();
   913         }
   914         result = null;
   915     }
   917     public void visitDoLoop(JCDoWhileLoop tree) {
   918         attribStat(tree.body, env.dup(tree));
   919         attribExpr(tree.cond, env, syms.booleanType);
   920         result = null;
   921     }
   923     public void visitWhileLoop(JCWhileLoop tree) {
   924         attribExpr(tree.cond, env, syms.booleanType);
   925         attribStat(tree.body, env.dup(tree));
   926         result = null;
   927     }
   929     public void visitForLoop(JCForLoop tree) {
   930         Env<AttrContext> loopEnv =
   931             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   932         attribStats(tree.init, loopEnv);
   933         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   934         loopEnv.tree = tree; // before, we were not in loop!
   935         attribStats(tree.step, loopEnv);
   936         attribStat(tree.body, loopEnv);
   937         loopEnv.info.scope.leave();
   938         result = null;
   939     }
   941     public void visitForeachLoop(JCEnhancedForLoop tree) {
   942         Env<AttrContext> loopEnv =
   943             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   944         attribStat(tree.var, loopEnv);
   945         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   946         chk.checkNonVoid(tree.pos(), exprType);
   947         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   948         if (elemtype == null) {
   949             // or perhaps expr implements Iterable<T>?
   950             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   951             if (base == null) {
   952                 log.error(tree.expr.pos(),
   953                         "foreach.not.applicable.to.type",
   954                         exprType,
   955                         diags.fragment("type.req.array.or.iterable"));
   956                 elemtype = types.createErrorType(exprType);
   957             } else {
   958                 List<Type> iterableParams = base.allparams();
   959                 elemtype = iterableParams.isEmpty()
   960                     ? syms.objectType
   961                     : types.upperBound(iterableParams.head);
   962             }
   963         }
   964         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   965         loopEnv.tree = tree; // before, we were not in loop!
   966         attribStat(tree.body, loopEnv);
   967         loopEnv.info.scope.leave();
   968         result = null;
   969     }
   971     public void visitLabelled(JCLabeledStatement tree) {
   972         // Check that label is not used in an enclosing statement
   973         Env<AttrContext> env1 = env;
   974         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   975             if (env1.tree.getTag() == JCTree.LABELLED &&
   976                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   977                 log.error(tree.pos(), "label.already.in.use",
   978                           tree.label);
   979                 break;
   980             }
   981             env1 = env1.next;
   982         }
   984         attribStat(tree.body, env.dup(tree));
   985         result = null;
   986     }
   988     public void visitSwitch(JCSwitch tree) {
   989         Type seltype = attribExpr(tree.selector, env);
   991         Env<AttrContext> switchEnv =
   992             env.dup(tree, env.info.dup(env.info.scope.dup()));
   994         boolean enumSwitch =
   995             allowEnums &&
   996             (seltype.tsym.flags() & Flags.ENUM) != 0;
   997         boolean stringSwitch = false;
   998         if (types.isSameType(seltype, syms.stringType)) {
   999             if (allowStringsInSwitch) {
  1000                 stringSwitch = true;
  1001             } else {
  1002                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1005         if (!enumSwitch && !stringSwitch)
  1006             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1008         // Attribute all cases and
  1009         // check that there are no duplicate case labels or default clauses.
  1010         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1011         boolean hasDefault = false;      // Is there a default label?
  1012         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1013             JCCase c = l.head;
  1014             Env<AttrContext> caseEnv =
  1015                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1016             if (c.pat != null) {
  1017                 if (enumSwitch) {
  1018                     Symbol sym = enumConstant(c.pat, seltype);
  1019                     if (sym == null) {
  1020                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1021                     } else if (!labels.add(sym)) {
  1022                         log.error(c.pos(), "duplicate.case.label");
  1024                 } else {
  1025                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1026                     if (pattype.tag != ERROR) {
  1027                         if (pattype.constValue() == null) {
  1028                             log.error(c.pat.pos(),
  1029                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
  1030                         } else if (labels.contains(pattype.constValue())) {
  1031                             log.error(c.pos(), "duplicate.case.label");
  1032                         } else {
  1033                             labels.add(pattype.constValue());
  1037             } else if (hasDefault) {
  1038                 log.error(c.pos(), "duplicate.default.label");
  1039             } else {
  1040                 hasDefault = true;
  1042             attribStats(c.stats, caseEnv);
  1043             caseEnv.info.scope.leave();
  1044             addVars(c.stats, switchEnv.info.scope);
  1047         switchEnv.info.scope.leave();
  1048         result = null;
  1050     // where
  1051         /** Add any variables defined in stats to the switch scope. */
  1052         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1053             for (;stats.nonEmpty(); stats = stats.tail) {
  1054                 JCTree stat = stats.head;
  1055                 if (stat.getTag() == JCTree.VARDEF)
  1056                     switchScope.enter(((JCVariableDecl) stat).sym);
  1059     // where
  1060     /** Return the selected enumeration constant symbol, or null. */
  1061     private Symbol enumConstant(JCTree tree, Type enumType) {
  1062         if (tree.getTag() != JCTree.IDENT) {
  1063             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1064             return syms.errSymbol;
  1066         JCIdent ident = (JCIdent)tree;
  1067         Name name = ident.name;
  1068         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1069              e.scope != null; e = e.next()) {
  1070             if (e.sym.kind == VAR) {
  1071                 Symbol s = ident.sym = e.sym;
  1072                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1073                 ident.type = s.type;
  1074                 return ((s.flags_field & Flags.ENUM) == 0)
  1075                     ? null : s;
  1078         return null;
  1081     public void visitSynchronized(JCSynchronized tree) {
  1082         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1083         attribStat(tree.body, env);
  1084         result = null;
  1087     public void visitTry(JCTry tree) {
  1088         // Create a new local environment with a local
  1089         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1090         boolean isTryWithResource = tree.resources.nonEmpty();
  1091         // Create a nested environment for attributing the try block if needed
  1092         Env<AttrContext> tryEnv = isTryWithResource ?
  1093             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1094             localEnv;
  1095         // Attribute resource declarations
  1096         for (JCTree resource : tree.resources) {
  1097             if (resource.getTag() == JCTree.VARDEF) {
  1098                 attribStat(resource, tryEnv);
  1099                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1101                 //check that resource type cannot throw InterruptedException
  1102                 checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1104                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1105                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1106             } else {
  1107                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1110         // Attribute body
  1111         attribStat(tree.body, tryEnv);
  1112         if (isTryWithResource)
  1113             tryEnv.info.scope.leave();
  1115         // Attribute catch clauses
  1116         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1117             JCCatch c = l.head;
  1118             Env<AttrContext> catchEnv =
  1119                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1120             Type ctype = attribStat(c.param, catchEnv);
  1121             if (TreeInfo.isMultiCatch(c)) {
  1122                 //multi-catch parameter is implicitly marked as final
  1123                 c.param.sym.flags_field |= FINAL | UNION;
  1125             if (c.param.sym.kind == Kinds.VAR) {
  1126                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1128             chk.checkType(c.param.vartype.pos(),
  1129                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1130                           syms.throwableType);
  1131             attribStat(c.body, catchEnv);
  1132             catchEnv.info.scope.leave();
  1135         // Attribute finalizer
  1136         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1138         localEnv.info.scope.leave();
  1139         result = null;
  1142     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1143         if (!resource.isErroneous() &&
  1144                 types.asSuper(resource, syms.autoCloseableType.tsym) != null) {
  1145             Symbol close = syms.noSymbol;
  1146             boolean prevDeferDiags = log.deferDiagnostics;
  1147             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1148             try {
  1149                 log.deferDiagnostics = true;
  1150                 log.deferredDiagnostics = ListBuffer.lb();
  1151                 close = rs.resolveQualifiedMethod(pos,
  1152                         env,
  1153                         resource,
  1154                         names.close,
  1155                         List.<Type>nil(),
  1156                         List.<Type>nil());
  1158             finally {
  1159                 log.deferDiagnostics = prevDeferDiags;
  1160                 log.deferredDiagnostics = prevDeferredDiags;
  1162             if (close.kind == MTH &&
  1163                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1164                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1165                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1166                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1171     public void visitConditional(JCConditional tree) {
  1172         attribExpr(tree.cond, env, syms.booleanType);
  1173         attribExpr(tree.truepart, env);
  1174         attribExpr(tree.falsepart, env);
  1175         result = check(tree,
  1176                        capture(condType(tree.pos(), tree.cond.type,
  1177                                         tree.truepart.type, tree.falsepart.type)),
  1178                        VAL, pkind, pt);
  1180     //where
  1181         /** Compute the type of a conditional expression, after
  1182          *  checking that it exists. See Spec 15.25.
  1184          *  @param pos      The source position to be used for
  1185          *                  error diagnostics.
  1186          *  @param condtype The type of the expression's condition.
  1187          *  @param thentype The type of the expression's then-part.
  1188          *  @param elsetype The type of the expression's else-part.
  1189          */
  1190         private Type condType(DiagnosticPosition pos,
  1191                               Type condtype,
  1192                               Type thentype,
  1193                               Type elsetype) {
  1194             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1196             // If condition and both arms are numeric constants,
  1197             // evaluate at compile-time.
  1198             return ((condtype.constValue() != null) &&
  1199                     (thentype.constValue() != null) &&
  1200                     (elsetype.constValue() != null))
  1201                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1202                 : ctype;
  1204         /** Compute the type of a conditional expression, after
  1205          *  checking that it exists.  Does not take into
  1206          *  account the special case where condition and both arms
  1207          *  are constants.
  1209          *  @param pos      The source position to be used for error
  1210          *                  diagnostics.
  1211          *  @param condtype The type of the expression's condition.
  1212          *  @param thentype The type of the expression's then-part.
  1213          *  @param elsetype The type of the expression's else-part.
  1214          */
  1215         private Type condType1(DiagnosticPosition pos, Type condtype,
  1216                                Type thentype, Type elsetype) {
  1217             // If same type, that is the result
  1218             if (types.isSameType(thentype, elsetype))
  1219                 return thentype.baseType();
  1221             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1222                 ? thentype : types.unboxedType(thentype);
  1223             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1224                 ? elsetype : types.unboxedType(elsetype);
  1226             // Otherwise, if both arms can be converted to a numeric
  1227             // type, return the least numeric type that fits both arms
  1228             // (i.e. return larger of the two, or return int if one
  1229             // arm is short, the other is char).
  1230             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1231                 // If one arm has an integer subrange type (i.e., byte,
  1232                 // short, or char), and the other is an integer constant
  1233                 // that fits into the subrange, return the subrange type.
  1234                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1235                     types.isAssignable(elseUnboxed, thenUnboxed))
  1236                     return thenUnboxed.baseType();
  1237                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1238                     types.isAssignable(thenUnboxed, elseUnboxed))
  1239                     return elseUnboxed.baseType();
  1241                 for (int i = BYTE; i < VOID; i++) {
  1242                     Type candidate = syms.typeOfTag[i];
  1243                     if (types.isSubtype(thenUnboxed, candidate) &&
  1244                         types.isSubtype(elseUnboxed, candidate))
  1245                         return candidate;
  1249             // Those were all the cases that could result in a primitive
  1250             if (allowBoxing) {
  1251                 if (thentype.isPrimitive())
  1252                     thentype = types.boxedClass(thentype).type;
  1253                 if (elsetype.isPrimitive())
  1254                     elsetype = types.boxedClass(elsetype).type;
  1257             if (types.isSubtype(thentype, elsetype))
  1258                 return elsetype.baseType();
  1259             if (types.isSubtype(elsetype, thentype))
  1260                 return thentype.baseType();
  1262             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1263                 log.error(pos, "neither.conditional.subtype",
  1264                           thentype, elsetype);
  1265                 return thentype.baseType();
  1268             // both are known to be reference types.  The result is
  1269             // lub(thentype,elsetype). This cannot fail, as it will
  1270             // always be possible to infer "Object" if nothing better.
  1271             return types.lub(thentype.baseType(), elsetype.baseType());
  1274     public void visitIf(JCIf tree) {
  1275         attribExpr(tree.cond, env, syms.booleanType);
  1276         attribStat(tree.thenpart, env);
  1277         if (tree.elsepart != null)
  1278             attribStat(tree.elsepart, env);
  1279         chk.checkEmptyIf(tree);
  1280         result = null;
  1283     public void visitExec(JCExpressionStatement tree) {
  1284         //a fresh environment is required for 292 inference to work properly ---
  1285         //see Infer.instantiatePolymorphicSignatureInstance()
  1286         Env<AttrContext> localEnv = env.dup(tree);
  1287         attribExpr(tree.expr, localEnv);
  1288         result = null;
  1291     public void visitBreak(JCBreak tree) {
  1292         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1293         result = null;
  1296     public void visitContinue(JCContinue tree) {
  1297         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1298         result = null;
  1300     //where
  1301         /** Return the target of a break or continue statement, if it exists,
  1302          *  report an error if not.
  1303          *  Note: The target of a labelled break or continue is the
  1304          *  (non-labelled) statement tree referred to by the label,
  1305          *  not the tree representing the labelled statement itself.
  1307          *  @param pos     The position to be used for error diagnostics
  1308          *  @param tag     The tag of the jump statement. This is either
  1309          *                 Tree.BREAK or Tree.CONTINUE.
  1310          *  @param label   The label of the jump statement, or null if no
  1311          *                 label is given.
  1312          *  @param env     The environment current at the jump statement.
  1313          */
  1314         private JCTree findJumpTarget(DiagnosticPosition pos,
  1315                                     int tag,
  1316                                     Name label,
  1317                                     Env<AttrContext> env) {
  1318             // Search environments outwards from the point of jump.
  1319             Env<AttrContext> env1 = env;
  1320             LOOP:
  1321             while (env1 != null) {
  1322                 switch (env1.tree.getTag()) {
  1323                 case JCTree.LABELLED:
  1324                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1325                     if (label == labelled.label) {
  1326                         // If jump is a continue, check that target is a loop.
  1327                         if (tag == JCTree.CONTINUE) {
  1328                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1329                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1330                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1331                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1332                                 log.error(pos, "not.loop.label", label);
  1333                             // Found labelled statement target, now go inwards
  1334                             // to next non-labelled tree.
  1335                             return TreeInfo.referencedStatement(labelled);
  1336                         } else {
  1337                             return labelled;
  1340                     break;
  1341                 case JCTree.DOLOOP:
  1342                 case JCTree.WHILELOOP:
  1343                 case JCTree.FORLOOP:
  1344                 case JCTree.FOREACHLOOP:
  1345                     if (label == null) return env1.tree;
  1346                     break;
  1347                 case JCTree.SWITCH:
  1348                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1349                     break;
  1350                 case JCTree.METHODDEF:
  1351                 case JCTree.CLASSDEF:
  1352                     break LOOP;
  1353                 default:
  1355                 env1 = env1.next;
  1357             if (label != null)
  1358                 log.error(pos, "undef.label", label);
  1359             else if (tag == JCTree.CONTINUE)
  1360                 log.error(pos, "cont.outside.loop");
  1361             else
  1362                 log.error(pos, "break.outside.switch.loop");
  1363             return null;
  1366     public void visitReturn(JCReturn tree) {
  1367         // Check that there is an enclosing method which is
  1368         // nested within than the enclosing class.
  1369         if (env.enclMethod == null ||
  1370             env.enclMethod.sym.owner != env.enclClass.sym) {
  1371             log.error(tree.pos(), "ret.outside.meth");
  1373         } else {
  1374             // Attribute return expression, if it exists, and check that
  1375             // it conforms to result type of enclosing method.
  1376             Symbol m = env.enclMethod.sym;
  1377             if (m.type.getReturnType().tag == VOID) {
  1378                 if (tree.expr != null)
  1379                     log.error(tree.expr.pos(),
  1380                               "cant.ret.val.from.meth.decl.void");
  1381             } else if (tree.expr == null) {
  1382                 log.error(tree.pos(), "missing.ret.val");
  1383             } else {
  1384                 attribExpr(tree.expr, env, m.type.getReturnType());
  1387         result = null;
  1390     public void visitThrow(JCThrow tree) {
  1391         attribExpr(tree.expr, env, syms.throwableType);
  1392         result = null;
  1395     public void visitAssert(JCAssert tree) {
  1396         attribExpr(tree.cond, env, syms.booleanType);
  1397         if (tree.detail != null) {
  1398             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1400         result = null;
  1403      /** Visitor method for method invocations.
  1404      *  NOTE: The method part of an application will have in its type field
  1405      *        the return type of the method, not the method's type itself!
  1406      */
  1407     public void visitApply(JCMethodInvocation tree) {
  1408         // The local environment of a method application is
  1409         // a new environment nested in the current one.
  1410         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1412         // The types of the actual method arguments.
  1413         List<Type> argtypes;
  1415         // The types of the actual method type arguments.
  1416         List<Type> typeargtypes = null;
  1418         Name methName = TreeInfo.name(tree.meth);
  1420         boolean isConstructorCall =
  1421             methName == names._this || methName == names._super;
  1423         if (isConstructorCall) {
  1424             // We are seeing a ...this(...) or ...super(...) call.
  1425             // Check that this is the first statement in a constructor.
  1426             if (checkFirstConstructorStat(tree, env)) {
  1428                 // Record the fact
  1429                 // that this is a constructor call (using isSelfCall).
  1430                 localEnv.info.isSelfCall = true;
  1432                 // Attribute arguments, yielding list of argument types.
  1433                 argtypes = attribArgs(tree.args, localEnv);
  1434                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1436                 // Variable `site' points to the class in which the called
  1437                 // constructor is defined.
  1438                 Type site = env.enclClass.sym.type;
  1439                 if (methName == names._super) {
  1440                     if (site == syms.objectType) {
  1441                         log.error(tree.meth.pos(), "no.superclass", site);
  1442                         site = types.createErrorType(syms.objectType);
  1443                     } else {
  1444                         site = types.supertype(site);
  1448                 if (site.tag == CLASS) {
  1449                     Type encl = site.getEnclosingType();
  1450                     while (encl != null && encl.tag == TYPEVAR)
  1451                         encl = encl.getUpperBound();
  1452                     if (encl.tag == CLASS) {
  1453                         // we are calling a nested class
  1455                         if (tree.meth.getTag() == JCTree.SELECT) {
  1456                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1458                             // We are seeing a prefixed call, of the form
  1459                             //     <expr>.super(...).
  1460                             // Check that the prefix expression conforms
  1461                             // to the outer instance type of the class.
  1462                             chk.checkRefType(qualifier.pos(),
  1463                                              attribExpr(qualifier, localEnv,
  1464                                                         encl));
  1465                         } else if (methName == names._super) {
  1466                             // qualifier omitted; check for existence
  1467                             // of an appropriate implicit qualifier.
  1468                             rs.resolveImplicitThis(tree.meth.pos(),
  1469                                                    localEnv, site, true);
  1471                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1472                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1473                                   site.tsym);
  1476                     // if we're calling a java.lang.Enum constructor,
  1477                     // prefix the implicit String and int parameters
  1478                     if (site.tsym == syms.enumSym && allowEnums)
  1479                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1481                     // Resolve the called constructor under the assumption
  1482                     // that we are referring to a superclass instance of the
  1483                     // current instance (JLS ???).
  1484                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1485                     localEnv.info.selectSuper = true;
  1486                     localEnv.info.varArgs = false;
  1487                     Symbol sym = rs.resolveConstructor(
  1488                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1489                     localEnv.info.selectSuper = selectSuperPrev;
  1491                     // Set method symbol to resolved constructor...
  1492                     TreeInfo.setSymbol(tree.meth, sym);
  1494                     // ...and check that it is legal in the current context.
  1495                     // (this will also set the tree's type)
  1496                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1497                     checkId(tree.meth, site, sym, localEnv, MTH,
  1498                             mpt, tree.varargsElement != null);
  1500                 // Otherwise, `site' is an error type and we do nothing
  1502             result = tree.type = syms.voidType;
  1503         } else {
  1504             // Otherwise, we are seeing a regular method call.
  1505             // Attribute the arguments, yielding list of argument types, ...
  1506             argtypes = attribArgs(tree.args, localEnv);
  1507             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1509             // ... and attribute the method using as a prototype a methodtype
  1510             // whose formal argument types is exactly the list of actual
  1511             // arguments (this will also set the method symbol).
  1512             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1513             localEnv.info.varArgs = false;
  1514             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1515             if (localEnv.info.varArgs)
  1516                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
  1518             // Compute the result type.
  1519             Type restype = mtype.getReturnType();
  1520             if (restype.tag == WILDCARD)
  1521                 throw new AssertionError(mtype);
  1523             // as a special case, array.clone() has a result that is
  1524             // the same as static type of the array being cloned
  1525             if (tree.meth.getTag() == JCTree.SELECT &&
  1526                 allowCovariantReturns &&
  1527                 methName == names.clone &&
  1528                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1529                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1531             // as a special case, x.getClass() has type Class<? extends |X|>
  1532             if (allowGenerics &&
  1533                 methName == names.getClass && tree.args.isEmpty()) {
  1534                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1535                     ? ((JCFieldAccess) tree.meth).selected.type
  1536                     : env.enclClass.sym.type;
  1537                 restype = new
  1538                     ClassType(restype.getEnclosingType(),
  1539                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1540                                                                BoundKind.EXTENDS,
  1541                                                                syms.boundClass)),
  1542                               restype.tsym);
  1545             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1547             // Check that value of resulting type is admissible in the
  1548             // current context.  Also, capture the return type
  1549             result = check(tree, capture(restype), VAL, pkind, pt);
  1551         chk.validate(tree.typeargs, localEnv);
  1553     //where
  1554         /** Check that given application node appears as first statement
  1555          *  in a constructor call.
  1556          *  @param tree   The application node
  1557          *  @param env    The environment current at the application.
  1558          */
  1559         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1560             JCMethodDecl enclMethod = env.enclMethod;
  1561             if (enclMethod != null && enclMethod.name == names.init) {
  1562                 JCBlock body = enclMethod.body;
  1563                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1564                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1565                     return true;
  1567             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1568                       TreeInfo.name(tree.meth));
  1569             return false;
  1572         /** Obtain a method type with given argument types.
  1573          */
  1574         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1575             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1576             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1579     public void visitNewClass(JCNewClass tree) {
  1580         Type owntype = types.createErrorType(tree.type);
  1582         // The local environment of a class creation is
  1583         // a new environment nested in the current one.
  1584         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1586         // The anonymous inner class definition of the new expression,
  1587         // if one is defined by it.
  1588         JCClassDecl cdef = tree.def;
  1590         // If enclosing class is given, attribute it, and
  1591         // complete class name to be fully qualified
  1592         JCExpression clazz = tree.clazz; // Class field following new
  1593         JCExpression clazzid =          // Identifier in class field
  1594             (clazz.getTag() == JCTree.TYPEAPPLY)
  1595             ? ((JCTypeApply) clazz).clazz
  1596             : clazz;
  1598         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1600         if (tree.encl != null) {
  1601             // We are seeing a qualified new, of the form
  1602             //    <expr>.new C <...> (...) ...
  1603             // In this case, we let clazz stand for the name of the
  1604             // allocated class C prefixed with the type of the qualifier
  1605             // expression, so that we can
  1606             // resolve it with standard techniques later. I.e., if
  1607             // <expr> has type T, then <expr>.new C <...> (...)
  1608             // yields a clazz T.C.
  1609             Type encltype = chk.checkRefType(tree.encl.pos(),
  1610                                              attribExpr(tree.encl, env));
  1611             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1612                                                  ((JCIdent) clazzid).name);
  1613             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1614                 clazz = make.at(tree.pos).
  1615                     TypeApply(clazzid1,
  1616                               ((JCTypeApply) clazz).arguments);
  1617             else
  1618                 clazz = clazzid1;
  1621         // Attribute clazz expression and store
  1622         // symbol + type back into the attributed tree.
  1623         Type clazztype = attribType(clazz, env);
  1624         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
  1625         clazztype = chk.checkDiamond(tree, clazztype);
  1626         chk.validate(clazz, localEnv);
  1627         if (tree.encl != null) {
  1628             // We have to work in this case to store
  1629             // symbol + type back into the attributed tree.
  1630             tree.clazz.type = clazztype;
  1631             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1632             clazzid.type = ((JCIdent) clazzid).sym.type;
  1633             if (!clazztype.isErroneous()) {
  1634                 if (cdef != null && clazztype.tsym.isInterface()) {
  1635                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1636                 } else if (clazztype.tsym.isStatic()) {
  1637                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1640         } else if (!clazztype.tsym.isInterface() &&
  1641                    clazztype.getEnclosingType().tag == CLASS) {
  1642             // Check for the existence of an apropos outer instance
  1643             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1646         // Attribute constructor arguments.
  1647         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1648         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1650         if (TreeInfo.isDiamond(tree) && !clazztype.isErroneous()) {
  1651             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1652             clazz.type = clazztype;
  1653         } else if (allowDiamondFinder &&
  1654                 tree.def == null &&
  1655                 !clazztype.isErroneous() &&
  1656                 clazztype.getTypeArguments().nonEmpty() &&
  1657                 findDiamonds) {
  1658             boolean prevDeferDiags = log.deferDiagnostics;
  1659             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1660             Type inferred = null;
  1661             try {
  1662                 //disable diamond-related diagnostics
  1663                 log.deferDiagnostics = true;
  1664                 log.deferredDiagnostics = ListBuffer.lb();
  1665                 inferred = attribDiamond(localEnv,
  1666                         tree,
  1667                         clazztype,
  1668                         mapping,
  1669                         argtypes,
  1670                         typeargtypes);
  1672             finally {
  1673                 log.deferDiagnostics = prevDeferDiags;
  1674                 log.deferredDiagnostics = prevDeferredDiags;
  1676             if (inferred != null &&
  1677                     !inferred.isErroneous() &&
  1678                     inferred.tag == CLASS &&
  1679                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings)) {
  1680                 String key = types.isSameType(clazztype, inferred) ?
  1681                     "diamond.redundant.args" :
  1682                     "diamond.redundant.args.1";
  1683                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1687         // If we have made no mistakes in the class type...
  1688         if (clazztype.tag == CLASS) {
  1689             // Enums may not be instantiated except implicitly
  1690             if (allowEnums &&
  1691                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1692                 (env.tree.getTag() != JCTree.VARDEF ||
  1693                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1694                  ((JCVariableDecl) env.tree).init != tree))
  1695                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1696             // Check that class is not abstract
  1697             if (cdef == null &&
  1698                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1699                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1700                           clazztype.tsym);
  1701             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1702                 // Check that no constructor arguments are given to
  1703                 // anonymous classes implementing an interface
  1704                 if (!argtypes.isEmpty())
  1705                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1707                 if (!typeargtypes.isEmpty())
  1708                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1710                 // Error recovery: pretend no arguments were supplied.
  1711                 argtypes = List.nil();
  1712                 typeargtypes = List.nil();
  1715             // Resolve the called constructor under the assumption
  1716             // that we are referring to a superclass instance of the
  1717             // current instance (JLS ???).
  1718             else {
  1719                 //the following code alters some of the fields in the current
  1720                 //AttrContext - hence, the current context must be dup'ed in
  1721                 //order to avoid downstream failures
  1722                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  1723                 rsEnv.info.selectSuper = cdef != null;
  1724                 rsEnv.info.varArgs = false;
  1725                 tree.constructor = rs.resolveConstructor(
  1726                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  1727                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1728                     syms.errType :
  1729                     checkMethod(clazztype,
  1730                         tree.constructor,
  1731                         rsEnv,
  1732                         tree.args,
  1733                         argtypes,
  1734                         typeargtypes,
  1735                         rsEnv.info.varArgs);
  1736                 if (rsEnv.info.varArgs)
  1737                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1740             if (cdef != null) {
  1741                 // We are seeing an anonymous class instance creation.
  1742                 // In this case, the class instance creation
  1743                 // expression
  1744                 //
  1745                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1746                 //
  1747                 // is represented internally as
  1748                 //
  1749                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1750                 //
  1751                 // This expression is then *transformed* as follows:
  1752                 //
  1753                 // (1) add a STATIC flag to the class definition
  1754                 //     if the current environment is static
  1755                 // (2) add an extends or implements clause
  1756                 // (3) add a constructor.
  1757                 //
  1758                 // For instance, if C is a class, and ET is the type of E,
  1759                 // the expression
  1760                 //
  1761                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1762                 //
  1763                 // is translated to (where X is a fresh name and typarams is the
  1764                 // parameter list of the super constructor):
  1765                 //
  1766                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1767                 //     X extends C<typargs2> {
  1768                 //       <typarams> X(ET e, args) {
  1769                 //         e.<typeargs1>super(args)
  1770                 //       }
  1771                 //       ...
  1772                 //     }
  1773                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1775                 if (clazztype.tsym.isInterface()) {
  1776                     cdef.implementing = List.of(clazz);
  1777                 } else {
  1778                     cdef.extending = clazz;
  1781                 attribStat(cdef, localEnv);
  1783                 // If an outer instance is given,
  1784                 // prefix it to the constructor arguments
  1785                 // and delete it from the new expression
  1786                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1787                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1788                     argtypes = argtypes.prepend(tree.encl.type);
  1789                     tree.encl = null;
  1792                 // Reassign clazztype and recompute constructor.
  1793                 clazztype = cdef.sym.type;
  1794                 boolean useVarargs = tree.varargsElement != null;
  1795                 Symbol sym = rs.resolveConstructor(
  1796                     tree.pos(), localEnv, clazztype, argtypes,
  1797                     typeargtypes, true, useVarargs);
  1798                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
  1799                 tree.constructor = sym;
  1800                 if (tree.constructor.kind > ERRONEOUS) {
  1801                     tree.constructorType =  syms.errType;
  1803                 else {
  1804                     tree.constructorType = checkMethod(clazztype,
  1805                             tree.constructor,
  1806                             localEnv,
  1807                             tree.args,
  1808                             argtypes,
  1809                             typeargtypes,
  1810                             useVarargs);
  1814             if (tree.constructor != null && tree.constructor.kind == MTH)
  1815                 owntype = clazztype;
  1817         result = check(tree, owntype, VAL, pkind, pt);
  1818         chk.validate(tree.typeargs, localEnv);
  1821     Type attribDiamond(Env<AttrContext> env,
  1822                         JCNewClass tree,
  1823                         Type clazztype,
  1824                         Pair<Scope, Scope> mapping,
  1825                         List<Type> argtypes,
  1826                         List<Type> typeargtypes) {
  1827         if (clazztype.isErroneous() ||
  1828                 clazztype.isInterface() ||
  1829                 mapping == erroneousMapping) {
  1830             //if the type of the instance creation expression is erroneous,
  1831             //or if it's an interface, or if something prevented us to form a valid
  1832             //mapping, return the (possibly erroneous) type unchanged
  1833             return clazztype;
  1836         //dup attribution environment and augment the set of inference variables
  1837         Env<AttrContext> localEnv = env.dup(tree);
  1838         localEnv.info.tvars = clazztype.tsym.type.getTypeArguments();
  1840         //if the type of the instance creation expression is a class type
  1841         //apply method resolution inference (JLS 15.12.2.7). The return type
  1842         //of the resolved constructor will be a partially instantiated type
  1843         ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1844         Symbol constructor;
  1845         try {
  1846             constructor = rs.resolveDiamond(tree.pos(),
  1847                     localEnv,
  1848                     clazztype,
  1849                     argtypes,
  1850                     typeargtypes);
  1851         } finally {
  1852             ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1854         if (constructor.kind == MTH) {
  1855             ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1856                     clazztype.tsym.type.getTypeArguments(),
  1857                     clazztype.tsym);
  1858             clazztype = checkMethod(ct,
  1859                     constructor,
  1860                     localEnv,
  1861                     tree.args,
  1862                     argtypes,
  1863                     typeargtypes,
  1864                     localEnv.info.varArgs).getReturnType();
  1865         } else {
  1866             clazztype = syms.errType;
  1869         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1870             //if the resolved constructor's return type has some uninferred
  1871             //type-variables, infer them using the expected type and declared
  1872             //bounds (JLS 15.12.2.8).
  1873             try {
  1874                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1875                         pt.tag == NONE ? syms.objectType : pt,
  1876                         Warner.noWarnings);
  1877             } catch (Infer.InferenceException ex) {
  1878                 //an error occurred while inferring uninstantiated type-variables
  1879                 log.error(tree.clazz.pos(),
  1880                         "cant.apply.diamond.1",
  1881                         diags.fragment("diamond", clazztype.tsym),
  1882                         ex.diagnostic);
  1885         return chk.checkClassType(tree.clazz.pos(),
  1886                 clazztype,
  1887                 true);
  1890     /** Creates a synthetic scope containing fake generic constructors.
  1891      *  Assuming that the original scope contains a constructor of the kind:
  1892      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1893      *  the synthetic scope is added a generic constructor of the kind:
  1894      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1895      *  inference. The inferred return type of the synthetic constructor IS
  1896      *  the inferred type for the diamond operator.
  1897      */
  1898     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
  1899         if (ctype.tag != CLASS) {
  1900             return erroneousMapping;
  1903         Pair<Scope, Scope> mapping =
  1904                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1906         //for each constructor in the original scope, create a synthetic constructor
  1907         //whose return type is the type of the class in which the constructor is
  1908         //declared, and insert it into the new scope.
  1909         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1910                 e.scope != null;
  1911                 e = e.next()) {
  1912             Type synthRestype = new ClassType(ctype.getEnclosingType(),
  1913                         ctype.tsym.type.getTypeArguments(),
  1914                         ctype.tsym);
  1915             MethodSymbol synhConstr = new MethodSymbol(e.sym.flags(),
  1916                     names.init,
  1917                     types.createMethodTypeWithReturn(e.sym.type, synthRestype),
  1918                     e.sym.owner);
  1919             mapping.snd.enter(synhConstr);
  1921         return mapping;
  1924     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1926     /** Make an attributed null check tree.
  1927      */
  1928     public JCExpression makeNullCheck(JCExpression arg) {
  1929         // optimization: X.this is never null; skip null check
  1930         Name name = TreeInfo.name(arg);
  1931         if (name == names._this || name == names._super) return arg;
  1933         int optag = JCTree.NULLCHK;
  1934         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1935         tree.operator = syms.nullcheck;
  1936         tree.type = arg.type;
  1937         return tree;
  1940     public void visitNewArray(JCNewArray tree) {
  1941         Type owntype = types.createErrorType(tree.type);
  1942         Type elemtype;
  1943         if (tree.elemtype != null) {
  1944             elemtype = attribType(tree.elemtype, env);
  1945             chk.validate(tree.elemtype, env);
  1946             owntype = elemtype;
  1947             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1948                 attribExpr(l.head, env, syms.intType);
  1949                 owntype = new ArrayType(owntype, syms.arrayClass);
  1951         } else {
  1952             // we are seeing an untyped aggregate { ... }
  1953             // this is allowed only if the prototype is an array
  1954             if (pt.tag == ARRAY) {
  1955                 elemtype = types.elemtype(pt);
  1956             } else {
  1957                 if (pt.tag != ERROR) {
  1958                     log.error(tree.pos(), "illegal.initializer.for.type",
  1959                               pt);
  1961                 elemtype = types.createErrorType(pt);
  1964         if (tree.elems != null) {
  1965             attribExprs(tree.elems, env, elemtype);
  1966             owntype = new ArrayType(elemtype, syms.arrayClass);
  1968         if (!types.isReifiable(elemtype))
  1969             log.error(tree.pos(), "generic.array.creation");
  1970         result = check(tree, owntype, VAL, pkind, pt);
  1973     public void visitParens(JCParens tree) {
  1974         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1975         result = check(tree, owntype, pkind, pkind, pt);
  1976         Symbol sym = TreeInfo.symbol(tree);
  1977         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1978             log.error(tree.pos(), "illegal.start.of.type");
  1981     public void visitAssign(JCAssign tree) {
  1982         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1983         Type capturedType = capture(owntype);
  1984         attribExpr(tree.rhs, env, owntype);
  1985         result = check(tree, capturedType, VAL, pkind, pt);
  1988     public void visitAssignop(JCAssignOp tree) {
  1989         // Attribute arguments.
  1990         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1991         Type operand = attribExpr(tree.rhs, env);
  1992         // Find operator.
  1993         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1994             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1995             owntype, operand);
  1997         if (operator.kind == MTH &&
  1998                 !owntype.isErroneous() &&
  1999                 !operand.isErroneous()) {
  2000             chk.checkOperator(tree.pos(),
  2001                               (OperatorSymbol)operator,
  2002                               tree.getTag() - JCTree.ASGOffset,
  2003                               owntype,
  2004                               operand);
  2005             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2006             chk.checkCastable(tree.rhs.pos(),
  2007                               operator.type.getReturnType(),
  2008                               owntype);
  2010         result = check(tree, owntype, VAL, pkind, pt);
  2013     public void visitUnary(JCUnary tree) {
  2014         // Attribute arguments.
  2015         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2016             ? attribTree(tree.arg, env, VAR, Type.noType)
  2017             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2019         // Find operator.
  2020         Symbol operator = tree.operator =
  2021             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2023         Type owntype = types.createErrorType(tree.type);
  2024         if (operator.kind == MTH &&
  2025                 !argtype.isErroneous()) {
  2026             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2027                 ? tree.arg.type
  2028                 : operator.type.getReturnType();
  2029             int opc = ((OperatorSymbol)operator).opcode;
  2031             // If the argument is constant, fold it.
  2032             if (argtype.constValue() != null) {
  2033                 Type ctype = cfolder.fold1(opc, argtype);
  2034                 if (ctype != null) {
  2035                     owntype = cfolder.coerce(ctype, owntype);
  2037                     // Remove constant types from arguments to
  2038                     // conserve space. The parser will fold concatenations
  2039                     // of string literals; the code here also
  2040                     // gets rid of intermediate results when some of the
  2041                     // operands are constant identifiers.
  2042                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2043                         tree.arg.type = syms.stringType;
  2048         result = check(tree, owntype, VAL, pkind, pt);
  2051     public void visitBinary(JCBinary tree) {
  2052         // Attribute arguments.
  2053         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2054         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2056         // Find operator.
  2057         Symbol operator = tree.operator =
  2058             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2060         Type owntype = types.createErrorType(tree.type);
  2061         if (operator.kind == MTH &&
  2062                 !left.isErroneous() &&
  2063                 !right.isErroneous()) {
  2064             owntype = operator.type.getReturnType();
  2065             int opc = chk.checkOperator(tree.lhs.pos(),
  2066                                         (OperatorSymbol)operator,
  2067                                         tree.getTag(),
  2068                                         left,
  2069                                         right);
  2071             // If both arguments are constants, fold them.
  2072             if (left.constValue() != null && right.constValue() != null) {
  2073                 Type ctype = cfolder.fold2(opc, left, right);
  2074                 if (ctype != null) {
  2075                     owntype = cfolder.coerce(ctype, owntype);
  2077                     // Remove constant types from arguments to
  2078                     // conserve space. The parser will fold concatenations
  2079                     // of string literals; the code here also
  2080                     // gets rid of intermediate results when some of the
  2081                     // operands are constant identifiers.
  2082                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2083                         tree.lhs.type = syms.stringType;
  2085                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2086                         tree.rhs.type = syms.stringType;
  2091             // Check that argument types of a reference ==, != are
  2092             // castable to each other, (JLS???).
  2093             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2094                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2095                     log.error(tree.pos(), "incomparable.types", left, right);
  2099             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2101         result = check(tree, owntype, VAL, pkind, pt);
  2104     public void visitTypeCast(JCTypeCast tree) {
  2105         Type clazztype = attribType(tree.clazz, env);
  2106         chk.validate(tree.clazz, env, false);
  2107         //a fresh environment is required for 292 inference to work properly ---
  2108         //see Infer.instantiatePolymorphicSignatureInstance()
  2109         Env<AttrContext> localEnv = env.dup(tree);
  2110         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2111         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2112         if (exprtype.constValue() != null)
  2113             owntype = cfolder.coerce(exprtype, owntype);
  2114         result = check(tree, capture(owntype), VAL, pkind, pt);
  2117     public void visitTypeTest(JCInstanceOf tree) {
  2118         Type exprtype = chk.checkNullOrRefType(
  2119             tree.expr.pos(), attribExpr(tree.expr, env));
  2120         Type clazztype = chk.checkReifiableReferenceType(
  2121             tree.clazz.pos(), attribType(tree.clazz, env));
  2122         chk.validate(tree.clazz, env, false);
  2123         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2124         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2127     public void visitIndexed(JCArrayAccess tree) {
  2128         Type owntype = types.createErrorType(tree.type);
  2129         Type atype = attribExpr(tree.indexed, env);
  2130         attribExpr(tree.index, env, syms.intType);
  2131         if (types.isArray(atype))
  2132             owntype = types.elemtype(atype);
  2133         else if (atype.tag != ERROR)
  2134             log.error(tree.pos(), "array.req.but.found", atype);
  2135         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2136         result = check(tree, owntype, VAR, pkind, pt);
  2139     public void visitIdent(JCIdent tree) {
  2140         Symbol sym;
  2141         boolean varArgs = false;
  2143         // Find symbol
  2144         if (pt.tag == METHOD || pt.tag == FORALL) {
  2145             // If we are looking for a method, the prototype `pt' will be a
  2146             // method type with the type of the call's arguments as parameters.
  2147             env.info.varArgs = false;
  2148             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2149             varArgs = env.info.varArgs;
  2150         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2151             sym = tree.sym;
  2152         } else {
  2153             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2155         tree.sym = sym;
  2157         // (1) Also find the environment current for the class where
  2158         //     sym is defined (`symEnv').
  2159         // Only for pre-tiger versions (1.4 and earlier):
  2160         // (2) Also determine whether we access symbol out of an anonymous
  2161         //     class in a this or super call.  This is illegal for instance
  2162         //     members since such classes don't carry a this$n link.
  2163         //     (`noOuterThisPath').
  2164         Env<AttrContext> symEnv = env;
  2165         boolean noOuterThisPath = false;
  2166         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2167             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2168             sym.owner.kind == TYP &&
  2169             tree.name != names._this && tree.name != names._super) {
  2171             // Find environment in which identifier is defined.
  2172             while (symEnv.outer != null &&
  2173                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2174                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2175                     noOuterThisPath = !allowAnonOuterThis;
  2176                 symEnv = symEnv.outer;
  2180         // If symbol is a variable, ...
  2181         if (sym.kind == VAR) {
  2182             VarSymbol v = (VarSymbol)sym;
  2184             // ..., evaluate its initializer, if it has one, and check for
  2185             // illegal forward reference.
  2186             checkInit(tree, env, v, false);
  2188             // If symbol is a local variable accessed from an embedded
  2189             // inner class check that it is final.
  2190             if (v.owner.kind == MTH &&
  2191                 v.owner != env.info.scope.owner &&
  2192                 (v.flags_field & FINAL) == 0) {
  2193                 log.error(tree.pos(),
  2194                           "local.var.accessed.from.icls.needs.final",
  2195                           v);
  2198             // If we are expecting a variable (as opposed to a value), check
  2199             // that the variable is assignable in the current environment.
  2200             if (pkind == VAR)
  2201                 checkAssignable(tree.pos(), v, null, env);
  2204         // In a constructor body,
  2205         // if symbol is a field or instance method, check that it is
  2206         // not accessed before the supertype constructor is called.
  2207         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2208             (sym.kind & (VAR | MTH)) != 0 &&
  2209             sym.owner.kind == TYP &&
  2210             (sym.flags() & STATIC) == 0) {
  2211             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2213         Env<AttrContext> env1 = env;
  2214         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2215             // If the found symbol is inaccessible, then it is
  2216             // accessed through an enclosing instance.  Locate this
  2217             // enclosing instance:
  2218             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2219                 env1 = env1.outer;
  2221         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2224     public void visitSelect(JCFieldAccess tree) {
  2225         // Determine the expected kind of the qualifier expression.
  2226         int skind = 0;
  2227         if (tree.name == names._this || tree.name == names._super ||
  2228             tree.name == names._class)
  2230             skind = TYP;
  2231         } else {
  2232             if ((pkind & PCK) != 0) skind = skind | PCK;
  2233             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2234             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2237         // Attribute the qualifier expression, and determine its symbol (if any).
  2238         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2239         if ((pkind & (PCK | TYP)) == 0)
  2240             site = capture(site); // Capture field access
  2242         // don't allow T.class T[].class, etc
  2243         if (skind == TYP) {
  2244             Type elt = site;
  2245             while (elt.tag == ARRAY)
  2246                 elt = ((ArrayType)elt).elemtype;
  2247             if (elt.tag == TYPEVAR) {
  2248                 log.error(tree.pos(), "type.var.cant.be.deref");
  2249                 result = types.createErrorType(tree.type);
  2250                 return;
  2254         // If qualifier symbol is a type or `super', assert `selectSuper'
  2255         // for the selection. This is relevant for determining whether
  2256         // protected symbols are accessible.
  2257         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2258         boolean selectSuperPrev = env.info.selectSuper;
  2259         env.info.selectSuper =
  2260             sitesym != null &&
  2261             sitesym.name == names._super;
  2263         // If selected expression is polymorphic, strip
  2264         // type parameters and remember in env.info.tvars, so that
  2265         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2266         if (tree.selected.type.tag == FORALL) {
  2267             ForAll pstype = (ForAll)tree.selected.type;
  2268             env.info.tvars = pstype.tvars;
  2269             site = tree.selected.type = pstype.qtype;
  2272         // Determine the symbol represented by the selection.
  2273         env.info.varArgs = false;
  2274         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2275         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2276             site = capture(site);
  2277             sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2279         boolean varArgs = env.info.varArgs;
  2280         tree.sym = sym;
  2282         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2283             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2284             site = capture(site);
  2287         // If that symbol is a variable, ...
  2288         if (sym.kind == VAR) {
  2289             VarSymbol v = (VarSymbol)sym;
  2291             // ..., evaluate its initializer, if it has one, and check for
  2292             // illegal forward reference.
  2293             checkInit(tree, env, v, true);
  2295             // If we are expecting a variable (as opposed to a value), check
  2296             // that the variable is assignable in the current environment.
  2297             if (pkind == VAR)
  2298                 checkAssignable(tree.pos(), v, tree.selected, env);
  2301         if (sitesym != null &&
  2302                 sitesym.kind == VAR &&
  2303                 ((VarSymbol)sitesym).isResourceVariable() &&
  2304                 sym.kind == MTH &&
  2305                 sym.name.equals(names.close) &&
  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          * @jls  section 8.9 Enums
  2649          */
  2650         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2651             // JLS:
  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                                          types.erasure(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();
  2883             if (actuals.isEmpty()) //diamond
  2884                 actuals = formals;
  2886             if (actuals.length() == formals.length()) {
  2887                 List<Type> a = actuals;
  2888                 List<Type> f = formals;
  2889                 while (a.nonEmpty()) {
  2890                     a.head = a.head.withTypeVar(f.head);
  2891                     a = a.tail;
  2892                     f = f.tail;
  2894                 // Compute the proper generic outer
  2895                 Type clazzOuter = clazztype.getEnclosingType();
  2896                 if (clazzOuter.tag == CLASS) {
  2897                     Type site;
  2898                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2899                     if (clazz.getTag() == JCTree.IDENT) {
  2900                         site = env.enclClass.sym.type;
  2901                     } else if (clazz.getTag() == JCTree.SELECT) {
  2902                         site = ((JCFieldAccess) clazz).selected.type;
  2903                     } else throw new AssertionError(""+tree);
  2904                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2905                         if (site.tag == CLASS)
  2906                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2907                         if (site == null)
  2908                             site = types.erasure(clazzOuter);
  2909                         clazzOuter = site;
  2912                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2913             } else {
  2914                 if (formals.length() != 0) {
  2915                     log.error(tree.pos(), "wrong.number.type.args",
  2916                               Integer.toString(formals.length()));
  2917                 } else {
  2918                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2920                 owntype = types.createErrorType(tree.type);
  2923         result = check(tree, owntype, TYP, pkind, pt);
  2926     public void visitTypeUnion(JCTypeUnion tree) {
  2927         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2928         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  2929         for (JCExpression typeTree : tree.alternatives) {
  2930             Type ctype = attribType(typeTree, env);
  2931             ctype = chk.checkType(typeTree.pos(),
  2932                           chk.checkClassType(typeTree.pos(), ctype),
  2933                           syms.throwableType);
  2934             if (!ctype.isErroneous()) {
  2935                 //check that alternatives of a union type are pairwise
  2936                 //unrelated w.r.t. subtyping
  2937                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  2938                     for (Type t : multicatchTypes) {
  2939                         boolean sub = types.isSubtype(ctype, t);
  2940                         boolean sup = types.isSubtype(t, ctype);
  2941                         if (sub || sup) {
  2942                             //assume 'a' <: 'b'
  2943                             Type a = sub ? ctype : t;
  2944                             Type b = sub ? t : ctype;
  2945                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  2949                 multicatchTypes.append(ctype);
  2950                 if (all_multicatchTypes != null)
  2951                     all_multicatchTypes.append(ctype);
  2952             } else {
  2953                 if (all_multicatchTypes == null) {
  2954                     all_multicatchTypes = ListBuffer.lb();
  2955                     all_multicatchTypes.appendList(multicatchTypes);
  2957                 all_multicatchTypes.append(ctype);
  2960         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2961         if (t.tag == CLASS) {
  2962             List<Type> alternatives =
  2963                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  2964             t = new UnionClassType((ClassType) t, alternatives);
  2966         tree.type = result = t;
  2969     public void visitTypeParameter(JCTypeParameter tree) {
  2970         TypeVar a = (TypeVar)tree.type;
  2971         Set<Type> boundSet = new HashSet<Type>();
  2972         if (a.bound.isErroneous())
  2973             return;
  2974         List<Type> bs = types.getBounds(a);
  2975         if (tree.bounds.nonEmpty()) {
  2976             // accept class or interface or typevar as first bound.
  2977             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2978             boundSet.add(types.erasure(b));
  2979             if (b.isErroneous()) {
  2980                 a.bound = b;
  2982             else if (b.tag == TYPEVAR) {
  2983                 // if first bound was a typevar, do not accept further bounds.
  2984                 if (tree.bounds.tail.nonEmpty()) {
  2985                     log.error(tree.bounds.tail.head.pos(),
  2986                               "type.var.may.not.be.followed.by.other.bounds");
  2987                     tree.bounds = List.of(tree.bounds.head);
  2988                     a.bound = bs.head;
  2990             } else {
  2991                 // if first bound was a class or interface, accept only interfaces
  2992                 // as further bounds.
  2993                 for (JCExpression bound : tree.bounds.tail) {
  2994                     bs = bs.tail;
  2995                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2996                     if (i.isErroneous())
  2997                         a.bound = i;
  2998                     else if (i.tag == CLASS)
  2999                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  3003         bs = types.getBounds(a);
  3005         // in case of multiple bounds ...
  3006         if (bs.length() > 1) {
  3007             // ... the variable's bound is a class type flagged COMPOUND
  3008             // (see comment for TypeVar.bound).
  3009             // In this case, generate a class tree that represents the
  3010             // bound class, ...
  3011             JCExpression extending;
  3012             List<JCExpression> implementing;
  3013             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  3014                 extending = tree.bounds.head;
  3015                 implementing = tree.bounds.tail;
  3016             } else {
  3017                 extending = null;
  3018                 implementing = tree.bounds;
  3020             JCClassDecl cd = make.at(tree.pos).ClassDef(
  3021                 make.Modifiers(PUBLIC | ABSTRACT),
  3022                 tree.name, List.<JCTypeParameter>nil(),
  3023                 extending, implementing, List.<JCTree>nil());
  3025             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  3026             Assert.check((c.flags() & COMPOUND) != 0);
  3027             cd.sym = c;
  3028             c.sourcefile = env.toplevel.sourcefile;
  3030             // ... and attribute the bound class
  3031             c.flags_field |= UNATTRIBUTED;
  3032             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3033             enter.typeEnvs.put(c, cenv);
  3038     public void visitWildcard(JCWildcard tree) {
  3039         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3040         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3041             ? syms.objectType
  3042             : attribType(tree.inner, env);
  3043         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3044                                               tree.kind.kind,
  3045                                               syms.boundClass),
  3046                        TYP, pkind, pt);
  3049     public void visitAnnotation(JCAnnotation tree) {
  3050         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  3051         result = tree.type = syms.errType;
  3054     public void visitErroneous(JCErroneous tree) {
  3055         if (tree.errs != null)
  3056             for (JCTree err : tree.errs)
  3057                 attribTree(err, env, ERR, pt);
  3058         result = tree.type = syms.errType;
  3061     /** Default visitor method for all other trees.
  3062      */
  3063     public void visitTree(JCTree tree) {
  3064         throw new AssertionError();
  3067     /**
  3068      * Attribute an env for either a top level tree or class declaration.
  3069      */
  3070     public void attrib(Env<AttrContext> env) {
  3071         if (env.tree.getTag() == JCTree.TOPLEVEL)
  3072             attribTopLevel(env);
  3073         else
  3074             attribClass(env.tree.pos(), env.enclClass.sym);
  3077     /**
  3078      * Attribute a top level tree. These trees are encountered when the
  3079      * package declaration has annotations.
  3080      */
  3081     public void attribTopLevel(Env<AttrContext> env) {
  3082         JCCompilationUnit toplevel = env.toplevel;
  3083         try {
  3084             annotate.flush();
  3085             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  3086         } catch (CompletionFailure ex) {
  3087             chk.completionError(toplevel.pos(), ex);
  3091     /** Main method: attribute class definition associated with given class symbol.
  3092      *  reporting completion failures at the given position.
  3093      *  @param pos The source position at which completion errors are to be
  3094      *             reported.
  3095      *  @param c   The class symbol whose definition will be attributed.
  3096      */
  3097     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3098         try {
  3099             annotate.flush();
  3100             attribClass(c);
  3101         } catch (CompletionFailure ex) {
  3102             chk.completionError(pos, ex);
  3106     /** Attribute class definition associated with given class symbol.
  3107      *  @param c   The class symbol whose definition will be attributed.
  3108      */
  3109     void attribClass(ClassSymbol c) throws CompletionFailure {
  3110         if (c.type.tag == ERROR) return;
  3112         // Check for cycles in the inheritance graph, which can arise from
  3113         // ill-formed class files.
  3114         chk.checkNonCyclic(null, c.type);
  3116         Type st = types.supertype(c.type);
  3117         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3118             // First, attribute superclass.
  3119             if (st.tag == CLASS)
  3120                 attribClass((ClassSymbol)st.tsym);
  3122             // Next attribute owner, if it is a class.
  3123             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3124                 attribClass((ClassSymbol)c.owner);
  3127         // The previous operations might have attributed the current class
  3128         // if there was a cycle. So we test first whether the class is still
  3129         // UNATTRIBUTED.
  3130         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3131             c.flags_field &= ~UNATTRIBUTED;
  3133             // Get environment current at the point of class definition.
  3134             Env<AttrContext> env = enter.typeEnvs.get(c);
  3136             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3137             // because the annotations were not available at the time the env was created. Therefore,
  3138             // we look up the environment chain for the first enclosing environment for which the
  3139             // lint value is set. Typically, this is the parent env, but might be further if there
  3140             // are any envs created as a result of TypeParameter nodes.
  3141             Env<AttrContext> lintEnv = env;
  3142             while (lintEnv.info.lint == null)
  3143                 lintEnv = lintEnv.next;
  3145             // Having found the enclosing lint value, we can initialize the lint value for this class
  3146             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3148             Lint prevLint = chk.setLint(env.info.lint);
  3149             JavaFileObject prev = log.useSource(c.sourcefile);
  3151             try {
  3152                 // java.lang.Enum may not be subclassed by a non-enum
  3153                 if (st.tsym == syms.enumSym &&
  3154                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3155                     log.error(env.tree.pos(), "enum.no.subclassing");
  3157                 // Enums may not be extended by source-level classes
  3158                 if (st.tsym != null &&
  3159                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3160                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3161                     !target.compilerBootstrap(c)) {
  3162                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3164                 attribClassBody(env, c);
  3166                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3167             } finally {
  3168                 log.useSource(prev);
  3169                 chk.setLint(prevLint);
  3175     public void visitImport(JCImport tree) {
  3176         // nothing to do
  3179     /** Finish the attribution of a class. */
  3180     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3181         JCClassDecl tree = (JCClassDecl)env.tree;
  3182         Assert.check(c == tree.sym);
  3184         // Validate annotations
  3185         chk.validateAnnotations(tree.mods.annotations, c);
  3187         // Validate type parameters, supertype and interfaces.
  3188         attribBounds(tree.typarams);
  3189         if (!c.isAnonymous()) {
  3190             //already checked if anonymous
  3191             chk.validate(tree.typarams, env);
  3192             chk.validate(tree.extending, env);
  3193             chk.validate(tree.implementing, env);
  3196         // If this is a non-abstract class, check that it has no abstract
  3197         // methods or unimplemented methods of an implemented interface.
  3198         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3199             if (!relax)
  3200                 chk.checkAllDefined(tree.pos(), c);
  3203         if ((c.flags() & ANNOTATION) != 0) {
  3204             if (tree.implementing.nonEmpty())
  3205                 log.error(tree.implementing.head.pos(),
  3206                           "cant.extend.intf.annotation");
  3207             if (tree.typarams.nonEmpty())
  3208                 log.error(tree.typarams.head.pos(),
  3209                           "intf.annotation.cant.have.type.params");
  3210         } else {
  3211             // Check that all extended classes and interfaces
  3212             // are compatible (i.e. no two define methods with same arguments
  3213             // yet different return types).  (JLS 8.4.6.3)
  3214             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3217         // Check that class does not import the same parameterized interface
  3218         // with two different argument lists.
  3219         chk.checkClassBounds(tree.pos(), c.type);
  3221         tree.type = c.type;
  3223         for (List<JCTypeParameter> l = tree.typarams;
  3224              l.nonEmpty(); l = l.tail) {
  3225              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3228         // Check that a generic class doesn't extend Throwable
  3229         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3230             log.error(tree.extending.pos(), "generic.throwable");
  3232         // Check that all methods which implement some
  3233         // method conform to the method they implement.
  3234         chk.checkImplementations(tree);
  3236         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  3237         checkAutoCloseable(tree.pos(), env, c.type);
  3239         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3240             // Attribute declaration
  3241             attribStat(l.head, env);
  3242             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3243             // Make an exception for static constants.
  3244             if (c.owner.kind != PCK &&
  3245                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3246                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3247                 Symbol sym = null;
  3248                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3249                 if (sym == null ||
  3250                     sym.kind != VAR ||
  3251                     ((VarSymbol) sym).getConstValue() == null)
  3252                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3256         // Check for cycles among non-initial constructors.
  3257         chk.checkCyclicConstructors(tree);
  3259         // Check for cycles among annotation elements.
  3260         chk.checkNonCyclicElements(tree);
  3262         // Check for proper use of serialVersionUID
  3263         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3264             isSerializable(c) &&
  3265             (c.flags() & Flags.ENUM) == 0 &&
  3266             (c.flags() & ABSTRACT) == 0) {
  3267             checkSerialVersionUID(tree, c);
  3270         // where
  3271         /** check if a class is a subtype of Serializable, if that is available. */
  3272         private boolean isSerializable(ClassSymbol c) {
  3273             try {
  3274                 syms.serializableType.complete();
  3276             catch (CompletionFailure e) {
  3277                 return false;
  3279             return types.isSubtype(c.type, syms.serializableType);
  3282         /** Check that an appropriate serialVersionUID member is defined. */
  3283         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3285             // check for presence of serialVersionUID
  3286             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3287             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3288             if (e.scope == null) {
  3289                 log.warning(LintCategory.SERIAL,
  3290                         tree.pos(), "missing.SVUID", c);
  3291                 return;
  3294             // check that it is static final
  3295             VarSymbol svuid = (VarSymbol)e.sym;
  3296             if ((svuid.flags() & (STATIC | FINAL)) !=
  3297                 (STATIC | FINAL))
  3298                 log.warning(LintCategory.SERIAL,
  3299                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3301             // check that it is long
  3302             else if (svuid.type.tag != TypeTags.LONG)
  3303                 log.warning(LintCategory.SERIAL,
  3304                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3306             // check constant
  3307             else if (svuid.getConstValue() == null)
  3308                 log.warning(LintCategory.SERIAL,
  3309                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3312     private Type capture(Type type) {
  3313         return types.capture(type);
  3316     // <editor-fold desc="post-attribution visitor">
  3318     /**
  3319      * Handle missing types/symbols in an AST. This routine is useful when
  3320      * the compiler has encountered some errors (which might have ended up
  3321      * terminating attribution abruptly); if the compiler is used in fail-over
  3322      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3323      * prevents NPE to be progagated during subsequent compilation steps.
  3324      */
  3325     public void postAttr(Env<AttrContext> env) {
  3326         new PostAttrAnalyzer().scan(env.tree);
  3329     class PostAttrAnalyzer extends TreeScanner {
  3331         private void initTypeIfNeeded(JCTree that) {
  3332             if (that.type == null) {
  3333                 that.type = syms.unknownType;
  3337         @Override
  3338         public void scan(JCTree tree) {
  3339             if (tree == null) return;
  3340             if (tree instanceof JCExpression) {
  3341                 initTypeIfNeeded(tree);
  3343             super.scan(tree);
  3346         @Override
  3347         public void visitIdent(JCIdent that) {
  3348             if (that.sym == null) {
  3349                 that.sym = syms.unknownSymbol;
  3353         @Override
  3354         public void visitSelect(JCFieldAccess that) {
  3355             if (that.sym == null) {
  3356                 that.sym = syms.unknownSymbol;
  3358             super.visitSelect(that);
  3361         @Override
  3362         public void visitClassDef(JCClassDecl that) {
  3363             initTypeIfNeeded(that);
  3364             if (that.sym == null) {
  3365                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3367             super.visitClassDef(that);
  3370         @Override
  3371         public void visitMethodDef(JCMethodDecl that) {
  3372             initTypeIfNeeded(that);
  3373             if (that.sym == null) {
  3374                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3376             super.visitMethodDef(that);
  3379         @Override
  3380         public void visitVarDef(JCVariableDecl that) {
  3381             initTypeIfNeeded(that);
  3382             if (that.sym == null) {
  3383                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3384                 that.sym.adr = 0;
  3386             super.visitVarDef(that);
  3389         @Override
  3390         public void visitNewClass(JCNewClass that) {
  3391             if (that.constructor == null) {
  3392                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3394             if (that.constructorType == null) {
  3395                 that.constructorType = syms.unknownType;
  3397             super.visitNewClass(that);
  3400         @Override
  3401         public void visitAssignop(JCAssignOp that) {
  3402             if (that.operator == null)
  3403                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3404             super.visitAssignop(that);
  3407         @Override
  3408         public void visitBinary(JCBinary that) {
  3409             if (that.operator == null)
  3410                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3411             super.visitBinary(that);
  3414         @Override
  3415         public void visitUnary(JCUnary that) {
  3416             if (that.operator == null)
  3417                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3418             super.visitUnary(that);
  3421     // </editor-fold>

mercurial