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

Wed, 26 Jan 2011 11:20:19 -0800

author
jjg
date
Wed, 26 Jan 2011 11:20:19 -0800
changeset 841
df371fd16386
parent 830
02e6e7dd1a64
child 852
899f7c3d9426
permissions
-rw-r--r--

6554097: "final" confuses @SuppressWarnings
Reviewed-by: mcimadamore

     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;
    87     public static Attr instance(Context context) {
    88         Attr instance = context.get(attrKey);
    89         if (instance == null)
    90             instance = new Attr(context);
    91         return instance;
    92     }
    94     protected Attr(Context context) {
    95         context.put(attrKey, this);
    97         names = Names.instance(context);
    98         log = Log.instance(context);
    99         syms = Symtab.instance(context);
   100         rs = Resolve.instance(context);
   101         chk = Check.instance(context);
   102         memberEnter = MemberEnter.instance(context);
   103         make = TreeMaker.instance(context);
   104         enter = Enter.instance(context);
   105         infer = Infer.instance(context);
   106         cfolder = ConstFold.instance(context);
   107         target = Target.instance(context);
   108         types = Types.instance(context);
   109         diags = JCDiagnostic.Factory.instance(context);
   110         annotate = Annotate.instance(context);
   112         Options options = Options.instance(context);
   114         Source source = Source.instance(context);
   115         allowGenerics = source.allowGenerics();
   116         allowVarargs = source.allowVarargs();
   117         allowEnums = source.allowEnums();
   118         allowBoxing = source.allowBoxing();
   119         allowCovariantReturns = source.allowCovariantReturns();
   120         allowAnonOuterThis = source.allowAnonOuterThis();
   121         allowStringsInSwitch = source.allowStringsInSwitch();
   122         sourceName = source.name;
   123         relax = (options.isSet("-retrofit") ||
   124                  options.isSet("-relax"));
   125         findDiamonds = options.get("findDiamond") != null &&
   126                  source.allowDiamond();
   127         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   128         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   129     }
   131     /** Switch: relax some constraints for retrofit mode.
   132      */
   133     boolean relax;
   135     /** Switch: support generics?
   136      */
   137     boolean allowGenerics;
   139     /** Switch: allow variable-arity methods.
   140      */
   141     boolean allowVarargs;
   143     /** Switch: support enums?
   144      */
   145     boolean allowEnums;
   147     /** Switch: support boxing and unboxing?
   148      */
   149     boolean allowBoxing;
   151     /** Switch: support covariant result types?
   152      */
   153     boolean allowCovariantReturns;
   155     /** Switch: allow references to surrounding object from anonymous
   156      * objects during constructor call?
   157      */
   158     boolean allowAnonOuterThis;
   160     /** Switch: generates a warning if diamond can be safely applied
   161      *  to a given new expression
   162      */
   163     boolean findDiamonds;
   165     /**
   166      * Internally enables/disables diamond finder feature
   167      */
   168     static final boolean allowDiamondFinder = true;
   170     /**
   171      * Switch: warn about use of variable before declaration?
   172      * RFE: 6425594
   173      */
   174     boolean useBeforeDeclarationWarning;
   176     /**
   177      * Switch: allow lint infrastructure to control proprietary
   178      * API warnings.
   179      */
   180     boolean enableSunApiLintControl;
   182     /**
   183      * Switch: allow strings in switch?
   184      */
   185     boolean allowStringsInSwitch;
   187     /**
   188      * Switch: name of source level; used for error reporting.
   189      */
   190     String sourceName;
   192     /** Check kind and type of given tree against protokind and prototype.
   193      *  If check succeeds, store type in tree and return it.
   194      *  If check fails, store errType in tree and return it.
   195      *  No checks are performed if the prototype is a method type.
   196      *  It is not necessary in this case since we know that kind and type
   197      *  are correct.
   198      *
   199      *  @param tree     The tree whose kind and type is checked
   200      *  @param owntype  The computed type of the tree
   201      *  @param ownkind  The computed kind of the tree
   202      *  @param pkind    The expected kind (or: protokind) of the tree
   203      *  @param pt       The expected type (or: prototype) of the tree
   204      */
   205     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   206         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   207             if ((ownkind & ~pkind) == 0) {
   208                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
   209             } else {
   210                 log.error(tree.pos(), "unexpected.type",
   211                           kindNames(pkind),
   212                           kindName(ownkind));
   213                 owntype = types.createErrorType(owntype);
   214             }
   215         }
   216         tree.type = owntype;
   217         return owntype;
   218     }
   220     /** Is given blank final variable assignable, i.e. in a scope where it
   221      *  may be assigned to even though it is final?
   222      *  @param v      The blank final variable.
   223      *  @param env    The current environment.
   224      */
   225     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   226         Symbol owner = env.info.scope.owner;
   227            // owner refers to the innermost variable, method or
   228            // initializer block declaration at this point.
   229         return
   230             v.owner == owner
   231             ||
   232             ((owner.name == names.init ||    // i.e. we are in a constructor
   233               owner.kind == VAR ||           // i.e. we are in a variable initializer
   234               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   235              &&
   236              v.owner == owner.owner
   237              &&
   238              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   239     }
   241     /** Check that variable can be assigned to.
   242      *  @param pos    The current source code position.
   243      *  @param v      The assigned varaible
   244      *  @param base   If the variable is referred to in a Select, the part
   245      *                to the left of the `.', null otherwise.
   246      *  @param env    The current environment.
   247      */
   248     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   249         if ((v.flags() & FINAL) != 0 &&
   250             ((v.flags() & HASINIT) != 0
   251              ||
   252              !((base == null ||
   253                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   254                isAssignableAsBlankFinal(v, env)))) {
   255             if (v.isResourceVariable()) { //TWR resource
   256                 log.error(pos, "try.resource.may.not.be.assigned", v);
   257             } else {
   258                 log.error(pos, "cant.assign.val.to.final.var", v);
   259             }
   260         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
   261             v.flags_field &= ~EFFECTIVELY_FINAL;
   262         }
   263     }
   265     /** Does tree represent a static reference to an identifier?
   266      *  It is assumed that tree is either a SELECT or an IDENT.
   267      *  We have to weed out selects from non-type names here.
   268      *  @param tree    The candidate tree.
   269      */
   270     boolean isStaticReference(JCTree tree) {
   271         if (tree.getTag() == JCTree.SELECT) {
   272             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   273             if (lsym == null || lsym.kind != TYP) {
   274                 return false;
   275             }
   276         }
   277         return true;
   278     }
   280     /** Is this symbol a type?
   281      */
   282     static boolean isType(Symbol sym) {
   283         return sym != null && sym.kind == TYP;
   284     }
   286     /** The current `this' symbol.
   287      *  @param env    The current environment.
   288      */
   289     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   290         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   291     }
   293     /** Attribute a parsed identifier.
   294      * @param tree Parsed identifier name
   295      * @param topLevel The toplevel to use
   296      */
   297     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   298         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   299         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   300                                            syms.errSymbol.name,
   301                                            null, null, null, null);
   302         localEnv.enclClass.sym = syms.errSymbol;
   303         return tree.accept(identAttributer, localEnv);
   304     }
   305     // where
   306         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   307         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   308             @Override
   309             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   310                 Symbol site = visit(node.getExpression(), env);
   311                 if (site.kind == ERR)
   312                     return site;
   313                 Name name = (Name)node.getIdentifier();
   314                 if (site.kind == PCK) {
   315                     env.toplevel.packge = (PackageSymbol)site;
   316                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   317                 } else {
   318                     env.enclClass.sym = (ClassSymbol)site;
   319                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   320                 }
   321             }
   323             @Override
   324             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   325                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   326             }
   327         }
   329     public Type coerce(Type etype, Type ttype) {
   330         return cfolder.coerce(etype, ttype);
   331     }
   333     public Type attribType(JCTree node, TypeSymbol sym) {
   334         Env<AttrContext> env = enter.typeEnvs.get(sym);
   335         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   336         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   337     }
   339     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   340         breakTree = tree;
   341         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   342         try {
   343             attribExpr(expr, env);
   344         } catch (BreakAttr b) {
   345             return b.env;
   346         } catch (AssertionError ae) {
   347             if (ae.getCause() instanceof BreakAttr) {
   348                 return ((BreakAttr)(ae.getCause())).env;
   349             } else {
   350                 throw ae;
   351             }
   352         } finally {
   353             breakTree = null;
   354             log.useSource(prev);
   355         }
   356         return env;
   357     }
   359     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   360         breakTree = tree;
   361         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   362         try {
   363             attribStat(stmt, env);
   364         } catch (BreakAttr b) {
   365             return b.env;
   366         } catch (AssertionError ae) {
   367             if (ae.getCause() instanceof BreakAttr) {
   368                 return ((BreakAttr)(ae.getCause())).env;
   369             } else {
   370                 throw ae;
   371             }
   372         } finally {
   373             breakTree = null;
   374             log.useSource(prev);
   375         }
   376         return env;
   377     }
   379     private JCTree breakTree = null;
   381     private static class BreakAttr extends RuntimeException {
   382         static final long serialVersionUID = -6924771130405446405L;
   383         private Env<AttrContext> env;
   384         private BreakAttr(Env<AttrContext> env) {
   385             this.env = env;
   386         }
   387     }
   390 /* ************************************************************************
   391  * Visitor methods
   392  *************************************************************************/
   394     /** Visitor argument: the current environment.
   395      */
   396     Env<AttrContext> env;
   398     /** Visitor argument: the currently expected proto-kind.
   399      */
   400     int pkind;
   402     /** Visitor argument: the currently expected proto-type.
   403      */
   404     Type pt;
   406     /** Visitor argument: the error key to be generated when a type error occurs
   407      */
   408     String errKey;
   410     /** Visitor result: the computed type.
   411      */
   412     Type result;
   414     /** Visitor method: attribute a tree, catching any completion failure
   415      *  exceptions. Return the tree's type.
   416      *
   417      *  @param tree    The tree to be visited.
   418      *  @param env     The environment visitor argument.
   419      *  @param pkind   The protokind visitor argument.
   420      *  @param pt      The prototype visitor argument.
   421      */
   422     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   423         return attribTree(tree, env, pkind, pt, "incompatible.types");
   424     }
   426     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
   427         Env<AttrContext> prevEnv = this.env;
   428         int prevPkind = this.pkind;
   429         Type prevPt = this.pt;
   430         String prevErrKey = this.errKey;
   431         try {
   432             this.env = env;
   433             this.pkind = pkind;
   434             this.pt = pt;
   435             this.errKey = errKey;
   436             tree.accept(this);
   437             if (tree == breakTree)
   438                 throw new BreakAttr(env);
   439             return result;
   440         } catch (CompletionFailure ex) {
   441             tree.type = syms.errType;
   442             return chk.completionError(tree.pos(), ex);
   443         } finally {
   444             this.env = prevEnv;
   445             this.pkind = prevPkind;
   446             this.pt = prevPt;
   447             this.errKey = prevErrKey;
   448         }
   449     }
   451     /** Derived visitor method: attribute an expression tree.
   452      */
   453     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   454         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   455     }
   457     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
   458         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
   459     }
   461     /** Derived visitor method: attribute an expression tree with
   462      *  no constraints on the computed type.
   463      */
   464     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   465         return attribTree(tree, env, VAL, Type.noType);
   466     }
   468     /** Derived visitor method: attribute a type tree.
   469      */
   470     Type attribType(JCTree tree, Env<AttrContext> env) {
   471         Type result = attribType(tree, env, Type.noType);
   472         return result;
   473     }
   475     /** Derived visitor method: attribute a type tree.
   476      */
   477     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   478         Type result = attribTree(tree, env, TYP, pt);
   479         return result;
   480     }
   482     /** Derived visitor method: attribute a statement or definition tree.
   483      */
   484     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   485         return attribTree(tree, env, NIL, Type.noType);
   486     }
   488     /** Attribute a list of expressions, returning a list of types.
   489      */
   490     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   491         ListBuffer<Type> ts = new ListBuffer<Type>();
   492         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   493             ts.append(attribExpr(l.head, env, pt));
   494         return ts.toList();
   495     }
   497     /** Attribute a list of statements, returning nothing.
   498      */
   499     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   500         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   501             attribStat(l.head, env);
   502     }
   504     /** Attribute the arguments in a method call, returning a list of types.
   505      */
   506     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   507         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   508         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   509             argtypes.append(chk.checkNonVoid(
   510                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   511         return argtypes.toList();
   512     }
   514     /** Attribute a type argument list, returning a list of types.
   515      *  Caller is responsible for calling checkRefTypes.
   516      */
   517     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   518         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   519         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   520             argtypes.append(attribType(l.head, env));
   521         return argtypes.toList();
   522     }
   524     /** Attribute a type argument list, returning a list of types.
   525      *  Check that all the types are references.
   526      */
   527     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   528         List<Type> types = attribAnyTypes(trees, env);
   529         return chk.checkRefTypes(trees, types);
   530     }
   532     /**
   533      * Attribute type variables (of generic classes or methods).
   534      * Compound types are attributed later in attribBounds.
   535      * @param typarams the type variables to enter
   536      * @param env      the current environment
   537      */
   538     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   539         for (JCTypeParameter tvar : typarams) {
   540             TypeVar a = (TypeVar)tvar.type;
   541             a.tsym.flags_field |= UNATTRIBUTED;
   542             a.bound = Type.noType;
   543             if (!tvar.bounds.isEmpty()) {
   544                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   545                 for (JCExpression bound : tvar.bounds.tail)
   546                     bounds = bounds.prepend(attribType(bound, env));
   547                 types.setBounds(a, bounds.reverse());
   548             } else {
   549                 // if no bounds are given, assume a single bound of
   550                 // java.lang.Object.
   551                 types.setBounds(a, List.of(syms.objectType));
   552             }
   553             a.tsym.flags_field &= ~UNATTRIBUTED;
   554         }
   555         for (JCTypeParameter tvar : typarams)
   556             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   557         attribStats(typarams, env);
   558     }
   560     void attribBounds(List<JCTypeParameter> typarams) {
   561         for (JCTypeParameter typaram : typarams) {
   562             Type bound = typaram.type.getUpperBound();
   563             if (bound != null && bound.tsym instanceof ClassSymbol) {
   564                 ClassSymbol c = (ClassSymbol)bound.tsym;
   565                 if ((c.flags_field & COMPOUND) != 0) {
   566                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   567                     attribClass(typaram.pos(), c);
   568                 }
   569             }
   570         }
   571     }
   573     /**
   574      * Attribute the type references in a list of annotations.
   575      */
   576     void attribAnnotationTypes(List<JCAnnotation> annotations,
   577                                Env<AttrContext> env) {
   578         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   579             JCAnnotation a = al.head;
   580             attribType(a.annotationType, env);
   581         }
   582     }
   584     /**
   585      * Attribute a "lazy constant value".
   586      *  @param env         The env for the const value
   587      *  @param initializer The initializer for the const value
   588      *  @param type        The expected type, or null
   589      *  @see VarSymbol#setlazyConstValue
   590      */
   591     public Object attribLazyConstantValue(Env<AttrContext> env,
   592                                       JCTree.JCExpression initializer,
   593                                       Type type) {
   595         // in case no lint value has been set up for this env, scan up
   596         // env stack looking for smallest enclosing env for which it is set.
   597         Env<AttrContext> lintEnv = env;
   598         while (lintEnv.info.lint == null)
   599             lintEnv = lintEnv.next;
   601         // Having found the enclosing lint value, we can initialize the lint value for this class
   602         env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.attributes_field, env.info.enclVar.flags());
   604         Lint prevLint = chk.setLint(env.info.lint);
   605         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   607         try {
   608             Type itype = attribExpr(initializer, env, type);
   609             if (itype.constValue() != null)
   610                 return coerce(itype, type).constValue();
   611             else
   612                 return null;
   613         } finally {
   614             env.info.lint = prevLint;
   615             log.useSource(prevSource);
   616         }
   617     }
   619     /** Attribute type reference in an `extends' or `implements' clause.
   620      *  Supertypes of anonymous inner classes are usually already attributed.
   621      *
   622      *  @param tree              The tree making up the type reference.
   623      *  @param env               The environment current at the reference.
   624      *  @param classExpected     true if only a class is expected here.
   625      *  @param interfaceExpected true if only an interface is expected here.
   626      */
   627     Type attribBase(JCTree tree,
   628                     Env<AttrContext> env,
   629                     boolean classExpected,
   630                     boolean interfaceExpected,
   631                     boolean checkExtensible) {
   632         Type t = tree.type != null ?
   633             tree.type :
   634             attribType(tree, env);
   635         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   636     }
   637     Type checkBase(Type t,
   638                    JCTree tree,
   639                    Env<AttrContext> env,
   640                    boolean classExpected,
   641                    boolean interfaceExpected,
   642                    boolean checkExtensible) {
   643         if (t.isErroneous())
   644             return t;
   645         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   646             // check that type variable is already visible
   647             if (t.getUpperBound() == null) {
   648                 log.error(tree.pos(), "illegal.forward.ref");
   649                 return types.createErrorType(t);
   650             }
   651         } else {
   652             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   653         }
   654         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   655             log.error(tree.pos(), "intf.expected.here");
   656             // return errType is necessary since otherwise there might
   657             // be undetected cycles which cause attribution to loop
   658             return types.createErrorType(t);
   659         } else if (checkExtensible &&
   660                    classExpected &&
   661                    (t.tsym.flags() & INTERFACE) != 0) {
   662                 log.error(tree.pos(), "no.intf.expected.here");
   663             return types.createErrorType(t);
   664         }
   665         if (checkExtensible &&
   666             ((t.tsym.flags() & FINAL) != 0)) {
   667             log.error(tree.pos(),
   668                       "cant.inherit.from.final", t.tsym);
   669         }
   670         chk.checkNonCyclic(tree.pos(), t);
   671         return t;
   672     }
   674     public void visitClassDef(JCClassDecl tree) {
   675         // Local classes have not been entered yet, so we need to do it now:
   676         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   677             enter.classEnter(tree, env);
   679         ClassSymbol c = tree.sym;
   680         if (c == null) {
   681             // exit in case something drastic went wrong during enter.
   682             result = null;
   683         } else {
   684             // make sure class has been completed:
   685             c.complete();
   687             // If this class appears as an anonymous class
   688             // in a superclass constructor call where
   689             // no explicit outer instance is given,
   690             // disable implicit outer instance from being passed.
   691             // (This would be an illegal access to "this before super").
   692             if (env.info.isSelfCall &&
   693                 env.tree.getTag() == JCTree.NEWCLASS &&
   694                 ((JCNewClass) env.tree).encl == null)
   695             {
   696                 c.flags_field |= NOOUTERTHIS;
   697             }
   698             attribClass(tree.pos(), c);
   699             result = tree.type = c.type;
   700         }
   701     }
   703     public void visitMethodDef(JCMethodDecl tree) {
   704         MethodSymbol m = tree.sym;
   706         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   707         Lint prevLint = chk.setLint(lint);
   708         MethodSymbol prevMethod = chk.setMethod(m);
   709         try {
   710             chk.checkDeprecatedAnnotation(tree.pos(), m);
   712             attribBounds(tree.typarams);
   714             // If we override any other methods, check that we do so properly.
   715             // JLS ???
   716             chk.checkClashes(tree.pos(), env.enclClass.type, m);
   717             chk.checkOverride(tree, m);
   719             // Create a new environment with local scope
   720             // for attributing the method.
   721             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   723             localEnv.info.lint = lint;
   725             // Enter all type parameters into the local method scope.
   726             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   727                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   729             ClassSymbol owner = env.enclClass.sym;
   730             if ((owner.flags() & ANNOTATION) != 0 &&
   731                 tree.params.nonEmpty())
   732                 log.error(tree.params.head.pos(),
   733                           "intf.annotation.members.cant.have.params");
   735             // Attribute all value parameters.
   736             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   737                 attribStat(l.head, localEnv);
   738             }
   740             chk.checkVarargsMethodDecl(localEnv, tree);
   742             // Check that type parameters are well-formed.
   743             chk.validate(tree.typarams, localEnv);
   745             // Check that result type is well-formed.
   746             chk.validate(tree.restype, localEnv);
   748             // annotation method checks
   749             if ((owner.flags() & ANNOTATION) != 0) {
   750                 // annotation method cannot have throws clause
   751                 if (tree.thrown.nonEmpty()) {
   752                     log.error(tree.thrown.head.pos(),
   753                             "throws.not.allowed.in.intf.annotation");
   754                 }
   755                 // annotation method cannot declare type-parameters
   756                 if (tree.typarams.nonEmpty()) {
   757                     log.error(tree.typarams.head.pos(),
   758                             "intf.annotation.members.cant.have.type.params");
   759                 }
   760                 // validate annotation method's return type (could be an annotation type)
   761                 chk.validateAnnotationType(tree.restype);
   762                 // ensure that annotation method does not clash with members of Object/Annotation
   763                 chk.validateAnnotationMethod(tree.pos(), m);
   765                 if (tree.defaultValue != null) {
   766                     // if default value is an annotation, check it is a well-formed
   767                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   768                     chk.validateAnnotationTree(tree.defaultValue);
   769                 }
   770             }
   772             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   773                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   775             if (tree.body == null) {
   776                 // Empty bodies are only allowed for
   777                 // abstract, native, or interface methods, or for methods
   778                 // in a retrofit signature class.
   779                 if ((owner.flags() & INTERFACE) == 0 &&
   780                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   781                     !relax)
   782                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   783                 if (tree.defaultValue != null) {
   784                     if ((owner.flags() & ANNOTATION) == 0)
   785                         log.error(tree.pos(),
   786                                   "default.allowed.in.intf.annotation.member");
   787                 }
   788             } else if ((owner.flags() & INTERFACE) != 0) {
   789                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   790             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   791                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   792             } else if ((tree.mods.flags & NATIVE) != 0) {
   793                 log.error(tree.pos(), "native.meth.cant.have.body");
   794             } else {
   795                 // Add an implicit super() call unless an explicit call to
   796                 // super(...) or this(...) is given
   797                 // or we are compiling class java.lang.Object.
   798                 if (tree.name == names.init && owner.type != syms.objectType) {
   799                     JCBlock body = tree.body;
   800                     if (body.stats.isEmpty() ||
   801                         !TreeInfo.isSelfCall(body.stats.head)) {
   802                         body.stats = body.stats.
   803                             prepend(memberEnter.SuperCall(make.at(body.pos),
   804                                                           List.<Type>nil(),
   805                                                           List.<JCVariableDecl>nil(),
   806                                                           false));
   807                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   808                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   809                                TreeInfo.isSuperCall(body.stats.head)) {
   810                         // enum constructors are not allowed to call super
   811                         // directly, so make sure there aren't any super calls
   812                         // in enum constructors, except in the compiler
   813                         // generated one.
   814                         log.error(tree.body.stats.head.pos(),
   815                                   "call.to.super.not.allowed.in.enum.ctor",
   816                                   env.enclClass.sym);
   817                     }
   818                 }
   820                 // Attribute method body.
   821                 attribStat(tree.body, localEnv);
   822             }
   823             localEnv.info.scope.leave();
   824             result = tree.type = m.type;
   825             chk.validateAnnotations(tree.mods.annotations, m);
   826         }
   827         finally {
   828             chk.setLint(prevLint);
   829             chk.setMethod(prevMethod);
   830         }
   831     }
   833     public void visitVarDef(JCVariableDecl tree) {
   834         // Local variables have not been entered yet, so we need to do it now:
   835         if (env.info.scope.owner.kind == MTH) {
   836             if (tree.sym != null) {
   837                 // parameters have already been entered
   838                 env.info.scope.enter(tree.sym);
   839             } else {
   840                 memberEnter.memberEnter(tree, env);
   841                 annotate.flush();
   842             }
   843             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   844         }
   846         VarSymbol v = tree.sym;
   847         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   848         Lint prevLint = chk.setLint(lint);
   850         // Check that the variable's declared type is well-formed.
   851         chk.validate(tree.vartype, env);
   853         try {
   854             chk.checkDeprecatedAnnotation(tree.pos(), v);
   856             if (tree.init != null) {
   857                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   858                     // In this case, `v' is final.  Ensure that it's initializer is
   859                     // evaluated.
   860                     v.getConstValue(); // ensure initializer is evaluated
   861                 } else {
   862                     // Attribute initializer in a new environment
   863                     // with the declared variable as owner.
   864                     // Check that initializer conforms to variable's declared type.
   865                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   866                     initEnv.info.lint = lint;
   867                     // In order to catch self-references, we set the variable's
   868                     // declaration position to maximal possible value, effectively
   869                     // marking the variable as undefined.
   870                     initEnv.info.enclVar = v;
   871                     attribExpr(tree.init, initEnv, v.type);
   872                 }
   873             }
   874             result = tree.type = v.type;
   875             chk.validateAnnotations(tree.mods.annotations, v);
   876         }
   877         finally {
   878             chk.setLint(prevLint);
   879         }
   880     }
   882     public void visitSkip(JCSkip tree) {
   883         result = null;
   884     }
   886     public void visitBlock(JCBlock tree) {
   887         if (env.info.scope.owner.kind == TYP) {
   888             // Block is a static or instance initializer;
   889             // let the owner of the environment be a freshly
   890             // created BLOCK-method.
   891             Env<AttrContext> localEnv =
   892                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   893             localEnv.info.scope.owner =
   894                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   895                                  env.info.scope.owner);
   896             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   897             attribStats(tree.stats, localEnv);
   898         } else {
   899             // Create a new local environment with a local scope.
   900             Env<AttrContext> localEnv =
   901                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   902             attribStats(tree.stats, localEnv);
   903             localEnv.info.scope.leave();
   904         }
   905         result = null;
   906     }
   908     public void visitDoLoop(JCDoWhileLoop tree) {
   909         attribStat(tree.body, env.dup(tree));
   910         attribExpr(tree.cond, env, syms.booleanType);
   911         result = null;
   912     }
   914     public void visitWhileLoop(JCWhileLoop tree) {
   915         attribExpr(tree.cond, env, syms.booleanType);
   916         attribStat(tree.body, env.dup(tree));
   917         result = null;
   918     }
   920     public void visitForLoop(JCForLoop tree) {
   921         Env<AttrContext> loopEnv =
   922             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   923         attribStats(tree.init, loopEnv);
   924         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   925         loopEnv.tree = tree; // before, we were not in loop!
   926         attribStats(tree.step, loopEnv);
   927         attribStat(tree.body, loopEnv);
   928         loopEnv.info.scope.leave();
   929         result = null;
   930     }
   932     public void visitForeachLoop(JCEnhancedForLoop tree) {
   933         Env<AttrContext> loopEnv =
   934             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   935         attribStat(tree.var, loopEnv);
   936         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   937         chk.checkNonVoid(tree.pos(), exprType);
   938         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   939         if (elemtype == null) {
   940             // or perhaps expr implements Iterable<T>?
   941             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   942             if (base == null) {
   943                 log.error(tree.expr.pos(),
   944                         "foreach.not.applicable.to.type",
   945                         exprType,
   946                         diags.fragment("type.req.array.or.iterable"));
   947                 elemtype = types.createErrorType(exprType);
   948             } else {
   949                 List<Type> iterableParams = base.allparams();
   950                 elemtype = iterableParams.isEmpty()
   951                     ? syms.objectType
   952                     : types.upperBound(iterableParams.head);
   953             }
   954         }
   955         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   956         loopEnv.tree = tree; // before, we were not in loop!
   957         attribStat(tree.body, loopEnv);
   958         loopEnv.info.scope.leave();
   959         result = null;
   960     }
   962     public void visitLabelled(JCLabeledStatement tree) {
   963         // Check that label is not used in an enclosing statement
   964         Env<AttrContext> env1 = env;
   965         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   966             if (env1.tree.getTag() == JCTree.LABELLED &&
   967                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   968                 log.error(tree.pos(), "label.already.in.use",
   969                           tree.label);
   970                 break;
   971             }
   972             env1 = env1.next;
   973         }
   975         attribStat(tree.body, env.dup(tree));
   976         result = null;
   977     }
   979     public void visitSwitch(JCSwitch tree) {
   980         Type seltype = attribExpr(tree.selector, env);
   982         Env<AttrContext> switchEnv =
   983             env.dup(tree, env.info.dup(env.info.scope.dup()));
   985         boolean enumSwitch =
   986             allowEnums &&
   987             (seltype.tsym.flags() & Flags.ENUM) != 0;
   988         boolean stringSwitch = false;
   989         if (types.isSameType(seltype, syms.stringType)) {
   990             if (allowStringsInSwitch) {
   991                 stringSwitch = true;
   992             } else {
   993                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   994             }
   995         }
   996         if (!enumSwitch && !stringSwitch)
   997             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   999         // Attribute all cases and
  1000         // check that there are no duplicate case labels or default clauses.
  1001         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1002         boolean hasDefault = false;      // Is there a default label?
  1003         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1004             JCCase c = l.head;
  1005             Env<AttrContext> caseEnv =
  1006                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1007             if (c.pat != null) {
  1008                 if (enumSwitch) {
  1009                     Symbol sym = enumConstant(c.pat, seltype);
  1010                     if (sym == null) {
  1011                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1012                     } else if (!labels.add(sym)) {
  1013                         log.error(c.pos(), "duplicate.case.label");
  1015                 } else {
  1016                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1017                     if (pattype.tag != ERROR) {
  1018                         if (pattype.constValue() == null) {
  1019                             log.error(c.pat.pos(),
  1020                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
  1021                         } else if (labels.contains(pattype.constValue())) {
  1022                             log.error(c.pos(), "duplicate.case.label");
  1023                         } else {
  1024                             labels.add(pattype.constValue());
  1028             } else if (hasDefault) {
  1029                 log.error(c.pos(), "duplicate.default.label");
  1030             } else {
  1031                 hasDefault = true;
  1033             attribStats(c.stats, caseEnv);
  1034             caseEnv.info.scope.leave();
  1035             addVars(c.stats, switchEnv.info.scope);
  1038         switchEnv.info.scope.leave();
  1039         result = null;
  1041     // where
  1042         /** Add any variables defined in stats to the switch scope. */
  1043         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1044             for (;stats.nonEmpty(); stats = stats.tail) {
  1045                 JCTree stat = stats.head;
  1046                 if (stat.getTag() == JCTree.VARDEF)
  1047                     switchScope.enter(((JCVariableDecl) stat).sym);
  1050     // where
  1051     /** Return the selected enumeration constant symbol, or null. */
  1052     private Symbol enumConstant(JCTree tree, Type enumType) {
  1053         if (tree.getTag() != JCTree.IDENT) {
  1054             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1055             return syms.errSymbol;
  1057         JCIdent ident = (JCIdent)tree;
  1058         Name name = ident.name;
  1059         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1060              e.scope != null; e = e.next()) {
  1061             if (e.sym.kind == VAR) {
  1062                 Symbol s = ident.sym = e.sym;
  1063                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1064                 ident.type = s.type;
  1065                 return ((s.flags_field & Flags.ENUM) == 0)
  1066                     ? null : s;
  1069         return null;
  1072     public void visitSynchronized(JCSynchronized tree) {
  1073         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1074         attribStat(tree.body, env);
  1075         result = null;
  1078     public void visitTry(JCTry tree) {
  1079         // Create a new local environment with a local
  1080         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1081         boolean isTryWithResource = tree.resources.nonEmpty();
  1082         // Create a nested environment for attributing the try block if needed
  1083         Env<AttrContext> tryEnv = isTryWithResource ?
  1084             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1085             localEnv;
  1086         // Attribute resource declarations
  1087         for (JCTree resource : tree.resources) {
  1088             if (resource.getTag() == JCTree.VARDEF) {
  1089                 attribStat(resource, tryEnv);
  1090                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1091                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1092                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1093             } else {
  1094                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1097         // Attribute body
  1098         attribStat(tree.body, tryEnv);
  1099         if (isTryWithResource)
  1100             tryEnv.info.scope.leave();
  1102         // Attribute catch clauses
  1103         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1104             JCCatch c = l.head;
  1105             Env<AttrContext> catchEnv =
  1106                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1107             Type ctype = attribStat(c.param, catchEnv);
  1108             if (TreeInfo.isMultiCatch(c)) {
  1109                 //multi-catch parameter is implicitly marked as final
  1110                 c.param.sym.flags_field |= FINAL | DISJUNCTION;
  1112             if (c.param.sym.kind == Kinds.VAR) {
  1113                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1115             chk.checkType(c.param.vartype.pos(),
  1116                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1117                           syms.throwableType);
  1118             attribStat(c.body, catchEnv);
  1119             catchEnv.info.scope.leave();
  1122         // Attribute finalizer
  1123         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1125         localEnv.info.scope.leave();
  1126         result = null;
  1129     public void visitConditional(JCConditional tree) {
  1130         attribExpr(tree.cond, env, syms.booleanType);
  1131         attribExpr(tree.truepart, env);
  1132         attribExpr(tree.falsepart, env);
  1133         result = check(tree,
  1134                        capture(condType(tree.pos(), tree.cond.type,
  1135                                         tree.truepart.type, tree.falsepart.type)),
  1136                        VAL, pkind, pt);
  1138     //where
  1139         /** Compute the type of a conditional expression, after
  1140          *  checking that it exists. See Spec 15.25.
  1142          *  @param pos      The source position to be used for
  1143          *                  error diagnostics.
  1144          *  @param condtype The type of the expression's condition.
  1145          *  @param thentype The type of the expression's then-part.
  1146          *  @param elsetype The type of the expression's else-part.
  1147          */
  1148         private Type condType(DiagnosticPosition pos,
  1149                               Type condtype,
  1150                               Type thentype,
  1151                               Type elsetype) {
  1152             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1154             // If condition and both arms are numeric constants,
  1155             // evaluate at compile-time.
  1156             return ((condtype.constValue() != null) &&
  1157                     (thentype.constValue() != null) &&
  1158                     (elsetype.constValue() != null))
  1159                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1160                 : ctype;
  1162         /** Compute the type of a conditional expression, after
  1163          *  checking that it exists.  Does not take into
  1164          *  account the special case where condition and both arms
  1165          *  are constants.
  1167          *  @param pos      The source position to be used for error
  1168          *                  diagnostics.
  1169          *  @param condtype The type of the expression's condition.
  1170          *  @param thentype The type of the expression's then-part.
  1171          *  @param elsetype The type of the expression's else-part.
  1172          */
  1173         private Type condType1(DiagnosticPosition pos, Type condtype,
  1174                                Type thentype, Type elsetype) {
  1175             // If same type, that is the result
  1176             if (types.isSameType(thentype, elsetype))
  1177                 return thentype.baseType();
  1179             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1180                 ? thentype : types.unboxedType(thentype);
  1181             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1182                 ? elsetype : types.unboxedType(elsetype);
  1184             // Otherwise, if both arms can be converted to a numeric
  1185             // type, return the least numeric type that fits both arms
  1186             // (i.e. return larger of the two, or return int if one
  1187             // arm is short, the other is char).
  1188             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1189                 // If one arm has an integer subrange type (i.e., byte,
  1190                 // short, or char), and the other is an integer constant
  1191                 // that fits into the subrange, return the subrange type.
  1192                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1193                     types.isAssignable(elseUnboxed, thenUnboxed))
  1194                     return thenUnboxed.baseType();
  1195                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1196                     types.isAssignable(thenUnboxed, elseUnboxed))
  1197                     return elseUnboxed.baseType();
  1199                 for (int i = BYTE; i < VOID; i++) {
  1200                     Type candidate = syms.typeOfTag[i];
  1201                     if (types.isSubtype(thenUnboxed, candidate) &&
  1202                         types.isSubtype(elseUnboxed, candidate))
  1203                         return candidate;
  1207             // Those were all the cases that could result in a primitive
  1208             if (allowBoxing) {
  1209                 if (thentype.isPrimitive())
  1210                     thentype = types.boxedClass(thentype).type;
  1211                 if (elsetype.isPrimitive())
  1212                     elsetype = types.boxedClass(elsetype).type;
  1215             if (types.isSubtype(thentype, elsetype))
  1216                 return elsetype.baseType();
  1217             if (types.isSubtype(elsetype, thentype))
  1218                 return thentype.baseType();
  1220             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1221                 log.error(pos, "neither.conditional.subtype",
  1222                           thentype, elsetype);
  1223                 return thentype.baseType();
  1226             // both are known to be reference types.  The result is
  1227             // lub(thentype,elsetype). This cannot fail, as it will
  1228             // always be possible to infer "Object" if nothing better.
  1229             return types.lub(thentype.baseType(), elsetype.baseType());
  1232     public void visitIf(JCIf tree) {
  1233         attribExpr(tree.cond, env, syms.booleanType);
  1234         attribStat(tree.thenpart, env);
  1235         if (tree.elsepart != null)
  1236             attribStat(tree.elsepart, env);
  1237         chk.checkEmptyIf(tree);
  1238         result = null;
  1241     public void visitExec(JCExpressionStatement tree) {
  1242         //a fresh environment is required for 292 inference to work properly ---
  1243         //see Infer.instantiatePolymorphicSignatureInstance()
  1244         Env<AttrContext> localEnv = env.dup(tree);
  1245         attribExpr(tree.expr, localEnv);
  1246         result = null;
  1249     public void visitBreak(JCBreak tree) {
  1250         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1251         result = null;
  1254     public void visitContinue(JCContinue tree) {
  1255         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1256         result = null;
  1258     //where
  1259         /** Return the target of a break or continue statement, if it exists,
  1260          *  report an error if not.
  1261          *  Note: The target of a labelled break or continue is the
  1262          *  (non-labelled) statement tree referred to by the label,
  1263          *  not the tree representing the labelled statement itself.
  1265          *  @param pos     The position to be used for error diagnostics
  1266          *  @param tag     The tag of the jump statement. This is either
  1267          *                 Tree.BREAK or Tree.CONTINUE.
  1268          *  @param label   The label of the jump statement, or null if no
  1269          *                 label is given.
  1270          *  @param env     The environment current at the jump statement.
  1271          */
  1272         private JCTree findJumpTarget(DiagnosticPosition pos,
  1273                                     int tag,
  1274                                     Name label,
  1275                                     Env<AttrContext> env) {
  1276             // Search environments outwards from the point of jump.
  1277             Env<AttrContext> env1 = env;
  1278             LOOP:
  1279             while (env1 != null) {
  1280                 switch (env1.tree.getTag()) {
  1281                 case JCTree.LABELLED:
  1282                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1283                     if (label == labelled.label) {
  1284                         // If jump is a continue, check that target is a loop.
  1285                         if (tag == JCTree.CONTINUE) {
  1286                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1287                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1288                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1289                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1290                                 log.error(pos, "not.loop.label", label);
  1291                             // Found labelled statement target, now go inwards
  1292                             // to next non-labelled tree.
  1293                             return TreeInfo.referencedStatement(labelled);
  1294                         } else {
  1295                             return labelled;
  1298                     break;
  1299                 case JCTree.DOLOOP:
  1300                 case JCTree.WHILELOOP:
  1301                 case JCTree.FORLOOP:
  1302                 case JCTree.FOREACHLOOP:
  1303                     if (label == null) return env1.tree;
  1304                     break;
  1305                 case JCTree.SWITCH:
  1306                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1307                     break;
  1308                 case JCTree.METHODDEF:
  1309                 case JCTree.CLASSDEF:
  1310                     break LOOP;
  1311                 default:
  1313                 env1 = env1.next;
  1315             if (label != null)
  1316                 log.error(pos, "undef.label", label);
  1317             else if (tag == JCTree.CONTINUE)
  1318                 log.error(pos, "cont.outside.loop");
  1319             else
  1320                 log.error(pos, "break.outside.switch.loop");
  1321             return null;
  1324     public void visitReturn(JCReturn tree) {
  1325         // Check that there is an enclosing method which is
  1326         // nested within than the enclosing class.
  1327         if (env.enclMethod == null ||
  1328             env.enclMethod.sym.owner != env.enclClass.sym) {
  1329             log.error(tree.pos(), "ret.outside.meth");
  1331         } else {
  1332             // Attribute return expression, if it exists, and check that
  1333             // it conforms to result type of enclosing method.
  1334             Symbol m = env.enclMethod.sym;
  1335             if (m.type.getReturnType().tag == VOID) {
  1336                 if (tree.expr != null)
  1337                     log.error(tree.expr.pos(),
  1338                               "cant.ret.val.from.meth.decl.void");
  1339             } else if (tree.expr == null) {
  1340                 log.error(tree.pos(), "missing.ret.val");
  1341             } else {
  1342                 attribExpr(tree.expr, env, m.type.getReturnType());
  1345         result = null;
  1348     public void visitThrow(JCThrow tree) {
  1349         attribExpr(tree.expr, env, syms.throwableType);
  1350         result = null;
  1353     public void visitAssert(JCAssert tree) {
  1354         attribExpr(tree.cond, env, syms.booleanType);
  1355         if (tree.detail != null) {
  1356             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1358         result = null;
  1361      /** Visitor method for method invocations.
  1362      *  NOTE: The method part of an application will have in its type field
  1363      *        the return type of the method, not the method's type itself!
  1364      */
  1365     public void visitApply(JCMethodInvocation tree) {
  1366         // The local environment of a method application is
  1367         // a new environment nested in the current one.
  1368         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1370         // The types of the actual method arguments.
  1371         List<Type> argtypes;
  1373         // The types of the actual method type arguments.
  1374         List<Type> typeargtypes = null;
  1376         Name methName = TreeInfo.name(tree.meth);
  1378         boolean isConstructorCall =
  1379             methName == names._this || methName == names._super;
  1381         if (isConstructorCall) {
  1382             // We are seeing a ...this(...) or ...super(...) call.
  1383             // Check that this is the first statement in a constructor.
  1384             if (checkFirstConstructorStat(tree, env)) {
  1386                 // Record the fact
  1387                 // that this is a constructor call (using isSelfCall).
  1388                 localEnv.info.isSelfCall = true;
  1390                 // Attribute arguments, yielding list of argument types.
  1391                 argtypes = attribArgs(tree.args, localEnv);
  1392                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1394                 // Variable `site' points to the class in which the called
  1395                 // constructor is defined.
  1396                 Type site = env.enclClass.sym.type;
  1397                 if (methName == names._super) {
  1398                     if (site == syms.objectType) {
  1399                         log.error(tree.meth.pos(), "no.superclass", site);
  1400                         site = types.createErrorType(syms.objectType);
  1401                     } else {
  1402                         site = types.supertype(site);
  1406                 if (site.tag == CLASS) {
  1407                     Type encl = site.getEnclosingType();
  1408                     while (encl != null && encl.tag == TYPEVAR)
  1409                         encl = encl.getUpperBound();
  1410                     if (encl.tag == CLASS) {
  1411                         // we are calling a nested class
  1413                         if (tree.meth.getTag() == JCTree.SELECT) {
  1414                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1416                             // We are seeing a prefixed call, of the form
  1417                             //     <expr>.super(...).
  1418                             // Check that the prefix expression conforms
  1419                             // to the outer instance type of the class.
  1420                             chk.checkRefType(qualifier.pos(),
  1421                                              attribExpr(qualifier, localEnv,
  1422                                                         encl));
  1423                         } else if (methName == names._super) {
  1424                             // qualifier omitted; check for existence
  1425                             // of an appropriate implicit qualifier.
  1426                             rs.resolveImplicitThis(tree.meth.pos(),
  1427                                                    localEnv, site);
  1429                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1430                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1431                                   site.tsym);
  1434                     // if we're calling a java.lang.Enum constructor,
  1435                     // prefix the implicit String and int parameters
  1436                     if (site.tsym == syms.enumSym && allowEnums)
  1437                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1439                     // Resolve the called constructor under the assumption
  1440                     // that we are referring to a superclass instance of the
  1441                     // current instance (JLS ???).
  1442                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1443                     localEnv.info.selectSuper = true;
  1444                     localEnv.info.varArgs = false;
  1445                     Symbol sym = rs.resolveConstructor(
  1446                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1447                     localEnv.info.selectSuper = selectSuperPrev;
  1449                     // Set method symbol to resolved constructor...
  1450                     TreeInfo.setSymbol(tree.meth, sym);
  1452                     // ...and check that it is legal in the current context.
  1453                     // (this will also set the tree's type)
  1454                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1455                     checkId(tree.meth, site, sym, localEnv, MTH,
  1456                             mpt, tree.varargsElement != null);
  1458                 // Otherwise, `site' is an error type and we do nothing
  1460             result = tree.type = syms.voidType;
  1461         } else {
  1462             // Otherwise, we are seeing a regular method call.
  1463             // Attribute the arguments, yielding list of argument types, ...
  1464             argtypes = attribArgs(tree.args, localEnv);
  1465             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1467             // ... and attribute the method using as a prototype a methodtype
  1468             // whose formal argument types is exactly the list of actual
  1469             // arguments (this will also set the method symbol).
  1470             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1471             localEnv.info.varArgs = false;
  1472             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1473             if (localEnv.info.varArgs)
  1474                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
  1476             // Compute the result type.
  1477             Type restype = mtype.getReturnType();
  1478             if (restype.tag == WILDCARD)
  1479                 throw new AssertionError(mtype);
  1481             // as a special case, array.clone() has a result that is
  1482             // the same as static type of the array being cloned
  1483             if (tree.meth.getTag() == JCTree.SELECT &&
  1484                 allowCovariantReturns &&
  1485                 methName == names.clone &&
  1486                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1487                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1489             // as a special case, x.getClass() has type Class<? extends |X|>
  1490             if (allowGenerics &&
  1491                 methName == names.getClass && tree.args.isEmpty()) {
  1492                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1493                     ? ((JCFieldAccess) tree.meth).selected.type
  1494                     : env.enclClass.sym.type;
  1495                 restype = new
  1496                     ClassType(restype.getEnclosingType(),
  1497                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1498                                                                BoundKind.EXTENDS,
  1499                                                                syms.boundClass)),
  1500                               restype.tsym);
  1503             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1505             // Check that value of resulting type is admissible in the
  1506             // current context.  Also, capture the return type
  1507             result = check(tree, capture(restype), VAL, pkind, pt);
  1509         chk.validate(tree.typeargs, localEnv);
  1511     //where
  1512         /** Check that given application node appears as first statement
  1513          *  in a constructor call.
  1514          *  @param tree   The application node
  1515          *  @param env    The environment current at the application.
  1516          */
  1517         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1518             JCMethodDecl enclMethod = env.enclMethod;
  1519             if (enclMethod != null && enclMethod.name == names.init) {
  1520                 JCBlock body = enclMethod.body;
  1521                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1522                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1523                     return true;
  1525             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1526                       TreeInfo.name(tree.meth));
  1527             return false;
  1530         /** Obtain a method type with given argument types.
  1531          */
  1532         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1533             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1534             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1537     public void visitNewClass(JCNewClass tree) {
  1538         Type owntype = types.createErrorType(tree.type);
  1540         // The local environment of a class creation is
  1541         // a new environment nested in the current one.
  1542         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1544         // The anonymous inner class definition of the new expression,
  1545         // if one is defined by it.
  1546         JCClassDecl cdef = tree.def;
  1548         // If enclosing class is given, attribute it, and
  1549         // complete class name to be fully qualified
  1550         JCExpression clazz = tree.clazz; // Class field following new
  1551         JCExpression clazzid =          // Identifier in class field
  1552             (clazz.getTag() == JCTree.TYPEAPPLY)
  1553             ? ((JCTypeApply) clazz).clazz
  1554             : clazz;
  1556         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1558         if (tree.encl != null) {
  1559             // We are seeing a qualified new, of the form
  1560             //    <expr>.new C <...> (...) ...
  1561             // In this case, we let clazz stand for the name of the
  1562             // allocated class C prefixed with the type of the qualifier
  1563             // expression, so that we can
  1564             // resolve it with standard techniques later. I.e., if
  1565             // <expr> has type T, then <expr>.new C <...> (...)
  1566             // yields a clazz T.C.
  1567             Type encltype = chk.checkRefType(tree.encl.pos(),
  1568                                              attribExpr(tree.encl, env));
  1569             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1570                                                  ((JCIdent) clazzid).name);
  1571             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1572                 clazz = make.at(tree.pos).
  1573                     TypeApply(clazzid1,
  1574                               ((JCTypeApply) clazz).arguments);
  1575             else
  1576                 clazz = clazzid1;
  1579         // Attribute clazz expression and store
  1580         // symbol + type back into the attributed tree.
  1581         Type clazztype = attribType(clazz, env);
  1582         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype, cdef != null);
  1583         if (!TreeInfo.isDiamond(tree)) {
  1584             clazztype = chk.checkClassType(
  1585                 tree.clazz.pos(), clazztype, true);
  1587         chk.validate(clazz, localEnv);
  1588         if (tree.encl != null) {
  1589             // We have to work in this case to store
  1590             // symbol + type back into the attributed tree.
  1591             tree.clazz.type = clazztype;
  1592             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1593             clazzid.type = ((JCIdent) clazzid).sym.type;
  1594             if (!clazztype.isErroneous()) {
  1595                 if (cdef != null && clazztype.tsym.isInterface()) {
  1596                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1597                 } else if (clazztype.tsym.isStatic()) {
  1598                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1601         } else if (!clazztype.tsym.isInterface() &&
  1602                    clazztype.getEnclosingType().tag == CLASS) {
  1603             // Check for the existence of an apropos outer instance
  1604             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1607         // Attribute constructor arguments.
  1608         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1609         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1611         if (TreeInfo.isDiamond(tree)) {
  1612             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1613             clazz.type = clazztype;
  1614         } else if (allowDiamondFinder &&
  1615                 clazztype.getTypeArguments().nonEmpty() &&
  1616                 findDiamonds) {
  1617             boolean prevDeferDiags = log.deferDiagnostics;
  1618             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1619             Type inferred = null;
  1620             try {
  1621                 //disable diamond-related diagnostics
  1622                 log.deferDiagnostics = true;
  1623                 log.deferredDiagnostics = ListBuffer.lb();
  1624                 inferred = attribDiamond(localEnv,
  1625                         tree,
  1626                         clazztype,
  1627                         mapping,
  1628                         argtypes,
  1629                         typeargtypes);
  1631             finally {
  1632                 log.deferDiagnostics = prevDeferDiags;
  1633                 log.deferredDiagnostics = prevDeferredDiags;
  1635             if (inferred != null &&
  1636                     !inferred.isErroneous() &&
  1637                     inferred.tag == CLASS &&
  1638                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
  1639                     chk.checkDiamond((ClassType)inferred).isEmpty()) {
  1640                 String key = types.isSameType(clazztype, inferred) ?
  1641                     "diamond.redundant.args" :
  1642                     "diamond.redundant.args.1";
  1643                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1647         // If we have made no mistakes in the class type...
  1648         if (clazztype.tag == CLASS) {
  1649             // Enums may not be instantiated except implicitly
  1650             if (allowEnums &&
  1651                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1652                 (env.tree.getTag() != JCTree.VARDEF ||
  1653                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1654                  ((JCVariableDecl) env.tree).init != tree))
  1655                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1656             // Check that class is not abstract
  1657             if (cdef == null &&
  1658                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1659                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1660                           clazztype.tsym);
  1661             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1662                 // Check that no constructor arguments are given to
  1663                 // anonymous classes implementing an interface
  1664                 if (!argtypes.isEmpty())
  1665                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1667                 if (!typeargtypes.isEmpty())
  1668                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1670                 // Error recovery: pretend no arguments were supplied.
  1671                 argtypes = List.nil();
  1672                 typeargtypes = List.nil();
  1675             // Resolve the called constructor under the assumption
  1676             // that we are referring to a superclass instance of the
  1677             // current instance (JLS ???).
  1678             else {
  1679                 localEnv.info.selectSuper = cdef != null;
  1680                 localEnv.info.varArgs = false;
  1681                 tree.constructor = rs.resolveConstructor(
  1682                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1683                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1684                     syms.errType :
  1685                     checkMethod(clazztype,
  1686                         tree.constructor,
  1687                         localEnv,
  1688                         tree.args,
  1689                         argtypes,
  1690                         typeargtypes,
  1691                         localEnv.info.varArgs);
  1692                 if (localEnv.info.varArgs)
  1693                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1696             if (cdef != null) {
  1697                 // We are seeing an anonymous class instance creation.
  1698                 // In this case, the class instance creation
  1699                 // expression
  1700                 //
  1701                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1702                 //
  1703                 // is represented internally as
  1704                 //
  1705                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1706                 //
  1707                 // This expression is then *transformed* as follows:
  1708                 //
  1709                 // (1) add a STATIC flag to the class definition
  1710                 //     if the current environment is static
  1711                 // (2) add an extends or implements clause
  1712                 // (3) add a constructor.
  1713                 //
  1714                 // For instance, if C is a class, and ET is the type of E,
  1715                 // the expression
  1716                 //
  1717                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1718                 //
  1719                 // is translated to (where X is a fresh name and typarams is the
  1720                 // parameter list of the super constructor):
  1721                 //
  1722                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1723                 //     X extends C<typargs2> {
  1724                 //       <typarams> X(ET e, args) {
  1725                 //         e.<typeargs1>super(args)
  1726                 //       }
  1727                 //       ...
  1728                 //     }
  1729                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1731                 if (clazztype.tsym.isInterface()) {
  1732                     cdef.implementing = List.of(clazz);
  1733                 } else {
  1734                     cdef.extending = clazz;
  1737                 attribStat(cdef, localEnv);
  1739                 // If an outer instance is given,
  1740                 // prefix it to the constructor arguments
  1741                 // and delete it from the new expression
  1742                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1743                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1744                     argtypes = argtypes.prepend(tree.encl.type);
  1745                     tree.encl = null;
  1748                 // Reassign clazztype and recompute constructor.
  1749                 clazztype = cdef.sym.type;
  1750                 Symbol sym = rs.resolveConstructor(
  1751                     tree.pos(), localEnv, clazztype, argtypes,
  1752                     typeargtypes, true, tree.varargsElement != null);
  1753                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
  1754                 tree.constructor = sym;
  1755                 if (tree.constructor.kind > ERRONEOUS) {
  1756                     tree.constructorType =  syms.errType;
  1758                 else {
  1759                     tree.constructorType = checkMethod(clazztype,
  1760                             tree.constructor,
  1761                             localEnv,
  1762                             tree.args,
  1763                             argtypes,
  1764                             typeargtypes,
  1765                             localEnv.info.varArgs);
  1769             if (tree.constructor != null && tree.constructor.kind == MTH)
  1770                 owntype = clazztype;
  1772         result = check(tree, owntype, VAL, pkind, pt);
  1773         chk.validate(tree.typeargs, localEnv);
  1776     Type attribDiamond(Env<AttrContext> env,
  1777                         JCNewClass tree,
  1778                         Type clazztype,
  1779                         Pair<Scope, Scope> mapping,
  1780                         List<Type> argtypes,
  1781                         List<Type> typeargtypes) {
  1782         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1783             //if the type of the instance creation expression is erroneous,
  1784             //or something prevented us to form a valid mapping, return the
  1785             //(possibly erroneous) type unchanged
  1786             return clazztype;
  1788         else if (clazztype.isInterface()) {
  1789             //if the type of the instance creation expression is an interface
  1790             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1791             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1792             clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
  1793                 @Override
  1794                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
  1795                     switch (ck) {
  1796                         case EXTENDS: return types.getBounds(tv);
  1797                         default: return List.nil();
  1800                 @Override
  1801                 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
  1802                     // check that inferred bounds conform to their bounds
  1803                     infer.checkWithinBounds(tvars,
  1804                            types.subst(tvars, tvars, inferred), Warner.noWarnings);
  1805                     return super.inst(inferred, types);
  1807             };
  1808         } else {
  1809             //if the type of the instance creation expression is a class type
  1810             //apply method resolution inference (JLS 15.12.2.7). The return type
  1811             //of the resolved constructor will be a partially instantiated type
  1812             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1813             Symbol constructor;
  1814             try {
  1815                 constructor = rs.resolveDiamond(tree.pos(),
  1816                         env,
  1817                         clazztype.tsym.type,
  1818                         argtypes,
  1819                         typeargtypes);
  1820             } finally {
  1821                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1823             if (constructor.kind == MTH) {
  1824                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1825                         clazztype.tsym.type.getTypeArguments(),
  1826                         clazztype.tsym);
  1827                 clazztype = checkMethod(ct,
  1828                         constructor,
  1829                         env,
  1830                         tree.args,
  1831                         argtypes,
  1832                         typeargtypes,
  1833                         env.info.varArgs).getReturnType();
  1834             } else {
  1835                 clazztype = syms.errType;
  1838         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1839             //if the resolved constructor's return type has some uninferred
  1840             //type-variables, infer them using the expected type and declared
  1841             //bounds (JLS 15.12.2.8).
  1842             try {
  1843                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1844                         pt.tag == NONE ? syms.objectType : pt,
  1845                         Warner.noWarnings);
  1846             } catch (Infer.InferenceException ex) {
  1847                 //an error occurred while inferring uninstantiated type-variables
  1848                 log.error(tree.clazz.pos(),
  1849                         "cant.apply.diamond.1",
  1850                         diags.fragment("diamond", clazztype.tsym),
  1851                         ex.diagnostic);
  1854         clazztype = chk.checkClassType(tree.clazz.pos(),
  1855                 clazztype,
  1856                 true);
  1857         if (clazztype.tag == CLASS) {
  1858             List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1859             if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1860                 //one or more types inferred in the previous steps is either a
  1861                 //captured type or an intersection type --- we need to report an error.
  1862                 String subkey = invalidDiamondArgs.size() > 1 ?
  1863                     "diamond.invalid.args" :
  1864                     "diamond.invalid.arg";
  1865                 //The error message is of the kind:
  1866                 //
  1867                 //cannot infer type arguments for {clazztype}<>;
  1868                 //reason: {subkey}
  1869                 //
  1870                 //where subkey is a fragment of the kind:
  1871                 //
  1872                 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1873                 log.error(tree.clazz.pos(),
  1874                             "cant.apply.diamond.1",
  1875                             diags.fragment("diamond", clazztype.tsym),
  1876                             diags.fragment(subkey,
  1877                                            invalidDiamondArgs,
  1878                                            diags.fragment("diamond", clazztype.tsym)));
  1881         return clazztype;
  1884     /** Creates a synthetic scope containing fake generic constructors.
  1885      *  Assuming that the original scope contains a constructor of the kind:
  1886      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1887      *  the synthetic scope is added a generic constructor of the kind:
  1888      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1889      *  inference. The inferred return type of the synthetic constructor IS
  1890      *  the inferred type for the diamond operator.
  1891      */
  1892     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype, boolean overrideProtectedAccess) {
  1893         if (ctype.tag != CLASS) {
  1894             return erroneousMapping;
  1896         Pair<Scope, Scope> mapping =
  1897                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1898         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1899         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1900                 e.scope != null;
  1901                 e = e.next()) {
  1902             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1903             if (overrideProtectedAccess && (newConstr.flags() & PROTECTED) != 0) {
  1904                 //make protected constructor public (this is required for
  1905                 //anonymous inner class creation expressions using diamond)
  1906                 newConstr.flags_field |= PUBLIC;
  1907                 newConstr.flags_field &= ~PROTECTED;
  1909             newConstr.name = names.init;
  1910             List<Type> oldTypeargs = List.nil();
  1911             if (newConstr.type.tag == FORALL) {
  1912                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1914             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1915                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1916                     newConstr.type.getThrownTypes(),
  1917                     syms.methodClass);
  1918             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1919             mapping.snd.enter(newConstr);
  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             chk.checkOperator(tree.pos(),
  1999                               (OperatorSymbol)operator,
  2000                               tree.getTag() - JCTree.ASGOffset,
  2001                               owntype,
  2002                               operand);
  2003             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2004             chk.checkCastable(tree.rhs.pos(),
  2005                               operator.type.getReturnType(),
  2006                               owntype);
  2008         result = check(tree, owntype, VAL, pkind, pt);
  2011     public void visitUnary(JCUnary tree) {
  2012         // Attribute arguments.
  2013         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2014             ? attribTree(tree.arg, env, VAR, Type.noType)
  2015             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2017         // Find operator.
  2018         Symbol operator = tree.operator =
  2019             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2021         Type owntype = types.createErrorType(tree.type);
  2022         if (operator.kind == MTH) {
  2023             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  2024                 ? tree.arg.type
  2025                 : operator.type.getReturnType();
  2026             int opc = ((OperatorSymbol)operator).opcode;
  2028             // If the argument is constant, fold it.
  2029             if (argtype.constValue() != null) {
  2030                 Type ctype = cfolder.fold1(opc, argtype);
  2031                 if (ctype != null) {
  2032                     owntype = cfolder.coerce(ctype, owntype);
  2034                     // Remove constant types from arguments to
  2035                     // conserve space. The parser will fold concatenations
  2036                     // of string literals; the code here also
  2037                     // gets rid of intermediate results when some of the
  2038                     // operands are constant identifiers.
  2039                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2040                         tree.arg.type = syms.stringType;
  2045         result = check(tree, owntype, VAL, pkind, pt);
  2048     public void visitBinary(JCBinary tree) {
  2049         // Attribute arguments.
  2050         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2051         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2053         // Find operator.
  2054         Symbol operator = tree.operator =
  2055             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2057         Type owntype = types.createErrorType(tree.type);
  2058         if (operator.kind == MTH) {
  2059             owntype = operator.type.getReturnType();
  2060             int opc = chk.checkOperator(tree.lhs.pos(),
  2061                                         (OperatorSymbol)operator,
  2062                                         tree.getTag(),
  2063                                         left,
  2064                                         right);
  2066             // If both arguments are constants, fold them.
  2067             if (left.constValue() != null && right.constValue() != null) {
  2068                 Type ctype = cfolder.fold2(opc, left, right);
  2069                 if (ctype != null) {
  2070                     owntype = cfolder.coerce(ctype, owntype);
  2072                     // Remove constant types from arguments to
  2073                     // conserve space. The parser will fold concatenations
  2074                     // of string literals; the code here also
  2075                     // gets rid of intermediate results when some of the
  2076                     // operands are constant identifiers.
  2077                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2078                         tree.lhs.type = syms.stringType;
  2080                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2081                         tree.rhs.type = syms.stringType;
  2086             // Check that argument types of a reference ==, != are
  2087             // castable to each other, (JLS???).
  2088             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2089                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2090                     log.error(tree.pos(), "incomparable.types", left, right);
  2094             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2096         result = check(tree, owntype, VAL, pkind, pt);
  2099     public void visitTypeCast(JCTypeCast tree) {
  2100         Type clazztype = attribType(tree.clazz, env);
  2101         chk.validate(tree.clazz, env, false);
  2102         //a fresh environment is required for 292 inference to work properly ---
  2103         //see Infer.instantiatePolymorphicSignatureInstance()
  2104         Env<AttrContext> localEnv = env.dup(tree);
  2105         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2106         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2107         if (exprtype.constValue() != null)
  2108             owntype = cfolder.coerce(exprtype, owntype);
  2109         result = check(tree, capture(owntype), VAL, pkind, pt);
  2112     public void visitTypeTest(JCInstanceOf tree) {
  2113         Type exprtype = chk.checkNullOrRefType(
  2114             tree.expr.pos(), attribExpr(tree.expr, env));
  2115         Type clazztype = chk.checkReifiableReferenceType(
  2116             tree.clazz.pos(), attribType(tree.clazz, env));
  2117         chk.validate(tree.clazz, env, false);
  2118         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2119         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2122     public void visitIndexed(JCArrayAccess tree) {
  2123         Type owntype = types.createErrorType(tree.type);
  2124         Type atype = attribExpr(tree.indexed, env);
  2125         attribExpr(tree.index, env, syms.intType);
  2126         if (types.isArray(atype))
  2127             owntype = types.elemtype(atype);
  2128         else if (atype.tag != ERROR)
  2129             log.error(tree.pos(), "array.req.but.found", atype);
  2130         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2131         result = check(tree, owntype, VAR, pkind, pt);
  2134     public void visitIdent(JCIdent tree) {
  2135         Symbol sym;
  2136         boolean varArgs = false;
  2138         // Find symbol
  2139         if (pt.tag == METHOD || pt.tag == FORALL) {
  2140             // If we are looking for a method, the prototype `pt' will be a
  2141             // method type with the type of the call's arguments as parameters.
  2142             env.info.varArgs = false;
  2143             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2144             varArgs = env.info.varArgs;
  2145         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2146             sym = tree.sym;
  2147         } else {
  2148             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2150         tree.sym = sym;
  2152         // (1) Also find the environment current for the class where
  2153         //     sym is defined (`symEnv').
  2154         // Only for pre-tiger versions (1.4 and earlier):
  2155         // (2) Also determine whether we access symbol out of an anonymous
  2156         //     class in a this or super call.  This is illegal for instance
  2157         //     members since such classes don't carry a this$n link.
  2158         //     (`noOuterThisPath').
  2159         Env<AttrContext> symEnv = env;
  2160         boolean noOuterThisPath = false;
  2161         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2162             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2163             sym.owner.kind == TYP &&
  2164             tree.name != names._this && tree.name != names._super) {
  2166             // Find environment in which identifier is defined.
  2167             while (symEnv.outer != null &&
  2168                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2169                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2170                     noOuterThisPath = !allowAnonOuterThis;
  2171                 symEnv = symEnv.outer;
  2175         // If symbol is a variable, ...
  2176         if (sym.kind == VAR) {
  2177             VarSymbol v = (VarSymbol)sym;
  2179             // ..., evaluate its initializer, if it has one, and check for
  2180             // illegal forward reference.
  2181             checkInit(tree, env, v, false);
  2183             // If symbol is a local variable accessed from an embedded
  2184             // inner class check that it is final.
  2185             if (v.owner.kind == MTH &&
  2186                 v.owner != env.info.scope.owner &&
  2187                 (v.flags_field & FINAL) == 0) {
  2188                 log.error(tree.pos(),
  2189                           "local.var.accessed.from.icls.needs.final",
  2190                           v);
  2193             // If we are expecting a variable (as opposed to a value), check
  2194             // that the variable is assignable in the current environment.
  2195             if (pkind == VAR)
  2196                 checkAssignable(tree.pos(), v, null, env);
  2199         // In a constructor body,
  2200         // if symbol is a field or instance method, check that it is
  2201         // not accessed before the supertype constructor is called.
  2202         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2203             (sym.kind & (VAR | MTH)) != 0 &&
  2204             sym.owner.kind == TYP &&
  2205             (sym.flags() & STATIC) == 0) {
  2206             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2208         Env<AttrContext> env1 = env;
  2209         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2210             // If the found symbol is inaccessible, then it is
  2211             // accessed through an enclosing instance.  Locate this
  2212             // enclosing instance:
  2213             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2214                 env1 = env1.outer;
  2216         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2219     public void visitSelect(JCFieldAccess tree) {
  2220         // Determine the expected kind of the qualifier expression.
  2221         int skind = 0;
  2222         if (tree.name == names._this || tree.name == names._super ||
  2223             tree.name == names._class)
  2225             skind = TYP;
  2226         } else {
  2227             if ((pkind & PCK) != 0) skind = skind | PCK;
  2228             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2229             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2232         // Attribute the qualifier expression, and determine its symbol (if any).
  2233         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2234         if ((pkind & (PCK | TYP)) == 0)
  2235             site = capture(site); // Capture field access
  2237         // don't allow T.class T[].class, etc
  2238         if (skind == TYP) {
  2239             Type elt = site;
  2240             while (elt.tag == ARRAY)
  2241                 elt = ((ArrayType)elt).elemtype;
  2242             if (elt.tag == TYPEVAR) {
  2243                 log.error(tree.pos(), "type.var.cant.be.deref");
  2244                 result = types.createErrorType(tree.type);
  2245                 return;
  2249         // If qualifier symbol is a type or `super', assert `selectSuper'
  2250         // for the selection. This is relevant for determining whether
  2251         // protected symbols are accessible.
  2252         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2253         boolean selectSuperPrev = env.info.selectSuper;
  2254         env.info.selectSuper =
  2255             sitesym != null &&
  2256             sitesym.name == names._super;
  2258         // If selected expression is polymorphic, strip
  2259         // type parameters and remember in env.info.tvars, so that
  2260         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2261         if (tree.selected.type.tag == FORALL) {
  2262             ForAll pstype = (ForAll)tree.selected.type;
  2263             env.info.tvars = pstype.tvars;
  2264             site = tree.selected.type = pstype.qtype;
  2267         // Determine the symbol represented by the selection.
  2268         env.info.varArgs = false;
  2269         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2270         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2271             site = capture(site);
  2272             sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2274         boolean varArgs = env.info.varArgs;
  2275         tree.sym = sym;
  2277         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2278             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2279             site = capture(site);
  2282         // If that symbol is a variable, ...
  2283         if (sym.kind == VAR) {
  2284             VarSymbol v = (VarSymbol)sym;
  2286             // ..., evaluate its initializer, if it has one, and check for
  2287             // illegal forward reference.
  2288             checkInit(tree, env, v, true);
  2290             // If we are expecting a variable (as opposed to a value), check
  2291             // that the variable is assignable in the current environment.
  2292             if (pkind == VAR)
  2293                 checkAssignable(tree.pos(), v, tree.selected, env);
  2296         if (sitesym != null &&
  2297                 sitesym.kind == VAR &&
  2298                 ((VarSymbol)sitesym).isResourceVariable() &&
  2299                 sym.kind == MTH &&
  2300                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2301                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2302             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2305         // Disallow selecting a type from an expression
  2306         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2307             tree.type = check(tree.selected, pt,
  2308                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2311         if (isType(sitesym)) {
  2312             if (sym.name == names._this) {
  2313                 // If `C' is the currently compiled class, check that
  2314                 // C.this' does not appear in a call to a super(...)
  2315                 if (env.info.isSelfCall &&
  2316                     site.tsym == env.enclClass.sym) {
  2317                     chk.earlyRefError(tree.pos(), sym);
  2319             } else {
  2320                 // Check if type-qualified fields or methods are static (JLS)
  2321                 if ((sym.flags() & STATIC) == 0 &&
  2322                     sym.name != names._super &&
  2323                     (sym.kind == VAR || sym.kind == MTH)) {
  2324                     rs.access(rs.new StaticError(sym),
  2325                               tree.pos(), site, sym.name, true);
  2328         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2329             // If the qualified item is not a type and the selected item is static, report
  2330             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2331             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2334         // If we are selecting an instance member via a `super', ...
  2335         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2337             // Check that super-qualified symbols are not abstract (JLS)
  2338             rs.checkNonAbstract(tree.pos(), sym);
  2340             if (site.isRaw()) {
  2341                 // Determine argument types for site.
  2342                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2343                 if (site1 != null) site = site1;
  2347         env.info.selectSuper = selectSuperPrev;
  2348         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2349         env.info.tvars = List.nil();
  2351     //where
  2352         /** Determine symbol referenced by a Select expression,
  2354          *  @param tree   The select tree.
  2355          *  @param site   The type of the selected expression,
  2356          *  @param env    The current environment.
  2357          *  @param pt     The current prototype.
  2358          *  @param pkind  The expected kind(s) of the Select expression.
  2359          */
  2360         private Symbol selectSym(JCFieldAccess tree,
  2361                                      Type site,
  2362                                      Env<AttrContext> env,
  2363                                      Type pt,
  2364                                      int pkind) {
  2365             return selectSym(tree, site.tsym, site, env, pt, pkind);
  2367         private Symbol selectSym(JCFieldAccess tree,
  2368                                  Symbol location,
  2369                                  Type site,
  2370                                  Env<AttrContext> env,
  2371                                  Type pt,
  2372                                  int pkind) {
  2373             DiagnosticPosition pos = tree.pos();
  2374             Name name = tree.name;
  2376             switch (site.tag) {
  2377             case PACKAGE:
  2378                 return rs.access(
  2379                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2380                     pos, location, site, name, true);
  2381             case ARRAY:
  2382             case CLASS:
  2383                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2384                     return rs.resolveQualifiedMethod(
  2385                         pos, env, location, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2386                 } else if (name == names._this || name == names._super) {
  2387                     return rs.resolveSelf(pos, env, site.tsym, name);
  2388                 } else if (name == names._class) {
  2389                     // In this case, we have already made sure in
  2390                     // visitSelect that qualifier expression is a type.
  2391                     Type t = syms.classType;
  2392                     List<Type> typeargs = allowGenerics
  2393                         ? List.of(types.erasure(site))
  2394                         : List.<Type>nil();
  2395                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2396                     return new VarSymbol(
  2397                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2398                 } else {
  2399                     // We are seeing a plain identifier as selector.
  2400                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2401                     if ((pkind & ERRONEOUS) == 0)
  2402                         sym = rs.access(sym, pos, location, site, name, true);
  2403                     return sym;
  2405             case WILDCARD:
  2406                 throw new AssertionError(tree);
  2407             case TYPEVAR:
  2408                 // Normally, site.getUpperBound() shouldn't be null.
  2409                 // It should only happen during memberEnter/attribBase
  2410                 // when determining the super type which *must* beac
  2411                 // done before attributing the type variables.  In
  2412                 // other words, we are seeing this illegal program:
  2413                 // class B<T> extends A<T.foo> {}
  2414                 Symbol sym = (site.getUpperBound() != null)
  2415                     ? selectSym(tree, location, capture(site.getUpperBound()), env, pt, pkind)
  2416                     : null;
  2417                 if (sym == null) {
  2418                     log.error(pos, "type.var.cant.be.deref");
  2419                     return syms.errSymbol;
  2420                 } else {
  2421                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2422                         rs.new AccessError(env, site, sym) :
  2423                                 sym;
  2424                     rs.access(sym2, pos, location, site, name, true);
  2425                     return sym;
  2427             case ERROR:
  2428                 // preserve identifier names through errors
  2429                 return types.createErrorType(name, site.tsym, site).tsym;
  2430             default:
  2431                 // The qualifier expression is of a primitive type -- only
  2432                 // .class is allowed for these.
  2433                 if (name == names._class) {
  2434                     // In this case, we have already made sure in Select that
  2435                     // qualifier expression is a type.
  2436                     Type t = syms.classType;
  2437                     Type arg = types.boxedClass(site).type;
  2438                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2439                     return new VarSymbol(
  2440                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2441                 } else {
  2442                     log.error(pos, "cant.deref", site);
  2443                     return syms.errSymbol;
  2448         /** Determine type of identifier or select expression and check that
  2449          *  (1) the referenced symbol is not deprecated
  2450          *  (2) the symbol's type is safe (@see checkSafe)
  2451          *  (3) if symbol is a variable, check that its type and kind are
  2452          *      compatible with the prototype and protokind.
  2453          *  (4) if symbol is an instance field of a raw type,
  2454          *      which is being assigned to, issue an unchecked warning if its
  2455          *      type changes under erasure.
  2456          *  (5) if symbol is an instance method of a raw type, issue an
  2457          *      unchecked warning if its argument types change under erasure.
  2458          *  If checks succeed:
  2459          *    If symbol is a constant, return its constant type
  2460          *    else if symbol is a method, return its result type
  2461          *    otherwise return its type.
  2462          *  Otherwise return errType.
  2464          *  @param tree       The syntax tree representing the identifier
  2465          *  @param site       If this is a select, the type of the selected
  2466          *                    expression, otherwise the type of the current class.
  2467          *  @param sym        The symbol representing the identifier.
  2468          *  @param env        The current environment.
  2469          *  @param pkind      The set of expected kinds.
  2470          *  @param pt         The expected type.
  2471          */
  2472         Type checkId(JCTree tree,
  2473                      Type site,
  2474                      Symbol sym,
  2475                      Env<AttrContext> env,
  2476                      int pkind,
  2477                      Type pt,
  2478                      boolean useVarargs) {
  2479             if (pt.isErroneous()) return types.createErrorType(site);
  2480             Type owntype; // The computed type of this identifier occurrence.
  2481             switch (sym.kind) {
  2482             case TYP:
  2483                 // For types, the computed type equals the symbol's type,
  2484                 // except for two situations:
  2485                 owntype = sym.type;
  2486                 if (owntype.tag == CLASS) {
  2487                     Type ownOuter = owntype.getEnclosingType();
  2489                     // (a) If the symbol's type is parameterized, erase it
  2490                     // because no type parameters were given.
  2491                     // We recover generic outer type later in visitTypeApply.
  2492                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2493                         owntype = types.erasure(owntype);
  2496                     // (b) If the symbol's type is an inner class, then
  2497                     // we have to interpret its outer type as a superclass
  2498                     // of the site type. Example:
  2499                     //
  2500                     // class Tree<A> { class Visitor { ... } }
  2501                     // class PointTree extends Tree<Point> { ... }
  2502                     // ...PointTree.Visitor...
  2503                     //
  2504                     // Then the type of the last expression above is
  2505                     // Tree<Point>.Visitor.
  2506                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2507                         Type normOuter = site;
  2508                         if (normOuter.tag == CLASS)
  2509                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2510                         if (normOuter == null) // perhaps from an import
  2511                             normOuter = types.erasure(ownOuter);
  2512                         if (normOuter != ownOuter)
  2513                             owntype = new ClassType(
  2514                                 normOuter, List.<Type>nil(), owntype.tsym);
  2517                 break;
  2518             case VAR:
  2519                 VarSymbol v = (VarSymbol)sym;
  2520                 // Test (4): if symbol is an instance field of a raw type,
  2521                 // which is being assigned to, issue an unchecked warning if
  2522                 // its type changes under erasure.
  2523                 if (allowGenerics &&
  2524                     pkind == VAR &&
  2525                     v.owner.kind == TYP &&
  2526                     (v.flags() & STATIC) == 0 &&
  2527                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2528                     Type s = types.asOuterSuper(site, v.owner);
  2529                     if (s != null &&
  2530                         s.isRaw() &&
  2531                         !types.isSameType(v.type, v.erasure(types))) {
  2532                         chk.warnUnchecked(tree.pos(),
  2533                                           "unchecked.assign.to.var",
  2534                                           v, s);
  2537                 // The computed type of a variable is the type of the
  2538                 // variable symbol, taken as a member of the site type.
  2539                 owntype = (sym.owner.kind == TYP &&
  2540                            sym.name != names._this && sym.name != names._super)
  2541                     ? types.memberType(site, sym)
  2542                     : sym.type;
  2544                 if (env.info.tvars.nonEmpty()) {
  2545                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2546                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2547                         if (!owntype.contains(l.head)) {
  2548                             log.error(tree.pos(), "undetermined.type", owntype1);
  2549                             owntype1 = types.createErrorType(owntype1);
  2551                     owntype = owntype1;
  2554                 // If the variable is a constant, record constant value in
  2555                 // computed type.
  2556                 if (v.getConstValue() != null && isStaticReference(tree))
  2557                     owntype = owntype.constType(v.getConstValue());
  2559                 if (pkind == VAL) {
  2560                     owntype = capture(owntype); // capture "names as expressions"
  2562                 break;
  2563             case MTH: {
  2564                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2565                 owntype = checkMethod(site, sym, env, app.args,
  2566                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2567                                       env.info.varArgs);
  2568                 break;
  2570             case PCK: case ERR:
  2571                 owntype = sym.type;
  2572                 break;
  2573             default:
  2574                 throw new AssertionError("unexpected kind: " + sym.kind +
  2575                                          " in tree " + tree);
  2578             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2579             // (for constructors, the error was given when the constructor was
  2580             // resolved)
  2581             if (sym.name != names.init &&
  2582                 (sym.flags() & DEPRECATED) != 0 &&
  2583                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2584                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2585                 chk.warnDeprecated(tree.pos(), sym);
  2587             if ((sym.flags() & PROPRIETARY) != 0) {
  2588                 if (enableSunApiLintControl)
  2589                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
  2590                 else
  2591                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2594             // Test (3): if symbol is a variable, check that its type and
  2595             // kind are compatible with the prototype and protokind.
  2596             return check(tree, owntype, sym.kind, pkind, pt);
  2599         /** Check that variable is initialized and evaluate the variable's
  2600          *  initializer, if not yet done. Also check that variable is not
  2601          *  referenced before it is defined.
  2602          *  @param tree    The tree making up the variable reference.
  2603          *  @param env     The current environment.
  2604          *  @param v       The variable's symbol.
  2605          */
  2606         private void checkInit(JCTree tree,
  2607                                Env<AttrContext> env,
  2608                                VarSymbol v,
  2609                                boolean onlyWarning) {
  2610 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2611 //                             tree.pos + " " + v.pos + " " +
  2612 //                             Resolve.isStatic(env));//DEBUG
  2614             // A forward reference is diagnosed if the declaration position
  2615             // of the variable is greater than the current tree position
  2616             // and the tree and variable definition occur in the same class
  2617             // definition.  Note that writes don't count as references.
  2618             // This check applies only to class and instance
  2619             // variables.  Local variables follow different scope rules,
  2620             // and are subject to definite assignment checking.
  2621             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2622                 v.owner.kind == TYP &&
  2623                 canOwnInitializer(env.info.scope.owner) &&
  2624                 v.owner == env.info.scope.owner.enclClass() &&
  2625                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2626                 (env.tree.getTag() != JCTree.ASSIGN ||
  2627                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2628                 String suffix = (env.info.enclVar == v) ?
  2629                                 "self.ref" : "forward.ref";
  2630                 if (!onlyWarning || isStaticEnumField(v)) {
  2631                     log.error(tree.pos(), "illegal." + suffix);
  2632                 } else if (useBeforeDeclarationWarning) {
  2633                     log.warning(tree.pos(), suffix, v);
  2637             v.getConstValue(); // ensure initializer is evaluated
  2639             checkEnumInitializer(tree, env, v);
  2642         /**
  2643          * Check for illegal references to static members of enum.  In
  2644          * an enum type, constructors and initializers may not
  2645          * reference its static members unless they are constant.
  2647          * @param tree    The tree making up the variable reference.
  2648          * @param env     The current environment.
  2649          * @param v       The variable's symbol.
  2650          * @see JLS 3rd Ed. (8.9 Enums)
  2651          */
  2652         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2653             // JLS 3rd Ed.:
  2654             //
  2655             // "It is a compile-time error to reference a static field
  2656             // of an enum type that is not a compile-time constant
  2657             // (15.28) from constructors, instance initializer blocks,
  2658             // or instance variable initializer expressions of that
  2659             // type. It is a compile-time error for the constructors,
  2660             // instance initializer blocks, or instance variable
  2661             // initializer expressions of an enum constant e to refer
  2662             // to itself or to an enum constant of the same type that
  2663             // is declared to the right of e."
  2664             if (isStaticEnumField(v)) {
  2665                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2667                 if (enclClass == null || enclClass.owner == null)
  2668                     return;
  2670                 // See if the enclosing class is the enum (or a
  2671                 // subclass thereof) declaring v.  If not, this
  2672                 // reference is OK.
  2673                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2674                     return;
  2676                 // If the reference isn't from an initializer, then
  2677                 // the reference is OK.
  2678                 if (!Resolve.isInitializer(env))
  2679                     return;
  2681                 log.error(tree.pos(), "illegal.enum.static.ref");
  2685         /** Is the given symbol a static, non-constant field of an Enum?
  2686          *  Note: enum literals should not be regarded as such
  2687          */
  2688         private boolean isStaticEnumField(VarSymbol v) {
  2689             return Flags.isEnum(v.owner) &&
  2690                    Flags.isStatic(v) &&
  2691                    !Flags.isConstant(v) &&
  2692                    v.name != names._class;
  2695         /** Can the given symbol be the owner of code which forms part
  2696          *  if class initialization? This is the case if the symbol is
  2697          *  a type or field, or if the symbol is the synthetic method.
  2698          *  owning a block.
  2699          */
  2700         private boolean canOwnInitializer(Symbol sym) {
  2701             return
  2702                 (sym.kind & (VAR | TYP)) != 0 ||
  2703                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2706     Warner noteWarner = new Warner();
  2708     /**
  2709      * Check that method arguments conform to its instantation.
  2710      **/
  2711     public Type checkMethod(Type site,
  2712                             Symbol sym,
  2713                             Env<AttrContext> env,
  2714                             final List<JCExpression> argtrees,
  2715                             List<Type> argtypes,
  2716                             List<Type> typeargtypes,
  2717                             boolean useVarargs) {
  2718         // Test (5): if symbol is an instance method of a raw type, issue
  2719         // an unchecked warning if its argument types change under erasure.
  2720         if (allowGenerics &&
  2721             (sym.flags() & STATIC) == 0 &&
  2722             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2723             Type s = types.asOuterSuper(site, sym.owner);
  2724             if (s != null && s.isRaw() &&
  2725                 !types.isSameTypes(sym.type.getParameterTypes(),
  2726                                    sym.erasure(types).getParameterTypes())) {
  2727                 chk.warnUnchecked(env.tree.pos(),
  2728                                   "unchecked.call.mbr.of.raw.type",
  2729                                   sym, s);
  2733         // Compute the identifier's instantiated type.
  2734         // For methods, we need to compute the instance type by
  2735         // Resolve.instantiate from the symbol's type as well as
  2736         // any type arguments and value arguments.
  2737         noteWarner.clear();
  2738         Type owntype = rs.instantiate(env,
  2739                                       site,
  2740                                       sym,
  2741                                       argtypes,
  2742                                       typeargtypes,
  2743                                       true,
  2744                                       useVarargs,
  2745                                       noteWarner);
  2746         boolean warned = noteWarner.hasNonSilentLint(LintCategory.UNCHECKED);
  2748         // If this fails, something went wrong; we should not have
  2749         // found the identifier in the first place.
  2750         if (owntype == null) {
  2751             if (!pt.isErroneous())
  2752                 log.error(env.tree.pos(),
  2753                           "internal.error.cant.instantiate",
  2754                           sym, site,
  2755                           Type.toString(pt.getParameterTypes()));
  2756             owntype = types.createErrorType(site);
  2757         } else {
  2758             // System.out.println("call   : " + env.tree);
  2759             // System.out.println("method : " + owntype);
  2760             // System.out.println("actuals: " + argtypes);
  2761             List<Type> formals = owntype.getParameterTypes();
  2762             Type last = useVarargs ? formals.last() : null;
  2763             if (sym.name==names.init &&
  2764                 sym.owner == syms.enumSym)
  2765                 formals = formals.tail.tail;
  2766             List<JCExpression> args = argtrees;
  2767             while (formals.head != last) {
  2768                 JCTree arg = args.head;
  2769                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2770                 assertConvertible(arg, arg.type, formals.head, warn);
  2771                 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2772                 args = args.tail;
  2773                 formals = formals.tail;
  2775             if (useVarargs) {
  2776                 Type varArg = types.elemtype(last);
  2777                 while (args.tail != null) {
  2778                     JCTree arg = args.head;
  2779                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2780                     assertConvertible(arg, arg.type, varArg, warn);
  2781                     warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2782                     args = args.tail;
  2784             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2785                 // non-varargs call to varargs method
  2786                 Type varParam = owntype.getParameterTypes().last();
  2787                 Type lastArg = argtypes.last();
  2788                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2789                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2790                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2791                                 types.elemtype(varParam),
  2792                                 varParam);
  2795             if (warned && sym.type.tag == FORALL) {
  2796                 chk.warnUnchecked(env.tree.pos(),
  2797                                   "unchecked.meth.invocation.applied",
  2798                                   kindName(sym),
  2799                                   sym.name,
  2800                                   rs.methodArguments(sym.type.getParameterTypes()),
  2801                                   rs.methodArguments(argtypes),
  2802                                   kindName(sym.location()),
  2803                                   sym.location());
  2804                 owntype = new MethodType(owntype.getParameterTypes(),
  2805                                          types.erasure(owntype.getReturnType()),
  2806                                          owntype.getThrownTypes(),
  2807                                          syms.methodClass);
  2809             if (useVarargs) {
  2810                 JCTree tree = env.tree;
  2811                 Type argtype = owntype.getParameterTypes().last();
  2812                 if (owntype.getReturnType().tag != FORALL || warned) {
  2813                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym);
  2815                 Type elemtype = types.elemtype(argtype);
  2816                 switch (tree.getTag()) {
  2817                 case JCTree.APPLY:
  2818                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2819                     break;
  2820                 case JCTree.NEWCLASS:
  2821                     ((JCNewClass) tree).varargsElement = elemtype;
  2822                     break;
  2823                 default:
  2824                     throw new AssertionError(""+tree);
  2828         return owntype;
  2831     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2832         if (types.isConvertible(actual, formal, warn))
  2833             return;
  2835         if (formal.isCompound()
  2836             && types.isSubtype(actual, types.supertype(formal))
  2837             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2838             return;
  2840         if (false) {
  2841             // TODO: make assertConvertible work
  2842             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2843             throw new AssertionError("Tree: " + tree
  2844                                      + " actual:" + actual
  2845                                      + " formal: " + formal);
  2849     public void visitLiteral(JCLiteral tree) {
  2850         result = check(
  2851             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2853     //where
  2854     /** Return the type of a literal with given type tag.
  2855      */
  2856     Type litType(int tag) {
  2857         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2860     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2861         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2864     public void visitTypeArray(JCArrayTypeTree tree) {
  2865         Type etype = attribType(tree.elemtype, env);
  2866         Type type = new ArrayType(etype, syms.arrayClass);
  2867         result = check(tree, type, TYP, pkind, pt);
  2870     /** Visitor method for parameterized types.
  2871      *  Bound checking is left until later, since types are attributed
  2872      *  before supertype structure is completely known
  2873      */
  2874     public void visitTypeApply(JCTypeApply tree) {
  2875         Type owntype = types.createErrorType(tree.type);
  2877         // Attribute functor part of application and make sure it's a class.
  2878         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2880         // Attribute type parameters
  2881         List<Type> actuals = attribTypes(tree.arguments, env);
  2883         if (clazztype.tag == CLASS) {
  2884             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2886             if (actuals.length() == formals.length() || actuals.length() == 0) {
  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 visitTypeDisjunction(JCTypeDisjunction tree) {
  2927         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2928         for (JCExpression typeTree : tree.alternatives) {
  2929             Type ctype = attribType(typeTree, env);
  2930             ctype = chk.checkType(typeTree.pos(),
  2931                           chk.checkClassType(typeTree.pos(), ctype),
  2932                           syms.throwableType);
  2933             multicatchTypes.append(ctype);
  2935         tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2938     public void visitTypeParameter(JCTypeParameter tree) {
  2939         TypeVar a = (TypeVar)tree.type;
  2940         Set<Type> boundSet = new HashSet<Type>();
  2941         if (a.bound.isErroneous())
  2942             return;
  2943         List<Type> bs = types.getBounds(a);
  2944         if (tree.bounds.nonEmpty()) {
  2945             // accept class or interface or typevar as first bound.
  2946             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2947             boundSet.add(types.erasure(b));
  2948             if (b.isErroneous()) {
  2949                 a.bound = b;
  2951             else if (b.tag == TYPEVAR) {
  2952                 // if first bound was a typevar, do not accept further bounds.
  2953                 if (tree.bounds.tail.nonEmpty()) {
  2954                     log.error(tree.bounds.tail.head.pos(),
  2955                               "type.var.may.not.be.followed.by.other.bounds");
  2956                     tree.bounds = List.of(tree.bounds.head);
  2957                     a.bound = bs.head;
  2959             } else {
  2960                 // if first bound was a class or interface, accept only interfaces
  2961                 // as further bounds.
  2962                 for (JCExpression bound : tree.bounds.tail) {
  2963                     bs = bs.tail;
  2964                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2965                     if (i.isErroneous())
  2966                         a.bound = i;
  2967                     else if (i.tag == CLASS)
  2968                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2972         bs = types.getBounds(a);
  2974         // in case of multiple bounds ...
  2975         if (bs.length() > 1) {
  2976             // ... the variable's bound is a class type flagged COMPOUND
  2977             // (see comment for TypeVar.bound).
  2978             // In this case, generate a class tree that represents the
  2979             // bound class, ...
  2980             JCTree extending;
  2981             List<JCExpression> implementing;
  2982             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2983                 extending = tree.bounds.head;
  2984                 implementing = tree.bounds.tail;
  2985             } else {
  2986                 extending = null;
  2987                 implementing = tree.bounds;
  2989             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2990                 make.Modifiers(PUBLIC | ABSTRACT),
  2991                 tree.name, List.<JCTypeParameter>nil(),
  2992                 extending, implementing, List.<JCTree>nil());
  2994             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2995             Assert.check((c.flags() & COMPOUND) != 0);
  2996             cd.sym = c;
  2997             c.sourcefile = env.toplevel.sourcefile;
  2999             // ... and attribute the bound class
  3000             c.flags_field |= UNATTRIBUTED;
  3001             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3002             enter.typeEnvs.put(c, cenv);
  3007     public void visitWildcard(JCWildcard tree) {
  3008         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3009         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3010             ? syms.objectType
  3011             : attribType(tree.inner, env);
  3012         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3013                                               tree.kind.kind,
  3014                                               syms.boundClass),
  3015                        TYP, pkind, pt);
  3018     public void visitAnnotation(JCAnnotation tree) {
  3019         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  3020         result = tree.type = syms.errType;
  3023     public void visitErroneous(JCErroneous tree) {
  3024         if (tree.errs != null)
  3025             for (JCTree err : tree.errs)
  3026                 attribTree(err, env, ERR, pt);
  3027         result = tree.type = syms.errType;
  3030     /** Default visitor method for all other trees.
  3031      */
  3032     public void visitTree(JCTree tree) {
  3033         throw new AssertionError();
  3036     /** Main method: attribute class definition associated with given class symbol.
  3037      *  reporting completion failures at the given position.
  3038      *  @param pos The source position at which completion errors are to be
  3039      *             reported.
  3040      *  @param c   The class symbol whose definition will be attributed.
  3041      */
  3042     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3043         try {
  3044             annotate.flush();
  3045             attribClass(c);
  3046         } catch (CompletionFailure ex) {
  3047             chk.completionError(pos, ex);
  3051     /** Attribute class definition associated with given class symbol.
  3052      *  @param c   The class symbol whose definition will be attributed.
  3053      */
  3054     void attribClass(ClassSymbol c) throws CompletionFailure {
  3055         if (c.type.tag == ERROR) return;
  3057         // Check for cycles in the inheritance graph, which can arise from
  3058         // ill-formed class files.
  3059         chk.checkNonCyclic(null, c.type);
  3061         Type st = types.supertype(c.type);
  3062         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3063             // First, attribute superclass.
  3064             if (st.tag == CLASS)
  3065                 attribClass((ClassSymbol)st.tsym);
  3067             // Next attribute owner, if it is a class.
  3068             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3069                 attribClass((ClassSymbol)c.owner);
  3072         // The previous operations might have attributed the current class
  3073         // if there was a cycle. So we test first whether the class is still
  3074         // UNATTRIBUTED.
  3075         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3076             c.flags_field &= ~UNATTRIBUTED;
  3078             // Get environment current at the point of class definition.
  3079             Env<AttrContext> env = enter.typeEnvs.get(c);
  3081             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3082             // because the annotations were not available at the time the env was created. Therefore,
  3083             // we look up the environment chain for the first enclosing environment for which the
  3084             // lint value is set. Typically, this is the parent env, but might be further if there
  3085             // are any envs created as a result of TypeParameter nodes.
  3086             Env<AttrContext> lintEnv = env;
  3087             while (lintEnv.info.lint == null)
  3088                 lintEnv = lintEnv.next;
  3090             // Having found the enclosing lint value, we can initialize the lint value for this class
  3091             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3093             Lint prevLint = chk.setLint(env.info.lint);
  3094             JavaFileObject prev = log.useSource(c.sourcefile);
  3096             try {
  3097                 // java.lang.Enum may not be subclassed by a non-enum
  3098                 if (st.tsym == syms.enumSym &&
  3099                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3100                     log.error(env.tree.pos(), "enum.no.subclassing");
  3102                 // Enums may not be extended by source-level classes
  3103                 if (st.tsym != null &&
  3104                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3105                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3106                     !target.compilerBootstrap(c)) {
  3107                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3109                 attribClassBody(env, c);
  3111                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3112             } finally {
  3113                 log.useSource(prev);
  3114                 chk.setLint(prevLint);
  3120     public void visitImport(JCImport tree) {
  3121         // nothing to do
  3124     /** Finish the attribution of a class. */
  3125     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3126         JCClassDecl tree = (JCClassDecl)env.tree;
  3127         Assert.check(c == tree.sym);
  3129         // Validate annotations
  3130         chk.validateAnnotations(tree.mods.annotations, c);
  3132         // Validate type parameters, supertype and interfaces.
  3133         attribBounds(tree.typarams);
  3134         if (!c.isAnonymous()) {
  3135             //already checked if anonymous
  3136             chk.validate(tree.typarams, env);
  3137             chk.validate(tree.extending, env);
  3138             chk.validate(tree.implementing, env);
  3141         // If this is a non-abstract class, check that it has no abstract
  3142         // methods or unimplemented methods of an implemented interface.
  3143         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3144             if (!relax)
  3145                 chk.checkAllDefined(tree.pos(), c);
  3148         if ((c.flags() & ANNOTATION) != 0) {
  3149             if (tree.implementing.nonEmpty())
  3150                 log.error(tree.implementing.head.pos(),
  3151                           "cant.extend.intf.annotation");
  3152             if (tree.typarams.nonEmpty())
  3153                 log.error(tree.typarams.head.pos(),
  3154                           "intf.annotation.cant.have.type.params");
  3155         } else {
  3156             // Check that all extended classes and interfaces
  3157             // are compatible (i.e. no two define methods with same arguments
  3158             // yet different return types).  (JLS 8.4.6.3)
  3159             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3162         // Check that class does not import the same parameterized interface
  3163         // with two different argument lists.
  3164         chk.checkClassBounds(tree.pos(), c.type);
  3166         tree.type = c.type;
  3168         for (List<JCTypeParameter> l = tree.typarams;
  3169              l.nonEmpty(); l = l.tail) {
  3170              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3173         // Check that a generic class doesn't extend Throwable
  3174         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3175             log.error(tree.extending.pos(), "generic.throwable");
  3177         // Check that all methods which implement some
  3178         // method conform to the method they implement.
  3179         chk.checkImplementations(tree);
  3181         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3182             // Attribute declaration
  3183             attribStat(l.head, env);
  3184             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3185             // Make an exception for static constants.
  3186             if (c.owner.kind != PCK &&
  3187                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3188                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3189                 Symbol sym = null;
  3190                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3191                 if (sym == null ||
  3192                     sym.kind != VAR ||
  3193                     ((VarSymbol) sym).getConstValue() == null)
  3194                     log.error(l.head.pos(), "icls.cant.have.static.decl", sym.location());
  3198         // Check for cycles among non-initial constructors.
  3199         chk.checkCyclicConstructors(tree);
  3201         // Check for cycles among annotation elements.
  3202         chk.checkNonCyclicElements(tree);
  3204         // Check for proper use of serialVersionUID
  3205         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3206             isSerializable(c) &&
  3207             (c.flags() & Flags.ENUM) == 0 &&
  3208             (c.flags() & ABSTRACT) == 0) {
  3209             checkSerialVersionUID(tree, c);
  3212         // where
  3213         /** check if a class is a subtype of Serializable, if that is available. */
  3214         private boolean isSerializable(ClassSymbol c) {
  3215             try {
  3216                 syms.serializableType.complete();
  3218             catch (CompletionFailure e) {
  3219                 return false;
  3221             return types.isSubtype(c.type, syms.serializableType);
  3224         /** Check that an appropriate serialVersionUID member is defined. */
  3225         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3227             // check for presence of serialVersionUID
  3228             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3229             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3230             if (e.scope == null) {
  3231                 log.warning(LintCategory.SERIAL,
  3232                         tree.pos(), "missing.SVUID", c);
  3233                 return;
  3236             // check that it is static final
  3237             VarSymbol svuid = (VarSymbol)e.sym;
  3238             if ((svuid.flags() & (STATIC | FINAL)) !=
  3239                 (STATIC | FINAL))
  3240                 log.warning(LintCategory.SERIAL,
  3241                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3243             // check that it is long
  3244             else if (svuid.type.tag != TypeTags.LONG)
  3245                 log.warning(LintCategory.SERIAL,
  3246                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3248             // check constant
  3249             else if (svuid.getConstValue() == null)
  3250                 log.warning(LintCategory.SERIAL,
  3251                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3254     private Type capture(Type type) {
  3255         return types.capture(type);
  3258     // <editor-fold desc="post-attribution visitor">
  3260     /**
  3261      * Handle missing types/symbols in an AST. This routine is useful when
  3262      * the compiler has encountered some errors (which might have ended up
  3263      * terminating attribution abruptly); if the compiler is used in fail-over
  3264      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3265      * prevents NPE to be progagated during subsequent compilation steps.
  3266      */
  3267     public void postAttr(Env<AttrContext> env) {
  3268         new PostAttrAnalyzer().scan(env.tree);
  3271     class PostAttrAnalyzer extends TreeScanner {
  3273         private void initTypeIfNeeded(JCTree that) {
  3274             if (that.type == null) {
  3275                 that.type = syms.unknownType;
  3279         @Override
  3280         public void scan(JCTree tree) {
  3281             if (tree == null) return;
  3282             if (tree instanceof JCExpression) {
  3283                 initTypeIfNeeded(tree);
  3285             super.scan(tree);
  3288         @Override
  3289         public void visitIdent(JCIdent that) {
  3290             if (that.sym == null) {
  3291                 that.sym = syms.unknownSymbol;
  3295         @Override
  3296         public void visitSelect(JCFieldAccess that) {
  3297             if (that.sym == null) {
  3298                 that.sym = syms.unknownSymbol;
  3300             super.visitSelect(that);
  3303         @Override
  3304         public void visitClassDef(JCClassDecl that) {
  3305             initTypeIfNeeded(that);
  3306             if (that.sym == null) {
  3307                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3309             super.visitClassDef(that);
  3312         @Override
  3313         public void visitMethodDef(JCMethodDecl that) {
  3314             initTypeIfNeeded(that);
  3315             if (that.sym == null) {
  3316                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3318             super.visitMethodDef(that);
  3321         @Override
  3322         public void visitVarDef(JCVariableDecl that) {
  3323             initTypeIfNeeded(that);
  3324             if (that.sym == null) {
  3325                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3326                 that.sym.adr = 0;
  3328             super.visitVarDef(that);
  3331         @Override
  3332         public void visitNewClass(JCNewClass that) {
  3333             if (that.constructor == null) {
  3334                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3336             if (that.constructorType == null) {
  3337                 that.constructorType = syms.unknownType;
  3339             super.visitNewClass(that);
  3342         @Override
  3343         public void visitBinary(JCBinary that) {
  3344             if (that.operator == null)
  3345                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3346             super.visitBinary(that);
  3349         @Override
  3350         public void visitUnary(JCUnary that) {
  3351             if (that.operator == null)
  3352                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3353             super.visitUnary(that);
  3356     // </editor-fold>

mercurial