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

Mon, 24 Jan 2011 15:45:06 +0000

author
mcimadamore
date
Mon, 24 Jan 2011 15:45:06 +0000
changeset 830
02e6e7dd1a64
parent 829
ce6175cfe11e
child 841
df371fd16386
permissions
-rw-r--r--

6510286: Wording of javac error for inner classes
Summary: 'inner classes cannot have static declarations' message needs to be reworked
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.jvm.Target;
    41 import com.sun.tools.javac.code.Lint.LintCategory;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.tree.JCTree.*;
    44 import com.sun.tools.javac.code.Type.*;
    46 import com.sun.source.tree.IdentifierTree;
    47 import com.sun.source.tree.MemberSelectTree;
    48 import com.sun.source.tree.TreeVisitor;
    49 import com.sun.source.util.SimpleTreeVisitor;
    51 import static com.sun.tools.javac.code.Flags.*;
    52 import static com.sun.tools.javac.code.Kinds.*;
    53 import static com.sun.tools.javac.code.TypeTags.*;
    55 /** This is the main context-dependent analysis phase in GJC. It
    56  *  encompasses name resolution, type checking and constant folding as
    57  *  subtasks. Some subtasks involve auxiliary classes.
    58  *  @see Check
    59  *  @see Resolve
    60  *  @see ConstFold
    61  *  @see Infer
    62  *
    63  *  <p><b>This is NOT part of any supported API.
    64  *  If you write code that depends on this, you do so at your own risk.
    65  *  This code and its internal interfaces are subject to change or
    66  *  deletion without notice.</b>
    67  */
    68 public class Attr extends JCTree.Visitor {
    69     protected static final Context.Key<Attr> attrKey =
    70         new Context.Key<Attr>();
    72     final Names names;
    73     final Log log;
    74     final Symtab syms;
    75     final Resolve rs;
    76     final Infer infer;
    77     final Check chk;
    78     final MemberEnter memberEnter;
    79     final TreeMaker make;
    80     final ConstFold cfolder;
    81     final Enter enter;
    82     final Target target;
    83     final Types types;
    84     final JCDiagnostic.Factory diags;
    85     final Annotate annotate;
    87     public static Attr instance(Context context) {
    88         Attr instance = context.get(attrKey);
    89         if (instance == null)
    90             instance = new Attr(context);
    91         return instance;
    92     }
    94     protected Attr(Context context) {
    95         context.put(attrKey, this);
    97         names = Names.instance(context);
    98         log = Log.instance(context);
    99         syms = Symtab.instance(context);
   100         rs = Resolve.instance(context);
   101         chk = Check.instance(context);
   102         memberEnter = MemberEnter.instance(context);
   103         make = TreeMaker.instance(context);
   104         enter = Enter.instance(context);
   105         infer = Infer.instance(context);
   106         cfolder = ConstFold.instance(context);
   107         target = Target.instance(context);
   108         types = Types.instance(context);
   109         diags = JCDiagnostic.Factory.instance(context);
   110         annotate = Annotate.instance(context);
   112         Options options = Options.instance(context);
   114         Source source = Source.instance(context);
   115         allowGenerics = source.allowGenerics();
   116         allowVarargs = source.allowVarargs();
   117         allowEnums = source.allowEnums();
   118         allowBoxing = source.allowBoxing();
   119         allowCovariantReturns = source.allowCovariantReturns();
   120         allowAnonOuterThis = source.allowAnonOuterThis();
   121         allowStringsInSwitch = source.allowStringsInSwitch();
   122         sourceName = source.name;
   123         relax = (options.isSet("-retrofit") ||
   124                  options.isSet("-relax"));
   125         findDiamonds = options.get("findDiamond") != null &&
   126                  source.allowDiamond();
   127         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   128         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   129     }
   131     /** Switch: relax some constraints for retrofit mode.
   132      */
   133     boolean relax;
   135     /** Switch: support generics?
   136      */
   137     boolean allowGenerics;
   139     /** Switch: allow variable-arity methods.
   140      */
   141     boolean allowVarargs;
   143     /** Switch: support enums?
   144      */
   145     boolean allowEnums;
   147     /** Switch: support boxing and unboxing?
   148      */
   149     boolean allowBoxing;
   151     /** Switch: support covariant result types?
   152      */
   153     boolean allowCovariantReturns;
   155     /** Switch: allow references to surrounding object from anonymous
   156      * objects during constructor call?
   157      */
   158     boolean allowAnonOuterThis;
   160     /** Switch: generates a warning if diamond can be safely applied
   161      *  to a given new expression
   162      */
   163     boolean findDiamonds;
   165     /**
   166      * Internally enables/disables diamond finder feature
   167      */
   168     static final boolean allowDiamondFinder = true;
   170     /**
   171      * Switch: warn about use of variable before declaration?
   172      * RFE: 6425594
   173      */
   174     boolean useBeforeDeclarationWarning;
   176     /**
   177      * Switch: allow lint infrastructure to control proprietary
   178      * API warnings.
   179      */
   180     boolean enableSunApiLintControl;
   182     /**
   183      * Switch: allow strings in switch?
   184      */
   185     boolean allowStringsInSwitch;
   187     /**
   188      * Switch: name of source level; used for error reporting.
   189      */
   190     String sourceName;
   192     /** Check kind and type of given tree against protokind and prototype.
   193      *  If check succeeds, store type in tree and return it.
   194      *  If check fails, store errType in tree and return it.
   195      *  No checks are performed if the prototype is a method type.
   196      *  It is not necessary in this case since we know that kind and type
   197      *  are correct.
   198      *
   199      *  @param tree     The tree whose kind and type is checked
   200      *  @param owntype  The computed type of the tree
   201      *  @param ownkind  The computed kind of the tree
   202      *  @param pkind    The expected kind (or: protokind) of the tree
   203      *  @param pt       The expected type (or: prototype) of the tree
   204      */
   205     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
   206         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
   207             if ((ownkind & ~pkind) == 0) {
   208                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
   209             } else {
   210                 log.error(tree.pos(), "unexpected.type",
   211                           kindNames(pkind),
   212                           kindName(ownkind));
   213                 owntype = types.createErrorType(owntype);
   214             }
   215         }
   216         tree.type = owntype;
   217         return owntype;
   218     }
   220     /** Is given blank final variable assignable, i.e. in a scope where it
   221      *  may be assigned to even though it is final?
   222      *  @param v      The blank final variable.
   223      *  @param env    The current environment.
   224      */
   225     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   226         Symbol owner = env.info.scope.owner;
   227            // owner refers to the innermost variable, method or
   228            // initializer block declaration at this point.
   229         return
   230             v.owner == owner
   231             ||
   232             ((owner.name == names.init ||    // i.e. we are in a constructor
   233               owner.kind == VAR ||           // i.e. we are in a variable initializer
   234               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   235              &&
   236              v.owner == owner.owner
   237              &&
   238              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   239     }
   241     /** Check that variable can be assigned to.
   242      *  @param pos    The current source code position.
   243      *  @param v      The assigned varaible
   244      *  @param base   If the variable is referred to in a Select, the part
   245      *                to the left of the `.', null otherwise.
   246      *  @param env    The current environment.
   247      */
   248     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   249         if ((v.flags() & FINAL) != 0 &&
   250             ((v.flags() & HASINIT) != 0
   251              ||
   252              !((base == null ||
   253                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
   254                isAssignableAsBlankFinal(v, env)))) {
   255             if (v.isResourceVariable()) { //TWR resource
   256                 log.error(pos, "try.resource.may.not.be.assigned", v);
   257             } else {
   258                 log.error(pos, "cant.assign.val.to.final.var", v);
   259             }
   260         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
   261             v.flags_field &= ~EFFECTIVELY_FINAL;
   262         }
   263     }
   265     /** Does tree represent a static reference to an identifier?
   266      *  It is assumed that tree is either a SELECT or an IDENT.
   267      *  We have to weed out selects from non-type names here.
   268      *  @param tree    The candidate tree.
   269      */
   270     boolean isStaticReference(JCTree tree) {
   271         if (tree.getTag() == JCTree.SELECT) {
   272             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   273             if (lsym == null || lsym.kind != TYP) {
   274                 return false;
   275             }
   276         }
   277         return true;
   278     }
   280     /** Is this symbol a type?
   281      */
   282     static boolean isType(Symbol sym) {
   283         return sym != null && sym.kind == TYP;
   284     }
   286     /** The current `this' symbol.
   287      *  @param env    The current environment.
   288      */
   289     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   290         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   291     }
   293     /** Attribute a parsed identifier.
   294      * @param tree Parsed identifier name
   295      * @param topLevel The toplevel to use
   296      */
   297     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   298         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   299         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   300                                            syms.errSymbol.name,
   301                                            null, null, null, null);
   302         localEnv.enclClass.sym = syms.errSymbol;
   303         return tree.accept(identAttributer, localEnv);
   304     }
   305     // where
   306         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   307         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   308             @Override
   309             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   310                 Symbol site = visit(node.getExpression(), env);
   311                 if (site.kind == ERR)
   312                     return site;
   313                 Name name = (Name)node.getIdentifier();
   314                 if (site.kind == PCK) {
   315                     env.toplevel.packge = (PackageSymbol)site;
   316                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   317                 } else {
   318                     env.enclClass.sym = (ClassSymbol)site;
   319                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   320                 }
   321             }
   323             @Override
   324             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   325                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   326             }
   327         }
   329     public Type coerce(Type etype, Type ttype) {
   330         return cfolder.coerce(etype, ttype);
   331     }
   333     public Type attribType(JCTree node, TypeSymbol sym) {
   334         Env<AttrContext> env = enter.typeEnvs.get(sym);
   335         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   336         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
   337     }
   339     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   340         breakTree = tree;
   341         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   342         try {
   343             attribExpr(expr, env);
   344         } catch (BreakAttr b) {
   345             return b.env;
   346         } catch (AssertionError ae) {
   347             if (ae.getCause() instanceof BreakAttr) {
   348                 return ((BreakAttr)(ae.getCause())).env;
   349             } else {
   350                 throw ae;
   351             }
   352         } finally {
   353             breakTree = null;
   354             log.useSource(prev);
   355         }
   356         return env;
   357     }
   359     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   360         breakTree = tree;
   361         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   362         try {
   363             attribStat(stmt, env);
   364         } catch (BreakAttr b) {
   365             return b.env;
   366         } catch (AssertionError ae) {
   367             if (ae.getCause() instanceof BreakAttr) {
   368                 return ((BreakAttr)(ae.getCause())).env;
   369             } else {
   370                 throw ae;
   371             }
   372         } finally {
   373             breakTree = null;
   374             log.useSource(prev);
   375         }
   376         return env;
   377     }
   379     private JCTree breakTree = null;
   381     private static class BreakAttr extends RuntimeException {
   382         static final long serialVersionUID = -6924771130405446405L;
   383         private Env<AttrContext> env;
   384         private BreakAttr(Env<AttrContext> env) {
   385             this.env = env;
   386         }
   387     }
   390 /* ************************************************************************
   391  * Visitor methods
   392  *************************************************************************/
   394     /** Visitor argument: the current environment.
   395      */
   396     Env<AttrContext> env;
   398     /** Visitor argument: the currently expected proto-kind.
   399      */
   400     int pkind;
   402     /** Visitor argument: the currently expected proto-type.
   403      */
   404     Type pt;
   406     /** Visitor argument: the error key to be generated when a type error occurs
   407      */
   408     String errKey;
   410     /** Visitor result: the computed type.
   411      */
   412     Type result;
   414     /** Visitor method: attribute a tree, catching any completion failure
   415      *  exceptions. Return the tree's type.
   416      *
   417      *  @param tree    The tree to be visited.
   418      *  @param env     The environment visitor argument.
   419      *  @param pkind   The protokind visitor argument.
   420      *  @param pt      The prototype visitor argument.
   421      */
   422     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
   423         return attribTree(tree, env, pkind, pt, "incompatible.types");
   424     }
   426     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
   427         Env<AttrContext> prevEnv = this.env;
   428         int prevPkind = this.pkind;
   429         Type prevPt = this.pt;
   430         String prevErrKey = this.errKey;
   431         try {
   432             this.env = env;
   433             this.pkind = pkind;
   434             this.pt = pt;
   435             this.errKey = errKey;
   436             tree.accept(this);
   437             if (tree == breakTree)
   438                 throw new BreakAttr(env);
   439             return result;
   440         } catch (CompletionFailure ex) {
   441             tree.type = syms.errType;
   442             return chk.completionError(tree.pos(), ex);
   443         } finally {
   444             this.env = prevEnv;
   445             this.pkind = prevPkind;
   446             this.pt = prevPt;
   447             this.errKey = prevErrKey;
   448         }
   449     }
   451     /** Derived visitor method: attribute an expression tree.
   452      */
   453     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   454         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
   455     }
   457     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
   458         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
   459     }
   461     /** Derived visitor method: attribute an expression tree with
   462      *  no constraints on the computed type.
   463      */
   464     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   465         return attribTree(tree, env, VAL, Type.noType);
   466     }
   468     /** Derived visitor method: attribute a type tree.
   469      */
   470     Type attribType(JCTree tree, Env<AttrContext> env) {
   471         Type result = attribType(tree, env, Type.noType);
   472         return result;
   473     }
   475     /** Derived visitor method: attribute a type tree.
   476      */
   477     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   478         Type result = attribTree(tree, env, TYP, pt);
   479         return result;
   480     }
   482     /** Derived visitor method: attribute a statement or definition tree.
   483      */
   484     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   485         return attribTree(tree, env, NIL, Type.noType);
   486     }
   488     /** Attribute a list of expressions, returning a list of types.
   489      */
   490     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   491         ListBuffer<Type> ts = new ListBuffer<Type>();
   492         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   493             ts.append(attribExpr(l.head, env, pt));
   494         return ts.toList();
   495     }
   497     /** Attribute a list of statements, returning nothing.
   498      */
   499     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   500         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   501             attribStat(l.head, env);
   502     }
   504     /** Attribute the arguments in a method call, returning a list of types.
   505      */
   506     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   507         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   508         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   509             argtypes.append(chk.checkNonVoid(
   510                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
   511         return argtypes.toList();
   512     }
   514     /** Attribute a type argument list, returning a list of types.
   515      *  Caller is responsible for calling checkRefTypes.
   516      */
   517     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   518         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   519         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   520             argtypes.append(attribType(l.head, env));
   521         return argtypes.toList();
   522     }
   524     /** Attribute a type argument list, returning a list of types.
   525      *  Check that all the types are references.
   526      */
   527     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   528         List<Type> types = attribAnyTypes(trees, env);
   529         return chk.checkRefTypes(trees, types);
   530     }
   532     /**
   533      * Attribute type variables (of generic classes or methods).
   534      * Compound types are attributed later in attribBounds.
   535      * @param typarams the type variables to enter
   536      * @param env      the current environment
   537      */
   538     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   539         for (JCTypeParameter tvar : typarams) {
   540             TypeVar a = (TypeVar)tvar.type;
   541             a.tsym.flags_field |= UNATTRIBUTED;
   542             a.bound = Type.noType;
   543             if (!tvar.bounds.isEmpty()) {
   544                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   545                 for (JCExpression bound : tvar.bounds.tail)
   546                     bounds = bounds.prepend(attribType(bound, env));
   547                 types.setBounds(a, bounds.reverse());
   548             } else {
   549                 // if no bounds are given, assume a single bound of
   550                 // java.lang.Object.
   551                 types.setBounds(a, List.of(syms.objectType));
   552             }
   553             a.tsym.flags_field &= ~UNATTRIBUTED;
   554         }
   555         for (JCTypeParameter tvar : typarams)
   556             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   557         attribStats(typarams, env);
   558     }
   560     void attribBounds(List<JCTypeParameter> typarams) {
   561         for (JCTypeParameter typaram : typarams) {
   562             Type bound = typaram.type.getUpperBound();
   563             if (bound != null && bound.tsym instanceof ClassSymbol) {
   564                 ClassSymbol c = (ClassSymbol)bound.tsym;
   565                 if ((c.flags_field & COMPOUND) != 0) {
   566                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   567                     attribClass(typaram.pos(), c);
   568                 }
   569             }
   570         }
   571     }
   573     /**
   574      * Attribute the type references in a list of annotations.
   575      */
   576     void attribAnnotationTypes(List<JCAnnotation> annotations,
   577                                Env<AttrContext> env) {
   578         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   579             JCAnnotation a = al.head;
   580             attribType(a.annotationType, env);
   581         }
   582     }
   584     /** Attribute type reference in an `extends' or `implements' clause.
   585      *  Supertypes of anonymous inner classes are usually already attributed.
   586      *
   587      *  @param tree              The tree making up the type reference.
   588      *  @param env               The environment current at the reference.
   589      *  @param classExpected     true if only a class is expected here.
   590      *  @param interfaceExpected true if only an interface is expected here.
   591      */
   592     Type attribBase(JCTree tree,
   593                     Env<AttrContext> env,
   594                     boolean classExpected,
   595                     boolean interfaceExpected,
   596                     boolean checkExtensible) {
   597         Type t = tree.type != null ?
   598             tree.type :
   599             attribType(tree, env);
   600         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   601     }
   602     Type checkBase(Type t,
   603                    JCTree tree,
   604                    Env<AttrContext> env,
   605                    boolean classExpected,
   606                    boolean interfaceExpected,
   607                    boolean checkExtensible) {
   608         if (t.isErroneous())
   609             return t;
   610         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   611             // check that type variable is already visible
   612             if (t.getUpperBound() == null) {
   613                 log.error(tree.pos(), "illegal.forward.ref");
   614                 return types.createErrorType(t);
   615             }
   616         } else {
   617             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   618         }
   619         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   620             log.error(tree.pos(), "intf.expected.here");
   621             // return errType is necessary since otherwise there might
   622             // be undetected cycles which cause attribution to loop
   623             return types.createErrorType(t);
   624         } else if (checkExtensible &&
   625                    classExpected &&
   626                    (t.tsym.flags() & INTERFACE) != 0) {
   627                 log.error(tree.pos(), "no.intf.expected.here");
   628             return types.createErrorType(t);
   629         }
   630         if (checkExtensible &&
   631             ((t.tsym.flags() & FINAL) != 0)) {
   632             log.error(tree.pos(),
   633                       "cant.inherit.from.final", t.tsym);
   634         }
   635         chk.checkNonCyclic(tree.pos(), t);
   636         return t;
   637     }
   639     public void visitClassDef(JCClassDecl tree) {
   640         // Local classes have not been entered yet, so we need to do it now:
   641         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   642             enter.classEnter(tree, env);
   644         ClassSymbol c = tree.sym;
   645         if (c == null) {
   646             // exit in case something drastic went wrong during enter.
   647             result = null;
   648         } else {
   649             // make sure class has been completed:
   650             c.complete();
   652             // If this class appears as an anonymous class
   653             // in a superclass constructor call where
   654             // no explicit outer instance is given,
   655             // disable implicit outer instance from being passed.
   656             // (This would be an illegal access to "this before super").
   657             if (env.info.isSelfCall &&
   658                 env.tree.getTag() == JCTree.NEWCLASS &&
   659                 ((JCNewClass) env.tree).encl == null)
   660             {
   661                 c.flags_field |= NOOUTERTHIS;
   662             }
   663             attribClass(tree.pos(), c);
   664             result = tree.type = c.type;
   665         }
   666     }
   668     public void visitMethodDef(JCMethodDecl tree) {
   669         MethodSymbol m = tree.sym;
   671         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
   672         Lint prevLint = chk.setLint(lint);
   673         MethodSymbol prevMethod = chk.setMethod(m);
   674         try {
   675             chk.checkDeprecatedAnnotation(tree.pos(), m);
   677             attribBounds(tree.typarams);
   679             // If we override any other methods, check that we do so properly.
   680             // JLS ???
   681             chk.checkClashes(tree.pos(), env.enclClass.type, m);
   682             chk.checkOverride(tree, m);
   684             // Create a new environment with local scope
   685             // for attributing the method.
   686             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   688             localEnv.info.lint = lint;
   690             // Enter all type parameters into the local method scope.
   691             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   692                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   694             ClassSymbol owner = env.enclClass.sym;
   695             if ((owner.flags() & ANNOTATION) != 0 &&
   696                 tree.params.nonEmpty())
   697                 log.error(tree.params.head.pos(),
   698                           "intf.annotation.members.cant.have.params");
   700             // Attribute all value parameters.
   701             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   702                 attribStat(l.head, localEnv);
   703             }
   705             chk.checkVarargsMethodDecl(localEnv, tree);
   707             // Check that type parameters are well-formed.
   708             chk.validate(tree.typarams, localEnv);
   710             // Check that result type is well-formed.
   711             chk.validate(tree.restype, localEnv);
   713             // annotation method checks
   714             if ((owner.flags() & ANNOTATION) != 0) {
   715                 // annotation method cannot have throws clause
   716                 if (tree.thrown.nonEmpty()) {
   717                     log.error(tree.thrown.head.pos(),
   718                             "throws.not.allowed.in.intf.annotation");
   719                 }
   720                 // annotation method cannot declare type-parameters
   721                 if (tree.typarams.nonEmpty()) {
   722                     log.error(tree.typarams.head.pos(),
   723                             "intf.annotation.members.cant.have.type.params");
   724                 }
   725                 // validate annotation method's return type (could be an annotation type)
   726                 chk.validateAnnotationType(tree.restype);
   727                 // ensure that annotation method does not clash with members of Object/Annotation
   728                 chk.validateAnnotationMethod(tree.pos(), m);
   730                 if (tree.defaultValue != null) {
   731                     // if default value is an annotation, check it is a well-formed
   732                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   733                     chk.validateAnnotationTree(tree.defaultValue);
   734                 }
   735             }
   737             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   738                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   740             if (tree.body == null) {
   741                 // Empty bodies are only allowed for
   742                 // abstract, native, or interface methods, or for methods
   743                 // in a retrofit signature class.
   744                 if ((owner.flags() & INTERFACE) == 0 &&
   745                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   746                     !relax)
   747                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   748                 if (tree.defaultValue != null) {
   749                     if ((owner.flags() & ANNOTATION) == 0)
   750                         log.error(tree.pos(),
   751                                   "default.allowed.in.intf.annotation.member");
   752                 }
   753             } else if ((owner.flags() & INTERFACE) != 0) {
   754                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   755             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   756                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   757             } else if ((tree.mods.flags & NATIVE) != 0) {
   758                 log.error(tree.pos(), "native.meth.cant.have.body");
   759             } else {
   760                 // Add an implicit super() call unless an explicit call to
   761                 // super(...) or this(...) is given
   762                 // or we are compiling class java.lang.Object.
   763                 if (tree.name == names.init && owner.type != syms.objectType) {
   764                     JCBlock body = tree.body;
   765                     if (body.stats.isEmpty() ||
   766                         !TreeInfo.isSelfCall(body.stats.head)) {
   767                         body.stats = body.stats.
   768                             prepend(memberEnter.SuperCall(make.at(body.pos),
   769                                                           List.<Type>nil(),
   770                                                           List.<JCVariableDecl>nil(),
   771                                                           false));
   772                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   773                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   774                                TreeInfo.isSuperCall(body.stats.head)) {
   775                         // enum constructors are not allowed to call super
   776                         // directly, so make sure there aren't any super calls
   777                         // in enum constructors, except in the compiler
   778                         // generated one.
   779                         log.error(tree.body.stats.head.pos(),
   780                                   "call.to.super.not.allowed.in.enum.ctor",
   781                                   env.enclClass.sym);
   782                     }
   783                 }
   785                 // Attribute method body.
   786                 attribStat(tree.body, localEnv);
   787             }
   788             localEnv.info.scope.leave();
   789             result = tree.type = m.type;
   790             chk.validateAnnotations(tree.mods.annotations, m);
   791         }
   792         finally {
   793             chk.setLint(prevLint);
   794             chk.setMethod(prevMethod);
   795         }
   796     }
   798     public void visitVarDef(JCVariableDecl tree) {
   799         // Local variables have not been entered yet, so we need to do it now:
   800         if (env.info.scope.owner.kind == MTH) {
   801             if (tree.sym != null) {
   802                 // parameters have already been entered
   803                 env.info.scope.enter(tree.sym);
   804             } else {
   805                 memberEnter.memberEnter(tree, env);
   806                 annotate.flush();
   807             }
   808             tree.sym.flags_field |= EFFECTIVELY_FINAL;
   809         }
   811         VarSymbol v = tree.sym;
   812         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
   813         Lint prevLint = chk.setLint(lint);
   815         // Check that the variable's declared type is well-formed.
   816         chk.validate(tree.vartype, env);
   818         try {
   819             chk.checkDeprecatedAnnotation(tree.pos(), v);
   821             if (tree.init != null) {
   822                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   823                     // In this case, `v' is final.  Ensure that it's initializer is
   824                     // evaluated.
   825                     v.getConstValue(); // ensure initializer is evaluated
   826                 } else {
   827                     // Attribute initializer in a new environment
   828                     // with the declared variable as owner.
   829                     // Check that initializer conforms to variable's declared type.
   830                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   831                     initEnv.info.lint = lint;
   832                     // In order to catch self-references, we set the variable's
   833                     // declaration position to maximal possible value, effectively
   834                     // marking the variable as undefined.
   835                     initEnv.info.enclVar = v;
   836                     attribExpr(tree.init, initEnv, v.type);
   837                 }
   838             }
   839             result = tree.type = v.type;
   840             chk.validateAnnotations(tree.mods.annotations, v);
   841         }
   842         finally {
   843             chk.setLint(prevLint);
   844         }
   845     }
   847     public void visitSkip(JCSkip tree) {
   848         result = null;
   849     }
   851     public void visitBlock(JCBlock tree) {
   852         if (env.info.scope.owner.kind == TYP) {
   853             // Block is a static or instance initializer;
   854             // let the owner of the environment be a freshly
   855             // created BLOCK-method.
   856             Env<AttrContext> localEnv =
   857                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   858             localEnv.info.scope.owner =
   859                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   860                                  env.info.scope.owner);
   861             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   862             attribStats(tree.stats, localEnv);
   863         } else {
   864             // Create a new local environment with a local scope.
   865             Env<AttrContext> localEnv =
   866                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   867             attribStats(tree.stats, localEnv);
   868             localEnv.info.scope.leave();
   869         }
   870         result = null;
   871     }
   873     public void visitDoLoop(JCDoWhileLoop tree) {
   874         attribStat(tree.body, env.dup(tree));
   875         attribExpr(tree.cond, env, syms.booleanType);
   876         result = null;
   877     }
   879     public void visitWhileLoop(JCWhileLoop tree) {
   880         attribExpr(tree.cond, env, syms.booleanType);
   881         attribStat(tree.body, env.dup(tree));
   882         result = null;
   883     }
   885     public void visitForLoop(JCForLoop tree) {
   886         Env<AttrContext> loopEnv =
   887             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   888         attribStats(tree.init, loopEnv);
   889         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
   890         loopEnv.tree = tree; // before, we were not in loop!
   891         attribStats(tree.step, loopEnv);
   892         attribStat(tree.body, loopEnv);
   893         loopEnv.info.scope.leave();
   894         result = null;
   895     }
   897     public void visitForeachLoop(JCEnhancedForLoop tree) {
   898         Env<AttrContext> loopEnv =
   899             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
   900         attribStat(tree.var, loopEnv);
   901         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
   902         chk.checkNonVoid(tree.pos(), exprType);
   903         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
   904         if (elemtype == null) {
   905             // or perhaps expr implements Iterable<T>?
   906             Type base = types.asSuper(exprType, syms.iterableType.tsym);
   907             if (base == null) {
   908                 log.error(tree.expr.pos(),
   909                         "foreach.not.applicable.to.type",
   910                         exprType,
   911                         diags.fragment("type.req.array.or.iterable"));
   912                 elemtype = types.createErrorType(exprType);
   913             } else {
   914                 List<Type> iterableParams = base.allparams();
   915                 elemtype = iterableParams.isEmpty()
   916                     ? syms.objectType
   917                     : types.upperBound(iterableParams.head);
   918             }
   919         }
   920         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
   921         loopEnv.tree = tree; // before, we were not in loop!
   922         attribStat(tree.body, loopEnv);
   923         loopEnv.info.scope.leave();
   924         result = null;
   925     }
   927     public void visitLabelled(JCLabeledStatement tree) {
   928         // Check that label is not used in an enclosing statement
   929         Env<AttrContext> env1 = env;
   930         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
   931             if (env1.tree.getTag() == JCTree.LABELLED &&
   932                 ((JCLabeledStatement) env1.tree).label == tree.label) {
   933                 log.error(tree.pos(), "label.already.in.use",
   934                           tree.label);
   935                 break;
   936             }
   937             env1 = env1.next;
   938         }
   940         attribStat(tree.body, env.dup(tree));
   941         result = null;
   942     }
   944     public void visitSwitch(JCSwitch tree) {
   945         Type seltype = attribExpr(tree.selector, env);
   947         Env<AttrContext> switchEnv =
   948             env.dup(tree, env.info.dup(env.info.scope.dup()));
   950         boolean enumSwitch =
   951             allowEnums &&
   952             (seltype.tsym.flags() & Flags.ENUM) != 0;
   953         boolean stringSwitch = false;
   954         if (types.isSameType(seltype, syms.stringType)) {
   955             if (allowStringsInSwitch) {
   956                 stringSwitch = true;
   957             } else {
   958                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
   959             }
   960         }
   961         if (!enumSwitch && !stringSwitch)
   962             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
   964         // Attribute all cases and
   965         // check that there are no duplicate case labels or default clauses.
   966         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
   967         boolean hasDefault = false;      // Is there a default label?
   968         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   969             JCCase c = l.head;
   970             Env<AttrContext> caseEnv =
   971                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
   972             if (c.pat != null) {
   973                 if (enumSwitch) {
   974                     Symbol sym = enumConstant(c.pat, seltype);
   975                     if (sym == null) {
   976                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
   977                     } else if (!labels.add(sym)) {
   978                         log.error(c.pos(), "duplicate.case.label");
   979                     }
   980                 } else {
   981                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
   982                     if (pattype.tag != ERROR) {
   983                         if (pattype.constValue() == null) {
   984                             log.error(c.pat.pos(),
   985                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
   986                         } else if (labels.contains(pattype.constValue())) {
   987                             log.error(c.pos(), "duplicate.case.label");
   988                         } else {
   989                             labels.add(pattype.constValue());
   990                         }
   991                     }
   992                 }
   993             } else if (hasDefault) {
   994                 log.error(c.pos(), "duplicate.default.label");
   995             } else {
   996                 hasDefault = true;
   997             }
   998             attribStats(c.stats, caseEnv);
   999             caseEnv.info.scope.leave();
  1000             addVars(c.stats, switchEnv.info.scope);
  1003         switchEnv.info.scope.leave();
  1004         result = null;
  1006     // where
  1007         /** Add any variables defined in stats to the switch scope. */
  1008         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1009             for (;stats.nonEmpty(); stats = stats.tail) {
  1010                 JCTree stat = stats.head;
  1011                 if (stat.getTag() == JCTree.VARDEF)
  1012                     switchScope.enter(((JCVariableDecl) stat).sym);
  1015     // where
  1016     /** Return the selected enumeration constant symbol, or null. */
  1017     private Symbol enumConstant(JCTree tree, Type enumType) {
  1018         if (tree.getTag() != JCTree.IDENT) {
  1019             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1020             return syms.errSymbol;
  1022         JCIdent ident = (JCIdent)tree;
  1023         Name name = ident.name;
  1024         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1025              e.scope != null; e = e.next()) {
  1026             if (e.sym.kind == VAR) {
  1027                 Symbol s = ident.sym = e.sym;
  1028                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1029                 ident.type = s.type;
  1030                 return ((s.flags_field & Flags.ENUM) == 0)
  1031                     ? null : s;
  1034         return null;
  1037     public void visitSynchronized(JCSynchronized tree) {
  1038         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1039         attribStat(tree.body, env);
  1040         result = null;
  1043     public void visitTry(JCTry tree) {
  1044         // Create a new local environment with a local
  1045         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1046         boolean isTryWithResource = tree.resources.nonEmpty();
  1047         // Create a nested environment for attributing the try block if needed
  1048         Env<AttrContext> tryEnv = isTryWithResource ?
  1049             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1050             localEnv;
  1051         // Attribute resource declarations
  1052         for (JCTree resource : tree.resources) {
  1053             if (resource.getTag() == JCTree.VARDEF) {
  1054                 attribStat(resource, tryEnv);
  1055                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
  1056                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1057                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1058             } else {
  1059                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
  1062         // Attribute body
  1063         attribStat(tree.body, tryEnv);
  1064         if (isTryWithResource)
  1065             tryEnv.info.scope.leave();
  1067         // Attribute catch clauses
  1068         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1069             JCCatch c = l.head;
  1070             Env<AttrContext> catchEnv =
  1071                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1072             Type ctype = attribStat(c.param, catchEnv);
  1073             if (TreeInfo.isMultiCatch(c)) {
  1074                 //multi-catch parameter is implicitly marked as final
  1075                 c.param.sym.flags_field |= FINAL | DISJUNCTION;
  1077             if (c.param.sym.kind == Kinds.VAR) {
  1078                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1080             chk.checkType(c.param.vartype.pos(),
  1081                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1082                           syms.throwableType);
  1083             attribStat(c.body, catchEnv);
  1084             catchEnv.info.scope.leave();
  1087         // Attribute finalizer
  1088         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1090         localEnv.info.scope.leave();
  1091         result = null;
  1094     public void visitConditional(JCConditional tree) {
  1095         attribExpr(tree.cond, env, syms.booleanType);
  1096         attribExpr(tree.truepart, env);
  1097         attribExpr(tree.falsepart, env);
  1098         result = check(tree,
  1099                        capture(condType(tree.pos(), tree.cond.type,
  1100                                         tree.truepart.type, tree.falsepart.type)),
  1101                        VAL, pkind, pt);
  1103     //where
  1104         /** Compute the type of a conditional expression, after
  1105          *  checking that it exists. See Spec 15.25.
  1107          *  @param pos      The source position to be used for
  1108          *                  error diagnostics.
  1109          *  @param condtype The type of the expression's condition.
  1110          *  @param thentype The type of the expression's then-part.
  1111          *  @param elsetype The type of the expression's else-part.
  1112          */
  1113         private Type condType(DiagnosticPosition pos,
  1114                               Type condtype,
  1115                               Type thentype,
  1116                               Type elsetype) {
  1117             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1119             // If condition and both arms are numeric constants,
  1120             // evaluate at compile-time.
  1121             return ((condtype.constValue() != null) &&
  1122                     (thentype.constValue() != null) &&
  1123                     (elsetype.constValue() != null))
  1124                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1125                 : ctype;
  1127         /** Compute the type of a conditional expression, after
  1128          *  checking that it exists.  Does not take into
  1129          *  account the special case where condition and both arms
  1130          *  are constants.
  1132          *  @param pos      The source position to be used for error
  1133          *                  diagnostics.
  1134          *  @param condtype The type of the expression's condition.
  1135          *  @param thentype The type of the expression's then-part.
  1136          *  @param elsetype The type of the expression's else-part.
  1137          */
  1138         private Type condType1(DiagnosticPosition pos, Type condtype,
  1139                                Type thentype, Type elsetype) {
  1140             // If same type, that is the result
  1141             if (types.isSameType(thentype, elsetype))
  1142                 return thentype.baseType();
  1144             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1145                 ? thentype : types.unboxedType(thentype);
  1146             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1147                 ? elsetype : types.unboxedType(elsetype);
  1149             // Otherwise, if both arms can be converted to a numeric
  1150             // type, return the least numeric type that fits both arms
  1151             // (i.e. return larger of the two, or return int if one
  1152             // arm is short, the other is char).
  1153             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1154                 // If one arm has an integer subrange type (i.e., byte,
  1155                 // short, or char), and the other is an integer constant
  1156                 // that fits into the subrange, return the subrange type.
  1157                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1158                     types.isAssignable(elseUnboxed, thenUnboxed))
  1159                     return thenUnboxed.baseType();
  1160                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1161                     types.isAssignable(thenUnboxed, elseUnboxed))
  1162                     return elseUnboxed.baseType();
  1164                 for (int i = BYTE; i < VOID; i++) {
  1165                     Type candidate = syms.typeOfTag[i];
  1166                     if (types.isSubtype(thenUnboxed, candidate) &&
  1167                         types.isSubtype(elseUnboxed, candidate))
  1168                         return candidate;
  1172             // Those were all the cases that could result in a primitive
  1173             if (allowBoxing) {
  1174                 if (thentype.isPrimitive())
  1175                     thentype = types.boxedClass(thentype).type;
  1176                 if (elsetype.isPrimitive())
  1177                     elsetype = types.boxedClass(elsetype).type;
  1180             if (types.isSubtype(thentype, elsetype))
  1181                 return elsetype.baseType();
  1182             if (types.isSubtype(elsetype, thentype))
  1183                 return thentype.baseType();
  1185             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1186                 log.error(pos, "neither.conditional.subtype",
  1187                           thentype, elsetype);
  1188                 return thentype.baseType();
  1191             // both are known to be reference types.  The result is
  1192             // lub(thentype,elsetype). This cannot fail, as it will
  1193             // always be possible to infer "Object" if nothing better.
  1194             return types.lub(thentype.baseType(), elsetype.baseType());
  1197     public void visitIf(JCIf tree) {
  1198         attribExpr(tree.cond, env, syms.booleanType);
  1199         attribStat(tree.thenpart, env);
  1200         if (tree.elsepart != null)
  1201             attribStat(tree.elsepart, env);
  1202         chk.checkEmptyIf(tree);
  1203         result = null;
  1206     public void visitExec(JCExpressionStatement tree) {
  1207         //a fresh environment is required for 292 inference to work properly ---
  1208         //see Infer.instantiatePolymorphicSignatureInstance()
  1209         Env<AttrContext> localEnv = env.dup(tree);
  1210         attribExpr(tree.expr, localEnv);
  1211         result = null;
  1214     public void visitBreak(JCBreak tree) {
  1215         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1216         result = null;
  1219     public void visitContinue(JCContinue tree) {
  1220         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1221         result = null;
  1223     //where
  1224         /** Return the target of a break or continue statement, if it exists,
  1225          *  report an error if not.
  1226          *  Note: The target of a labelled break or continue is the
  1227          *  (non-labelled) statement tree referred to by the label,
  1228          *  not the tree representing the labelled statement itself.
  1230          *  @param pos     The position to be used for error diagnostics
  1231          *  @param tag     The tag of the jump statement. This is either
  1232          *                 Tree.BREAK or Tree.CONTINUE.
  1233          *  @param label   The label of the jump statement, or null if no
  1234          *                 label is given.
  1235          *  @param env     The environment current at the jump statement.
  1236          */
  1237         private JCTree findJumpTarget(DiagnosticPosition pos,
  1238                                     int tag,
  1239                                     Name label,
  1240                                     Env<AttrContext> env) {
  1241             // Search environments outwards from the point of jump.
  1242             Env<AttrContext> env1 = env;
  1243             LOOP:
  1244             while (env1 != null) {
  1245                 switch (env1.tree.getTag()) {
  1246                 case JCTree.LABELLED:
  1247                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1248                     if (label == labelled.label) {
  1249                         // If jump is a continue, check that target is a loop.
  1250                         if (tag == JCTree.CONTINUE) {
  1251                             if (labelled.body.getTag() != JCTree.DOLOOP &&
  1252                                 labelled.body.getTag() != JCTree.WHILELOOP &&
  1253                                 labelled.body.getTag() != JCTree.FORLOOP &&
  1254                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
  1255                                 log.error(pos, "not.loop.label", label);
  1256                             // Found labelled statement target, now go inwards
  1257                             // to next non-labelled tree.
  1258                             return TreeInfo.referencedStatement(labelled);
  1259                         } else {
  1260                             return labelled;
  1263                     break;
  1264                 case JCTree.DOLOOP:
  1265                 case JCTree.WHILELOOP:
  1266                 case JCTree.FORLOOP:
  1267                 case JCTree.FOREACHLOOP:
  1268                     if (label == null) return env1.tree;
  1269                     break;
  1270                 case JCTree.SWITCH:
  1271                     if (label == null && tag == JCTree.BREAK) return env1.tree;
  1272                     break;
  1273                 case JCTree.METHODDEF:
  1274                 case JCTree.CLASSDEF:
  1275                     break LOOP;
  1276                 default:
  1278                 env1 = env1.next;
  1280             if (label != null)
  1281                 log.error(pos, "undef.label", label);
  1282             else if (tag == JCTree.CONTINUE)
  1283                 log.error(pos, "cont.outside.loop");
  1284             else
  1285                 log.error(pos, "break.outside.switch.loop");
  1286             return null;
  1289     public void visitReturn(JCReturn tree) {
  1290         // Check that there is an enclosing method which is
  1291         // nested within than the enclosing class.
  1292         if (env.enclMethod == null ||
  1293             env.enclMethod.sym.owner != env.enclClass.sym) {
  1294             log.error(tree.pos(), "ret.outside.meth");
  1296         } else {
  1297             // Attribute return expression, if it exists, and check that
  1298             // it conforms to result type of enclosing method.
  1299             Symbol m = env.enclMethod.sym;
  1300             if (m.type.getReturnType().tag == VOID) {
  1301                 if (tree.expr != null)
  1302                     log.error(tree.expr.pos(),
  1303                               "cant.ret.val.from.meth.decl.void");
  1304             } else if (tree.expr == null) {
  1305                 log.error(tree.pos(), "missing.ret.val");
  1306             } else {
  1307                 attribExpr(tree.expr, env, m.type.getReturnType());
  1310         result = null;
  1313     public void visitThrow(JCThrow tree) {
  1314         attribExpr(tree.expr, env, syms.throwableType);
  1315         result = null;
  1318     public void visitAssert(JCAssert tree) {
  1319         attribExpr(tree.cond, env, syms.booleanType);
  1320         if (tree.detail != null) {
  1321             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1323         result = null;
  1326      /** Visitor method for method invocations.
  1327      *  NOTE: The method part of an application will have in its type field
  1328      *        the return type of the method, not the method's type itself!
  1329      */
  1330     public void visitApply(JCMethodInvocation tree) {
  1331         // The local environment of a method application is
  1332         // a new environment nested in the current one.
  1333         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1335         // The types of the actual method arguments.
  1336         List<Type> argtypes;
  1338         // The types of the actual method type arguments.
  1339         List<Type> typeargtypes = null;
  1341         Name methName = TreeInfo.name(tree.meth);
  1343         boolean isConstructorCall =
  1344             methName == names._this || methName == names._super;
  1346         if (isConstructorCall) {
  1347             // We are seeing a ...this(...) or ...super(...) call.
  1348             // Check that this is the first statement in a constructor.
  1349             if (checkFirstConstructorStat(tree, env)) {
  1351                 // Record the fact
  1352                 // that this is a constructor call (using isSelfCall).
  1353                 localEnv.info.isSelfCall = true;
  1355                 // Attribute arguments, yielding list of argument types.
  1356                 argtypes = attribArgs(tree.args, localEnv);
  1357                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1359                 // Variable `site' points to the class in which the called
  1360                 // constructor is defined.
  1361                 Type site = env.enclClass.sym.type;
  1362                 if (methName == names._super) {
  1363                     if (site == syms.objectType) {
  1364                         log.error(tree.meth.pos(), "no.superclass", site);
  1365                         site = types.createErrorType(syms.objectType);
  1366                     } else {
  1367                         site = types.supertype(site);
  1371                 if (site.tag == CLASS) {
  1372                     Type encl = site.getEnclosingType();
  1373                     while (encl != null && encl.tag == TYPEVAR)
  1374                         encl = encl.getUpperBound();
  1375                     if (encl.tag == CLASS) {
  1376                         // we are calling a nested class
  1378                         if (tree.meth.getTag() == JCTree.SELECT) {
  1379                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1381                             // We are seeing a prefixed call, of the form
  1382                             //     <expr>.super(...).
  1383                             // Check that the prefix expression conforms
  1384                             // to the outer instance type of the class.
  1385                             chk.checkRefType(qualifier.pos(),
  1386                                              attribExpr(qualifier, localEnv,
  1387                                                         encl));
  1388                         } else if (methName == names._super) {
  1389                             // qualifier omitted; check for existence
  1390                             // of an appropriate implicit qualifier.
  1391                             rs.resolveImplicitThis(tree.meth.pos(),
  1392                                                    localEnv, site);
  1394                     } else if (tree.meth.getTag() == JCTree.SELECT) {
  1395                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1396                                   site.tsym);
  1399                     // if we're calling a java.lang.Enum constructor,
  1400                     // prefix the implicit String and int parameters
  1401                     if (site.tsym == syms.enumSym && allowEnums)
  1402                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1404                     // Resolve the called constructor under the assumption
  1405                     // that we are referring to a superclass instance of the
  1406                     // current instance (JLS ???).
  1407                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1408                     localEnv.info.selectSuper = true;
  1409                     localEnv.info.varArgs = false;
  1410                     Symbol sym = rs.resolveConstructor(
  1411                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1412                     localEnv.info.selectSuper = selectSuperPrev;
  1414                     // Set method symbol to resolved constructor...
  1415                     TreeInfo.setSymbol(tree.meth, sym);
  1417                     // ...and check that it is legal in the current context.
  1418                     // (this will also set the tree's type)
  1419                     Type mpt = newMethTemplate(argtypes, typeargtypes);
  1420                     checkId(tree.meth, site, sym, localEnv, MTH,
  1421                             mpt, tree.varargsElement != null);
  1423                 // Otherwise, `site' is an error type and we do nothing
  1425             result = tree.type = syms.voidType;
  1426         } else {
  1427             // Otherwise, we are seeing a regular method call.
  1428             // Attribute the arguments, yielding list of argument types, ...
  1429             argtypes = attribArgs(tree.args, localEnv);
  1430             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1432             // ... and attribute the method using as a prototype a methodtype
  1433             // whose formal argument types is exactly the list of actual
  1434             // arguments (this will also set the method symbol).
  1435             Type mpt = newMethTemplate(argtypes, typeargtypes);
  1436             localEnv.info.varArgs = false;
  1437             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1438             if (localEnv.info.varArgs)
  1439                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
  1441             // Compute the result type.
  1442             Type restype = mtype.getReturnType();
  1443             if (restype.tag == WILDCARD)
  1444                 throw new AssertionError(mtype);
  1446             // as a special case, array.clone() has a result that is
  1447             // the same as static type of the array being cloned
  1448             if (tree.meth.getTag() == JCTree.SELECT &&
  1449                 allowCovariantReturns &&
  1450                 methName == names.clone &&
  1451                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1452                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1454             // as a special case, x.getClass() has type Class<? extends |X|>
  1455             if (allowGenerics &&
  1456                 methName == names.getClass && tree.args.isEmpty()) {
  1457                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
  1458                     ? ((JCFieldAccess) tree.meth).selected.type
  1459                     : env.enclClass.sym.type;
  1460                 restype = new
  1461                     ClassType(restype.getEnclosingType(),
  1462                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1463                                                                BoundKind.EXTENDS,
  1464                                                                syms.boundClass)),
  1465                               restype.tsym);
  1468             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1470             // Check that value of resulting type is admissible in the
  1471             // current context.  Also, capture the return type
  1472             result = check(tree, capture(restype), VAL, pkind, pt);
  1474         chk.validate(tree.typeargs, localEnv);
  1476     //where
  1477         /** Check that given application node appears as first statement
  1478          *  in a constructor call.
  1479          *  @param tree   The application node
  1480          *  @param env    The environment current at the application.
  1481          */
  1482         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1483             JCMethodDecl enclMethod = env.enclMethod;
  1484             if (enclMethod != null && enclMethod.name == names.init) {
  1485                 JCBlock body = enclMethod.body;
  1486                 if (body.stats.head.getTag() == JCTree.EXEC &&
  1487                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1488                     return true;
  1490             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1491                       TreeInfo.name(tree.meth));
  1492             return false;
  1495         /** Obtain a method type with given argument types.
  1496          */
  1497         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
  1498             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
  1499             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1502     public void visitNewClass(JCNewClass tree) {
  1503         Type owntype = types.createErrorType(tree.type);
  1505         // The local environment of a class creation is
  1506         // a new environment nested in the current one.
  1507         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1509         // The anonymous inner class definition of the new expression,
  1510         // if one is defined by it.
  1511         JCClassDecl cdef = tree.def;
  1513         // If enclosing class is given, attribute it, and
  1514         // complete class name to be fully qualified
  1515         JCExpression clazz = tree.clazz; // Class field following new
  1516         JCExpression clazzid =          // Identifier in class field
  1517             (clazz.getTag() == JCTree.TYPEAPPLY)
  1518             ? ((JCTypeApply) clazz).clazz
  1519             : clazz;
  1521         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1523         if (tree.encl != null) {
  1524             // We are seeing a qualified new, of the form
  1525             //    <expr>.new C <...> (...) ...
  1526             // In this case, we let clazz stand for the name of the
  1527             // allocated class C prefixed with the type of the qualifier
  1528             // expression, so that we can
  1529             // resolve it with standard techniques later. I.e., if
  1530             // <expr> has type T, then <expr>.new C <...> (...)
  1531             // yields a clazz T.C.
  1532             Type encltype = chk.checkRefType(tree.encl.pos(),
  1533                                              attribExpr(tree.encl, env));
  1534             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1535                                                  ((JCIdent) clazzid).name);
  1536             if (clazz.getTag() == JCTree.TYPEAPPLY)
  1537                 clazz = make.at(tree.pos).
  1538                     TypeApply(clazzid1,
  1539                               ((JCTypeApply) clazz).arguments);
  1540             else
  1541                 clazz = clazzid1;
  1544         // Attribute clazz expression and store
  1545         // symbol + type back into the attributed tree.
  1546         Type clazztype = attribType(clazz, env);
  1547         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype, cdef != null);
  1548         if (!TreeInfo.isDiamond(tree)) {
  1549             clazztype = chk.checkClassType(
  1550                 tree.clazz.pos(), clazztype, true);
  1552         chk.validate(clazz, localEnv);
  1553         if (tree.encl != null) {
  1554             // We have to work in this case to store
  1555             // symbol + type back into the attributed tree.
  1556             tree.clazz.type = clazztype;
  1557             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1558             clazzid.type = ((JCIdent) clazzid).sym.type;
  1559             if (!clazztype.isErroneous()) {
  1560                 if (cdef != null && clazztype.tsym.isInterface()) {
  1561                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1562                 } else if (clazztype.tsym.isStatic()) {
  1563                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1566         } else if (!clazztype.tsym.isInterface() &&
  1567                    clazztype.getEnclosingType().tag == CLASS) {
  1568             // Check for the existence of an apropos outer instance
  1569             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1572         // Attribute constructor arguments.
  1573         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1574         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1576         if (TreeInfo.isDiamond(tree)) {
  1577             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
  1578             clazz.type = clazztype;
  1579         } else if (allowDiamondFinder &&
  1580                 clazztype.getTypeArguments().nonEmpty() &&
  1581                 findDiamonds) {
  1582             boolean prevDeferDiags = log.deferDiagnostics;
  1583             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1584             Type inferred = null;
  1585             try {
  1586                 //disable diamond-related diagnostics
  1587                 log.deferDiagnostics = true;
  1588                 log.deferredDiagnostics = ListBuffer.lb();
  1589                 inferred = attribDiamond(localEnv,
  1590                         tree,
  1591                         clazztype,
  1592                         mapping,
  1593                         argtypes,
  1594                         typeargtypes);
  1596             finally {
  1597                 log.deferDiagnostics = prevDeferDiags;
  1598                 log.deferredDiagnostics = prevDeferredDiags;
  1600             if (inferred != null &&
  1601                     !inferred.isErroneous() &&
  1602                     inferred.tag == CLASS &&
  1603                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
  1604                     chk.checkDiamond((ClassType)inferred).isEmpty()) {
  1605                 String key = types.isSameType(clazztype, inferred) ?
  1606                     "diamond.redundant.args" :
  1607                     "diamond.redundant.args.1";
  1608                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1612         // If we have made no mistakes in the class type...
  1613         if (clazztype.tag == CLASS) {
  1614             // Enums may not be instantiated except implicitly
  1615             if (allowEnums &&
  1616                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1617                 (env.tree.getTag() != JCTree.VARDEF ||
  1618                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1619                  ((JCVariableDecl) env.tree).init != tree))
  1620                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1621             // Check that class is not abstract
  1622             if (cdef == null &&
  1623                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1624                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1625                           clazztype.tsym);
  1626             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1627                 // Check that no constructor arguments are given to
  1628                 // anonymous classes implementing an interface
  1629                 if (!argtypes.isEmpty())
  1630                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1632                 if (!typeargtypes.isEmpty())
  1633                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1635                 // Error recovery: pretend no arguments were supplied.
  1636                 argtypes = List.nil();
  1637                 typeargtypes = List.nil();
  1640             // Resolve the called constructor under the assumption
  1641             // that we are referring to a superclass instance of the
  1642             // current instance (JLS ???).
  1643             else {
  1644                 localEnv.info.selectSuper = cdef != null;
  1645                 localEnv.info.varArgs = false;
  1646                 tree.constructor = rs.resolveConstructor(
  1647                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1648                 tree.constructorType = tree.constructor.type.isErroneous() ?
  1649                     syms.errType :
  1650                     checkMethod(clazztype,
  1651                         tree.constructor,
  1652                         localEnv,
  1653                         tree.args,
  1654                         argtypes,
  1655                         typeargtypes,
  1656                         localEnv.info.varArgs);
  1657                 if (localEnv.info.varArgs)
  1658                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1661             if (cdef != null) {
  1662                 // We are seeing an anonymous class instance creation.
  1663                 // In this case, the class instance creation
  1664                 // expression
  1665                 //
  1666                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1667                 //
  1668                 // is represented internally as
  1669                 //
  1670                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1671                 //
  1672                 // This expression is then *transformed* as follows:
  1673                 //
  1674                 // (1) add a STATIC flag to the class definition
  1675                 //     if the current environment is static
  1676                 // (2) add an extends or implements clause
  1677                 // (3) add a constructor.
  1678                 //
  1679                 // For instance, if C is a class, and ET is the type of E,
  1680                 // the expression
  1681                 //
  1682                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1683                 //
  1684                 // is translated to (where X is a fresh name and typarams is the
  1685                 // parameter list of the super constructor):
  1686                 //
  1687                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1688                 //     X extends C<typargs2> {
  1689                 //       <typarams> X(ET e, args) {
  1690                 //         e.<typeargs1>super(args)
  1691                 //       }
  1692                 //       ...
  1693                 //     }
  1694                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1696                 if (clazztype.tsym.isInterface()) {
  1697                     cdef.implementing = List.of(clazz);
  1698                 } else {
  1699                     cdef.extending = clazz;
  1702                 attribStat(cdef, localEnv);
  1704                 // If an outer instance is given,
  1705                 // prefix it to the constructor arguments
  1706                 // and delete it from the new expression
  1707                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1708                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1709                     argtypes = argtypes.prepend(tree.encl.type);
  1710                     tree.encl = null;
  1713                 // Reassign clazztype and recompute constructor.
  1714                 clazztype = cdef.sym.type;
  1715                 Symbol sym = rs.resolveConstructor(
  1716                     tree.pos(), localEnv, clazztype, argtypes,
  1717                     typeargtypes, true, tree.varargsElement != null);
  1718                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
  1719                 tree.constructor = sym;
  1720                 if (tree.constructor.kind > ERRONEOUS) {
  1721                     tree.constructorType =  syms.errType;
  1723                 else {
  1724                     tree.constructorType = checkMethod(clazztype,
  1725                             tree.constructor,
  1726                             localEnv,
  1727                             tree.args,
  1728                             argtypes,
  1729                             typeargtypes,
  1730                             localEnv.info.varArgs);
  1734             if (tree.constructor != null && tree.constructor.kind == MTH)
  1735                 owntype = clazztype;
  1737         result = check(tree, owntype, VAL, pkind, pt);
  1738         chk.validate(tree.typeargs, localEnv);
  1741     Type attribDiamond(Env<AttrContext> env,
  1742                         JCNewClass tree,
  1743                         Type clazztype,
  1744                         Pair<Scope, Scope> mapping,
  1745                         List<Type> argtypes,
  1746                         List<Type> typeargtypes) {
  1747         if (clazztype.isErroneous() || mapping == erroneousMapping) {
  1748             //if the type of the instance creation expression is erroneous,
  1749             //or something prevented us to form a valid mapping, return the
  1750             //(possibly erroneous) type unchanged
  1751             return clazztype;
  1753         else if (clazztype.isInterface()) {
  1754             //if the type of the instance creation expression is an interface
  1755             //skip the method resolution step (JLS 15.12.2.7). The type to be
  1756             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
  1757             clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
  1758                 @Override
  1759                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
  1760                     switch (ck) {
  1761                         case EXTENDS: return types.getBounds(tv);
  1762                         default: return List.nil();
  1765                 @Override
  1766                 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
  1767                     // check that inferred bounds conform to their bounds
  1768                     infer.checkWithinBounds(tvars,
  1769                            types.subst(tvars, tvars, inferred), Warner.noWarnings);
  1770                     return super.inst(inferred, types);
  1772             };
  1773         } else {
  1774             //if the type of the instance creation expression is a class type
  1775             //apply method resolution inference (JLS 15.12.2.7). The return type
  1776             //of the resolved constructor will be a partially instantiated type
  1777             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
  1778             Symbol constructor;
  1779             try {
  1780                 constructor = rs.resolveDiamond(tree.pos(),
  1781                         env,
  1782                         clazztype.tsym.type,
  1783                         argtypes,
  1784                         typeargtypes);
  1785             } finally {
  1786                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
  1788             if (constructor.kind == MTH) {
  1789                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
  1790                         clazztype.tsym.type.getTypeArguments(),
  1791                         clazztype.tsym);
  1792                 clazztype = checkMethod(ct,
  1793                         constructor,
  1794                         env,
  1795                         tree.args,
  1796                         argtypes,
  1797                         typeargtypes,
  1798                         env.info.varArgs).getReturnType();
  1799             } else {
  1800                 clazztype = syms.errType;
  1803         if (clazztype.tag == FORALL && !pt.isErroneous()) {
  1804             //if the resolved constructor's return type has some uninferred
  1805             //type-variables, infer them using the expected type and declared
  1806             //bounds (JLS 15.12.2.8).
  1807             try {
  1808                 clazztype = infer.instantiateExpr((ForAll) clazztype,
  1809                         pt.tag == NONE ? syms.objectType : pt,
  1810                         Warner.noWarnings);
  1811             } catch (Infer.InferenceException ex) {
  1812                 //an error occurred while inferring uninstantiated type-variables
  1813                 log.error(tree.clazz.pos(),
  1814                         "cant.apply.diamond.1",
  1815                         diags.fragment("diamond", clazztype.tsym),
  1816                         ex.diagnostic);
  1819         clazztype = chk.checkClassType(tree.clazz.pos(),
  1820                 clazztype,
  1821                 true);
  1822         if (clazztype.tag == CLASS) {
  1823             List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
  1824             if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  1825                 //one or more types inferred in the previous steps is either a
  1826                 //captured type or an intersection type --- we need to report an error.
  1827                 String subkey = invalidDiamondArgs.size() > 1 ?
  1828                     "diamond.invalid.args" :
  1829                     "diamond.invalid.arg";
  1830                 //The error message is of the kind:
  1831                 //
  1832                 //cannot infer type arguments for {clazztype}<>;
  1833                 //reason: {subkey}
  1834                 //
  1835                 //where subkey is a fragment of the kind:
  1836                 //
  1837                 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
  1838                 log.error(tree.clazz.pos(),
  1839                             "cant.apply.diamond.1",
  1840                             diags.fragment("diamond", clazztype.tsym),
  1841                             diags.fragment(subkey,
  1842                                            invalidDiamondArgs,
  1843                                            diags.fragment("diamond", clazztype.tsym)));
  1846         return clazztype;
  1849     /** Creates a synthetic scope containing fake generic constructors.
  1850      *  Assuming that the original scope contains a constructor of the kind:
  1851      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
  1852      *  the synthetic scope is added a generic constructor of the kind:
  1853      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
  1854      *  inference. The inferred return type of the synthetic constructor IS
  1855      *  the inferred type for the diamond operator.
  1856      */
  1857     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype, boolean overrideProtectedAccess) {
  1858         if (ctype.tag != CLASS) {
  1859             return erroneousMapping;
  1861         Pair<Scope, Scope> mapping =
  1862                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
  1863         List<Type> typevars = ctype.tsym.type.getTypeArguments();
  1864         for (Scope.Entry e = mapping.fst.lookup(names.init);
  1865                 e.scope != null;
  1866                 e = e.next()) {
  1867             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
  1868             if (overrideProtectedAccess && (newConstr.flags() & PROTECTED) != 0) {
  1869                 //make protected constructor public (this is required for
  1870                 //anonymous inner class creation expressions using diamond)
  1871                 newConstr.flags_field |= PUBLIC;
  1872                 newConstr.flags_field &= ~PROTECTED;
  1874             newConstr.name = names.init;
  1875             List<Type> oldTypeargs = List.nil();
  1876             if (newConstr.type.tag == FORALL) {
  1877                 oldTypeargs = ((ForAll) newConstr.type).tvars;
  1879             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
  1880                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
  1881                     newConstr.type.getThrownTypes(),
  1882                     syms.methodClass);
  1883             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
  1884             mapping.snd.enter(newConstr);
  1886         return mapping;
  1889     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
  1891     /** Make an attributed null check tree.
  1892      */
  1893     public JCExpression makeNullCheck(JCExpression arg) {
  1894         // optimization: X.this is never null; skip null check
  1895         Name name = TreeInfo.name(arg);
  1896         if (name == names._this || name == names._super) return arg;
  1898         int optag = JCTree.NULLCHK;
  1899         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1900         tree.operator = syms.nullcheck;
  1901         tree.type = arg.type;
  1902         return tree;
  1905     public void visitNewArray(JCNewArray tree) {
  1906         Type owntype = types.createErrorType(tree.type);
  1907         Type elemtype;
  1908         if (tree.elemtype != null) {
  1909             elemtype = attribType(tree.elemtype, env);
  1910             chk.validate(tree.elemtype, env);
  1911             owntype = elemtype;
  1912             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1913                 attribExpr(l.head, env, syms.intType);
  1914                 owntype = new ArrayType(owntype, syms.arrayClass);
  1916         } else {
  1917             // we are seeing an untyped aggregate { ... }
  1918             // this is allowed only if the prototype is an array
  1919             if (pt.tag == ARRAY) {
  1920                 elemtype = types.elemtype(pt);
  1921             } else {
  1922                 if (pt.tag != ERROR) {
  1923                     log.error(tree.pos(), "illegal.initializer.for.type",
  1924                               pt);
  1926                 elemtype = types.createErrorType(pt);
  1929         if (tree.elems != null) {
  1930             attribExprs(tree.elems, env, elemtype);
  1931             owntype = new ArrayType(elemtype, syms.arrayClass);
  1933         if (!types.isReifiable(elemtype))
  1934             log.error(tree.pos(), "generic.array.creation");
  1935         result = check(tree, owntype, VAL, pkind, pt);
  1938     public void visitParens(JCParens tree) {
  1939         Type owntype = attribTree(tree.expr, env, pkind, pt);
  1940         result = check(tree, owntype, pkind, pkind, pt);
  1941         Symbol sym = TreeInfo.symbol(tree);
  1942         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  1943             log.error(tree.pos(), "illegal.start.of.type");
  1946     public void visitAssign(JCAssign tree) {
  1947         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
  1948         Type capturedType = capture(owntype);
  1949         attribExpr(tree.rhs, env, owntype);
  1950         result = check(tree, capturedType, VAL, pkind, pt);
  1953     public void visitAssignop(JCAssignOp tree) {
  1954         // Attribute arguments.
  1955         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
  1956         Type operand = attribExpr(tree.rhs, env);
  1957         // Find operator.
  1958         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  1959             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
  1960             owntype, operand);
  1962         if (operator.kind == MTH) {
  1963             chk.checkOperator(tree.pos(),
  1964                               (OperatorSymbol)operator,
  1965                               tree.getTag() - JCTree.ASGOffset,
  1966                               owntype,
  1967                               operand);
  1968             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  1969             chk.checkCastable(tree.rhs.pos(),
  1970                               operator.type.getReturnType(),
  1971                               owntype);
  1973         result = check(tree, owntype, VAL, pkind, pt);
  1976     public void visitUnary(JCUnary tree) {
  1977         // Attribute arguments.
  1978         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1979             ? attribTree(tree.arg, env, VAR, Type.noType)
  1980             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  1982         // Find operator.
  1983         Symbol operator = tree.operator =
  1984             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  1986         Type owntype = types.createErrorType(tree.type);
  1987         if (operator.kind == MTH) {
  1988             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
  1989                 ? tree.arg.type
  1990                 : operator.type.getReturnType();
  1991             int opc = ((OperatorSymbol)operator).opcode;
  1993             // If the argument is constant, fold it.
  1994             if (argtype.constValue() != null) {
  1995                 Type ctype = cfolder.fold1(opc, argtype);
  1996                 if (ctype != null) {
  1997                     owntype = cfolder.coerce(ctype, owntype);
  1999                     // Remove constant types from arguments to
  2000                     // conserve space. The parser will fold concatenations
  2001                     // of string literals; the code here also
  2002                     // gets rid of intermediate results when some of the
  2003                     // operands are constant identifiers.
  2004                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2005                         tree.arg.type = syms.stringType;
  2010         result = check(tree, owntype, VAL, pkind, pt);
  2013     public void visitBinary(JCBinary tree) {
  2014         // Attribute arguments.
  2015         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2016         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2018         // Find operator.
  2019         Symbol operator = tree.operator =
  2020             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2022         Type owntype = types.createErrorType(tree.type);
  2023         if (operator.kind == MTH) {
  2024             owntype = operator.type.getReturnType();
  2025             int opc = chk.checkOperator(tree.lhs.pos(),
  2026                                         (OperatorSymbol)operator,
  2027                                         tree.getTag(),
  2028                                         left,
  2029                                         right);
  2031             // If both arguments are constants, fold them.
  2032             if (left.constValue() != null && right.constValue() != null) {
  2033                 Type ctype = cfolder.fold2(opc, left, right);
  2034                 if (ctype != null) {
  2035                     owntype = cfolder.coerce(ctype, owntype);
  2037                     // Remove constant types from arguments to
  2038                     // conserve space. The parser will fold concatenations
  2039                     // of string literals; the code here also
  2040                     // gets rid of intermediate results when some of the
  2041                     // operands are constant identifiers.
  2042                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2043                         tree.lhs.type = syms.stringType;
  2045                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2046                         tree.rhs.type = syms.stringType;
  2051             // Check that argument types of a reference ==, != are
  2052             // castable to each other, (JLS???).
  2053             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2054                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2055                     log.error(tree.pos(), "incomparable.types", left, right);
  2059             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2061         result = check(tree, owntype, VAL, pkind, pt);
  2064     public void visitTypeCast(JCTypeCast tree) {
  2065         Type clazztype = attribType(tree.clazz, env);
  2066         chk.validate(tree.clazz, env, false);
  2067         //a fresh environment is required for 292 inference to work properly ---
  2068         //see Infer.instantiatePolymorphicSignatureInstance()
  2069         Env<AttrContext> localEnv = env.dup(tree);
  2070         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2071         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2072         if (exprtype.constValue() != null)
  2073             owntype = cfolder.coerce(exprtype, owntype);
  2074         result = check(tree, capture(owntype), VAL, pkind, pt);
  2077     public void visitTypeTest(JCInstanceOf tree) {
  2078         Type exprtype = chk.checkNullOrRefType(
  2079             tree.expr.pos(), attribExpr(tree.expr, env));
  2080         Type clazztype = chk.checkReifiableReferenceType(
  2081             tree.clazz.pos(), attribType(tree.clazz, env));
  2082         chk.validate(tree.clazz, env, false);
  2083         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2084         result = check(tree, syms.booleanType, VAL, pkind, pt);
  2087     public void visitIndexed(JCArrayAccess tree) {
  2088         Type owntype = types.createErrorType(tree.type);
  2089         Type atype = attribExpr(tree.indexed, env);
  2090         attribExpr(tree.index, env, syms.intType);
  2091         if (types.isArray(atype))
  2092             owntype = types.elemtype(atype);
  2093         else if (atype.tag != ERROR)
  2094             log.error(tree.pos(), "array.req.but.found", atype);
  2095         if ((pkind & VAR) == 0) owntype = capture(owntype);
  2096         result = check(tree, owntype, VAR, pkind, pt);
  2099     public void visitIdent(JCIdent tree) {
  2100         Symbol sym;
  2101         boolean varArgs = false;
  2103         // Find symbol
  2104         if (pt.tag == METHOD || pt.tag == FORALL) {
  2105             // If we are looking for a method, the prototype `pt' will be a
  2106             // method type with the type of the call's arguments as parameters.
  2107             env.info.varArgs = false;
  2108             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
  2109             varArgs = env.info.varArgs;
  2110         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2111             sym = tree.sym;
  2112         } else {
  2113             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
  2115         tree.sym = sym;
  2117         // (1) Also find the environment current for the class where
  2118         //     sym is defined (`symEnv').
  2119         // Only for pre-tiger versions (1.4 and earlier):
  2120         // (2) Also determine whether we access symbol out of an anonymous
  2121         //     class in a this or super call.  This is illegal for instance
  2122         //     members since such classes don't carry a this$n link.
  2123         //     (`noOuterThisPath').
  2124         Env<AttrContext> symEnv = env;
  2125         boolean noOuterThisPath = false;
  2126         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2127             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2128             sym.owner.kind == TYP &&
  2129             tree.name != names._this && tree.name != names._super) {
  2131             // Find environment in which identifier is defined.
  2132             while (symEnv.outer != null &&
  2133                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2134                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2135                     noOuterThisPath = !allowAnonOuterThis;
  2136                 symEnv = symEnv.outer;
  2140         // If symbol is a variable, ...
  2141         if (sym.kind == VAR) {
  2142             VarSymbol v = (VarSymbol)sym;
  2144             // ..., evaluate its initializer, if it has one, and check for
  2145             // illegal forward reference.
  2146             checkInit(tree, env, v, false);
  2148             // If symbol is a local variable accessed from an embedded
  2149             // inner class check that it is final.
  2150             if (v.owner.kind == MTH &&
  2151                 v.owner != env.info.scope.owner &&
  2152                 (v.flags_field & FINAL) == 0) {
  2153                 log.error(tree.pos(),
  2154                           "local.var.accessed.from.icls.needs.final",
  2155                           v);
  2158             // If we are expecting a variable (as opposed to a value), check
  2159             // that the variable is assignable in the current environment.
  2160             if (pkind == VAR)
  2161                 checkAssignable(tree.pos(), v, null, env);
  2164         // In a constructor body,
  2165         // if symbol is a field or instance method, check that it is
  2166         // not accessed before the supertype constructor is called.
  2167         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2168             (sym.kind & (VAR | MTH)) != 0 &&
  2169             sym.owner.kind == TYP &&
  2170             (sym.flags() & STATIC) == 0) {
  2171             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2173         Env<AttrContext> env1 = env;
  2174         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2175             // If the found symbol is inaccessible, then it is
  2176             // accessed through an enclosing instance.  Locate this
  2177             // enclosing instance:
  2178             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2179                 env1 = env1.outer;
  2181         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
  2184     public void visitSelect(JCFieldAccess tree) {
  2185         // Determine the expected kind of the qualifier expression.
  2186         int skind = 0;
  2187         if (tree.name == names._this || tree.name == names._super ||
  2188             tree.name == names._class)
  2190             skind = TYP;
  2191         } else {
  2192             if ((pkind & PCK) != 0) skind = skind | PCK;
  2193             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
  2194             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2197         // Attribute the qualifier expression, and determine its symbol (if any).
  2198         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
  2199         if ((pkind & (PCK | TYP)) == 0)
  2200             site = capture(site); // Capture field access
  2202         // don't allow T.class T[].class, etc
  2203         if (skind == TYP) {
  2204             Type elt = site;
  2205             while (elt.tag == ARRAY)
  2206                 elt = ((ArrayType)elt).elemtype;
  2207             if (elt.tag == TYPEVAR) {
  2208                 log.error(tree.pos(), "type.var.cant.be.deref");
  2209                 result = types.createErrorType(tree.type);
  2210                 return;
  2214         // If qualifier symbol is a type or `super', assert `selectSuper'
  2215         // for the selection. This is relevant for determining whether
  2216         // protected symbols are accessible.
  2217         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2218         boolean selectSuperPrev = env.info.selectSuper;
  2219         env.info.selectSuper =
  2220             sitesym != null &&
  2221             sitesym.name == names._super;
  2223         // If selected expression is polymorphic, strip
  2224         // type parameters and remember in env.info.tvars, so that
  2225         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
  2226         if (tree.selected.type.tag == FORALL) {
  2227             ForAll pstype = (ForAll)tree.selected.type;
  2228             env.info.tvars = pstype.tvars;
  2229             site = tree.selected.type = pstype.qtype;
  2232         // Determine the symbol represented by the selection.
  2233         env.info.varArgs = false;
  2234         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2235         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
  2236             site = capture(site);
  2237             sym = selectSym(tree, sitesym, site, env, pt, pkind);
  2239         boolean varArgs = env.info.varArgs;
  2240         tree.sym = sym;
  2242         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2243             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2244             site = capture(site);
  2247         // If that symbol is a variable, ...
  2248         if (sym.kind == VAR) {
  2249             VarSymbol v = (VarSymbol)sym;
  2251             // ..., evaluate its initializer, if it has one, and check for
  2252             // illegal forward reference.
  2253             checkInit(tree, env, v, true);
  2255             // If we are expecting a variable (as opposed to a value), check
  2256             // that the variable is assignable in the current environment.
  2257             if (pkind == VAR)
  2258                 checkAssignable(tree.pos(), v, tree.selected, env);
  2261         if (sitesym != null &&
  2262                 sitesym.kind == VAR &&
  2263                 ((VarSymbol)sitesym).isResourceVariable() &&
  2264                 sym.kind == MTH &&
  2265                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2266                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2267             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2270         // Disallow selecting a type from an expression
  2271         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2272             tree.type = check(tree.selected, pt,
  2273                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
  2276         if (isType(sitesym)) {
  2277             if (sym.name == names._this) {
  2278                 // If `C' is the currently compiled class, check that
  2279                 // C.this' does not appear in a call to a super(...)
  2280                 if (env.info.isSelfCall &&
  2281                     site.tsym == env.enclClass.sym) {
  2282                     chk.earlyRefError(tree.pos(), sym);
  2284             } else {
  2285                 // Check if type-qualified fields or methods are static (JLS)
  2286                 if ((sym.flags() & STATIC) == 0 &&
  2287                     sym.name != names._super &&
  2288                     (sym.kind == VAR || sym.kind == MTH)) {
  2289                     rs.access(rs.new StaticError(sym),
  2290                               tree.pos(), site, sym.name, true);
  2293         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2294             // If the qualified item is not a type and the selected item is static, report
  2295             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2296             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2299         // If we are selecting an instance member via a `super', ...
  2300         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2302             // Check that super-qualified symbols are not abstract (JLS)
  2303             rs.checkNonAbstract(tree.pos(), sym);
  2305             if (site.isRaw()) {
  2306                 // Determine argument types for site.
  2307                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2308                 if (site1 != null) site = site1;
  2312         env.info.selectSuper = selectSuperPrev;
  2313         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
  2314         env.info.tvars = List.nil();
  2316     //where
  2317         /** Determine symbol referenced by a Select expression,
  2319          *  @param tree   The select tree.
  2320          *  @param site   The type of the selected expression,
  2321          *  @param env    The current environment.
  2322          *  @param pt     The current prototype.
  2323          *  @param pkind  The expected kind(s) of the Select expression.
  2324          */
  2325         private Symbol selectSym(JCFieldAccess tree,
  2326                                      Type site,
  2327                                      Env<AttrContext> env,
  2328                                      Type pt,
  2329                                      int pkind) {
  2330             return selectSym(tree, site.tsym, site, env, pt, pkind);
  2332         private Symbol selectSym(JCFieldAccess tree,
  2333                                  Symbol location,
  2334                                  Type site,
  2335                                  Env<AttrContext> env,
  2336                                  Type pt,
  2337                                  int pkind) {
  2338             DiagnosticPosition pos = tree.pos();
  2339             Name name = tree.name;
  2341             switch (site.tag) {
  2342             case PACKAGE:
  2343                 return rs.access(
  2344                     rs.findIdentInPackage(env, site.tsym, name, pkind),
  2345                     pos, location, site, name, true);
  2346             case ARRAY:
  2347             case CLASS:
  2348                 if (pt.tag == METHOD || pt.tag == FORALL) {
  2349                     return rs.resolveQualifiedMethod(
  2350                         pos, env, location, site, name, pt.getParameterTypes(), pt.getTypeArguments());
  2351                 } else if (name == names._this || name == names._super) {
  2352                     return rs.resolveSelf(pos, env, site.tsym, name);
  2353                 } else if (name == names._class) {
  2354                     // In this case, we have already made sure in
  2355                     // visitSelect that qualifier expression is a type.
  2356                     Type t = syms.classType;
  2357                     List<Type> typeargs = allowGenerics
  2358                         ? List.of(types.erasure(site))
  2359                         : List.<Type>nil();
  2360                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2361                     return new VarSymbol(
  2362                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2363                 } else {
  2364                     // We are seeing a plain identifier as selector.
  2365                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
  2366                     if ((pkind & ERRONEOUS) == 0)
  2367                         sym = rs.access(sym, pos, location, site, name, true);
  2368                     return sym;
  2370             case WILDCARD:
  2371                 throw new AssertionError(tree);
  2372             case TYPEVAR:
  2373                 // Normally, site.getUpperBound() shouldn't be null.
  2374                 // It should only happen during memberEnter/attribBase
  2375                 // when determining the super type which *must* beac
  2376                 // done before attributing the type variables.  In
  2377                 // other words, we are seeing this illegal program:
  2378                 // class B<T> extends A<T.foo> {}
  2379                 Symbol sym = (site.getUpperBound() != null)
  2380                     ? selectSym(tree, location, capture(site.getUpperBound()), env, pt, pkind)
  2381                     : null;
  2382                 if (sym == null) {
  2383                     log.error(pos, "type.var.cant.be.deref");
  2384                     return syms.errSymbol;
  2385                 } else {
  2386                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2387                         rs.new AccessError(env, site, sym) :
  2388                                 sym;
  2389                     rs.access(sym2, pos, location, site, name, true);
  2390                     return sym;
  2392             case ERROR:
  2393                 // preserve identifier names through errors
  2394                 return types.createErrorType(name, site.tsym, site).tsym;
  2395             default:
  2396                 // The qualifier expression is of a primitive type -- only
  2397                 // .class is allowed for these.
  2398                 if (name == names._class) {
  2399                     // In this case, we have already made sure in Select that
  2400                     // qualifier expression is a type.
  2401                     Type t = syms.classType;
  2402                     Type arg = types.boxedClass(site).type;
  2403                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2404                     return new VarSymbol(
  2405                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2406                 } else {
  2407                     log.error(pos, "cant.deref", site);
  2408                     return syms.errSymbol;
  2413         /** Determine type of identifier or select expression and check that
  2414          *  (1) the referenced symbol is not deprecated
  2415          *  (2) the symbol's type is safe (@see checkSafe)
  2416          *  (3) if symbol is a variable, check that its type and kind are
  2417          *      compatible with the prototype and protokind.
  2418          *  (4) if symbol is an instance field of a raw type,
  2419          *      which is being assigned to, issue an unchecked warning if its
  2420          *      type changes under erasure.
  2421          *  (5) if symbol is an instance method of a raw type, issue an
  2422          *      unchecked warning if its argument types change under erasure.
  2423          *  If checks succeed:
  2424          *    If symbol is a constant, return its constant type
  2425          *    else if symbol is a method, return its result type
  2426          *    otherwise return its type.
  2427          *  Otherwise return errType.
  2429          *  @param tree       The syntax tree representing the identifier
  2430          *  @param site       If this is a select, the type of the selected
  2431          *                    expression, otherwise the type of the current class.
  2432          *  @param sym        The symbol representing the identifier.
  2433          *  @param env        The current environment.
  2434          *  @param pkind      The set of expected kinds.
  2435          *  @param pt         The expected type.
  2436          */
  2437         Type checkId(JCTree tree,
  2438                      Type site,
  2439                      Symbol sym,
  2440                      Env<AttrContext> env,
  2441                      int pkind,
  2442                      Type pt,
  2443                      boolean useVarargs) {
  2444             if (pt.isErroneous()) return types.createErrorType(site);
  2445             Type owntype; // The computed type of this identifier occurrence.
  2446             switch (sym.kind) {
  2447             case TYP:
  2448                 // For types, the computed type equals the symbol's type,
  2449                 // except for two situations:
  2450                 owntype = sym.type;
  2451                 if (owntype.tag == CLASS) {
  2452                     Type ownOuter = owntype.getEnclosingType();
  2454                     // (a) If the symbol's type is parameterized, erase it
  2455                     // because no type parameters were given.
  2456                     // We recover generic outer type later in visitTypeApply.
  2457                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2458                         owntype = types.erasure(owntype);
  2461                     // (b) If the symbol's type is an inner class, then
  2462                     // we have to interpret its outer type as a superclass
  2463                     // of the site type. Example:
  2464                     //
  2465                     // class Tree<A> { class Visitor { ... } }
  2466                     // class PointTree extends Tree<Point> { ... }
  2467                     // ...PointTree.Visitor...
  2468                     //
  2469                     // Then the type of the last expression above is
  2470                     // Tree<Point>.Visitor.
  2471                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2472                         Type normOuter = site;
  2473                         if (normOuter.tag == CLASS)
  2474                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2475                         if (normOuter == null) // perhaps from an import
  2476                             normOuter = types.erasure(ownOuter);
  2477                         if (normOuter != ownOuter)
  2478                             owntype = new ClassType(
  2479                                 normOuter, List.<Type>nil(), owntype.tsym);
  2482                 break;
  2483             case VAR:
  2484                 VarSymbol v = (VarSymbol)sym;
  2485                 // Test (4): if symbol is an instance field of a raw type,
  2486                 // which is being assigned to, issue an unchecked warning if
  2487                 // its type changes under erasure.
  2488                 if (allowGenerics &&
  2489                     pkind == VAR &&
  2490                     v.owner.kind == TYP &&
  2491                     (v.flags() & STATIC) == 0 &&
  2492                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2493                     Type s = types.asOuterSuper(site, v.owner);
  2494                     if (s != null &&
  2495                         s.isRaw() &&
  2496                         !types.isSameType(v.type, v.erasure(types))) {
  2497                         chk.warnUnchecked(tree.pos(),
  2498                                           "unchecked.assign.to.var",
  2499                                           v, s);
  2502                 // The computed type of a variable is the type of the
  2503                 // variable symbol, taken as a member of the site type.
  2504                 owntype = (sym.owner.kind == TYP &&
  2505                            sym.name != names._this && sym.name != names._super)
  2506                     ? types.memberType(site, sym)
  2507                     : sym.type;
  2509                 if (env.info.tvars.nonEmpty()) {
  2510                     Type owntype1 = new ForAll(env.info.tvars, owntype);
  2511                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
  2512                         if (!owntype.contains(l.head)) {
  2513                             log.error(tree.pos(), "undetermined.type", owntype1);
  2514                             owntype1 = types.createErrorType(owntype1);
  2516                     owntype = owntype1;
  2519                 // If the variable is a constant, record constant value in
  2520                 // computed type.
  2521                 if (v.getConstValue() != null && isStaticReference(tree))
  2522                     owntype = owntype.constType(v.getConstValue());
  2524                 if (pkind == VAL) {
  2525                     owntype = capture(owntype); // capture "names as expressions"
  2527                 break;
  2528             case MTH: {
  2529                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
  2530                 owntype = checkMethod(site, sym, env, app.args,
  2531                                       pt.getParameterTypes(), pt.getTypeArguments(),
  2532                                       env.info.varArgs);
  2533                 break;
  2535             case PCK: case ERR:
  2536                 owntype = sym.type;
  2537                 break;
  2538             default:
  2539                 throw new AssertionError("unexpected kind: " + sym.kind +
  2540                                          " in tree " + tree);
  2543             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2544             // (for constructors, the error was given when the constructor was
  2545             // resolved)
  2546             if (sym.name != names.init &&
  2547                 (sym.flags() & DEPRECATED) != 0 &&
  2548                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
  2549                 sym.outermostClass() != env.info.scope.owner.outermostClass())
  2550                 chk.warnDeprecated(tree.pos(), sym);
  2552             if ((sym.flags() & PROPRIETARY) != 0) {
  2553                 if (enableSunApiLintControl)
  2554                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
  2555                 else
  2556                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
  2559             // Test (3): if symbol is a variable, check that its type and
  2560             // kind are compatible with the prototype and protokind.
  2561             return check(tree, owntype, sym.kind, pkind, pt);
  2564         /** Check that variable is initialized and evaluate the variable's
  2565          *  initializer, if not yet done. Also check that variable is not
  2566          *  referenced before it is defined.
  2567          *  @param tree    The tree making up the variable reference.
  2568          *  @param env     The current environment.
  2569          *  @param v       The variable's symbol.
  2570          */
  2571         private void checkInit(JCTree tree,
  2572                                Env<AttrContext> env,
  2573                                VarSymbol v,
  2574                                boolean onlyWarning) {
  2575 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2576 //                             tree.pos + " " + v.pos + " " +
  2577 //                             Resolve.isStatic(env));//DEBUG
  2579             // A forward reference is diagnosed if the declaration position
  2580             // of the variable is greater than the current tree position
  2581             // and the tree and variable definition occur in the same class
  2582             // definition.  Note that writes don't count as references.
  2583             // This check applies only to class and instance
  2584             // variables.  Local variables follow different scope rules,
  2585             // and are subject to definite assignment checking.
  2586             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2587                 v.owner.kind == TYP &&
  2588                 canOwnInitializer(env.info.scope.owner) &&
  2589                 v.owner == env.info.scope.owner.enclClass() &&
  2590                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2591                 (env.tree.getTag() != JCTree.ASSIGN ||
  2592                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2593                 String suffix = (env.info.enclVar == v) ?
  2594                                 "self.ref" : "forward.ref";
  2595                 if (!onlyWarning || isStaticEnumField(v)) {
  2596                     log.error(tree.pos(), "illegal." + suffix);
  2597                 } else if (useBeforeDeclarationWarning) {
  2598                     log.warning(tree.pos(), suffix, v);
  2602             v.getConstValue(); // ensure initializer is evaluated
  2604             checkEnumInitializer(tree, env, v);
  2607         /**
  2608          * Check for illegal references to static members of enum.  In
  2609          * an enum type, constructors and initializers may not
  2610          * reference its static members unless they are constant.
  2612          * @param tree    The tree making up the variable reference.
  2613          * @param env     The current environment.
  2614          * @param v       The variable's symbol.
  2615          * @see JLS 3rd Ed. (8.9 Enums)
  2616          */
  2617         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2618             // JLS 3rd Ed.:
  2619             //
  2620             // "It is a compile-time error to reference a static field
  2621             // of an enum type that is not a compile-time constant
  2622             // (15.28) from constructors, instance initializer blocks,
  2623             // or instance variable initializer expressions of that
  2624             // type. It is a compile-time error for the constructors,
  2625             // instance initializer blocks, or instance variable
  2626             // initializer expressions of an enum constant e to refer
  2627             // to itself or to an enum constant of the same type that
  2628             // is declared to the right of e."
  2629             if (isStaticEnumField(v)) {
  2630                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2632                 if (enclClass == null || enclClass.owner == null)
  2633                     return;
  2635                 // See if the enclosing class is the enum (or a
  2636                 // subclass thereof) declaring v.  If not, this
  2637                 // reference is OK.
  2638                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2639                     return;
  2641                 // If the reference isn't from an initializer, then
  2642                 // the reference is OK.
  2643                 if (!Resolve.isInitializer(env))
  2644                     return;
  2646                 log.error(tree.pos(), "illegal.enum.static.ref");
  2650         /** Is the given symbol a static, non-constant field of an Enum?
  2651          *  Note: enum literals should not be regarded as such
  2652          */
  2653         private boolean isStaticEnumField(VarSymbol v) {
  2654             return Flags.isEnum(v.owner) &&
  2655                    Flags.isStatic(v) &&
  2656                    !Flags.isConstant(v) &&
  2657                    v.name != names._class;
  2660         /** Can the given symbol be the owner of code which forms part
  2661          *  if class initialization? This is the case if the symbol is
  2662          *  a type or field, or if the symbol is the synthetic method.
  2663          *  owning a block.
  2664          */
  2665         private boolean canOwnInitializer(Symbol sym) {
  2666             return
  2667                 (sym.kind & (VAR | TYP)) != 0 ||
  2668                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2671     Warner noteWarner = new Warner();
  2673     /**
  2674      * Check that method arguments conform to its instantation.
  2675      **/
  2676     public Type checkMethod(Type site,
  2677                             Symbol sym,
  2678                             Env<AttrContext> env,
  2679                             final List<JCExpression> argtrees,
  2680                             List<Type> argtypes,
  2681                             List<Type> typeargtypes,
  2682                             boolean useVarargs) {
  2683         // Test (5): if symbol is an instance method of a raw type, issue
  2684         // an unchecked warning if its argument types change under erasure.
  2685         if (allowGenerics &&
  2686             (sym.flags() & STATIC) == 0 &&
  2687             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2688             Type s = types.asOuterSuper(site, sym.owner);
  2689             if (s != null && s.isRaw() &&
  2690                 !types.isSameTypes(sym.type.getParameterTypes(),
  2691                                    sym.erasure(types).getParameterTypes())) {
  2692                 chk.warnUnchecked(env.tree.pos(),
  2693                                   "unchecked.call.mbr.of.raw.type",
  2694                                   sym, s);
  2698         // Compute the identifier's instantiated type.
  2699         // For methods, we need to compute the instance type by
  2700         // Resolve.instantiate from the symbol's type as well as
  2701         // any type arguments and value arguments.
  2702         noteWarner.clear();
  2703         Type owntype = rs.instantiate(env,
  2704                                       site,
  2705                                       sym,
  2706                                       argtypes,
  2707                                       typeargtypes,
  2708                                       true,
  2709                                       useVarargs,
  2710                                       noteWarner);
  2711         boolean warned = noteWarner.hasNonSilentLint(LintCategory.UNCHECKED);
  2713         // If this fails, something went wrong; we should not have
  2714         // found the identifier in the first place.
  2715         if (owntype == null) {
  2716             if (!pt.isErroneous())
  2717                 log.error(env.tree.pos(),
  2718                           "internal.error.cant.instantiate",
  2719                           sym, site,
  2720                           Type.toString(pt.getParameterTypes()));
  2721             owntype = types.createErrorType(site);
  2722         } else {
  2723             // System.out.println("call   : " + env.tree);
  2724             // System.out.println("method : " + owntype);
  2725             // System.out.println("actuals: " + argtypes);
  2726             List<Type> formals = owntype.getParameterTypes();
  2727             Type last = useVarargs ? formals.last() : null;
  2728             if (sym.name==names.init &&
  2729                 sym.owner == syms.enumSym)
  2730                 formals = formals.tail.tail;
  2731             List<JCExpression> args = argtrees;
  2732             while (formals.head != last) {
  2733                 JCTree arg = args.head;
  2734                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
  2735                 assertConvertible(arg, arg.type, formals.head, warn);
  2736                 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2737                 args = args.tail;
  2738                 formals = formals.tail;
  2740             if (useVarargs) {
  2741                 Type varArg = types.elemtype(last);
  2742                 while (args.tail != null) {
  2743                     JCTree arg = args.head;
  2744                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
  2745                     assertConvertible(arg, arg.type, varArg, warn);
  2746                     warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
  2747                     args = args.tail;
  2749             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
  2750                 // non-varargs call to varargs method
  2751                 Type varParam = owntype.getParameterTypes().last();
  2752                 Type lastArg = argtypes.last();
  2753                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
  2754                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
  2755                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
  2756                                 types.elemtype(varParam),
  2757                                 varParam);
  2760             if (warned && sym.type.tag == FORALL) {
  2761                 chk.warnUnchecked(env.tree.pos(),
  2762                                   "unchecked.meth.invocation.applied",
  2763                                   kindName(sym),
  2764                                   sym.name,
  2765                                   rs.methodArguments(sym.type.getParameterTypes()),
  2766                                   rs.methodArguments(argtypes),
  2767                                   kindName(sym.location()),
  2768                                   sym.location());
  2769                 owntype = new MethodType(owntype.getParameterTypes(),
  2770                                          types.erasure(owntype.getReturnType()),
  2771                                          owntype.getThrownTypes(),
  2772                                          syms.methodClass);
  2774             if (useVarargs) {
  2775                 JCTree tree = env.tree;
  2776                 Type argtype = owntype.getParameterTypes().last();
  2777                 if (owntype.getReturnType().tag != FORALL || warned) {
  2778                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym);
  2780                 Type elemtype = types.elemtype(argtype);
  2781                 switch (tree.getTag()) {
  2782                 case JCTree.APPLY:
  2783                     ((JCMethodInvocation) tree).varargsElement = elemtype;
  2784                     break;
  2785                 case JCTree.NEWCLASS:
  2786                     ((JCNewClass) tree).varargsElement = elemtype;
  2787                     break;
  2788                 default:
  2789                     throw new AssertionError(""+tree);
  2793         return owntype;
  2796     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
  2797         if (types.isConvertible(actual, formal, warn))
  2798             return;
  2800         if (formal.isCompound()
  2801             && types.isSubtype(actual, types.supertype(formal))
  2802             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
  2803             return;
  2805         if (false) {
  2806             // TODO: make assertConvertible work
  2807             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
  2808             throw new AssertionError("Tree: " + tree
  2809                                      + " actual:" + actual
  2810                                      + " formal: " + formal);
  2814     public void visitLiteral(JCLiteral tree) {
  2815         result = check(
  2816             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
  2818     //where
  2819     /** Return the type of a literal with given type tag.
  2820      */
  2821     Type litType(int tag) {
  2822         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2825     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2826         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
  2829     public void visitTypeArray(JCArrayTypeTree tree) {
  2830         Type etype = attribType(tree.elemtype, env);
  2831         Type type = new ArrayType(etype, syms.arrayClass);
  2832         result = check(tree, type, TYP, pkind, pt);
  2835     /** Visitor method for parameterized types.
  2836      *  Bound checking is left until later, since types are attributed
  2837      *  before supertype structure is completely known
  2838      */
  2839     public void visitTypeApply(JCTypeApply tree) {
  2840         Type owntype = types.createErrorType(tree.type);
  2842         // Attribute functor part of application and make sure it's a class.
  2843         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2845         // Attribute type parameters
  2846         List<Type> actuals = attribTypes(tree.arguments, env);
  2848         if (clazztype.tag == CLASS) {
  2849             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2851             if (actuals.length() == formals.length() || actuals.length() == 0) {
  2852                 List<Type> a = actuals;
  2853                 List<Type> f = formals;
  2854                 while (a.nonEmpty()) {
  2855                     a.head = a.head.withTypeVar(f.head);
  2856                     a = a.tail;
  2857                     f = f.tail;
  2859                 // Compute the proper generic outer
  2860                 Type clazzOuter = clazztype.getEnclosingType();
  2861                 if (clazzOuter.tag == CLASS) {
  2862                     Type site;
  2863                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2864                     if (clazz.getTag() == JCTree.IDENT) {
  2865                         site = env.enclClass.sym.type;
  2866                     } else if (clazz.getTag() == JCTree.SELECT) {
  2867                         site = ((JCFieldAccess) clazz).selected.type;
  2868                     } else throw new AssertionError(""+tree);
  2869                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2870                         if (site.tag == CLASS)
  2871                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2872                         if (site == null)
  2873                             site = types.erasure(clazzOuter);
  2874                         clazzOuter = site;
  2877                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2878             } else {
  2879                 if (formals.length() != 0) {
  2880                     log.error(tree.pos(), "wrong.number.type.args",
  2881                               Integer.toString(formals.length()));
  2882                 } else {
  2883                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2885                 owntype = types.createErrorType(tree.type);
  2888         result = check(tree, owntype, TYP, pkind, pt);
  2891     public void visitTypeDisjunction(JCTypeDisjunction tree) {
  2892         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2893         for (JCExpression typeTree : tree.alternatives) {
  2894             Type ctype = attribType(typeTree, env);
  2895             ctype = chk.checkType(typeTree.pos(),
  2896                           chk.checkClassType(typeTree.pos(), ctype),
  2897                           syms.throwableType);
  2898             multicatchTypes.append(ctype);
  2900         tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
  2903     public void visitTypeParameter(JCTypeParameter tree) {
  2904         TypeVar a = (TypeVar)tree.type;
  2905         Set<Type> boundSet = new HashSet<Type>();
  2906         if (a.bound.isErroneous())
  2907             return;
  2908         List<Type> bs = types.getBounds(a);
  2909         if (tree.bounds.nonEmpty()) {
  2910             // accept class or interface or typevar as first bound.
  2911             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2912             boundSet.add(types.erasure(b));
  2913             if (b.isErroneous()) {
  2914                 a.bound = b;
  2916             else if (b.tag == TYPEVAR) {
  2917                 // if first bound was a typevar, do not accept further bounds.
  2918                 if (tree.bounds.tail.nonEmpty()) {
  2919                     log.error(tree.bounds.tail.head.pos(),
  2920                               "type.var.may.not.be.followed.by.other.bounds");
  2921                     tree.bounds = List.of(tree.bounds.head);
  2922                     a.bound = bs.head;
  2924             } else {
  2925                 // if first bound was a class or interface, accept only interfaces
  2926                 // as further bounds.
  2927                 for (JCExpression bound : tree.bounds.tail) {
  2928                     bs = bs.tail;
  2929                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2930                     if (i.isErroneous())
  2931                         a.bound = i;
  2932                     else if (i.tag == CLASS)
  2933                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2937         bs = types.getBounds(a);
  2939         // in case of multiple bounds ...
  2940         if (bs.length() > 1) {
  2941             // ... the variable's bound is a class type flagged COMPOUND
  2942             // (see comment for TypeVar.bound).
  2943             // In this case, generate a class tree that represents the
  2944             // bound class, ...
  2945             JCTree extending;
  2946             List<JCExpression> implementing;
  2947             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2948                 extending = tree.bounds.head;
  2949                 implementing = tree.bounds.tail;
  2950             } else {
  2951                 extending = null;
  2952                 implementing = tree.bounds;
  2954             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2955                 make.Modifiers(PUBLIC | ABSTRACT),
  2956                 tree.name, List.<JCTypeParameter>nil(),
  2957                 extending, implementing, List.<JCTree>nil());
  2959             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2960             Assert.check((c.flags() & COMPOUND) != 0);
  2961             cd.sym = c;
  2962             c.sourcefile = env.toplevel.sourcefile;
  2964             // ... and attribute the bound class
  2965             c.flags_field |= UNATTRIBUTED;
  2966             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2967             enter.typeEnvs.put(c, cenv);
  2972     public void visitWildcard(JCWildcard tree) {
  2973         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2974         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2975             ? syms.objectType
  2976             : attribType(tree.inner, env);
  2977         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2978                                               tree.kind.kind,
  2979                                               syms.boundClass),
  2980                        TYP, pkind, pt);
  2983     public void visitAnnotation(JCAnnotation tree) {
  2984         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
  2985         result = tree.type = syms.errType;
  2988     public void visitErroneous(JCErroneous tree) {
  2989         if (tree.errs != null)
  2990             for (JCTree err : tree.errs)
  2991                 attribTree(err, env, ERR, pt);
  2992         result = tree.type = syms.errType;
  2995     /** Default visitor method for all other trees.
  2996      */
  2997     public void visitTree(JCTree tree) {
  2998         throw new AssertionError();
  3001     /** Main method: attribute class definition associated with given class symbol.
  3002      *  reporting completion failures at the given position.
  3003      *  @param pos The source position at which completion errors are to be
  3004      *             reported.
  3005      *  @param c   The class symbol whose definition will be attributed.
  3006      */
  3007     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3008         try {
  3009             annotate.flush();
  3010             attribClass(c);
  3011         } catch (CompletionFailure ex) {
  3012             chk.completionError(pos, ex);
  3016     /** Attribute class definition associated with given class symbol.
  3017      *  @param c   The class symbol whose definition will be attributed.
  3018      */
  3019     void attribClass(ClassSymbol c) throws CompletionFailure {
  3020         if (c.type.tag == ERROR) return;
  3022         // Check for cycles in the inheritance graph, which can arise from
  3023         // ill-formed class files.
  3024         chk.checkNonCyclic(null, c.type);
  3026         Type st = types.supertype(c.type);
  3027         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3028             // First, attribute superclass.
  3029             if (st.tag == CLASS)
  3030                 attribClass((ClassSymbol)st.tsym);
  3032             // Next attribute owner, if it is a class.
  3033             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3034                 attribClass((ClassSymbol)c.owner);
  3037         // The previous operations might have attributed the current class
  3038         // if there was a cycle. So we test first whether the class is still
  3039         // UNATTRIBUTED.
  3040         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3041             c.flags_field &= ~UNATTRIBUTED;
  3043             // Get environment current at the point of class definition.
  3044             Env<AttrContext> env = enter.typeEnvs.get(c);
  3046             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3047             // because the annotations were not available at the time the env was created. Therefore,
  3048             // we look up the environment chain for the first enclosing environment for which the
  3049             // lint value is set. Typically, this is the parent env, but might be further if there
  3050             // are any envs created as a result of TypeParameter nodes.
  3051             Env<AttrContext> lintEnv = env;
  3052             while (lintEnv.info.lint == null)
  3053                 lintEnv = lintEnv.next;
  3055             // Having found the enclosing lint value, we can initialize the lint value for this class
  3056             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
  3058             Lint prevLint = chk.setLint(env.info.lint);
  3059             JavaFileObject prev = log.useSource(c.sourcefile);
  3061             try {
  3062                 // java.lang.Enum may not be subclassed by a non-enum
  3063                 if (st.tsym == syms.enumSym &&
  3064                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3065                     log.error(env.tree.pos(), "enum.no.subclassing");
  3067                 // Enums may not be extended by source-level classes
  3068                 if (st.tsym != null &&
  3069                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3070                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3071                     !target.compilerBootstrap(c)) {
  3072                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3074                 attribClassBody(env, c);
  3076                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3077             } finally {
  3078                 log.useSource(prev);
  3079                 chk.setLint(prevLint);
  3085     public void visitImport(JCImport tree) {
  3086         // nothing to do
  3089     /** Finish the attribution of a class. */
  3090     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3091         JCClassDecl tree = (JCClassDecl)env.tree;
  3092         Assert.check(c == tree.sym);
  3094         // Validate annotations
  3095         chk.validateAnnotations(tree.mods.annotations, c);
  3097         // Validate type parameters, supertype and interfaces.
  3098         attribBounds(tree.typarams);
  3099         if (!c.isAnonymous()) {
  3100             //already checked if anonymous
  3101             chk.validate(tree.typarams, env);
  3102             chk.validate(tree.extending, env);
  3103             chk.validate(tree.implementing, env);
  3106         // If this is a non-abstract class, check that it has no abstract
  3107         // methods or unimplemented methods of an implemented interface.
  3108         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3109             if (!relax)
  3110                 chk.checkAllDefined(tree.pos(), c);
  3113         if ((c.flags() & ANNOTATION) != 0) {
  3114             if (tree.implementing.nonEmpty())
  3115                 log.error(tree.implementing.head.pos(),
  3116                           "cant.extend.intf.annotation");
  3117             if (tree.typarams.nonEmpty())
  3118                 log.error(tree.typarams.head.pos(),
  3119                           "intf.annotation.cant.have.type.params");
  3120         } else {
  3121             // Check that all extended classes and interfaces
  3122             // are compatible (i.e. no two define methods with same arguments
  3123             // yet different return types).  (JLS 8.4.6.3)
  3124             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3127         // Check that class does not import the same parameterized interface
  3128         // with two different argument lists.
  3129         chk.checkClassBounds(tree.pos(), c.type);
  3131         tree.type = c.type;
  3133         for (List<JCTypeParameter> l = tree.typarams;
  3134              l.nonEmpty(); l = l.tail) {
  3135              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3138         // Check that a generic class doesn't extend Throwable
  3139         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3140             log.error(tree.extending.pos(), "generic.throwable");
  3142         // Check that all methods which implement some
  3143         // method conform to the method they implement.
  3144         chk.checkImplementations(tree);
  3146         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3147             // Attribute declaration
  3148             attribStat(l.head, env);
  3149             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3150             // Make an exception for static constants.
  3151             if (c.owner.kind != PCK &&
  3152                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3153                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3154                 Symbol sym = null;
  3155                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
  3156                 if (sym == null ||
  3157                     sym.kind != VAR ||
  3158                     ((VarSymbol) sym).getConstValue() == null)
  3159                     log.error(l.head.pos(), "icls.cant.have.static.decl", sym.location());
  3163         // Check for cycles among non-initial constructors.
  3164         chk.checkCyclicConstructors(tree);
  3166         // Check for cycles among annotation elements.
  3167         chk.checkNonCyclicElements(tree);
  3169         // Check for proper use of serialVersionUID
  3170         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3171             isSerializable(c) &&
  3172             (c.flags() & Flags.ENUM) == 0 &&
  3173             (c.flags() & ABSTRACT) == 0) {
  3174             checkSerialVersionUID(tree, c);
  3177         // where
  3178         /** check if a class is a subtype of Serializable, if that is available. */
  3179         private boolean isSerializable(ClassSymbol c) {
  3180             try {
  3181                 syms.serializableType.complete();
  3183             catch (CompletionFailure e) {
  3184                 return false;
  3186             return types.isSubtype(c.type, syms.serializableType);
  3189         /** Check that an appropriate serialVersionUID member is defined. */
  3190         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3192             // check for presence of serialVersionUID
  3193             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3194             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3195             if (e.scope == null) {
  3196                 log.warning(LintCategory.SERIAL,
  3197                         tree.pos(), "missing.SVUID", c);
  3198                 return;
  3201             // check that it is static final
  3202             VarSymbol svuid = (VarSymbol)e.sym;
  3203             if ((svuid.flags() & (STATIC | FINAL)) !=
  3204                 (STATIC | FINAL))
  3205                 log.warning(LintCategory.SERIAL,
  3206                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3208             // check that it is long
  3209             else if (svuid.type.tag != TypeTags.LONG)
  3210                 log.warning(LintCategory.SERIAL,
  3211                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3213             // check constant
  3214             else if (svuid.getConstValue() == null)
  3215                 log.warning(LintCategory.SERIAL,
  3216                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3219     private Type capture(Type type) {
  3220         return types.capture(type);
  3223     // <editor-fold desc="post-attribution visitor">
  3225     /**
  3226      * Handle missing types/symbols in an AST. This routine is useful when
  3227      * the compiler has encountered some errors (which might have ended up
  3228      * terminating attribution abruptly); if the compiler is used in fail-over
  3229      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3230      * prevents NPE to be progagated during subsequent compilation steps.
  3231      */
  3232     public void postAttr(Env<AttrContext> env) {
  3233         new PostAttrAnalyzer().scan(env.tree);
  3236     class PostAttrAnalyzer extends TreeScanner {
  3238         private void initTypeIfNeeded(JCTree that) {
  3239             if (that.type == null) {
  3240                 that.type = syms.unknownType;
  3244         @Override
  3245         public void scan(JCTree tree) {
  3246             if (tree == null) return;
  3247             if (tree instanceof JCExpression) {
  3248                 initTypeIfNeeded(tree);
  3250             super.scan(tree);
  3253         @Override
  3254         public void visitIdent(JCIdent that) {
  3255             if (that.sym == null) {
  3256                 that.sym = syms.unknownSymbol;
  3260         @Override
  3261         public void visitSelect(JCFieldAccess that) {
  3262             if (that.sym == null) {
  3263                 that.sym = syms.unknownSymbol;
  3265             super.visitSelect(that);
  3268         @Override
  3269         public void visitClassDef(JCClassDecl that) {
  3270             initTypeIfNeeded(that);
  3271             if (that.sym == null) {
  3272                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3274             super.visitClassDef(that);
  3277         @Override
  3278         public void visitMethodDef(JCMethodDecl that) {
  3279             initTypeIfNeeded(that);
  3280             if (that.sym == null) {
  3281                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3283             super.visitMethodDef(that);
  3286         @Override
  3287         public void visitVarDef(JCVariableDecl that) {
  3288             initTypeIfNeeded(that);
  3289             if (that.sym == null) {
  3290                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3291                 that.sym.adr = 0;
  3293             super.visitVarDef(that);
  3296         @Override
  3297         public void visitNewClass(JCNewClass that) {
  3298             if (that.constructor == null) {
  3299                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3301             if (that.constructorType == null) {
  3302                 that.constructorType = syms.unknownType;
  3304             super.visitNewClass(that);
  3307         @Override
  3308         public void visitBinary(JCBinary that) {
  3309             if (that.operator == null)
  3310                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3311             super.visitBinary(that);
  3314         @Override
  3315         public void visitUnary(JCUnary that) {
  3316             if (that.operator == null)
  3317                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3318             super.visitUnary(that);
  3321     // </editor-fold>

mercurial