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

Mon, 28 Nov 2011 15:56:42 +0000

author
mcimadamore
date
Mon, 28 Nov 2011 15:56:42 +0000
changeset 1144
9448fe783fd2
parent 1127
ca49d50318dc
child 1145
3343b22e2761
permissions
-rw-r--r--

7115050: Add parser support for lambda expressions
Summary: Add support for parsing lambda expressions to JavacParser
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.jvm.Target;
    41 import com.sun.tools.javac.code.Lint.LintCategory;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.tree.JCTree.*;
    44 import com.sun.tools.javac.code.Type.*;
    46 import com.sun.source.tree.IdentifierTree;
    47 import com.sun.source.tree.MemberSelectTree;
    48 import com.sun.source.tree.TreeVisitor;
    49 import com.sun.source.util.SimpleTreeVisitor;
    51 import static com.sun.tools.javac.code.Flags.*;
    52 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    53 import static com.sun.tools.javac.code.Flags.BLOCK;
    54 import static com.sun.tools.javac.code.Kinds.*;
    55 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    56 import static com.sun.tools.javac.code.TypeTags.*;
    57 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
    58 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    60 /** This is the main context-dependent analysis phase in GJC. It
    61  *  encompasses name resolution, type checking and constant folding as
    62  *  subtasks. Some subtasks involve auxiliary classes.
    63  *  @see Check
    64  *  @see Resolve
    65  *  @see ConstFold
    66  *  @see Infer
    67  *
    68  *  <p><b>This is NOT part of any supported API.
    69  *  If you write code that depends on this, you do so at your own risk.
    70  *  This code and its internal interfaces are subject to change or
    71  *  deletion without notice.</b>
    72  */
    73 public class Attr extends JCTree.Visitor {
    74     protected static final Context.Key<Attr> attrKey =
    75         new Context.Key<Attr>();
    77     final Names names;
    78     final Log log;
    79     final Symtab syms;
    80     final Resolve rs;
    81     final Infer infer;
    82     final Check chk;
    83     final MemberEnter memberEnter;
    84     final TreeMaker make;
    85     final ConstFold cfolder;
    86     final Enter enter;
    87     final Target target;
    88     final Types types;
    89     final JCDiagnostic.Factory diags;
    90     final Annotate annotate;
    91     final DeferredLintHandler deferredLintHandler;
    93     public static Attr instance(Context context) {
    94         Attr instance = context.get(attrKey);
    95         if (instance == null)
    96             instance = new Attr(context);
    97         return instance;
    98     }
   100     protected Attr(Context context) {
   101         context.put(attrKey, this);
   103         names = Names.instance(context);
   104         log = Log.instance(context);
   105         syms = Symtab.instance(context);
   106         rs = Resolve.instance(context);
   107         chk = Check.instance(context);
   108         memberEnter = MemberEnter.instance(context);
   109         make = TreeMaker.instance(context);
   110         enter = Enter.instance(context);
   111         infer = Infer.instance(context);
   112         cfolder = ConstFold.instance(context);
   113         target = Target.instance(context);
   114         types = Types.instance(context);
   115         diags = JCDiagnostic.Factory.instance(context);
   116         annotate = Annotate.instance(context);
   117         deferredLintHandler = DeferredLintHandler.instance(context);
   119         Options options = Options.instance(context);
   121         Source source = Source.instance(context);
   122         allowGenerics = source.allowGenerics();
   123         allowVarargs = source.allowVarargs();
   124         allowEnums = source.allowEnums();
   125         allowBoxing = source.allowBoxing();
   126         allowCovariantReturns = source.allowCovariantReturns();
   127         allowAnonOuterThis = source.allowAnonOuterThis();
   128         allowStringsInSwitch = source.allowStringsInSwitch();
   129         sourceName = source.name;
   130         relax = (options.isSet("-retrofit") ||
   131                  options.isSet("-relax"));
   132         findDiamonds = options.get("findDiamond") != null &&
   133                  source.allowDiamond();
   134         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   135     }
   137     /** Switch: relax some constraints for retrofit mode.
   138      */
   139     boolean relax;
   141     /** Switch: support generics?
   142      */
   143     boolean allowGenerics;
   145     /** Switch: allow variable-arity methods.
   146      */
   147     boolean allowVarargs;
   149     /** Switch: support enums?
   150      */
   151     boolean allowEnums;
   153     /** Switch: support boxing and unboxing?
   154      */
   155     boolean allowBoxing;
   157     /** Switch: support covariant result types?
   158      */
   159     boolean allowCovariantReturns;
   161     /** Switch: allow references to surrounding object from anonymous
   162      * objects during constructor call?
   163      */
   164     boolean allowAnonOuterThis;
   166     /** Switch: generates a warning if diamond can be safely applied
   167      *  to a given new expression
   168      */
   169     boolean findDiamonds;
   171     /**
   172      * Internally enables/disables diamond finder feature
   173      */
   174     static final boolean allowDiamondFinder = true;
   176     /**
   177      * Switch: warn about use of variable before declaration?
   178      * RFE: 6425594
   179      */
   180     boolean useBeforeDeclarationWarning;
   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.hasTag(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.hasTag(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         // ... but ...
   603         // There's a problem with evaluating annotations in the right order, such that
   604         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   605         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   606         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   607         if (env.info.enclVar.attributes_field == null)
   608             env.info.lint = lintEnv.info.lint;
   609         else
   610             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.attributes_field, env.info.enclVar.flags());
   612         Lint prevLint = chk.setLint(env.info.lint);
   613         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   615         try {
   616             Type itype = attribExpr(initializer, env, type);
   617             if (itype.constValue() != null)
   618                 return coerce(itype, type).constValue();
   619             else
   620                 return null;
   621         } finally {
   622             env.info.lint = prevLint;
   623             log.useSource(prevSource);
   624         }
   625     }
   627     /** Attribute type reference in an `extends' or `implements' clause.
   628      *  Supertypes of anonymous inner classes are usually already attributed.
   629      *
   630      *  @param tree              The tree making up the type reference.
   631      *  @param env               The environment current at the reference.
   632      *  @param classExpected     true if only a class is expected here.
   633      *  @param interfaceExpected true if only an interface is expected here.
   634      */
   635     Type attribBase(JCTree tree,
   636                     Env<AttrContext> env,
   637                     boolean classExpected,
   638                     boolean interfaceExpected,
   639                     boolean checkExtensible) {
   640         Type t = tree.type != null ?
   641             tree.type :
   642             attribType(tree, env);
   643         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   644     }
   645     Type checkBase(Type t,
   646                    JCTree tree,
   647                    Env<AttrContext> env,
   648                    boolean classExpected,
   649                    boolean interfaceExpected,
   650                    boolean checkExtensible) {
   651         if (t.isErroneous())
   652             return t;
   653         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   654             // check that type variable is already visible
   655             if (t.getUpperBound() == null) {
   656                 log.error(tree.pos(), "illegal.forward.ref");
   657                 return types.createErrorType(t);
   658             }
   659         } else {
   660             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   661         }
   662         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   663             log.error(tree.pos(), "intf.expected.here");
   664             // return errType is necessary since otherwise there might
   665             // be undetected cycles which cause attribution to loop
   666             return types.createErrorType(t);
   667         } else if (checkExtensible &&
   668                    classExpected &&
   669                    (t.tsym.flags() & INTERFACE) != 0) {
   670                 log.error(tree.pos(), "no.intf.expected.here");
   671             return types.createErrorType(t);
   672         }
   673         if (checkExtensible &&
   674             ((t.tsym.flags() & FINAL) != 0)) {
   675             log.error(tree.pos(),
   676                       "cant.inherit.from.final", t.tsym);
   677         }
   678         chk.checkNonCyclic(tree.pos(), t);
   679         return t;
   680     }
   682     public void visitClassDef(JCClassDecl tree) {
   683         // Local classes have not been entered yet, so we need to do it now:
   684         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   685             enter.classEnter(tree, env);
   687         ClassSymbol c = tree.sym;
   688         if (c == null) {
   689             // exit in case something drastic went wrong during enter.
   690             result = null;
   691         } else {
   692             // make sure class has been completed:
   693             c.complete();
   695             // If this class appears as an anonymous class
   696             // in a superclass constructor call where
   697             // no explicit outer instance is given,
   698             // disable implicit outer instance from being passed.
   699             // (This would be an illegal access to "this before super").
   700             if (env.info.isSelfCall &&
   701                 env.tree.hasTag(NEWCLASS) &&
   702                 ((JCNewClass) env.tree).encl == null)
   703             {
   704                 c.flags_field |= NOOUTERTHIS;
   705             }
   706             attribClass(tree.pos(), c);
   707             result = tree.type = c.type;
   708         }
   709     }
   711     public void visitMethodDef(JCMethodDecl tree) {
   712         MethodSymbol m = tree.sym;
   714         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   715         Lint prevLint = chk.setLint(lint);
   716         MethodSymbol prevMethod = chk.setMethod(m);
   717         try {
   718             deferredLintHandler.flush(tree.pos());
   719             chk.checkDeprecatedAnnotation(tree.pos(), m);
   721             attribBounds(tree.typarams);
   723             // If we override any other methods, check that we do so properly.
   724             // JLS ???
   725             if (m.isStatic()) {
   726                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   727             } else {
   728                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   729             }
   730             chk.checkOverride(tree, m);
   732             // Create a new environment with local scope
   733             // for attributing the method.
   734             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   736             localEnv.info.lint = lint;
   738             // Enter all type parameters into the local method scope.
   739             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   740                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   742             ClassSymbol owner = env.enclClass.sym;
   743             if ((owner.flags() & ANNOTATION) != 0 &&
   744                 tree.params.nonEmpty())
   745                 log.error(tree.params.head.pos(),
   746                           "intf.annotation.members.cant.have.params");
   748             // Attribute all value parameters.
   749             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   750                 attribStat(l.head, localEnv);
   751             }
   753             chk.checkVarargsMethodDecl(localEnv, tree);
   755             // Check that type parameters are well-formed.
   756             chk.validate(tree.typarams, localEnv);
   758             // Check that result type is well-formed.
   759             chk.validate(tree.restype, localEnv);
   761             // annotation method checks
   762             if ((owner.flags() & ANNOTATION) != 0) {
   763                 // annotation method cannot have throws clause
   764                 if (tree.thrown.nonEmpty()) {
   765                     log.error(tree.thrown.head.pos(),
   766                             "throws.not.allowed.in.intf.annotation");
   767                 }
   768                 // annotation method cannot declare type-parameters
   769                 if (tree.typarams.nonEmpty()) {
   770                     log.error(tree.typarams.head.pos(),
   771                             "intf.annotation.members.cant.have.type.params");
   772                 }
   773                 // validate annotation method's return type (could be an annotation type)
   774                 chk.validateAnnotationType(tree.restype);
   775                 // ensure that annotation method does not clash with members of Object/Annotation
   776                 chk.validateAnnotationMethod(tree.pos(), m);
   778                 if (tree.defaultValue != null) {
   779                     // if default value is an annotation, check it is a well-formed
   780                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   781                     chk.validateAnnotationTree(tree.defaultValue);
   782                 }
   783             }
   785             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   786                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   788             if (tree.body == null) {
   789                 // Empty bodies are only allowed for
   790                 // abstract, native, or interface methods, or for methods
   791                 // in a retrofit signature class.
   792                 if ((owner.flags() & INTERFACE) == 0 &&
   793                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   794                     !relax)
   795                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   796                 if (tree.defaultValue != null) {
   797                     if ((owner.flags() & ANNOTATION) == 0)
   798                         log.error(tree.pos(),
   799                                   "default.allowed.in.intf.annotation.member");
   800                 }
   801             } else if ((owner.flags() & INTERFACE) != 0) {
   802                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   803             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   804                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   805             } else if ((tree.mods.flags & NATIVE) != 0) {
   806                 log.error(tree.pos(), "native.meth.cant.have.body");
   807             } else {
   808                 // Add an implicit super() call unless an explicit call to
   809                 // super(...) or this(...) is given
   810                 // or we are compiling class java.lang.Object.
   811                 if (tree.name == names.init && owner.type != syms.objectType) {
   812                     JCBlock body = tree.body;
   813                     if (body.stats.isEmpty() ||
   814                         !TreeInfo.isSelfCall(body.stats.head)) {
   815                         body.stats = body.stats.
   816                             prepend(memberEnter.SuperCall(make.at(body.pos),
   817                                                           List.<Type>nil(),
   818                                                           List.<JCVariableDecl>nil(),
   819                                                           false));
   820                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   821                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   822                                TreeInfo.isSuperCall(body.stats.head)) {
   823                         // enum constructors are not allowed to call super
   824                         // directly, so make sure there aren't any super calls
   825                         // in enum constructors, except in the compiler
   826                         // generated one.
   827                         log.error(tree.body.stats.head.pos(),
   828                                   "call.to.super.not.allowed.in.enum.ctor",
   829                                   env.enclClass.sym);
   830                     }
   831                 }
   833                 // Attribute method body.
   834                 attribStat(tree.body, localEnv);
   835             }
   836             localEnv.info.scope.leave();
   837             result = tree.type = m.type;
   838             chk.validateAnnotations(tree.mods.annotations, m);
   839         }
   840         finally {
   841             chk.setLint(prevLint);
   842             chk.setMethod(prevMethod);
   843         }
   844     }
   846     public void visitVarDef(JCVariableDecl tree) {
   847         // Local variables have not been entered yet, so we need to do it now:
   848         if (env.info.scope.owner.kind == MTH) {
   849             if (tree.sym != null) {
   850                 // parameters have already been entered
   851                 env.info.scope.enter(tree.sym);
   852             } else {
   853                 memberEnter.memberEnter(tree, env);
   854                 annotate.flush();
   855             }
   856             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   857         }
   859         VarSymbol v = tree.sym;
   860         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   861         Lint prevLint = chk.setLint(lint);
   863         // Check that the variable's declared type is well-formed.
   864         chk.validate(tree.vartype, env);
   865         deferredLintHandler.flush(tree.pos());
   867         try {
   868             chk.checkDeprecatedAnnotation(tree.pos(), v);
   870             if (tree.init != null) {
   871                 if ((v.flags_field & FINAL) != 0 && !tree.init.hasTag(NEWCLASS)) {
   872                     // In this case, `v' is final.  Ensure that it's initializer is
   873                     // evaluated.
   874                     v.getConstValue(); // ensure initializer is evaluated
   875                 } else {
   876                     // Attribute initializer in a new environment
   877                     // with the declared variable as owner.
   878                     // Check that initializer conforms to variable's declared type.
   879                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   880                     initEnv.info.lint = lint;
   881                     // In order to catch self-references, we set the variable's
   882                     // declaration position to maximal possible value, effectively
   883                     // marking the variable as undefined.
   884                     initEnv.info.enclVar = v;
   885                     attribExpr(tree.init, initEnv, v.type);
   886                 }
   887             }
   888             result = tree.type = v.type;
   889             chk.validateAnnotations(tree.mods.annotations, v);
   890         }
   891         finally {
   892             chk.setLint(prevLint);
   893         }
   894     }
   896     public void visitSkip(JCSkip tree) {
   897         result = null;
   898     }
   900     public void visitBlock(JCBlock tree) {
   901         if (env.info.scope.owner.kind == TYP) {
   902             // Block is a static or instance initializer;
   903             // let the owner of the environment be a freshly
   904             // created BLOCK-method.
   905             Env<AttrContext> localEnv =
   906                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   907             localEnv.info.scope.owner =
   908                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   909                                  env.info.scope.owner);
   910             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   911             attribStats(tree.stats, localEnv);
   912         } else {
   913             // Create a new local environment with a local scope.
   914             Env<AttrContext> localEnv =
   915                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   916             attribStats(tree.stats, localEnv);
   917             localEnv.info.scope.leave();
   918         }
   919         result = null;
   920     }
   922     public void visitDoLoop(JCDoWhileLoop tree) {
   923         attribStat(tree.body, env.dup(tree));
   924         attribExpr(tree.cond, env, syms.booleanType);
   925         result = null;
   926     }
   928     public void visitWhileLoop(JCWhileLoop tree) {
   929         attribExpr(tree.cond, env, syms.booleanType);
   930         attribStat(tree.body, env.dup(tree));
   931         result = null;
   932     }
   934     public void visitForLoop(JCForLoop tree) {
   935         Env<AttrContext> loopEnv =
   936             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   937         attribStats(tree.init, loopEnv);
   938         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   939         loopEnv.tree = tree; // before, we were not in loop!
   940         attribStats(tree.step, loopEnv);
   941         attribStat(tree.body, loopEnv);
   942         loopEnv.info.scope.leave();
   943         result = null;
   944     }
   946     public void visitForeachLoop(JCEnhancedForLoop tree) {
   947         Env<AttrContext> loopEnv =
   948             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   949         attribStat(tree.var, loopEnv);
   950         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   951         chk.checkNonVoid(tree.pos(), exprType);
   952         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   953         if (elemtype == null) {
   954             // or perhaps expr implements Iterable<T>?
   955             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   956             if (base == null) {
   957                 log.error(tree.expr.pos(),
   958                         "foreach.not.applicable.to.type",
   959                         exprType,
   960                         diags.fragment("type.req.array.or.iterable"));
   961                 elemtype = types.createErrorType(exprType);
   962             } else {
   963                 List<Type> iterableParams = base.allparams();
   964                 elemtype = iterableParams.isEmpty()
   965                     ? syms.objectType
   966                     : types.upperBound(iterableParams.head);
   967             }
   968         }
   969         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   970         loopEnv.tree = tree; // before, we were not in loop!
   971         attribStat(tree.body, loopEnv);
   972         loopEnv.info.scope.leave();
   973         result = null;
   974     }
   976     public void visitLabelled(JCLabeledStatement tree) {
   977         // Check that label is not used in an enclosing statement
   978         Env<AttrContext> env1 = env;
   979         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
   980             if (env1.tree.hasTag(LABELLED) &&
   981                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   982                 log.error(tree.pos(), "label.already.in.use",
   983                           tree.label);
   984                 break;
   985             }
   986             env1 = env1.next;
   987         }
   989         attribStat(tree.body, env.dup(tree));
   990         result = null;
   991     }
   993     public void visitSwitch(JCSwitch tree) {
   994         Type seltype = attribExpr(tree.selector, env);
   996         Env<AttrContext> switchEnv =
   997             env.dup(tree, env.info.dup(env.info.scope.dup()));
   999         boolean enumSwitch =
  1000             allowEnums &&
  1001             (seltype.tsym.flags() & Flags.ENUM) != 0;
  1002         boolean stringSwitch = false;
  1003         if (types.isSameType(seltype, syms.stringType)) {
  1004             if (allowStringsInSwitch) {
  1005                 stringSwitch = true;
  1006             } else {
  1007                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1010         if (!enumSwitch && !stringSwitch)
  1011             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1013         // Attribute all cases and
  1014         // check that there are no duplicate case labels or default clauses.
  1015         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1016         boolean hasDefault = false;      // Is there a default label?
  1017         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1018             JCCase c = l.head;
  1019             Env<AttrContext> caseEnv =
  1020                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1021             if (c.pat != null) {
  1022                 if (enumSwitch) {
  1023                     Symbol sym = enumConstant(c.pat, seltype);
  1024                     if (sym == null) {
  1025                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1026                     } else if (!labels.add(sym)) {
  1027                         log.error(c.pos(), "duplicate.case.label");
  1029                 } else {
  1030                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1031                     if (pattype.tag != ERROR) {
  1032                         if (pattype.constValue() == null) {
  1033                             log.error(c.pat.pos(),
  1034                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
  1035                         } else if (labels.contains(pattype.constValue())) {
  1036                             log.error(c.pos(), "duplicate.case.label");
  1037                         } else {
  1038                             labels.add(pattype.constValue());
  1042             } else if (hasDefault) {
  1043                 log.error(c.pos(), "duplicate.default.label");
  1044             } else {
  1045                 hasDefault = true;
  1047             attribStats(c.stats, caseEnv);
  1048             caseEnv.info.scope.leave();
  1049             addVars(c.stats, switchEnv.info.scope);
  1052         switchEnv.info.scope.leave();
  1053         result = null;
  1055     // where
  1056         /** Add any variables defined in stats to the switch scope. */
  1057         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1058             for (;stats.nonEmpty(); stats = stats.tail) {
  1059                 JCTree stat = stats.head;
  1060                 if (stat.hasTag(VARDEF))
  1061                     switchScope.enter(((JCVariableDecl) stat).sym);
  1064     // where
  1065     /** Return the selected enumeration constant symbol, or null. */
  1066     private Symbol enumConstant(JCTree tree, Type enumType) {
  1067         if (!tree.hasTag(IDENT)) {
  1068             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1069             return syms.errSymbol;
  1071         JCIdent ident = (JCIdent)tree;
  1072         Name name = ident.name;
  1073         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1074              e.scope != null; e = e.next()) {
  1075             if (e.sym.kind == VAR) {
  1076                 Symbol s = ident.sym = e.sym;
  1077                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1078                 ident.type = s.type;
  1079                 return ((s.flags_field & Flags.ENUM) == 0)
  1080                     ? null : s;
  1083         return null;
  1086     public void visitSynchronized(JCSynchronized tree) {
  1087         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1088         attribStat(tree.body, env);
  1089         result = null;
  1092     public void visitTry(JCTry tree) {
  1093         // Create a new local environment with a local
  1094         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1095         boolean isTryWithResource = tree.resources.nonEmpty();
  1096         // Create a nested environment for attributing the try block if needed
  1097         Env<AttrContext> tryEnv = isTryWithResource ?
  1098             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1099             localEnv;
  1100         // Attribute resource declarations
  1101         for (JCTree resource : tree.resources) {
  1102             if (resource.hasTag(VARDEF)) {
  1103                 attribStat(resource, tryEnv);
  1104                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1106                 //check that resource type cannot throw InterruptedException
  1107                 checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1109                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1110                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1111             } else {
  1112                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1115         // Attribute body
  1116         attribStat(tree.body, tryEnv);
  1117         if (isTryWithResource)
  1118             tryEnv.info.scope.leave();
  1120         // Attribute catch clauses
  1121         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1122             JCCatch c = l.head;
  1123             Env<AttrContext> catchEnv =
  1124                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1125             Type ctype = attribStat(c.param, catchEnv);
  1126             if (TreeInfo.isMultiCatch(c)) {
  1127                 //multi-catch parameter is implicitly marked as final
  1128                 c.param.sym.flags_field |= FINAL | UNION;
  1130             if (c.param.sym.kind == Kinds.VAR) {
  1131                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1133             chk.checkType(c.param.vartype.pos(),
  1134                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1135                           syms.throwableType);
  1136             attribStat(c.body, catchEnv);
  1137             catchEnv.info.scope.leave();
  1140         // Attribute finalizer
  1141         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1143         localEnv.info.scope.leave();
  1144         result = null;
  1147     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1148         if (!resource.isErroneous() &&
  1149                 types.asSuper(resource, syms.autoCloseableType.tsym) != null) {
  1150             Symbol close = syms.noSymbol;
  1151             boolean prevDeferDiags = log.deferDiagnostics;
  1152             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1153             try {
  1154                 log.deferDiagnostics = true;
  1155                 log.deferredDiagnostics = ListBuffer.lb();
  1156                 close = rs.resolveQualifiedMethod(pos,
  1157                         env,
  1158                         resource,
  1159                         names.close,
  1160                         List.<Type>nil(),
  1161                         List.<Type>nil());
  1163             finally {
  1164                 log.deferDiagnostics = prevDeferDiags;
  1165                 log.deferredDiagnostics = prevDeferredDiags;
  1167             if (close.kind == MTH &&
  1168                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1169                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1170                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1171                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1176     public void visitConditional(JCConditional tree) {
  1177         attribExpr(tree.cond, env, syms.booleanType);
  1178         attribExpr(tree.truepart, env);
  1179         attribExpr(tree.falsepart, env);
  1180         result = check(tree,
  1181                        capture(condType(tree.pos(), tree.cond.type,
  1182                                         tree.truepart.type, tree.falsepart.type)),
  1183                        VAL, pkind, pt);
  1185     //where
  1186         /** Compute the type of a conditional expression, after
  1187          *  checking that it exists. See Spec 15.25.
  1189          *  @param pos      The source position to be used for
  1190          *                  error diagnostics.
  1191          *  @param condtype The type of the expression's condition.
  1192          *  @param thentype The type of the expression's then-part.
  1193          *  @param elsetype The type of the expression's else-part.
  1194          */
  1195         private Type condType(DiagnosticPosition pos,
  1196                               Type condtype,
  1197                               Type thentype,
  1198                               Type elsetype) {
  1199             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1201             // If condition and both arms are numeric constants,
  1202             // evaluate at compile-time.
  1203             return ((condtype.constValue() != null) &&
  1204                     (thentype.constValue() != null) &&
  1205                     (elsetype.constValue() != null))
  1206                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1207                 : ctype;
  1209         /** Compute the type of a conditional expression, after
  1210          *  checking that it exists.  Does not take into
  1211          *  account the special case where condition and both arms
  1212          *  are constants.
  1214          *  @param pos      The source position to be used for error
  1215          *                  diagnostics.
  1216          *  @param condtype The type of the expression's condition.
  1217          *  @param thentype The type of the expression's then-part.
  1218          *  @param elsetype The type of the expression's else-part.
  1219          */
  1220         private Type condType1(DiagnosticPosition pos, Type condtype,
  1221                                Type thentype, Type elsetype) {
  1222             // If same type, that is the result
  1223             if (types.isSameType(thentype, elsetype))
  1224                 return thentype.baseType();
  1226             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1227                 ? thentype : types.unboxedType(thentype);
  1228             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1229                 ? elsetype : types.unboxedType(elsetype);
  1231             // Otherwise, if both arms can be converted to a numeric
  1232             // type, return the least numeric type that fits both arms
  1233             // (i.e. return larger of the two, or return int if one
  1234             // arm is short, the other is char).
  1235             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1236                 // If one arm has an integer subrange type (i.e., byte,
  1237                 // short, or char), and the other is an integer constant
  1238                 // that fits into the subrange, return the subrange type.
  1239                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1240                     types.isAssignable(elseUnboxed, thenUnboxed))
  1241                     return thenUnboxed.baseType();
  1242                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1243                     types.isAssignable(thenUnboxed, elseUnboxed))
  1244                     return elseUnboxed.baseType();
  1246                 for (int i = BYTE; i < VOID; i++) {
  1247                     Type candidate = syms.typeOfTag[i];
  1248                     if (types.isSubtype(thenUnboxed, candidate) &&
  1249                         types.isSubtype(elseUnboxed, candidate))
  1250                         return candidate;
  1254             // Those were all the cases that could result in a primitive
  1255             if (allowBoxing) {
  1256                 if (thentype.isPrimitive())
  1257                     thentype = types.boxedClass(thentype).type;
  1258                 if (elsetype.isPrimitive())
  1259                     elsetype = types.boxedClass(elsetype).type;
  1262             if (types.isSubtype(thentype, elsetype))
  1263                 return elsetype.baseType();
  1264             if (types.isSubtype(elsetype, thentype))
  1265                 return thentype.baseType();
  1267             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1268                 log.error(pos, "neither.conditional.subtype",
  1269                           thentype, elsetype);
  1270                 return thentype.baseType();
  1273             // both are known to be reference types.  The result is
  1274             // lub(thentype,elsetype). This cannot fail, as it will
  1275             // always be possible to infer "Object" if nothing better.
  1276             return types.lub(thentype.baseType(), elsetype.baseType());
  1279     public void visitIf(JCIf tree) {
  1280         attribExpr(tree.cond, env, syms.booleanType);
  1281         attribStat(tree.thenpart, env);
  1282         if (tree.elsepart != null)
  1283             attribStat(tree.elsepart, env);
  1284         chk.checkEmptyIf(tree);
  1285         result = null;
  1288     public void visitExec(JCExpressionStatement tree) {
  1289         //a fresh environment is required for 292 inference to work properly ---
  1290         //see Infer.instantiatePolymorphicSignatureInstance()
  1291         Env<AttrContext> localEnv = env.dup(tree);
  1292         attribExpr(tree.expr, localEnv);
  1293         result = null;
  1296     public void visitBreak(JCBreak tree) {
  1297         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1298         result = null;
  1301     public void visitContinue(JCContinue tree) {
  1302         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1303         result = null;
  1305     //where
  1306         /** Return the target of a break or continue statement, if it exists,
  1307          *  report an error if not.
  1308          *  Note: The target of a labelled break or continue is the
  1309          *  (non-labelled) statement tree referred to by the label,
  1310          *  not the tree representing the labelled statement itself.
  1312          *  @param pos     The position to be used for error diagnostics
  1313          *  @param tag     The tag of the jump statement. This is either
  1314          *                 Tree.BREAK or Tree.CONTINUE.
  1315          *  @param label   The label of the jump statement, or null if no
  1316          *                 label is given.
  1317          *  @param env     The environment current at the jump statement.
  1318          */
  1319         private JCTree findJumpTarget(DiagnosticPosition pos,
  1320                                     JCTree.Tag tag,
  1321                                     Name label,
  1322                                     Env<AttrContext> env) {
  1323             // Search environments outwards from the point of jump.
  1324             Env<AttrContext> env1 = env;
  1325             LOOP:
  1326             while (env1 != null) {
  1327                 switch (env1.tree.getTag()) {
  1328                 case LABELLED:
  1329                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1330                     if (label == labelled.label) {
  1331                         // If jump is a continue, check that target is a loop.
  1332                         if (tag == CONTINUE) {
  1333                             if (!labelled.body.hasTag(DOLOOP) &&
  1334                                 !labelled.body.hasTag(WHILELOOP) &&
  1335                                 !labelled.body.hasTag(FORLOOP) &&
  1336                                 !labelled.body.hasTag(FOREACHLOOP))
  1337                                 log.error(pos, "not.loop.label", label);
  1338                             // Found labelled statement target, now go inwards
  1339                             // to next non-labelled tree.
  1340                             return TreeInfo.referencedStatement(labelled);
  1341                         } else {
  1342                             return labelled;
  1345                     break;
  1346                 case DOLOOP:
  1347                 case WHILELOOP:
  1348                 case FORLOOP:
  1349                 case FOREACHLOOP:
  1350                     if (label == null) return env1.tree;
  1351                     break;
  1352                 case SWITCH:
  1353                     if (label == null && tag == BREAK) return env1.tree;
  1354                     break;
  1355                 case METHODDEF:
  1356                 case CLASSDEF:
  1357                     break LOOP;
  1358                 default:
  1360                 env1 = env1.next;
  1362             if (label != null)
  1363                 log.error(pos, "undef.label", label);
  1364             else if (tag == CONTINUE)
  1365                 log.error(pos, "cont.outside.loop");
  1366             else
  1367                 log.error(pos, "break.outside.switch.loop");
  1368             return null;
  1371     public void visitReturn(JCReturn tree) {
  1372         // Check that there is an enclosing method which is
  1373         // nested within than the enclosing class.
  1374         if (env.enclMethod == null ||
  1375             env.enclMethod.sym.owner != env.enclClass.sym) {
  1376             log.error(tree.pos(), "ret.outside.meth");
  1378         } else {
  1379             // Attribute return expression, if it exists, and check that
  1380             // it conforms to result type of enclosing method.
  1381             Symbol m = env.enclMethod.sym;
  1382             if (m.type.getReturnType().tag == VOID) {
  1383                 if (tree.expr != null)
  1384                     log.error(tree.expr.pos(),
  1385                               "cant.ret.val.from.meth.decl.void");
  1386             } else if (tree.expr == null) {
  1387                 log.error(tree.pos(), "missing.ret.val");
  1388             } else {
  1389                 attribExpr(tree.expr, env, m.type.getReturnType());
  1392         result = null;
  1395     public void visitThrow(JCThrow tree) {
  1396         attribExpr(tree.expr, env, syms.throwableType);
  1397         result = null;
  1400     public void visitAssert(JCAssert tree) {
  1401         attribExpr(tree.cond, env, syms.booleanType);
  1402         if (tree.detail != null) {
  1403             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1405         result = null;
  1408      /** Visitor method for method invocations.
  1409      *  NOTE: The method part of an application will have in its type field
  1410      *        the return type of the method, not the method's type itself!
  1411      */
  1412     public void visitApply(JCMethodInvocation tree) {
  1413         // The local environment of a method application is
  1414         // a new environment nested in the current one.
  1415         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1417         // The types of the actual method arguments.
  1418         List<Type> argtypes;
  1420         // The types of the actual method type arguments.
  1421         List<Type> typeargtypes = null;
  1423         Name methName = TreeInfo.name(tree.meth);
  1425         boolean isConstructorCall =
  1426             methName == names._this || methName == names._super;
  1428         if (isConstructorCall) {
  1429             // We are seeing a ...this(...) or ...super(...) call.
  1430             // Check that this is the first statement in a constructor.
  1431             if (checkFirstConstructorStat(tree, env)) {
  1433                 // Record the fact
  1434                 // that this is a constructor call (using isSelfCall).
  1435                 localEnv.info.isSelfCall = true;
  1437                 // Attribute arguments, yielding list of argument types.
  1438                 argtypes = attribArgs(tree.args, localEnv);
  1439                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1441                 // Variable `site' points to the class in which the called
  1442                 // constructor is defined.
  1443                 Type site = env.enclClass.sym.type;
  1444                 if (methName == names._super) {
  1445                     if (site == syms.objectType) {
  1446                         log.error(tree.meth.pos(), "no.superclass", site);
  1447                         site = types.createErrorType(syms.objectType);
  1448                     } else {
  1449                         site = types.supertype(site);
  1453                 if (site.tag == CLASS) {
  1454                     Type encl = site.getEnclosingType();
  1455                     while (encl != null && encl.tag == TYPEVAR)
  1456                         encl = encl.getUpperBound();
  1457                     if (encl.tag == CLASS) {
  1458                         // we are calling a nested class
  1460                         if (tree.meth.hasTag(SELECT)) {
  1461                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1463                             // We are seeing a prefixed call, of the form
  1464                             //     <expr>.super(...).
  1465                             // Check that the prefix expression conforms
  1466                             // to the outer instance type of the class.
  1467                             chk.checkRefType(qualifier.pos(),
  1468                                              attribExpr(qualifier, localEnv,
  1469                                                         encl));
  1470                         } else if (methName == names._super) {
  1471                             // qualifier omitted; check for existence
  1472                             // of an appropriate implicit qualifier.
  1473                             rs.resolveImplicitThis(tree.meth.pos(),
  1474                                                    localEnv, site, true);
  1476                     } else if (tree.meth.hasTag(SELECT)) {
  1477                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1478                                   site.tsym);
  1481                     // if we're calling a java.lang.Enum constructor,
  1482                     // prefix the implicit String and int parameters
  1483                     if (site.tsym == syms.enumSym && allowEnums)
  1484                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1486                     // Resolve the called constructor under the assumption
  1487                     // that we are referring to a superclass instance of the
  1488                     // current instance (JLS ???).
  1489                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1490                     localEnv.info.selectSuper = true;
  1491                     localEnv.info.varArgs = false;
  1492                     Symbol sym = rs.resolveConstructor(
  1493                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1494                     localEnv.info.selectSuper = selectSuperPrev;
  1496                     // Set method symbol to resolved constructor...
  1497                     TreeInfo.setSymbol(tree.meth, sym);
  1499                     // ...and check that it is legal in the current context.
  1500                     // (this will also set the tree's type)
  1501                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1502                     checkId(tree.meth, site, sym, localEnv, MTH,
  1503                             mpt, tree.varargsElement != null);
  1505                 // Otherwise, `site' is an error type and we do nothing
  1507             result = tree.type = syms.voidType;
  1508         } else {
  1509             // Otherwise, we are seeing a regular method call.
  1510             // Attribute the arguments, yielding list of argument types, ...
  1511             argtypes = attribArgs(tree.args, localEnv);
  1512             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1514             // ... and attribute the method using as a prototype a methodtype
  1515             // whose formal argument types is exactly the list of actual
  1516             // arguments (this will also set the method symbol).
  1517             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1518             localEnv.info.varArgs = false;
  1519             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1520             if (localEnv.info.varArgs)
  1521                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
  1523             // Compute the result type.
  1524             Type restype = mtype.getReturnType();
  1525             if (restype.tag == WILDCARD)
  1526                 throw new AssertionError(mtype);
  1528             // as a special case, array.clone() has a result that is
  1529             // the same as static type of the array being cloned
  1530             if (tree.meth.hasTag(SELECT) &&
  1531                 allowCovariantReturns &&
  1532                 methName == names.clone &&
  1533                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1534                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1536             // as a special case, x.getClass() has type Class<? extends |X|>
  1537             if (allowGenerics &&
  1538                 methName == names.getClass && tree.args.isEmpty()) {
  1539                 Type qualifier = (tree.meth.hasTag(SELECT))
  1540                     ? ((JCFieldAccess) tree.meth).selected.type
  1541                     : env.enclClass.sym.type;
  1542                 restype = new
  1543                     ClassType(restype.getEnclosingType(),
  1544                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1545                                                                BoundKind.EXTENDS,
  1546                                                                syms.boundClass)),
  1547                               restype.tsym);
  1550             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1552             // Check that value of resulting type is admissible in the
  1553             // current context.  Also, capture the return type
  1554             result = check(tree, capture(restype), VAL, pkind, pt);
  1556         chk.validate(tree.typeargs, localEnv);
  1558     //where
  1559         /** Check that given application node appears as first statement
  1560          *  in a constructor call.
  1561          *  @param tree   The application node
  1562          *  @param env    The environment current at the application.
  1563          */
  1564         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1565             JCMethodDecl enclMethod = env.enclMethod;
  1566             if (enclMethod != null && enclMethod.name == names.init) {
  1567                 JCBlock body = enclMethod.body;
  1568                 if (body.stats.head.hasTag(EXEC) &&
  1569                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1570                     return true;
  1572             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1573                       TreeInfo.name(tree.meth));
  1574             return false;
  1577         /** Obtain a method type with given argument types.
  1578          */
  1579         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1580             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1581             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1584     public void visitNewClass(JCNewClass tree) {
  1585         Type owntype = types.createErrorType(tree.type);
  1587         // The local environment of a class creation is
  1588         // a new environment nested in the current one.
  1589         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1591         // The anonymous inner class definition of the new expression,
  1592         // if one is defined by it.
  1593         JCClassDecl cdef = tree.def;
  1595         // If enclosing class is given, attribute it, and
  1596         // complete class name to be fully qualified
  1597         JCExpression clazz = tree.clazz; // Class field following new
  1598         JCExpression clazzid =          // Identifier in class field
  1599             (clazz.hasTag(TYPEAPPLY))
  1600             ? ((JCTypeApply) clazz).clazz
  1601             : clazz;
  1603         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1605         if (tree.encl != null) {
  1606             // We are seeing a qualified new, of the form
  1607             //    <expr>.new C <...> (...) ...
  1608             // In this case, we let clazz stand for the name of the
  1609             // allocated class C prefixed with the type of the qualifier
  1610             // expression, so that we can
  1611             // resolve it with standard techniques later. I.e., if
  1612             // <expr> has type T, then <expr>.new C <...> (...)
  1613             // yields a clazz T.C.
  1614             Type encltype = chk.checkRefType(tree.encl.pos(),
  1615                                              attribExpr(tree.encl, env));
  1616             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1617                                                  ((JCIdent) clazzid).name);
  1618             if (clazz.hasTag(TYPEAPPLY))
  1619                 clazz = make.at(tree.pos).
  1620                     TypeApply(clazzid1,
  1621                               ((JCTypeApply) clazz).arguments);
  1622             else
  1623                 clazz = clazzid1;
  1626         // Attribute clazz expression and store
  1627         // symbol + type back into the attributed tree.
  1628         Type clazztype = attribType(clazz, env);
  1629         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
  1630         clazztype = chk.checkDiamond(tree, clazztype);
  1631         chk.validate(clazz, localEnv);
  1632         if (tree.encl != null) {
  1633             // We have to work in this case to store
  1634             // symbol + type back into the attributed tree.
  1635             tree.clazz.type = clazztype;
  1636             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1637             clazzid.type = ((JCIdent) clazzid).sym.type;
  1638             if (!clazztype.isErroneous()) {
  1639                 if (cdef != null && clazztype.tsym.isInterface()) {
  1640                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1641                 } else if (clazztype.tsym.isStatic()) {
  1642                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1645         } else if (!clazztype.tsym.isInterface() &&
  1646                    clazztype.getEnclosingType().tag == CLASS) {
  1647             // Check for the existence of an apropos outer instance
  1648             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1651         // Attribute constructor arguments.
  1652         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1653         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1655         if (TreeInfo.isDiamond(tree) && !clazztype.isErroneous()) {
  1656             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1657             clazz.type = clazztype;
  1658         } else if (allowDiamondFinder &&
  1659                 tree.def == null &&
  1660                 !clazztype.isErroneous() &&
  1661                 clazztype.getTypeArguments().nonEmpty() &&
  1662                 findDiamonds) {
  1663             boolean prevDeferDiags = log.deferDiagnostics;
  1664             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1665             Type inferred = null;
  1666             try {
  1667                 //disable diamond-related diagnostics
  1668                 log.deferDiagnostics = true;
  1669                 log.deferredDiagnostics = ListBuffer.lb();
  1670                 inferred = attribDiamond(localEnv,
  1671                         tree,
  1672                         clazztype,
  1673                         mapping,
  1674                         argtypes,
  1675                         typeargtypes);
  1677             finally {
  1678                 log.deferDiagnostics = prevDeferDiags;
  1679                 log.deferredDiagnostics = prevDeferredDiags;
  1681             if (inferred != null &&
  1682                     !inferred.isErroneous() &&
  1683                     inferred.tag == CLASS &&
  1684                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings)) {
  1685                 String key = types.isSameType(clazztype, inferred) ?
  1686                     "diamond.redundant.args" :
  1687                     "diamond.redundant.args.1";
  1688                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1692         // If we have made no mistakes in the class type...
  1693         if (clazztype.tag == CLASS) {
  1694             // Enums may not be instantiated except implicitly
  1695             if (allowEnums &&
  1696                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1697                 (!env.tree.hasTag(VARDEF) ||
  1698                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1699                  ((JCVariableDecl) env.tree).init != tree))
  1700                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1701             // Check that class is not abstract
  1702             if (cdef == null &&
  1703                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1704                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1705                           clazztype.tsym);
  1706             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1707                 // Check that no constructor arguments are given to
  1708                 // anonymous classes implementing an interface
  1709                 if (!argtypes.isEmpty())
  1710                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1712                 if (!typeargtypes.isEmpty())
  1713                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1715                 // Error recovery: pretend no arguments were supplied.
  1716                 argtypes = List.nil();
  1717                 typeargtypes = List.nil();
  1720             // Resolve the called constructor under the assumption
  1721             // that we are referring to a superclass instance of the
  1722             // current instance (JLS ???).
  1723             else {
  1724                 //the following code alters some of the fields in the current
  1725                 //AttrContext - hence, the current context must be dup'ed in
  1726                 //order to avoid downstream failures
  1727                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  1728                 rsEnv.info.selectSuper = cdef != null;
  1729                 rsEnv.info.varArgs = false;
  1730                 tree.constructor = rs.resolveConstructor(
  1731                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  1732                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1733                     syms.errType :
  1734                     checkMethod(clazztype,
  1735                         tree.constructor,
  1736                         rsEnv,
  1737                         tree.args,
  1738                         argtypes,
  1739                         typeargtypes,
  1740                         rsEnv.info.varArgs);
  1741                 if (rsEnv.info.varArgs)
  1742                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1745             if (cdef != null) {
  1746                 // We are seeing an anonymous class instance creation.
  1747                 // In this case, the class instance creation
  1748                 // expression
  1749                 //
  1750                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1751                 //
  1752                 // is represented internally as
  1753                 //
  1754                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1755                 //
  1756                 // This expression is then *transformed* as follows:
  1757                 //
  1758                 // (1) add a STATIC flag to the class definition
  1759                 //     if the current environment is static
  1760                 // (2) add an extends or implements clause
  1761                 // (3) add a constructor.
  1762                 //
  1763                 // For instance, if C is a class, and ET is the type of E,
  1764                 // the expression
  1765                 //
  1766                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1767                 //
  1768                 // is translated to (where X is a fresh name and typarams is the
  1769                 // parameter list of the super constructor):
  1770                 //
  1771                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1772                 //     X extends C<typargs2> {
  1773                 //       <typarams> X(ET e, args) {
  1774                 //         e.<typeargs1>super(args)
  1775                 //       }
  1776                 //       ...
  1777                 //     }
  1778                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1780                 if (clazztype.tsym.isInterface()) {
  1781                     cdef.implementing = List.of(clazz);
  1782                 } else {
  1783                     cdef.extending = clazz;
  1786                 attribStat(cdef, localEnv);
  1788                 // If an outer instance is given,
  1789                 // prefix it to the constructor arguments
  1790                 // and delete it from the new expression
  1791                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1792                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1793                     argtypes = argtypes.prepend(tree.encl.type);
  1794                     tree.encl = null;
  1797                 // Reassign clazztype and recompute constructor.
  1798                 clazztype = cdef.sym.type;
  1799                 boolean useVarargs = tree.varargsElement != null;
  1800                 Symbol sym = rs.resolveConstructor(
  1801                     tree.pos(), localEnv, clazztype, argtypes,
  1802                     typeargtypes, true, useVarargs);
  1803                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
  1804                 tree.constructor = sym;
  1805                 if (tree.constructor.kind > ERRONEOUS) {
  1806                     tree.constructorType =  syms.errType;
  1808                 else {
  1809                     tree.constructorType = checkMethod(clazztype,
  1810                             tree.constructor,
  1811                             localEnv,
  1812                             tree.args,
  1813                             argtypes,
  1814                             typeargtypes,
  1815                             useVarargs);
  1819             if (tree.constructor != null && tree.constructor.kind == MTH)
  1820                 owntype = clazztype;
  1822         result = check(tree, owntype, VAL, pkind, pt);
  1823         chk.validate(tree.typeargs, localEnv);
  1826     Type attribDiamond(Env<AttrContext> env,
  1827                         JCNewClass tree,
  1828                         Type clazztype,
  1829                         Pair<Scope, Scope> mapping,
  1830                         List<Type> argtypes,
  1831                         List<Type> typeargtypes) {
  1832         if (clazztype.isErroneous() ||
  1833                 clazztype.isInterface() ||
  1834                 mapping == erroneousMapping) {
  1835             //if the type of the instance creation expression is erroneous,
  1836             //or if it's an interface, or if something prevented us to form a valid
  1837             //mapping, return the (possibly erroneous) type unchanged
  1838             return clazztype;
  1841         //dup attribution environment and augment the set of inference variables
  1842         Env<AttrContext> localEnv = env.dup(tree);
  1843         localEnv.info.tvars = clazztype.tsym.type.getTypeArguments();
  1845         //if the type of the instance creation expression is a class type
  1846         //apply method resolution inference (JLS 15.12.2.7). The return type
  1847         //of the resolved constructor will be a partially instantiated type
  1848         ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1849         Symbol constructor;
  1850         try {
  1851             constructor = rs.resolveDiamond(tree.pos(),
  1852                     localEnv,
  1853                     clazztype,
  1854                     argtypes,
  1855                     typeargtypes);
  1856         } finally {
  1857             ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1859         if (constructor.kind == MTH) {
  1860             ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1861                     clazztype.tsym.type.getTypeArguments(),
  1862                     clazztype.tsym);
  1863             clazztype = checkMethod(ct,
  1864                     constructor,
  1865                     localEnv,
  1866                     tree.args,
  1867                     argtypes,
  1868                     typeargtypes,
  1869                     localEnv.info.varArgs).getReturnType();
  1870         } else {
  1871             clazztype = syms.errType;
  1874         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1875             //if the resolved constructor's return type has some uninferred
  1876             //type-variables, infer them using the expected type and declared
  1877             //bounds (JLS 15.12.2.8).
  1878             try {
  1879                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1880                         pt.tag == NONE ? syms.objectType : pt,
  1881                         Warner.noWarnings);
  1882             } catch (Infer.InferenceException ex) {
  1883                 //an error occurred while inferring uninstantiated type-variables
  1884                 log.error(tree.clazz.pos(),
  1885                         "cant.apply.diamond.1",
  1886                         diags.fragment("diamond", clazztype.tsym),
  1887                         ex.diagnostic);
  1890         return chk.checkClassType(tree.clazz.pos(),
  1891                 clazztype,
  1892                 true);
  1895     /** Creates a synthetic scope containing fake generic constructors.
  1896      *  Assuming that the original scope contains a constructor of the kind:
  1897      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1898      *  the synthetic scope is added a generic constructor of the kind:
  1899      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1900      *  inference. The inferred return type of the synthetic constructor IS
  1901      *  the inferred type for the diamond operator.
  1902      */
  1903     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
  1904         if (ctype.tag != CLASS) {
  1905             return erroneousMapping;
  1908         Pair<Scope, Scope> mapping =
  1909                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1911         //for each constructor in the original scope, create a synthetic constructor
  1912         //whose return type is the type of the class in which the constructor is
  1913         //declared, and insert it into the new scope.
  1914         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1915                 e.scope != null;
  1916                 e = e.next()) {
  1917             Type synthRestype = new ClassType(ctype.getEnclosingType(),
  1918                         ctype.tsym.type.getTypeArguments(),
  1919                         ctype.tsym);
  1920             MethodSymbol synhConstr = new MethodSymbol(e.sym.flags(),
  1921                     names.init,
  1922                     types.createMethodTypeWithReturn(e.sym.type, synthRestype),
  1923                     e.sym.owner);
  1924             mapping.snd.enter(synhConstr);
  1926         return mapping;
  1929     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1931     /** Make an attributed null check tree.
  1932      */
  1933     public JCExpression makeNullCheck(JCExpression arg) {
  1934         // optimization: X.this is never null; skip null check
  1935         Name name = TreeInfo.name(arg);
  1936         if (name == names._this || name == names._super) return arg;
  1938         JCTree.Tag optag = NULLCHK;
  1939         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1940         tree.operator = syms.nullcheck;
  1941         tree.type = arg.type;
  1942         return tree;
  1945     public void visitNewArray(JCNewArray tree) {
  1946         Type owntype = types.createErrorType(tree.type);
  1947         Type elemtype;
  1948         if (tree.elemtype != null) {
  1949             elemtype = attribType(tree.elemtype, env);
  1950             chk.validate(tree.elemtype, env);
  1951             owntype = elemtype;
  1952             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1953                 attribExpr(l.head, env, syms.intType);
  1954                 owntype = new ArrayType(owntype, syms.arrayClass);
  1956         } else {
  1957             // we are seeing an untyped aggregate { ... }
  1958             // this is allowed only if the prototype is an array
  1959             if (pt.tag == ARRAY) {
  1960                 elemtype = types.elemtype(pt);
  1961             } else {
  1962                 if (pt.tag != ERROR) {
  1963                     log.error(tree.pos(), "illegal.initializer.for.type",
  1964                               pt);
  1966                 elemtype = types.createErrorType(pt);
  1969         if (tree.elems != null) {
  1970             attribExprs(tree.elems, env, elemtype);
  1971             owntype = new ArrayType(elemtype, syms.arrayClass);
  1973         if (!types.isReifiable(elemtype))
  1974             log.error(tree.pos(), "generic.array.creation");
  1975         result = check(tree, owntype, VAL, pkind, pt);
  1978     @Override
  1979     public void visitLambda(JCLambda that) {
  1980         throw new UnsupportedOperationException("Lambda expression not supported yet");
  1983     public void visitParens(JCParens tree) {
  1984         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1985         result = check(tree, owntype, pkind, pkind, pt);
  1986         Symbol sym = TreeInfo.symbol(tree);
  1987         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1988             log.error(tree.pos(), "illegal.start.of.type");
  1991     public void visitAssign(JCAssign tree) {
  1992         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1993         Type capturedType = capture(owntype);
  1994         attribExpr(tree.rhs, env, owntype);
  1995         result = check(tree, capturedType, VAL, pkind, pt);
  1998     public void visitAssignop(JCAssignOp tree) {
  1999         // Attribute arguments.
  2000         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  2001         Type operand = attribExpr(tree.rhs, env);
  2002         // Find operator.
  2003         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2004             tree.pos(), tree.getTag().noAssignOp(), env,
  2005             owntype, operand);
  2007         if (operator.kind == MTH &&
  2008                 !owntype.isErroneous() &&
  2009                 !operand.isErroneous()) {
  2010             chk.checkOperator(tree.pos(),
  2011                               (OperatorSymbol)operator,
  2012                               tree.getTag().noAssignOp(),
  2013                               owntype,
  2014                               operand);
  2015             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2016             chk.checkCastable(tree.rhs.pos(),
  2017                               operator.type.getReturnType(),
  2018                               owntype);
  2020         result = check(tree, owntype, VAL, pkind, pt);
  2023     public void visitUnary(JCUnary tree) {
  2024         // Attribute arguments.
  2025         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2026             ? attribTree(tree.arg, env, VAR, Type.noType)
  2027             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2029         // Find operator.
  2030         Symbol operator = tree.operator =
  2031             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2033         Type owntype = types.createErrorType(tree.type);
  2034         if (operator.kind == MTH &&
  2035                 !argtype.isErroneous()) {
  2036             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2037                 ? tree.arg.type
  2038                 : operator.type.getReturnType();
  2039             int opc = ((OperatorSymbol)operator).opcode;
  2041             // If the argument is constant, fold it.
  2042             if (argtype.constValue() != null) {
  2043                 Type ctype = cfolder.fold1(opc, argtype);
  2044                 if (ctype != null) {
  2045                     owntype = cfolder.coerce(ctype, owntype);
  2047                     // Remove constant types from arguments to
  2048                     // conserve space. The parser will fold concatenations
  2049                     // of string literals; the code here also
  2050                     // gets rid of intermediate results when some of the
  2051                     // operands are constant identifiers.
  2052                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2053                         tree.arg.type = syms.stringType;
  2058         result = check(tree, owntype, VAL, pkind, pt);
  2061     public void visitBinary(JCBinary tree) {
  2062         // Attribute arguments.
  2063         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2064         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2066         // Find operator.
  2067         Symbol operator = tree.operator =
  2068             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2070         Type owntype = types.createErrorType(tree.type);
  2071         if (operator.kind == MTH &&
  2072                 !left.isErroneous() &&
  2073                 !right.isErroneous()) {
  2074             owntype = operator.type.getReturnType();
  2075             int opc = chk.checkOperator(tree.lhs.pos(),
  2076                                         (OperatorSymbol)operator,
  2077                                         tree.getTag(),
  2078                                         left,
  2079                                         right);
  2081             // If both arguments are constants, fold them.
  2082             if (left.constValue() != null && right.constValue() != null) {
  2083                 Type ctype = cfolder.fold2(opc, left, right);
  2084                 if (ctype != null) {
  2085                     owntype = cfolder.coerce(ctype, owntype);
  2087                     // Remove constant types from arguments to
  2088                     // conserve space. The parser will fold concatenations
  2089                     // of string literals; the code here also
  2090                     // gets rid of intermediate results when some of the
  2091                     // operands are constant identifiers.
  2092                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2093                         tree.lhs.type = syms.stringType;
  2095                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2096                         tree.rhs.type = syms.stringType;
  2101             // Check that argument types of a reference ==, != are
  2102             // castable to each other, (JLS???).
  2103             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2104                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2105                     log.error(tree.pos(), "incomparable.types", left, right);
  2109             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2111         result = check(tree, owntype, VAL, pkind, pt);
  2114     public void visitTypeCast(JCTypeCast tree) {
  2115         Type clazztype = attribType(tree.clazz, env);
  2116         chk.validate(tree.clazz, env, false);
  2117         //a fresh environment is required for 292 inference to work properly ---
  2118         //see Infer.instantiatePolymorphicSignatureInstance()
  2119         Env<AttrContext> localEnv = env.dup(tree);
  2120         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2121         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2122         if (exprtype.constValue() != null)
  2123             owntype = cfolder.coerce(exprtype, owntype);
  2124         result = check(tree, capture(owntype), VAL, pkind, pt);
  2127     public void visitTypeTest(JCInstanceOf tree) {
  2128         Type exprtype = chk.checkNullOrRefType(
  2129             tree.expr.pos(), attribExpr(tree.expr, env));
  2130         Type clazztype = chk.checkReifiableReferenceType(
  2131             tree.clazz.pos(), attribType(tree.clazz, env));
  2132         chk.validate(tree.clazz, env, false);
  2133         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2134         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2137     public void visitIndexed(JCArrayAccess tree) {
  2138         Type owntype = types.createErrorType(tree.type);
  2139         Type atype = attribExpr(tree.indexed, env);
  2140         attribExpr(tree.index, env, syms.intType);
  2141         if (types.isArray(atype))
  2142             owntype = types.elemtype(atype);
  2143         else if (atype.tag != ERROR)
  2144             log.error(tree.pos(), "array.req.but.found", atype);
  2145         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2146         result = check(tree, owntype, VAR, pkind, pt);
  2149     public void visitIdent(JCIdent tree) {
  2150         Symbol sym;
  2151         boolean varArgs = false;
  2153         // Find symbol
  2154         if (pt.tag == METHOD || pt.tag == FORALL) {
  2155             // If we are looking for a method, the prototype `pt' will be a
  2156             // method type with the type of the call's arguments as parameters.
  2157             env.info.varArgs = false;
  2158             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2159             varArgs = env.info.varArgs;
  2160         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2161             sym = tree.sym;
  2162         } else {
  2163             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2165         tree.sym = sym;
  2167         // (1) Also find the environment current for the class where
  2168         //     sym is defined (`symEnv').
  2169         // Only for pre-tiger versions (1.4 and earlier):
  2170         // (2) Also determine whether we access symbol out of an anonymous
  2171         //     class in a this or super call.  This is illegal for instance
  2172         //     members since such classes don't carry a this$n link.
  2173         //     (`noOuterThisPath').
  2174         Env<AttrContext> symEnv = env;
  2175         boolean noOuterThisPath = false;
  2176         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2177             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2178             sym.owner.kind == TYP &&
  2179             tree.name != names._this && tree.name != names._super) {
  2181             // Find environment in which identifier is defined.
  2182             while (symEnv.outer != null &&
  2183                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2184                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2185                     noOuterThisPath = !allowAnonOuterThis;
  2186                 symEnv = symEnv.outer;
  2190         // If symbol is a variable, ...
  2191         if (sym.kind == VAR) {
  2192             VarSymbol v = (VarSymbol)sym;
  2194             // ..., evaluate its initializer, if it has one, and check for
  2195             // illegal forward reference.
  2196             checkInit(tree, env, v, false);
  2198             // If symbol is a local variable accessed from an embedded
  2199             // inner class check that it is final.
  2200             if (v.owner.kind == MTH &&
  2201                 v.owner != env.info.scope.owner &&
  2202                 (v.flags_field & FINAL) == 0) {
  2203                 log.error(tree.pos(),
  2204                           "local.var.accessed.from.icls.needs.final",
  2205                           v);
  2208             // If we are expecting a variable (as opposed to a value), check
  2209             // that the variable is assignable in the current environment.
  2210             if (pkind == VAR)
  2211                 checkAssignable(tree.pos(), v, null, env);
  2214         // In a constructor body,
  2215         // if symbol is a field or instance method, check that it is
  2216         // not accessed before the supertype constructor is called.
  2217         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2218             (sym.kind & (VAR | MTH)) != 0 &&
  2219             sym.owner.kind == TYP &&
  2220             (sym.flags() & STATIC) == 0) {
  2221             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2223         Env<AttrContext> env1 = env;
  2224         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2225             // If the found symbol is inaccessible, then it is
  2226             // accessed through an enclosing instance.  Locate this
  2227             // enclosing instance:
  2228             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2229                 env1 = env1.outer;
  2231         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2234     public void visitSelect(JCFieldAccess tree) {
  2235         // Determine the expected kind of the qualifier expression.
  2236         int skind = 0;
  2237         if (tree.name == names._this || tree.name == names._super ||
  2238             tree.name == names._class)
  2240             skind = TYP;
  2241         } else {
  2242             if ((pkind & PCK) != 0) skind = skind | PCK;
  2243             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2244             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2247         // Attribute the qualifier expression, and determine its symbol (if any).
  2248         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2249         if ((pkind & (PCK | TYP)) == 0)
  2250             site = capture(site); // Capture field access
  2252         // don't allow T.class T[].class, etc
  2253         if (skind == TYP) {
  2254             Type elt = site;
  2255             while (elt.tag == ARRAY)
  2256                 elt = ((ArrayType)elt).elemtype;
  2257             if (elt.tag == TYPEVAR) {
  2258                 log.error(tree.pos(), "type.var.cant.be.deref");
  2259                 result = types.createErrorType(tree.type);
  2260                 return;
  2264         // If qualifier symbol is a type or `super', assert `selectSuper'
  2265         // for the selection. This is relevant for determining whether
  2266         // protected symbols are accessible.
  2267         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2268         boolean selectSuperPrev = env.info.selectSuper;
  2269         env.info.selectSuper =
  2270             sitesym != null &&
  2271             sitesym.name == names._super;
  2273         // If selected expression is polymorphic, strip
  2274         // type parameters and remember in env.info.tvars, so that
  2275         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2276         if (tree.selected.type.tag == FORALL) {
  2277             ForAll pstype = (ForAll)tree.selected.type;
  2278             env.info.tvars = pstype.tvars;
  2279             site = tree.selected.type = pstype.qtype;
  2282         // Determine the symbol represented by the selection.
  2283         env.info.varArgs = false;
  2284         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2285         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2286             site = capture(site);
  2287             sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2289         boolean varArgs = env.info.varArgs;
  2290         tree.sym = sym;
  2292         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2293             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2294             site = capture(site);
  2297         // If that symbol is a variable, ...
  2298         if (sym.kind == VAR) {
  2299             VarSymbol v = (VarSymbol)sym;
  2301             // ..., evaluate its initializer, if it has one, and check for
  2302             // illegal forward reference.
  2303             checkInit(tree, env, v, true);
  2305             // If we are expecting a variable (as opposed to a value), check
  2306             // that the variable is assignable in the current environment.
  2307             if (pkind == VAR)
  2308                 checkAssignable(tree.pos(), v, tree.selected, env);
  2311         if (sitesym != null &&
  2312                 sitesym.kind == VAR &&
  2313                 ((VarSymbol)sitesym).isResourceVariable() &&
  2314                 sym.kind == MTH &&
  2315                 sym.name.equals(names.close) &&
  2316                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2317                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2318             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2321         // Disallow selecting a type from an expression
  2322         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2323             tree.type = check(tree.selected, pt,
  2324                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2327         if (isType(sitesym)) {
  2328             if (sym.name == names._this) {
  2329                 // If `C' is the currently compiled class, check that
  2330                 // C.this' does not appear in a call to a super(...)
  2331                 if (env.info.isSelfCall &&
  2332                     site.tsym == env.enclClass.sym) {
  2333                     chk.earlyRefError(tree.pos(), sym);
  2335             } else {
  2336                 // Check if type-qualified fields or methods are static (JLS)
  2337                 if ((sym.flags() & STATIC) == 0 &&
  2338                     sym.name != names._super &&
  2339                     (sym.kind == VAR || sym.kind == MTH)) {
  2340                     rs.access(rs.new StaticError(sym),
  2341                               tree.pos(), site, sym.name, true);
  2344         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2345             // If the qualified item is not a type and the selected item is static, report
  2346             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2347             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2350         // If we are selecting an instance member via a `super', ...
  2351         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2353             // Check that super-qualified symbols are not abstract (JLS)
  2354             rs.checkNonAbstract(tree.pos(), sym);
  2356             if (site.isRaw()) {
  2357                 // Determine argument types for site.
  2358                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2359                 if (site1 != null) site = site1;
  2363         env.info.selectSuper = selectSuperPrev;
  2364         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2365         env.info.tvars = List.nil();
  2367     //where
  2368         /** Determine symbol referenced by a Select expression,
  2370          *  @param tree   The select tree.
  2371          *  @param site   The type of the selected expression,
  2372          *  @param env    The current environment.
  2373          *  @param pt     The current prototype.
  2374          *  @param pkind  The expected kind(s) of the Select expression.
  2375          */
  2376         private Symbol selectSym(JCFieldAccess tree,
  2377                                      Type site,
  2378                                      Env<AttrContext> env,
  2379                                      Type pt,
  2380                                      int pkind) {
  2381             return selectSym(tree, site.tsym, site, env, pt, pkind);
  2383         private Symbol selectSym(JCFieldAccess tree,
  2384                                  Symbol location,
  2385                                  Type site,
  2386                                  Env<AttrContext> env,
  2387                                  Type pt,
  2388                                  int pkind) {
  2389             DiagnosticPosition pos = tree.pos();
  2390             Name name = tree.name;
  2391             switch (site.tag) {
  2392             case PACKAGE:
  2393                 return rs.access(
  2394                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2395                     pos, location, site, name, true);
  2396             case ARRAY:
  2397             case CLASS:
  2398                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2399                     return rs.resolveQualifiedMethod(
  2400                         pos, env, location, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2401                 } else if (name == names._this || name == names._super) {
  2402                     return rs.resolveSelf(pos, env, site.tsym, name);
  2403                 } else if (name == names._class) {
  2404                     // In this case, we have already made sure in
  2405                     // visitSelect that qualifier expression is a type.
  2406                     Type t = syms.classType;
  2407                     List<Type> typeargs = allowGenerics
  2408                         ? List.of(types.erasure(site))
  2409                         : List.<Type>nil();
  2410                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2411                     return new VarSymbol(
  2412                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2413                 } else {
  2414                     // We are seeing a plain identifier as selector.
  2415                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2416                     if ((pkind & ERRONEOUS) == 0)
  2417                         sym = rs.access(sym, pos, location, site, name, true);
  2418                     return sym;
  2420             case WILDCARD:
  2421                 throw new AssertionError(tree);
  2422             case TYPEVAR:
  2423                 // Normally, site.getUpperBound() shouldn't be null.
  2424                 // It should only happen during memberEnter/attribBase
  2425                 // when determining the super type which *must* beac
  2426                 // done before attributing the type variables.  In
  2427                 // other words, we are seeing this illegal program:
  2428                 // class B<T> extends A<T.foo> {}
  2429                 Symbol sym = (site.getUpperBound() != null)
  2430                     ? selectSym(tree, location, capture(site.getUpperBound()), env, pt, pkind)
  2431                     : null;
  2432                 if (sym == null) {
  2433                     log.error(pos, "type.var.cant.be.deref");
  2434                     return syms.errSymbol;
  2435                 } else {
  2436                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2437                         rs.new AccessError(env, site, sym) :
  2438                                 sym;
  2439                     rs.access(sym2, pos, location, site, name, true);
  2440                     return sym;
  2442             case ERROR:
  2443                 // preserve identifier names through errors
  2444                 return types.createErrorType(name, site.tsym, site).tsym;
  2445             default:
  2446                 // The qualifier expression is of a primitive type -- only
  2447                 // .class is allowed for these.
  2448                 if (name == names._class) {
  2449                     // In this case, we have already made sure in Select that
  2450                     // qualifier expression is a type.
  2451                     Type t = syms.classType;
  2452                     Type arg = types.boxedClass(site).type;
  2453                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2454                     return new VarSymbol(
  2455                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2456                 } else {
  2457                     log.error(pos, "cant.deref", site);
  2458                     return syms.errSymbol;
  2463         /** Determine type of identifier or select expression and check that
  2464          *  (1) the referenced symbol is not deprecated
  2465          *  (2) the symbol's type is safe (@see checkSafe)
  2466          *  (3) if symbol is a variable, check that its type and kind are
  2467          *      compatible with the prototype and protokind.
  2468          *  (4) if symbol is an instance field of a raw type,
  2469          *      which is being assigned to, issue an unchecked warning if its
  2470          *      type changes under erasure.
  2471          *  (5) if symbol is an instance method of a raw type, issue an
  2472          *      unchecked warning if its argument types change under erasure.
  2473          *  If checks succeed:
  2474          *    If symbol is a constant, return its constant type
  2475          *    else if symbol is a method, return its result type
  2476          *    otherwise return its type.
  2477          *  Otherwise return errType.
  2479          *  @param tree       The syntax tree representing the identifier
  2480          *  @param site       If this is a select, the type of the selected
  2481          *                    expression, otherwise the type of the current class.
  2482          *  @param sym        The symbol representing the identifier.
  2483          *  @param env        The current environment.
  2484          *  @param pkind      The set of expected kinds.
  2485          *  @param pt         The expected type.
  2486          */
  2487         Type checkId(JCTree tree,
  2488                      Type site,
  2489                      Symbol sym,
  2490                      Env<AttrContext> env,
  2491                      int pkind,
  2492                      Type pt,
  2493                      boolean useVarargs) {
  2494             if (pt.isErroneous()) return types.createErrorType(site);
  2495             Type owntype; // The computed type of this identifier occurrence.
  2496             switch (sym.kind) {
  2497             case TYP:
  2498                 // For types, the computed type equals the symbol's type,
  2499                 // except for two situations:
  2500                 owntype = sym.type;
  2501                 if (owntype.tag == CLASS) {
  2502                     Type ownOuter = owntype.getEnclosingType();
  2504                     // (a) If the symbol's type is parameterized, erase it
  2505                     // because no type parameters were given.
  2506                     // We recover generic outer type later in visitTypeApply.
  2507                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2508                         owntype = types.erasure(owntype);
  2511                     // (b) If the symbol's type is an inner class, then
  2512                     // we have to interpret its outer type as a superclass
  2513                     // of the site type. Example:
  2514                     //
  2515                     // class Tree<A> { class Visitor { ... } }
  2516                     // class PointTree extends Tree<Point> { ... }
  2517                     // ...PointTree.Visitor...
  2518                     //
  2519                     // Then the type of the last expression above is
  2520                     // Tree<Point>.Visitor.
  2521                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2522                         Type normOuter = site;
  2523                         if (normOuter.tag == CLASS)
  2524                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2525                         if (normOuter == null) // perhaps from an import
  2526                             normOuter = types.erasure(ownOuter);
  2527                         if (normOuter != ownOuter)
  2528                             owntype = new ClassType(
  2529                                 normOuter, List.<Type>nil(), owntype.tsym);
  2532                 break;
  2533             case VAR:
  2534                 VarSymbol v = (VarSymbol)sym;
  2535                 // Test (4): if symbol is an instance field of a raw type,
  2536                 // which is being assigned to, issue an unchecked warning if
  2537                 // its type changes under erasure.
  2538                 if (allowGenerics &&
  2539                     pkind == VAR &&
  2540                     v.owner.kind == TYP &&
  2541                     (v.flags() & STATIC) == 0 &&
  2542                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2543                     Type s = types.asOuterSuper(site, v.owner);
  2544                     if (s != null &&
  2545                         s.isRaw() &&
  2546                         !types.isSameType(v.type, v.erasure(types))) {
  2547                         chk.warnUnchecked(tree.pos(),
  2548                                           "unchecked.assign.to.var",
  2549                                           v, s);
  2552                 // The computed type of a variable is the type of the
  2553                 // variable symbol, taken as a member of the site type.
  2554                 owntype = (sym.owner.kind == TYP &&
  2555                            sym.name != names._this && sym.name != names._super)
  2556                     ? types.memberType(site, sym)
  2557                     : sym.type;
  2559                 if (env.info.tvars.nonEmpty()) {
  2560                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2561                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2562                         if (!owntype.contains(l.head)) {
  2563                             log.error(tree.pos(), "undetermined.type", owntype1);
  2564                             owntype1 = types.createErrorType(owntype1);
  2566                     owntype = owntype1;
  2569                 // If the variable is a constant, record constant value in
  2570                 // computed type.
  2571                 if (v.getConstValue() != null && isStaticReference(tree))
  2572                     owntype = owntype.constType(v.getConstValue());
  2574                 if (pkind == VAL) {
  2575                     owntype = capture(owntype); // capture "names as expressions"
  2577                 break;
  2578             case MTH: {
  2579                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2580                 owntype = checkMethod(site, sym, env, app.args,
  2581                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2582                                       env.info.varArgs);
  2583                 break;
  2585             case PCK: case ERR:
  2586                 owntype = sym.type;
  2587                 break;
  2588             default:
  2589                 throw new AssertionError("unexpected kind: " + sym.kind +
  2590                                          " in tree " + tree);
  2593             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2594             // (for constructors, the error was given when the constructor was
  2595             // resolved)
  2597             if (sym.name != names.init) {
  2598                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  2599                 chk.checkSunAPI(tree.pos(), sym);
  2602             // Test (3): if symbol is a variable, check that its type and
  2603             // kind are compatible with the prototype and protokind.
  2604             return check(tree, owntype, sym.kind, pkind, pt);
  2607         /** Check that variable is initialized and evaluate the variable's
  2608          *  initializer, if not yet done. Also check that variable is not
  2609          *  referenced before it is defined.
  2610          *  @param tree    The tree making up the variable reference.
  2611          *  @param env     The current environment.
  2612          *  @param v       The variable's symbol.
  2613          */
  2614         private void checkInit(JCTree tree,
  2615                                Env<AttrContext> env,
  2616                                VarSymbol v,
  2617                                boolean onlyWarning) {
  2618 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2619 //                             tree.pos + " " + v.pos + " " +
  2620 //                             Resolve.isStatic(env));//DEBUG
  2622             // A forward reference is diagnosed if the declaration position
  2623             // of the variable is greater than the current tree position
  2624             // and the tree and variable definition occur in the same class
  2625             // definition.  Note that writes don't count as references.
  2626             // This check applies only to class and instance
  2627             // variables.  Local variables follow different scope rules,
  2628             // and are subject to definite assignment checking.
  2629             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2630                 v.owner.kind == TYP &&
  2631                 canOwnInitializer(env.info.scope.owner) &&
  2632                 v.owner == env.info.scope.owner.enclClass() &&
  2633                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2634                 (!env.tree.hasTag(ASSIGN) ||
  2635                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2636                 String suffix = (env.info.enclVar == v) ?
  2637                                 "self.ref" : "forward.ref";
  2638                 if (!onlyWarning || isStaticEnumField(v)) {
  2639                     log.error(tree.pos(), "illegal." + suffix);
  2640                 } else if (useBeforeDeclarationWarning) {
  2641                     log.warning(tree.pos(), suffix, v);
  2645             v.getConstValue(); // ensure initializer is evaluated
  2647             checkEnumInitializer(tree, env, v);
  2650         /**
  2651          * Check for illegal references to static members of enum.  In
  2652          * an enum type, constructors and initializers may not
  2653          * reference its static members unless they are constant.
  2655          * @param tree    The tree making up the variable reference.
  2656          * @param env     The current environment.
  2657          * @param v       The variable's symbol.
  2658          * @jls  section 8.9 Enums
  2659          */
  2660         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2661             // JLS:
  2662             //
  2663             // "It is a compile-time error to reference a static field
  2664             // of an enum type that is not a compile-time constant
  2665             // (15.28) from constructors, instance initializer blocks,
  2666             // or instance variable initializer expressions of that
  2667             // type. It is a compile-time error for the constructors,
  2668             // instance initializer blocks, or instance variable
  2669             // initializer expressions of an enum constant e to refer
  2670             // to itself or to an enum constant of the same type that
  2671             // is declared to the right of e."
  2672             if (isStaticEnumField(v)) {
  2673                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2675                 if (enclClass == null || enclClass.owner == null)
  2676                     return;
  2678                 // See if the enclosing class is the enum (or a
  2679                 // subclass thereof) declaring v.  If not, this
  2680                 // reference is OK.
  2681                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2682                     return;
  2684                 // If the reference isn't from an initializer, then
  2685                 // the reference is OK.
  2686                 if (!Resolve.isInitializer(env))
  2687                     return;
  2689                 log.error(tree.pos(), "illegal.enum.static.ref");
  2693         /** Is the given symbol a static, non-constant field of an Enum?
  2694          *  Note: enum literals should not be regarded as such
  2695          */
  2696         private boolean isStaticEnumField(VarSymbol v) {
  2697             return Flags.isEnum(v.owner) &&
  2698                    Flags.isStatic(v) &&
  2699                    !Flags.isConstant(v) &&
  2700                    v.name != names._class;
  2703         /** Can the given symbol be the owner of code which forms part
  2704          *  if class initialization? This is the case if the symbol is
  2705          *  a type or field, or if the symbol is the synthetic method.
  2706          *  owning a block.
  2707          */
  2708         private boolean canOwnInitializer(Symbol sym) {
  2709             return
  2710                 (sym.kind & (VAR | TYP)) != 0 ||
  2711                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2714     Warner noteWarner = new Warner();
  2716     /**
  2717      * Check that method arguments conform to its instantation.
  2718      **/
  2719     public Type checkMethod(Type site,
  2720                             Symbol sym,
  2721                             Env<AttrContext> env,
  2722                             final List<JCExpression> argtrees,
  2723                             List<Type> argtypes,
  2724                             List<Type> typeargtypes,
  2725                             boolean useVarargs) {
  2726         // Test (5): if symbol is an instance method of a raw type, issue
  2727         // an unchecked warning if its argument types change under erasure.
  2728         if (allowGenerics &&
  2729             (sym.flags() & STATIC) == 0 &&
  2730             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2731             Type s = types.asOuterSuper(site, sym.owner);
  2732             if (s != null && s.isRaw() &&
  2733                 !types.isSameTypes(sym.type.getParameterTypes(),
  2734                                    sym.erasure(types).getParameterTypes())) {
  2735                 chk.warnUnchecked(env.tree.pos(),
  2736                                   "unchecked.call.mbr.of.raw.type",
  2737                                   sym, s);
  2741         // Compute the identifier's instantiated type.
  2742         // For methods, we need to compute the instance type by
  2743         // Resolve.instantiate from the symbol's type as well as
  2744         // any type arguments and value arguments.
  2745         noteWarner.clear();
  2746         Type owntype = rs.instantiate(env,
  2747                                       site,
  2748                                       sym,
  2749                                       argtypes,
  2750                                       typeargtypes,
  2751                                       true,
  2752                                       useVarargs,
  2753                                       noteWarner);
  2754         boolean warned = noteWarner.hasNonSilentLint(LintCategory.UNCHECKED);
  2756         // If this fails, something went wrong; we should not have
  2757         // found the identifier in the first place.
  2758         if (owntype == null) {
  2759             if (!pt.isErroneous())
  2760                 log.error(env.tree.pos(),
  2761                           "internal.error.cant.instantiate",
  2762                           sym, site,
  2763                           Type.toString(pt.getParameterTypes()));
  2764             owntype = types.createErrorType(site);
  2765         } else {
  2766             // System.out.println("call   : " + env.tree);
  2767             // System.out.println("method : " + owntype);
  2768             // System.out.println("actuals: " + argtypes);
  2769             List<Type> formals = owntype.getParameterTypes();
  2770             Type last = useVarargs ? formals.last() : null;
  2771             if (sym.name==names.init &&
  2772                 sym.owner == syms.enumSym)
  2773                 formals = formals.tail.tail;
  2774             List<JCExpression> args = argtrees;
  2775             while (formals.head != last) {
  2776                 JCTree arg = args.head;
  2777                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2778                 assertConvertible(arg, arg.type, formals.head, warn);
  2779                 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2780                 args = args.tail;
  2781                 formals = formals.tail;
  2783             if (useVarargs) {
  2784                 Type varArg = types.elemtype(last);
  2785                 while (args.tail != null) {
  2786                     JCTree arg = args.head;
  2787                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2788                     assertConvertible(arg, arg.type, varArg, warn);
  2789                     warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2790                     args = args.tail;
  2792             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2793                 // non-varargs call to varargs method
  2794                 Type varParam = owntype.getParameterTypes().last();
  2795                 Type lastArg = argtypes.last();
  2796                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2797                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2798                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2799                                 types.elemtype(varParam),
  2800                                 varParam);
  2803             if (warned && sym.type.tag == FORALL) {
  2804                 chk.warnUnchecked(env.tree.pos(),
  2805                                   "unchecked.meth.invocation.applied",
  2806                                   kindName(sym),
  2807                                   sym.name,
  2808                                   rs.methodArguments(sym.type.getParameterTypes()),
  2809                                   rs.methodArguments(argtypes),
  2810                                   kindName(sym.location()),
  2811                                   sym.location());
  2812                 owntype = new MethodType(owntype.getParameterTypes(),
  2813                                          types.erasure(owntype.getReturnType()),
  2814                                          types.erasure(owntype.getThrownTypes()),
  2815                                          syms.methodClass);
  2817             if (useVarargs) {
  2818                 JCTree tree = env.tree;
  2819                 Type argtype = owntype.getParameterTypes().last();
  2820                 if (owntype.getReturnType().tag != FORALL || warned) {
  2821                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym);
  2823                 Type elemtype = types.elemtype(argtype);
  2824                 switch (tree.getTag()) {
  2825                 case APPLY:
  2826                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2827                     break;
  2828                 case NEWCLASS:
  2829                     ((JCNewClass) tree).varargsElement = elemtype;
  2830                     break;
  2831                 default:
  2832                     throw new AssertionError(""+tree);
  2836         return owntype;
  2839     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2840         if (types.isConvertible(actual, formal, warn))
  2841             return;
  2843         if (formal.isCompound()
  2844             && types.isSubtype(actual, types.supertype(formal))
  2845             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2846             return;
  2848         if (false) {
  2849             // TODO: make assertConvertible work
  2850             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2851             throw new AssertionError("Tree: " + tree
  2852                                      + " actual:" + actual
  2853                                      + " formal: " + formal);
  2857     public void visitLiteral(JCLiteral tree) {
  2858         result = check(
  2859             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2861     //where
  2862     /** Return the type of a literal with given type tag.
  2863      */
  2864     Type litType(int tag) {
  2865         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2868     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2869         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2872     public void visitTypeArray(JCArrayTypeTree tree) {
  2873         Type etype = attribType(tree.elemtype, env);
  2874         Type type = new ArrayType(etype, syms.arrayClass);
  2875         result = check(tree, type, TYP, pkind, pt);
  2878     /** Visitor method for parameterized types.
  2879      *  Bound checking is left until later, since types are attributed
  2880      *  before supertype structure is completely known
  2881      */
  2882     public void visitTypeApply(JCTypeApply tree) {
  2883         Type owntype = types.createErrorType(tree.type);
  2885         // Attribute functor part of application and make sure it's a class.
  2886         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2888         // Attribute type parameters
  2889         List<Type> actuals = attribTypes(tree.arguments, env);
  2891         if (clazztype.tag == CLASS) {
  2892             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2893             if (actuals.isEmpty()) //diamond
  2894                 actuals = formals;
  2896             if (actuals.length() == formals.length()) {
  2897                 List<Type> a = actuals;
  2898                 List<Type> f = formals;
  2899                 while (a.nonEmpty()) {
  2900                     a.head = a.head.withTypeVar(f.head);
  2901                     a = a.tail;
  2902                     f = f.tail;
  2904                 // Compute the proper generic outer
  2905                 Type clazzOuter = clazztype.getEnclosingType();
  2906                 if (clazzOuter.tag == CLASS) {
  2907                     Type site;
  2908                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2909                     if (clazz.hasTag(IDENT)) {
  2910                         site = env.enclClass.sym.type;
  2911                     } else if (clazz.hasTag(SELECT)) {
  2912                         site = ((JCFieldAccess) clazz).selected.type;
  2913                     } else throw new AssertionError(""+tree);
  2914                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2915                         if (site.tag == CLASS)
  2916                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2917                         if (site == null)
  2918                             site = types.erasure(clazzOuter);
  2919                         clazzOuter = site;
  2922                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2923             } else {
  2924                 if (formals.length() != 0) {
  2925                     log.error(tree.pos(), "wrong.number.type.args",
  2926                               Integer.toString(formals.length()));
  2927                 } else {
  2928                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2930                 owntype = types.createErrorType(tree.type);
  2933         result = check(tree, owntype, TYP, pkind, pt);
  2936     public void visitTypeUnion(JCTypeUnion tree) {
  2937         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2938         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  2939         for (JCExpression typeTree : tree.alternatives) {
  2940             Type ctype = attribType(typeTree, env);
  2941             ctype = chk.checkType(typeTree.pos(),
  2942                           chk.checkClassType(typeTree.pos(), ctype),
  2943                           syms.throwableType);
  2944             if (!ctype.isErroneous()) {
  2945                 //check that alternatives of a union type are pairwise
  2946                 //unrelated w.r.t. subtyping
  2947                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  2948                     for (Type t : multicatchTypes) {
  2949                         boolean sub = types.isSubtype(ctype, t);
  2950                         boolean sup = types.isSubtype(t, ctype);
  2951                         if (sub || sup) {
  2952                             //assume 'a' <: 'b'
  2953                             Type a = sub ? ctype : t;
  2954                             Type b = sub ? t : ctype;
  2955                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  2959                 multicatchTypes.append(ctype);
  2960                 if (all_multicatchTypes != null)
  2961                     all_multicatchTypes.append(ctype);
  2962             } else {
  2963                 if (all_multicatchTypes == null) {
  2964                     all_multicatchTypes = ListBuffer.lb();
  2965                     all_multicatchTypes.appendList(multicatchTypes);
  2967                 all_multicatchTypes.append(ctype);
  2970         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2971         if (t.tag == CLASS) {
  2972             List<Type> alternatives =
  2973                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  2974             t = new UnionClassType((ClassType) t, alternatives);
  2976         tree.type = result = t;
  2979     public void visitTypeParameter(JCTypeParameter tree) {
  2980         TypeVar a = (TypeVar)tree.type;
  2981         Set<Type> boundSet = new HashSet<Type>();
  2982         if (a.bound.isErroneous())
  2983             return;
  2984         List<Type> bs = types.getBounds(a);
  2985         if (tree.bounds.nonEmpty()) {
  2986             // accept class or interface or typevar as first bound.
  2987             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2988             boundSet.add(types.erasure(b));
  2989             if (b.isErroneous()) {
  2990                 a.bound = b;
  2992             else if (b.tag == TYPEVAR) {
  2993                 // if first bound was a typevar, do not accept further bounds.
  2994                 if (tree.bounds.tail.nonEmpty()) {
  2995                     log.error(tree.bounds.tail.head.pos(),
  2996                               "type.var.may.not.be.followed.by.other.bounds");
  2997                     tree.bounds = List.of(tree.bounds.head);
  2998                     a.bound = bs.head;
  3000             } else {
  3001                 // if first bound was a class or interface, accept only interfaces
  3002                 // as further bounds.
  3003                 for (JCExpression bound : tree.bounds.tail) {
  3004                     bs = bs.tail;
  3005                     Type i = checkBase(bs.head, bound, env, false, true, false);
  3006                     if (i.isErroneous())
  3007                         a.bound = i;
  3008                     else if (i.tag == CLASS)
  3009                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  3013         bs = types.getBounds(a);
  3015         // in case of multiple bounds ...
  3016         if (bs.length() > 1) {
  3017             // ... the variable's bound is a class type flagged COMPOUND
  3018             // (see comment for TypeVar.bound).
  3019             // In this case, generate a class tree that represents the
  3020             // bound class, ...
  3021             JCExpression extending;
  3022             List<JCExpression> implementing;
  3023             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  3024                 extending = tree.bounds.head;
  3025                 implementing = tree.bounds.tail;
  3026             } else {
  3027                 extending = null;
  3028                 implementing = tree.bounds;
  3030             JCClassDecl cd = make.at(tree.pos).ClassDef(
  3031                 make.Modifiers(PUBLIC | ABSTRACT),
  3032                 tree.name, List.<JCTypeParameter>nil(),
  3033                 extending, implementing, List.<JCTree>nil());
  3035             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  3036             Assert.check((c.flags() & COMPOUND) != 0);
  3037             cd.sym = c;
  3038             c.sourcefile = env.toplevel.sourcefile;
  3040             // ... and attribute the bound class
  3041             c.flags_field |= UNATTRIBUTED;
  3042             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3043             enter.typeEnvs.put(c, cenv);
  3048     public void visitWildcard(JCWildcard tree) {
  3049         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3050         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3051             ? syms.objectType
  3052             : attribType(tree.inner, env);
  3053         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3054                                               tree.kind.kind,
  3055                                               syms.boundClass),
  3056                        TYP, pkind, pt);
  3059     public void visitAnnotation(JCAnnotation tree) {
  3060         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  3061         result = tree.type = syms.errType;
  3064     public void visitErroneous(JCErroneous tree) {
  3065         if (tree.errs != null)
  3066             for (JCTree err : tree.errs)
  3067                 attribTree(err, env, ERR, pt);
  3068         result = tree.type = syms.errType;
  3071     /** Default visitor method for all other trees.
  3072      */
  3073     public void visitTree(JCTree tree) {
  3074         throw new AssertionError();
  3077     /**
  3078      * Attribute an env for either a top level tree or class declaration.
  3079      */
  3080     public void attrib(Env<AttrContext> env) {
  3081         if (env.tree.hasTag(TOPLEVEL))
  3082             attribTopLevel(env);
  3083         else
  3084             attribClass(env.tree.pos(), env.enclClass.sym);
  3087     /**
  3088      * Attribute a top level tree. These trees are encountered when the
  3089      * package declaration has annotations.
  3090      */
  3091     public void attribTopLevel(Env<AttrContext> env) {
  3092         JCCompilationUnit toplevel = env.toplevel;
  3093         try {
  3094             annotate.flush();
  3095             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  3096         } catch (CompletionFailure ex) {
  3097             chk.completionError(toplevel.pos(), ex);
  3101     /** Main method: attribute class definition associated with given class symbol.
  3102      *  reporting completion failures at the given position.
  3103      *  @param pos The source position at which completion errors are to be
  3104      *             reported.
  3105      *  @param c   The class symbol whose definition will be attributed.
  3106      */
  3107     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3108         try {
  3109             annotate.flush();
  3110             attribClass(c);
  3111         } catch (CompletionFailure ex) {
  3112             chk.completionError(pos, ex);
  3116     /** Attribute class definition associated with given class symbol.
  3117      *  @param c   The class symbol whose definition will be attributed.
  3118      */
  3119     void attribClass(ClassSymbol c) throws CompletionFailure {
  3120         if (c.type.tag == ERROR) return;
  3122         // Check for cycles in the inheritance graph, which can arise from
  3123         // ill-formed class files.
  3124         chk.checkNonCyclic(null, c.type);
  3126         Type st = types.supertype(c.type);
  3127         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3128             // First, attribute superclass.
  3129             if (st.tag == CLASS)
  3130                 attribClass((ClassSymbol)st.tsym);
  3132             // Next attribute owner, if it is a class.
  3133             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3134                 attribClass((ClassSymbol)c.owner);
  3137         // The previous operations might have attributed the current class
  3138         // if there was a cycle. So we test first whether the class is still
  3139         // UNATTRIBUTED.
  3140         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3141             c.flags_field &= ~UNATTRIBUTED;
  3143             // Get environment current at the point of class definition.
  3144             Env<AttrContext> env = enter.typeEnvs.get(c);
  3146             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3147             // because the annotations were not available at the time the env was created. Therefore,
  3148             // we look up the environment chain for the first enclosing environment for which the
  3149             // lint value is set. Typically, this is the parent env, but might be further if there
  3150             // are any envs created as a result of TypeParameter nodes.
  3151             Env<AttrContext> lintEnv = env;
  3152             while (lintEnv.info.lint == null)
  3153                 lintEnv = lintEnv.next;
  3155             // Having found the enclosing lint value, we can initialize the lint value for this class
  3156             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3158             Lint prevLint = chk.setLint(env.info.lint);
  3159             JavaFileObject prev = log.useSource(c.sourcefile);
  3161             try {
  3162                 // java.lang.Enum may not be subclassed by a non-enum
  3163                 if (st.tsym == syms.enumSym &&
  3164                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3165                     log.error(env.tree.pos(), "enum.no.subclassing");
  3167                 // Enums may not be extended by source-level classes
  3168                 if (st.tsym != null &&
  3169                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3170                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3171                     !target.compilerBootstrap(c)) {
  3172                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3174                 attribClassBody(env, c);
  3176                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3177             } finally {
  3178                 log.useSource(prev);
  3179                 chk.setLint(prevLint);
  3185     public void visitImport(JCImport tree) {
  3186         // nothing to do
  3189     /** Finish the attribution of a class. */
  3190     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3191         JCClassDecl tree = (JCClassDecl)env.tree;
  3192         Assert.check(c == tree.sym);
  3194         // Validate annotations
  3195         chk.validateAnnotations(tree.mods.annotations, c);
  3197         // Validate type parameters, supertype and interfaces.
  3198         attribBounds(tree.typarams);
  3199         if (!c.isAnonymous()) {
  3200             //already checked if anonymous
  3201             chk.validate(tree.typarams, env);
  3202             chk.validate(tree.extending, env);
  3203             chk.validate(tree.implementing, env);
  3206         // If this is a non-abstract class, check that it has no abstract
  3207         // methods or unimplemented methods of an implemented interface.
  3208         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3209             if (!relax)
  3210                 chk.checkAllDefined(tree.pos(), c);
  3213         if ((c.flags() & ANNOTATION) != 0) {
  3214             if (tree.implementing.nonEmpty())
  3215                 log.error(tree.implementing.head.pos(),
  3216                           "cant.extend.intf.annotation");
  3217             if (tree.typarams.nonEmpty())
  3218                 log.error(tree.typarams.head.pos(),
  3219                           "intf.annotation.cant.have.type.params");
  3220         } else {
  3221             // Check that all extended classes and interfaces
  3222             // are compatible (i.e. no two define methods with same arguments
  3223             // yet different return types).  (JLS 8.4.6.3)
  3224             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3227         // Check that class does not import the same parameterized interface
  3228         // with two different argument lists.
  3229         chk.checkClassBounds(tree.pos(), c.type);
  3231         tree.type = c.type;
  3233         for (List<JCTypeParameter> l = tree.typarams;
  3234              l.nonEmpty(); l = l.tail) {
  3235              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3238         // Check that a generic class doesn't extend Throwable
  3239         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3240             log.error(tree.extending.pos(), "generic.throwable");
  3242         // Check that all methods which implement some
  3243         // method conform to the method they implement.
  3244         chk.checkImplementations(tree);
  3246         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  3247         checkAutoCloseable(tree.pos(), env, c.type);
  3249         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3250             // Attribute declaration
  3251             attribStat(l.head, env);
  3252             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3253             // Make an exception for static constants.
  3254             if (c.owner.kind != PCK &&
  3255                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3256                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3257                 Symbol sym = null;
  3258                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  3259                 if (sym == null ||
  3260                     sym.kind != VAR ||
  3261                     ((VarSymbol) sym).getConstValue() == null)
  3262                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3266         // Check for cycles among non-initial constructors.
  3267         chk.checkCyclicConstructors(tree);
  3269         // Check for cycles among annotation elements.
  3270         chk.checkNonCyclicElements(tree);
  3272         // Check for proper use of serialVersionUID
  3273         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3274             isSerializable(c) &&
  3275             (c.flags() & Flags.ENUM) == 0 &&
  3276             (c.flags() & ABSTRACT) == 0) {
  3277             checkSerialVersionUID(tree, c);
  3280         // where
  3281         /** check if a class is a subtype of Serializable, if that is available. */
  3282         private boolean isSerializable(ClassSymbol c) {
  3283             try {
  3284                 syms.serializableType.complete();
  3286             catch (CompletionFailure e) {
  3287                 return false;
  3289             return types.isSubtype(c.type, syms.serializableType);
  3292         /** Check that an appropriate serialVersionUID member is defined. */
  3293         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3295             // check for presence of serialVersionUID
  3296             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3297             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3298             if (e.scope == null) {
  3299                 log.warning(LintCategory.SERIAL,
  3300                         tree.pos(), "missing.SVUID", c);
  3301                 return;
  3304             // check that it is static final
  3305             VarSymbol svuid = (VarSymbol)e.sym;
  3306             if ((svuid.flags() & (STATIC | FINAL)) !=
  3307                 (STATIC | FINAL))
  3308                 log.warning(LintCategory.SERIAL,
  3309                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3311             // check that it is long
  3312             else if (svuid.type.tag != TypeTags.LONG)
  3313                 log.warning(LintCategory.SERIAL,
  3314                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3316             // check constant
  3317             else if (svuid.getConstValue() == null)
  3318                 log.warning(LintCategory.SERIAL,
  3319                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3322     private Type capture(Type type) {
  3323         return types.capture(type);
  3326     // <editor-fold desc="post-attribution visitor">
  3328     /**
  3329      * Handle missing types/symbols in an AST. This routine is useful when
  3330      * the compiler has encountered some errors (which might have ended up
  3331      * terminating attribution abruptly); if the compiler is used in fail-over
  3332      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3333      * prevents NPE to be progagated during subsequent compilation steps.
  3334      */
  3335     public void postAttr(Env<AttrContext> env) {
  3336         new PostAttrAnalyzer().scan(env.tree);
  3339     class PostAttrAnalyzer extends TreeScanner {
  3341         private void initTypeIfNeeded(JCTree that) {
  3342             if (that.type == null) {
  3343                 that.type = syms.unknownType;
  3347         @Override
  3348         public void scan(JCTree tree) {
  3349             if (tree == null) return;
  3350             if (tree instanceof JCExpression) {
  3351                 initTypeIfNeeded(tree);
  3353             super.scan(tree);
  3356         @Override
  3357         public void visitIdent(JCIdent that) {
  3358             if (that.sym == null) {
  3359                 that.sym = syms.unknownSymbol;
  3363         @Override
  3364         public void visitSelect(JCFieldAccess that) {
  3365             if (that.sym == null) {
  3366                 that.sym = syms.unknownSymbol;
  3368             super.visitSelect(that);
  3371         @Override
  3372         public void visitClassDef(JCClassDecl that) {
  3373             initTypeIfNeeded(that);
  3374             if (that.sym == null) {
  3375                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3377             super.visitClassDef(that);
  3380         @Override
  3381         public void visitMethodDef(JCMethodDecl that) {
  3382             initTypeIfNeeded(that);
  3383             if (that.sym == null) {
  3384                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3386             super.visitMethodDef(that);
  3389         @Override
  3390         public void visitVarDef(JCVariableDecl that) {
  3391             initTypeIfNeeded(that);
  3392             if (that.sym == null) {
  3393                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3394                 that.sym.adr = 0;
  3396             super.visitVarDef(that);
  3399         @Override
  3400         public void visitNewClass(JCNewClass that) {
  3401             if (that.constructor == null) {
  3402                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3404             if (that.constructorType == null) {
  3405                 that.constructorType = syms.unknownType;
  3407             super.visitNewClass(that);
  3410         @Override
  3411         public void visitAssignop(JCAssignOp that) {
  3412             if (that.operator == null)
  3413                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3414             super.visitAssignop(that);
  3417         @Override
  3418         public void visitBinary(JCBinary that) {
  3419             if (that.operator == null)
  3420                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3421             super.visitBinary(that);
  3424         @Override
  3425         public void visitUnary(JCUnary that) {
  3426             if (that.operator == null)
  3427                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3428             super.visitUnary(that);
  3431     // </editor-fold>

mercurial