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

Wed, 26 Sep 2012 14:22:41 +0100

author
mcimadamore
date
Wed, 26 Sep 2012 14:22:41 +0100
changeset 1341
db36841709e4
parent 1313
873ddd9f4900
child 1347
1408af4cd8b0
permissions
-rw-r--r--

7188968: New instance creation expression using diamond is checked twice
Summary: Unify method and constructor check logic
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, 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.*;
    45 import com.sun.tools.javac.comp.Check.CheckContext;
    47 import com.sun.source.tree.IdentifierTree;
    48 import com.sun.source.tree.MemberSelectTree;
    49 import com.sun.source.tree.TreeVisitor;
    50 import com.sun.source.util.SimpleTreeVisitor;
    52 import static com.sun.tools.javac.code.Flags.*;
    53 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    54 import static com.sun.tools.javac.code.Flags.BLOCK;
    55 import static com.sun.tools.javac.code.Kinds.*;
    56 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    57 import static com.sun.tools.javac.code.TypeTags.*;
    58 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
    59 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    61 /** This is the main context-dependent analysis phase in GJC. It
    62  *  encompasses name resolution, type checking and constant folding as
    63  *  subtasks. Some subtasks involve auxiliary classes.
    64  *  @see Check
    65  *  @see Resolve
    66  *  @see ConstFold
    67  *  @see Infer
    68  *
    69  *  <p><b>This is NOT part of any supported API.
    70  *  If you write code that depends on this, you do so at your own risk.
    71  *  This code and its internal interfaces are subject to change or
    72  *  deletion without notice.</b>
    73  */
    74 public class Attr extends JCTree.Visitor {
    75     protected static final Context.Key<Attr> attrKey =
    76         new Context.Key<Attr>();
    78     final Names names;
    79     final Log log;
    80     final Symtab syms;
    81     final Resolve rs;
    82     final Infer infer;
    83     final Check chk;
    84     final MemberEnter memberEnter;
    85     final TreeMaker make;
    86     final ConstFold cfolder;
    87     final Enter enter;
    88     final Target target;
    89     final Types types;
    90     final JCDiagnostic.Factory diags;
    91     final Annotate annotate;
    92     final DeferredLintHandler deferredLintHandler;
    94     public static Attr instance(Context context) {
    95         Attr instance = context.get(attrKey);
    96         if (instance == null)
    97             instance = new Attr(context);
    98         return instance;
    99     }
   101     protected Attr(Context context) {
   102         context.put(attrKey, this);
   104         names = Names.instance(context);
   105         log = Log.instance(context);
   106         syms = Symtab.instance(context);
   107         rs = Resolve.instance(context);
   108         chk = Check.instance(context);
   109         memberEnter = MemberEnter.instance(context);
   110         make = TreeMaker.instance(context);
   111         enter = Enter.instance(context);
   112         infer = Infer.instance(context);
   113         cfolder = ConstFold.instance(context);
   114         target = Target.instance(context);
   115         types = Types.instance(context);
   116         diags = JCDiagnostic.Factory.instance(context);
   117         annotate = Annotate.instance(context);
   118         deferredLintHandler = DeferredLintHandler.instance(context);
   120         Options options = Options.instance(context);
   122         Source source = Source.instance(context);
   123         allowGenerics = source.allowGenerics();
   124         allowVarargs = source.allowVarargs();
   125         allowEnums = source.allowEnums();
   126         allowBoxing = source.allowBoxing();
   127         allowCovariantReturns = source.allowCovariantReturns();
   128         allowAnonOuterThis = source.allowAnonOuterThis();
   129         allowStringsInSwitch = source.allowStringsInSwitch();
   130         sourceName = source.name;
   131         relax = (options.isSet("-retrofit") ||
   132                  options.isSet("-relax"));
   133         findDiamonds = options.get("findDiamond") != null &&
   134                  source.allowDiamond();
   135         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   137         statInfo = new ResultInfo(NIL, Type.noType);
   138         varInfo = new ResultInfo(VAR, Type.noType);
   139         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   140         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   141     }
   143     /** Switch: relax some constraints for retrofit mode.
   144      */
   145     boolean relax;
   147     /** Switch: support generics?
   148      */
   149     boolean allowGenerics;
   151     /** Switch: allow variable-arity methods.
   152      */
   153     boolean allowVarargs;
   155     /** Switch: support enums?
   156      */
   157     boolean allowEnums;
   159     /** Switch: support boxing and unboxing?
   160      */
   161     boolean allowBoxing;
   163     /** Switch: support covariant result types?
   164      */
   165     boolean allowCovariantReturns;
   167     /** Switch: allow references to surrounding object from anonymous
   168      * objects during constructor call?
   169      */
   170     boolean allowAnonOuterThis;
   172     /** Switch: generates a warning if diamond can be safely applied
   173      *  to a given new expression
   174      */
   175     boolean findDiamonds;
   177     /**
   178      * Internally enables/disables diamond finder feature
   179      */
   180     static final boolean allowDiamondFinder = true;
   182     /**
   183      * Switch: warn about use of variable before declaration?
   184      * RFE: 6425594
   185      */
   186     boolean useBeforeDeclarationWarning;
   188     /**
   189      * Switch: allow strings in switch?
   190      */
   191     boolean allowStringsInSwitch;
   193     /**
   194      * Switch: name of source level; used for error reporting.
   195      */
   196     String sourceName;
   198     /** Check kind and type of given tree against protokind and prototype.
   199      *  If check succeeds, store type in tree and return it.
   200      *  If check fails, store errType in tree and return it.
   201      *  No checks are performed if the prototype is a method type.
   202      *  It is not necessary in this case since we know that kind and type
   203      *  are correct.
   204      *
   205      *  @param tree     The tree whose kind and type is checked
   206      *  @param owntype  The computed type of the tree
   207      *  @param ownkind  The computed kind of the tree
   208      *  @param resultInfo  The expected result of the tree
   209      */
   210     Type check(JCTree tree, Type owntype, int ownkind, ResultInfo resultInfo) {
   211         if (owntype.tag != ERROR && resultInfo.pt.tag != METHOD && resultInfo.pt.tag != FORALL) {
   212             if ((ownkind & ~resultInfo.pkind) == 0) {
   213                 owntype = resultInfo.check(tree, owntype);
   214             } else {
   215                 log.error(tree.pos(), "unexpected.type",
   216                           kindNames(resultInfo.pkind),
   217                           kindName(ownkind));
   218                 owntype = types.createErrorType(owntype);
   219             }
   220         }
   221         tree.type = owntype;
   222         return owntype;
   223     }
   225     /** Is given blank final variable assignable, i.e. in a scope where it
   226      *  may be assigned to even though it is final?
   227      *  @param v      The blank final variable.
   228      *  @param env    The current environment.
   229      */
   230     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   231         Symbol owner = owner(env);
   232            // owner refers to the innermost variable, method or
   233            // initializer block declaration at this point.
   234         return
   235             v.owner == owner
   236             ||
   237             ((owner.name == names.init ||    // i.e. we are in a constructor
   238               owner.kind == VAR ||           // i.e. we are in a variable initializer
   239               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   240              &&
   241              v.owner == owner.owner
   242              &&
   243              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   244     }
   246     /**
   247      * Return the innermost enclosing owner symbol in a given attribution context
   248      */
   249     Symbol owner(Env<AttrContext> env) {
   250         while (true) {
   251             switch (env.tree.getTag()) {
   252                 case VARDEF:
   253                     //a field can be owner
   254                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   255                     if (vsym.owner.kind == TYP) {
   256                         return vsym;
   257                     }
   258                     break;
   259                 case METHODDEF:
   260                     //method def is always an owner
   261                     return ((JCMethodDecl)env.tree).sym;
   262                 case CLASSDEF:
   263                     //class def is always an owner
   264                     return ((JCClassDecl)env.tree).sym;
   265                 case BLOCK:
   266                     //static/instance init blocks are owner
   267                     Symbol blockSym = env.info.scope.owner;
   268                     if ((blockSym.flags() & BLOCK) != 0) {
   269                         return blockSym;
   270                     }
   271                     break;
   272                 case TOPLEVEL:
   273                     //toplevel is always an owner (for pkge decls)
   274                     return env.info.scope.owner;
   275             }
   276             Assert.checkNonNull(env.next);
   277             env = env.next;
   278         }
   279     }
   281     /** Check that variable can be assigned to.
   282      *  @param pos    The current source code position.
   283      *  @param v      The assigned varaible
   284      *  @param base   If the variable is referred to in a Select, the part
   285      *                to the left of the `.', null otherwise.
   286      *  @param env    The current environment.
   287      */
   288     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   289         if ((v.flags() & FINAL) != 0 &&
   290             ((v.flags() & HASINIT) != 0
   291              ||
   292              !((base == null ||
   293                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   294                isAssignableAsBlankFinal(v, env)))) {
   295             if (v.isResourceVariable()) { //TWR resource
   296                 log.error(pos, "try.resource.may.not.be.assigned", v);
   297             } else {
   298                 log.error(pos, "cant.assign.val.to.final.var", v);
   299             }
   300         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
   301             v.flags_field &= ~EFFECTIVELY_FINAL;
   302         }
   303     }
   305     /** Does tree represent a static reference to an identifier?
   306      *  It is assumed that tree is either a SELECT or an IDENT.
   307      *  We have to weed out selects from non-type names here.
   308      *  @param tree    The candidate tree.
   309      */
   310     boolean isStaticReference(JCTree tree) {
   311         if (tree.hasTag(SELECT)) {
   312             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   313             if (lsym == null || lsym.kind != TYP) {
   314                 return false;
   315             }
   316         }
   317         return true;
   318     }
   320     /** Is this symbol a type?
   321      */
   322     static boolean isType(Symbol sym) {
   323         return sym != null && sym.kind == TYP;
   324     }
   326     /** The current `this' symbol.
   327      *  @param env    The current environment.
   328      */
   329     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   330         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   331     }
   333     /** Attribute a parsed identifier.
   334      * @param tree Parsed identifier name
   335      * @param topLevel The toplevel to use
   336      */
   337     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   338         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   339         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   340                                            syms.errSymbol.name,
   341                                            null, null, null, null);
   342         localEnv.enclClass.sym = syms.errSymbol;
   343         return tree.accept(identAttributer, localEnv);
   344     }
   345     // where
   346         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   347         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   348             @Override
   349             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   350                 Symbol site = visit(node.getExpression(), env);
   351                 if (site.kind == ERR)
   352                     return site;
   353                 Name name = (Name)node.getIdentifier();
   354                 if (site.kind == PCK) {
   355                     env.toplevel.packge = (PackageSymbol)site;
   356                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   357                 } else {
   358                     env.enclClass.sym = (ClassSymbol)site;
   359                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   360                 }
   361             }
   363             @Override
   364             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   365                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   366             }
   367         }
   369     public Type coerce(Type etype, Type ttype) {
   370         return cfolder.coerce(etype, ttype);
   371     }
   373     public Type attribType(JCTree node, TypeSymbol sym) {
   374         Env<AttrContext> env = enter.typeEnvs.get(sym);
   375         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   376         return attribTree(node, localEnv, unknownTypeInfo);
   377     }
   379     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   380         // Attribute qualifying package or class.
   381         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   382         return attribTree(s.selected,
   383                        env,
   384                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   385                        Type.noType));
   386     }
   388     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   389         breakTree = tree;
   390         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   391         try {
   392             attribExpr(expr, env);
   393         } catch (BreakAttr b) {
   394             return b.env;
   395         } catch (AssertionError ae) {
   396             if (ae.getCause() instanceof BreakAttr) {
   397                 return ((BreakAttr)(ae.getCause())).env;
   398             } else {
   399                 throw ae;
   400             }
   401         } finally {
   402             breakTree = null;
   403             log.useSource(prev);
   404         }
   405         return env;
   406     }
   408     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   409         breakTree = tree;
   410         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   411         try {
   412             attribStat(stmt, env);
   413         } catch (BreakAttr b) {
   414             return b.env;
   415         } catch (AssertionError ae) {
   416             if (ae.getCause() instanceof BreakAttr) {
   417                 return ((BreakAttr)(ae.getCause())).env;
   418             } else {
   419                 throw ae;
   420             }
   421         } finally {
   422             breakTree = null;
   423             log.useSource(prev);
   424         }
   425         return env;
   426     }
   428     private JCTree breakTree = null;
   430     private static class BreakAttr extends RuntimeException {
   431         static final long serialVersionUID = -6924771130405446405L;
   432         private Env<AttrContext> env;
   433         private BreakAttr(Env<AttrContext> env) {
   434             this.env = env;
   435         }
   436     }
   438     class ResultInfo {
   439         int pkind;
   440         Type pt;
   441         CheckContext checkContext;
   443         ResultInfo(int pkind, Type pt) {
   444             this(pkind, pt, chk.basicHandler);
   445         }
   447         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   448             this.pkind = pkind;
   449             this.pt = pt;
   450             this.checkContext = checkContext;
   451         }
   453         protected Type check(DiagnosticPosition pos, Type found) {
   454             return chk.checkType(pos, found, pt, checkContext);
   455         }
   456     }
   458     private final ResultInfo statInfo;
   459     private final ResultInfo varInfo;
   460     private final ResultInfo unknownExprInfo;
   461     private final ResultInfo unknownTypeInfo;
   463     Type pt() {
   464         return resultInfo.pt;
   465     }
   467     int pkind() {
   468         return resultInfo.pkind;
   469     }
   471 /* ************************************************************************
   472  * Visitor methods
   473  *************************************************************************/
   475     /** Visitor argument: the current environment.
   476      */
   477     Env<AttrContext> env;
   479     /** Visitor argument: the currently expected attribution result.
   480      */
   481     ResultInfo resultInfo;
   483     /** Visitor result: the computed type.
   484      */
   485     Type result;
   487     /** Visitor method: attribute a tree, catching any completion failure
   488      *  exceptions. Return the tree's type.
   489      *
   490      *  @param tree    The tree to be visited.
   491      *  @param env     The environment visitor argument.
   492      *  @param resultInfo   The result info visitor argument.
   493      */
   494     private Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   495         Env<AttrContext> prevEnv = this.env;
   496         ResultInfo prevResult = this.resultInfo;
   497         try {
   498             this.env = env;
   499             this.resultInfo = resultInfo;
   500             tree.accept(this);
   501             if (tree == breakTree)
   502                 throw new BreakAttr(env);
   503             return result;
   504         } catch (CompletionFailure ex) {
   505             tree.type = syms.errType;
   506             return chk.completionError(tree.pos(), ex);
   507         } finally {
   508             this.env = prevEnv;
   509             this.resultInfo = prevResult;
   510         }
   511     }
   513     /** Derived visitor method: attribute an expression tree.
   514      */
   515     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   516         return attribTree(tree, env, new ResultInfo(VAL, pt.tag != ERROR ? pt : Type.noType));
   517     }
   519     /** Derived visitor method: attribute an expression tree with
   520      *  no constraints on the computed type.
   521      */
   522     Type attribExpr(JCTree tree, Env<AttrContext> env) {
   523         return attribTree(tree, env, unknownExprInfo);
   524     }
   526     /** Derived visitor method: attribute a type tree.
   527      */
   528     Type attribType(JCTree tree, Env<AttrContext> env) {
   529         Type result = attribType(tree, env, Type.noType);
   530         return result;
   531     }
   533     /** Derived visitor method: attribute a type tree.
   534      */
   535     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   536         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   537         return result;
   538     }
   540     /** Derived visitor method: attribute a statement or definition tree.
   541      */
   542     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   543         return attribTree(tree, env, statInfo);
   544     }
   546     /** Attribute a list of expressions, returning a list of types.
   547      */
   548     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   549         ListBuffer<Type> ts = new ListBuffer<Type>();
   550         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   551             ts.append(attribExpr(l.head, env, pt));
   552         return ts.toList();
   553     }
   555     /** Attribute a list of statements, returning nothing.
   556      */
   557     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   558         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   559             attribStat(l.head, env);
   560     }
   562     /** Attribute the arguments in a method call, returning a list of types.
   563      */
   564     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   565         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   566         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   567             argtypes.append(chk.checkNonVoid(
   568                 l.head.pos(), types.upperBound(attribExpr(l.head, env, Infer.anyPoly))));
   569         return argtypes.toList();
   570     }
   572     /** Attribute a type argument list, returning a list of types.
   573      *  Caller is responsible for calling checkRefTypes.
   574      */
   575     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   576         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   577         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   578             argtypes.append(attribType(l.head, env));
   579         return argtypes.toList();
   580     }
   582     /** Attribute a type argument list, returning a list of types.
   583      *  Check that all the types are references.
   584      */
   585     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   586         List<Type> types = attribAnyTypes(trees, env);
   587         return chk.checkRefTypes(trees, types);
   588     }
   590     /**
   591      * Attribute type variables (of generic classes or methods).
   592      * Compound types are attributed later in attribBounds.
   593      * @param typarams the type variables to enter
   594      * @param env      the current environment
   595      */
   596     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   597         for (JCTypeParameter tvar : typarams) {
   598             TypeVar a = (TypeVar)tvar.type;
   599             a.tsym.flags_field |= UNATTRIBUTED;
   600             a.bound = Type.noType;
   601             if (!tvar.bounds.isEmpty()) {
   602                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   603                 for (JCExpression bound : tvar.bounds.tail)
   604                     bounds = bounds.prepend(attribType(bound, env));
   605                 types.setBounds(a, bounds.reverse());
   606             } else {
   607                 // if no bounds are given, assume a single bound of
   608                 // java.lang.Object.
   609                 types.setBounds(a, List.of(syms.objectType));
   610             }
   611             a.tsym.flags_field &= ~UNATTRIBUTED;
   612         }
   613         for (JCTypeParameter tvar : typarams)
   614             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   615         attribStats(typarams, env);
   616     }
   618     void attribBounds(List<JCTypeParameter> typarams) {
   619         for (JCTypeParameter typaram : typarams) {
   620             Type bound = typaram.type.getUpperBound();
   621             if (bound != null && bound.tsym instanceof ClassSymbol) {
   622                 ClassSymbol c = (ClassSymbol)bound.tsym;
   623                 if ((c.flags_field & COMPOUND) != 0) {
   624                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
   625                     attribClass(typaram.pos(), c);
   626                 }
   627             }
   628         }
   629     }
   631     /**
   632      * Attribute the type references in a list of annotations.
   633      */
   634     void attribAnnotationTypes(List<JCAnnotation> annotations,
   635                                Env<AttrContext> env) {
   636         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   637             JCAnnotation a = al.head;
   638             attribType(a.annotationType, env);
   639         }
   640     }
   642     /**
   643      * Attribute a "lazy constant value".
   644      *  @param env         The env for the const value
   645      *  @param initializer The initializer for the const value
   646      *  @param type        The expected type, or null
   647      *  @see VarSymbol#setlazyConstValue
   648      */
   649     public Object attribLazyConstantValue(Env<AttrContext> env,
   650                                       JCTree.JCExpression initializer,
   651                                       Type type) {
   653         // in case no lint value has been set up for this env, scan up
   654         // env stack looking for smallest enclosing env for which it is set.
   655         Env<AttrContext> lintEnv = env;
   656         while (lintEnv.info.lint == null)
   657             lintEnv = lintEnv.next;
   659         // Having found the enclosing lint value, we can initialize the lint value for this class
   660         // ... but ...
   661         // There's a problem with evaluating annotations in the right order, such that
   662         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   663         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   664         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   665         if (env.info.enclVar.annotations.pendingCompletion()) {
   666             env.info.lint = lintEnv.info.lint;
   667         } else {
   668             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
   669                                                       env.info.enclVar.flags());
   670         }
   672         Lint prevLint = chk.setLint(env.info.lint);
   673         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   675         try {
   676             Type itype = attribExpr(initializer, env, type);
   677             if (itype.constValue() != null)
   678                 return coerce(itype, type).constValue();
   679             else
   680                 return null;
   681         } finally {
   682             env.info.lint = prevLint;
   683             log.useSource(prevSource);
   684         }
   685     }
   687     /** Attribute type reference in an `extends' or `implements' clause.
   688      *  Supertypes of anonymous inner classes are usually already attributed.
   689      *
   690      *  @param tree              The tree making up the type reference.
   691      *  @param env               The environment current at the reference.
   692      *  @param classExpected     true if only a class is expected here.
   693      *  @param interfaceExpected true if only an interface is expected here.
   694      */
   695     Type attribBase(JCTree tree,
   696                     Env<AttrContext> env,
   697                     boolean classExpected,
   698                     boolean interfaceExpected,
   699                     boolean checkExtensible) {
   700         Type t = tree.type != null ?
   701             tree.type :
   702             attribType(tree, env);
   703         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   704     }
   705     Type checkBase(Type t,
   706                    JCTree tree,
   707                    Env<AttrContext> env,
   708                    boolean classExpected,
   709                    boolean interfaceExpected,
   710                    boolean checkExtensible) {
   711         if (t.isErroneous())
   712             return t;
   713         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
   714             // check that type variable is already visible
   715             if (t.getUpperBound() == null) {
   716                 log.error(tree.pos(), "illegal.forward.ref");
   717                 return types.createErrorType(t);
   718             }
   719         } else {
   720             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   721         }
   722         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   723             log.error(tree.pos(), "intf.expected.here");
   724             // return errType is necessary since otherwise there might
   725             // be undetected cycles which cause attribution to loop
   726             return types.createErrorType(t);
   727         } else if (checkExtensible &&
   728                    classExpected &&
   729                    (t.tsym.flags() & INTERFACE) != 0) {
   730                 log.error(tree.pos(), "no.intf.expected.here");
   731             return types.createErrorType(t);
   732         }
   733         if (checkExtensible &&
   734             ((t.tsym.flags() & FINAL) != 0)) {
   735             log.error(tree.pos(),
   736                       "cant.inherit.from.final", t.tsym);
   737         }
   738         chk.checkNonCyclic(tree.pos(), t);
   739         return t;
   740     }
   742     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   743         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   744         id.type = env.info.scope.owner.type;
   745         id.sym = env.info.scope.owner;
   746         return id.type;
   747     }
   749     public void visitClassDef(JCClassDecl tree) {
   750         // Local classes have not been entered yet, so we need to do it now:
   751         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   752             enter.classEnter(tree, env);
   754         ClassSymbol c = tree.sym;
   755         if (c == null) {
   756             // exit in case something drastic went wrong during enter.
   757             result = null;
   758         } else {
   759             // make sure class has been completed:
   760             c.complete();
   762             // If this class appears as an anonymous class
   763             // in a superclass constructor call where
   764             // no explicit outer instance is given,
   765             // disable implicit outer instance from being passed.
   766             // (This would be an illegal access to "this before super").
   767             if (env.info.isSelfCall &&
   768                 env.tree.hasTag(NEWCLASS) &&
   769                 ((JCNewClass) env.tree).encl == null)
   770             {
   771                 c.flags_field |= NOOUTERTHIS;
   772             }
   773             attribClass(tree.pos(), c);
   774             result = tree.type = c.type;
   775         }
   776     }
   778     public void visitMethodDef(JCMethodDecl tree) {
   779         MethodSymbol m = tree.sym;
   781         Lint lint = env.info.lint.augment(m.annotations, m.flags());
   782         Lint prevLint = chk.setLint(lint);
   783         MethodSymbol prevMethod = chk.setMethod(m);
   784         try {
   785             deferredLintHandler.flush(tree.pos());
   786             chk.checkDeprecatedAnnotation(tree.pos(), m);
   788             attribBounds(tree.typarams);
   790             // If we override any other methods, check that we do so properly.
   791             // JLS ???
   792             if (m.isStatic()) {
   793                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   794             } else {
   795                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   796             }
   797             chk.checkOverride(tree, m);
   799             // Create a new environment with local scope
   800             // for attributing the method.
   801             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   803             localEnv.info.lint = lint;
   805             // Enter all type parameters into the local method scope.
   806             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   807                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   809             ClassSymbol owner = env.enclClass.sym;
   810             if ((owner.flags() & ANNOTATION) != 0 &&
   811                 tree.params.nonEmpty())
   812                 log.error(tree.params.head.pos(),
   813                           "intf.annotation.members.cant.have.params");
   815             // Attribute all value parameters.
   816             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   817                 attribStat(l.head, localEnv);
   818             }
   820             chk.checkVarargsMethodDecl(localEnv, tree);
   822             // Check that type parameters are well-formed.
   823             chk.validate(tree.typarams, localEnv);
   825             // Check that result type is well-formed.
   826             chk.validate(tree.restype, localEnv);
   828             // annotation method checks
   829             if ((owner.flags() & ANNOTATION) != 0) {
   830                 // annotation method cannot have throws clause
   831                 if (tree.thrown.nonEmpty()) {
   832                     log.error(tree.thrown.head.pos(),
   833                             "throws.not.allowed.in.intf.annotation");
   834                 }
   835                 // annotation method cannot declare type-parameters
   836                 if (tree.typarams.nonEmpty()) {
   837                     log.error(tree.typarams.head.pos(),
   838                             "intf.annotation.members.cant.have.type.params");
   839                 }
   840                 // validate annotation method's return type (could be an annotation type)
   841                 chk.validateAnnotationType(tree.restype);
   842                 // ensure that annotation method does not clash with members of Object/Annotation
   843                 chk.validateAnnotationMethod(tree.pos(), m);
   845                 if (tree.defaultValue != null) {
   846                     // if default value is an annotation, check it is a well-formed
   847                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   848                     chk.validateAnnotationTree(tree.defaultValue);
   849                 }
   850             }
   852             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   853                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   855             if (tree.body == null) {
   856                 // Empty bodies are only allowed for
   857                 // abstract, native, or interface methods, or for methods
   858                 // in a retrofit signature class.
   859                 if ((owner.flags() & INTERFACE) == 0 &&
   860                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
   861                     !relax)
   862                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   863                 if (tree.defaultValue != null) {
   864                     if ((owner.flags() & ANNOTATION) == 0)
   865                         log.error(tree.pos(),
   866                                   "default.allowed.in.intf.annotation.member");
   867                 }
   868             } else if ((owner.flags() & INTERFACE) != 0) {
   869                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
   870             } else if ((tree.mods.flags & ABSTRACT) != 0) {
   871                 log.error(tree.pos(), "abstract.meth.cant.have.body");
   872             } else if ((tree.mods.flags & NATIVE) != 0) {
   873                 log.error(tree.pos(), "native.meth.cant.have.body");
   874             } else {
   875                 // Add an implicit super() call unless an explicit call to
   876                 // super(...) or this(...) is given
   877                 // or we are compiling class java.lang.Object.
   878                 if (tree.name == names.init && owner.type != syms.objectType) {
   879                     JCBlock body = tree.body;
   880                     if (body.stats.isEmpty() ||
   881                         !TreeInfo.isSelfCall(body.stats.head)) {
   882                         body.stats = body.stats.
   883                             prepend(memberEnter.SuperCall(make.at(body.pos),
   884                                                           List.<Type>nil(),
   885                                                           List.<JCVariableDecl>nil(),
   886                                                           false));
   887                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   888                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   889                                TreeInfo.isSuperCall(body.stats.head)) {
   890                         // enum constructors are not allowed to call super
   891                         // directly, so make sure there aren't any super calls
   892                         // in enum constructors, except in the compiler
   893                         // generated one.
   894                         log.error(tree.body.stats.head.pos(),
   895                                   "call.to.super.not.allowed.in.enum.ctor",
   896                                   env.enclClass.sym);
   897                     }
   898                 }
   900                 // Attribute method body.
   901                 attribStat(tree.body, localEnv);
   902             }
   903             localEnv.info.scope.leave();
   904             result = tree.type = m.type;
   905             chk.validateAnnotations(tree.mods.annotations, m);
   906         }
   907         finally {
   908             chk.setLint(prevLint);
   909             chk.setMethod(prevMethod);
   910         }
   911     }
   913     public void visitVarDef(JCVariableDecl tree) {
   914         // Local variables have not been entered yet, so we need to do it now:
   915         if (env.info.scope.owner.kind == MTH) {
   916             if (tree.sym != null) {
   917                 // parameters have already been entered
   918                 env.info.scope.enter(tree.sym);
   919             } else {
   920                 memberEnter.memberEnter(tree, env);
   921                 annotate.flush();
   922             }
   923         }
   925         VarSymbol v = tree.sym;
   926         Lint lint = env.info.lint.augment(v.annotations, v.flags());
   927         Lint prevLint = chk.setLint(lint);
   929         // Check that the variable's declared type is well-formed.
   930         chk.validate(tree.vartype, env);
   931         deferredLintHandler.flush(tree.pos());
   933         try {
   934             chk.checkDeprecatedAnnotation(tree.pos(), v);
   936             if (tree.init != null) {
   937                 if ((v.flags_field & FINAL) != 0 && !tree.init.hasTag(NEWCLASS)) {
   938                     // In this case, `v' is final.  Ensure that it's initializer is
   939                     // evaluated.
   940                     v.getConstValue(); // ensure initializer is evaluated
   941                 } else {
   942                     // Attribute initializer in a new environment
   943                     // with the declared variable as owner.
   944                     // Check that initializer conforms to variable's declared type.
   945                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
   946                     initEnv.info.lint = lint;
   947                     // In order to catch self-references, we set the variable's
   948                     // declaration position to maximal possible value, effectively
   949                     // marking the variable as undefined.
   950                     initEnv.info.enclVar = v;
   951                     attribExpr(tree.init, initEnv, v.type);
   952                 }
   953             }
   954             result = tree.type = v.type;
   955             chk.validateAnnotations(tree.mods.annotations, v);
   956         }
   957         finally {
   958             chk.setLint(prevLint);
   959         }
   960     }
   962     public void visitSkip(JCSkip tree) {
   963         result = null;
   964     }
   966     public void visitBlock(JCBlock tree) {
   967         if (env.info.scope.owner.kind == TYP) {
   968             // Block is a static or instance initializer;
   969             // let the owner of the environment be a freshly
   970             // created BLOCK-method.
   971             Env<AttrContext> localEnv =
   972                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   973             localEnv.info.scope.owner =
   974                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
   975                                  env.info.scope.owner);
   976             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
   977             attribStats(tree.stats, localEnv);
   978         } else {
   979             // Create a new local environment with a local scope.
   980             Env<AttrContext> localEnv =
   981                 env.dup(tree, env.info.dup(env.info.scope.dup()));
   982             attribStats(tree.stats, localEnv);
   983             localEnv.info.scope.leave();
   984         }
   985         result = null;
   986     }
   988     public void visitDoLoop(JCDoWhileLoop tree) {
   989         attribStat(tree.body, env.dup(tree));
   990         attribExpr(tree.cond, env, syms.booleanType);
   991         result = null;
   992     }
   994     public void visitWhileLoop(JCWhileLoop tree) {
   995         attribExpr(tree.cond, env, syms.booleanType);
   996         attribStat(tree.body, env.dup(tree));
   997         result = null;
   998     }
  1000     public void visitForLoop(JCForLoop tree) {
  1001         Env<AttrContext> loopEnv =
  1002             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1003         attribStats(tree.init, loopEnv);
  1004         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1005         loopEnv.tree = tree; // before, we were not in loop!
  1006         attribStats(tree.step, loopEnv);
  1007         attribStat(tree.body, loopEnv);
  1008         loopEnv.info.scope.leave();
  1009         result = null;
  1012     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1013         Env<AttrContext> loopEnv =
  1014             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1015         attribStat(tree.var, loopEnv);
  1016         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1017         chk.checkNonVoid(tree.pos(), exprType);
  1018         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1019         if (elemtype == null) {
  1020             // or perhaps expr implements Iterable<T>?
  1021             Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1022             if (base == null) {
  1023                 log.error(tree.expr.pos(),
  1024                         "foreach.not.applicable.to.type",
  1025                         exprType,
  1026                         diags.fragment("type.req.array.or.iterable"));
  1027                 elemtype = types.createErrorType(exprType);
  1028             } else {
  1029                 List<Type> iterableParams = base.allparams();
  1030                 elemtype = iterableParams.isEmpty()
  1031                     ? syms.objectType
  1032                     : types.upperBound(iterableParams.head);
  1035         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1036         loopEnv.tree = tree; // before, we were not in loop!
  1037         attribStat(tree.body, loopEnv);
  1038         loopEnv.info.scope.leave();
  1039         result = null;
  1042     public void visitLabelled(JCLabeledStatement tree) {
  1043         // Check that label is not used in an enclosing statement
  1044         Env<AttrContext> env1 = env;
  1045         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1046             if (env1.tree.hasTag(LABELLED) &&
  1047                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1048                 log.error(tree.pos(), "label.already.in.use",
  1049                           tree.label);
  1050                 break;
  1052             env1 = env1.next;
  1055         attribStat(tree.body, env.dup(tree));
  1056         result = null;
  1059     public void visitSwitch(JCSwitch tree) {
  1060         Type seltype = attribExpr(tree.selector, env);
  1062         Env<AttrContext> switchEnv =
  1063             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1065         boolean enumSwitch =
  1066             allowEnums &&
  1067             (seltype.tsym.flags() & Flags.ENUM) != 0;
  1068         boolean stringSwitch = false;
  1069         if (types.isSameType(seltype, syms.stringType)) {
  1070             if (allowStringsInSwitch) {
  1071                 stringSwitch = true;
  1072             } else {
  1073                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1076         if (!enumSwitch && !stringSwitch)
  1077             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1079         // Attribute all cases and
  1080         // check that there are no duplicate case labels or default clauses.
  1081         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1082         boolean hasDefault = false;      // Is there a default label?
  1083         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1084             JCCase c = l.head;
  1085             Env<AttrContext> caseEnv =
  1086                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1087             if (c.pat != null) {
  1088                 if (enumSwitch) {
  1089                     Symbol sym = enumConstant(c.pat, seltype);
  1090                     if (sym == null) {
  1091                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1092                     } else if (!labels.add(sym)) {
  1093                         log.error(c.pos(), "duplicate.case.label");
  1095                 } else {
  1096                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1097                     if (pattype.tag != ERROR) {
  1098                         if (pattype.constValue() == null) {
  1099                             log.error(c.pat.pos(),
  1100                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
  1101                         } else if (labels.contains(pattype.constValue())) {
  1102                             log.error(c.pos(), "duplicate.case.label");
  1103                         } else {
  1104                             labels.add(pattype.constValue());
  1108             } else if (hasDefault) {
  1109                 log.error(c.pos(), "duplicate.default.label");
  1110             } else {
  1111                 hasDefault = true;
  1113             attribStats(c.stats, caseEnv);
  1114             caseEnv.info.scope.leave();
  1115             addVars(c.stats, switchEnv.info.scope);
  1118         switchEnv.info.scope.leave();
  1119         result = null;
  1121     // where
  1122         /** Add any variables defined in stats to the switch scope. */
  1123         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1124             for (;stats.nonEmpty(); stats = stats.tail) {
  1125                 JCTree stat = stats.head;
  1126                 if (stat.hasTag(VARDEF))
  1127                     switchScope.enter(((JCVariableDecl) stat).sym);
  1130     // where
  1131     /** Return the selected enumeration constant symbol, or null. */
  1132     private Symbol enumConstant(JCTree tree, Type enumType) {
  1133         if (!tree.hasTag(IDENT)) {
  1134             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1135             return syms.errSymbol;
  1137         JCIdent ident = (JCIdent)tree;
  1138         Name name = ident.name;
  1139         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1140              e.scope != null; e = e.next()) {
  1141             if (e.sym.kind == VAR) {
  1142                 Symbol s = ident.sym = e.sym;
  1143                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1144                 ident.type = s.type;
  1145                 return ((s.flags_field & Flags.ENUM) == 0)
  1146                     ? null : s;
  1149         return null;
  1152     public void visitSynchronized(JCSynchronized tree) {
  1153         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1154         attribStat(tree.body, env);
  1155         result = null;
  1158     public void visitTry(JCTry tree) {
  1159         // Create a new local environment with a local
  1160         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1161         boolean isTryWithResource = tree.resources.nonEmpty();
  1162         // Create a nested environment for attributing the try block if needed
  1163         Env<AttrContext> tryEnv = isTryWithResource ?
  1164             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1165             localEnv;
  1166         // Attribute resource declarations
  1167         for (JCTree resource : tree.resources) {
  1168             CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1169                 @Override
  1170                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1171                     chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1173             };
  1174             ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1175             if (resource.hasTag(VARDEF)) {
  1176                 attribStat(resource, tryEnv);
  1177                 twrResult.check(resource, resource.type);
  1179                 //check that resource type cannot throw InterruptedException
  1180                 checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1182                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
  1183                 var.setData(ElementKind.RESOURCE_VARIABLE);
  1184             } else {
  1185                 attribTree(resource, tryEnv, twrResult);
  1188         // Attribute body
  1189         attribStat(tree.body, tryEnv);
  1190         if (isTryWithResource)
  1191             tryEnv.info.scope.leave();
  1193         // Attribute catch clauses
  1194         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1195             JCCatch c = l.head;
  1196             Env<AttrContext> catchEnv =
  1197                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1198             Type ctype = attribStat(c.param, catchEnv);
  1199             if (TreeInfo.isMultiCatch(c)) {
  1200                 //multi-catch parameter is implicitly marked as final
  1201                 c.param.sym.flags_field |= FINAL | UNION;
  1203             if (c.param.sym.kind == Kinds.VAR) {
  1204                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1206             chk.checkType(c.param.vartype.pos(),
  1207                           chk.checkClassType(c.param.vartype.pos(), ctype),
  1208                           syms.throwableType);
  1209             attribStat(c.body, catchEnv);
  1210             catchEnv.info.scope.leave();
  1213         // Attribute finalizer
  1214         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1216         localEnv.info.scope.leave();
  1217         result = null;
  1220     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1221         if (!resource.isErroneous() &&
  1222             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1223             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1224             Symbol close = syms.noSymbol;
  1225             boolean prevDeferDiags = log.deferDiagnostics;
  1226             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1227             try {
  1228                 log.deferDiagnostics = true;
  1229                 log.deferredDiagnostics = ListBuffer.lb();
  1230                 close = rs.resolveQualifiedMethod(pos,
  1231                         env,
  1232                         resource,
  1233                         names.close,
  1234                         List.<Type>nil(),
  1235                         List.<Type>nil());
  1237             finally {
  1238                 log.deferDiagnostics = prevDeferDiags;
  1239                 log.deferredDiagnostics = prevDeferredDiags;
  1241             if (close.kind == MTH &&
  1242                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1243                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1244                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1245                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1250     public void visitConditional(JCConditional tree) {
  1251         attribExpr(tree.cond, env, syms.booleanType);
  1252         attribExpr(tree.truepart, env);
  1253         attribExpr(tree.falsepart, env);
  1254         result = check(tree,
  1255                        capture(condType(tree.pos(), tree.cond.type,
  1256                                         tree.truepart.type, tree.falsepart.type)),
  1257                        VAL, resultInfo);
  1259     //where
  1260         /** Compute the type of a conditional expression, after
  1261          *  checking that it exists. See Spec 15.25.
  1263          *  @param pos      The source position to be used for
  1264          *                  error diagnostics.
  1265          *  @param condtype The type of the expression's condition.
  1266          *  @param thentype The type of the expression's then-part.
  1267          *  @param elsetype The type of the expression's else-part.
  1268          */
  1269         private Type condType(DiagnosticPosition pos,
  1270                               Type condtype,
  1271                               Type thentype,
  1272                               Type elsetype) {
  1273             Type ctype = condType1(pos, condtype, thentype, elsetype);
  1275             // If condition and both arms are numeric constants,
  1276             // evaluate at compile-time.
  1277             return ((condtype.constValue() != null) &&
  1278                     (thentype.constValue() != null) &&
  1279                     (elsetype.constValue() != null))
  1280                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
  1281                 : ctype;
  1283         /** Compute the type of a conditional expression, after
  1284          *  checking that it exists.  Does not take into
  1285          *  account the special case where condition and both arms
  1286          *  are constants.
  1288          *  @param pos      The source position to be used for error
  1289          *                  diagnostics.
  1290          *  @param condtype The type of the expression's condition.
  1291          *  @param thentype The type of the expression's then-part.
  1292          *  @param elsetype The type of the expression's else-part.
  1293          */
  1294         private Type condType1(DiagnosticPosition pos, Type condtype,
  1295                                Type thentype, Type elsetype) {
  1296             // If same type, that is the result
  1297             if (types.isSameType(thentype, elsetype))
  1298                 return thentype.baseType();
  1300             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1301                 ? thentype : types.unboxedType(thentype);
  1302             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1303                 ? elsetype : types.unboxedType(elsetype);
  1305             // Otherwise, if both arms can be converted to a numeric
  1306             // type, return the least numeric type that fits both arms
  1307             // (i.e. return larger of the two, or return int if one
  1308             // arm is short, the other is char).
  1309             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1310                 // If one arm has an integer subrange type (i.e., byte,
  1311                 // short, or char), and the other is an integer constant
  1312                 // that fits into the subrange, return the subrange type.
  1313                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
  1314                     types.isAssignable(elseUnboxed, thenUnboxed))
  1315                     return thenUnboxed.baseType();
  1316                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
  1317                     types.isAssignable(thenUnboxed, elseUnboxed))
  1318                     return elseUnboxed.baseType();
  1320                 for (int i = BYTE; i < VOID; i++) {
  1321                     Type candidate = syms.typeOfTag[i];
  1322                     if (types.isSubtype(thenUnboxed, candidate) &&
  1323                         types.isSubtype(elseUnboxed, candidate))
  1324                         return candidate;
  1328             // Those were all the cases that could result in a primitive
  1329             if (allowBoxing) {
  1330                 if (thentype.isPrimitive())
  1331                     thentype = types.boxedClass(thentype).type;
  1332                 if (elsetype.isPrimitive())
  1333                     elsetype = types.boxedClass(elsetype).type;
  1336             if (types.isSubtype(thentype, elsetype))
  1337                 return elsetype.baseType();
  1338             if (types.isSubtype(elsetype, thentype))
  1339                 return thentype.baseType();
  1341             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
  1342                 log.error(pos, "neither.conditional.subtype",
  1343                           thentype, elsetype);
  1344                 return thentype.baseType();
  1347             // both are known to be reference types.  The result is
  1348             // lub(thentype,elsetype). This cannot fail, as it will
  1349             // always be possible to infer "Object" if nothing better.
  1350             return types.lub(thentype.baseType(), elsetype.baseType());
  1353     public void visitIf(JCIf tree) {
  1354         attribExpr(tree.cond, env, syms.booleanType);
  1355         attribStat(tree.thenpart, env);
  1356         if (tree.elsepart != null)
  1357             attribStat(tree.elsepart, env);
  1358         chk.checkEmptyIf(tree);
  1359         result = null;
  1362     public void visitExec(JCExpressionStatement tree) {
  1363         //a fresh environment is required for 292 inference to work properly ---
  1364         //see Infer.instantiatePolymorphicSignatureInstance()
  1365         Env<AttrContext> localEnv = env.dup(tree);
  1366         attribExpr(tree.expr, localEnv);
  1367         result = null;
  1370     public void visitBreak(JCBreak tree) {
  1371         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1372         result = null;
  1375     public void visitContinue(JCContinue tree) {
  1376         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1377         result = null;
  1379     //where
  1380         /** Return the target of a break or continue statement, if it exists,
  1381          *  report an error if not.
  1382          *  Note: The target of a labelled break or continue is the
  1383          *  (non-labelled) statement tree referred to by the label,
  1384          *  not the tree representing the labelled statement itself.
  1386          *  @param pos     The position to be used for error diagnostics
  1387          *  @param tag     The tag of the jump statement. This is either
  1388          *                 Tree.BREAK or Tree.CONTINUE.
  1389          *  @param label   The label of the jump statement, or null if no
  1390          *                 label is given.
  1391          *  @param env     The environment current at the jump statement.
  1392          */
  1393         private JCTree findJumpTarget(DiagnosticPosition pos,
  1394                                     JCTree.Tag tag,
  1395                                     Name label,
  1396                                     Env<AttrContext> env) {
  1397             // Search environments outwards from the point of jump.
  1398             Env<AttrContext> env1 = env;
  1399             LOOP:
  1400             while (env1 != null) {
  1401                 switch (env1.tree.getTag()) {
  1402                 case LABELLED:
  1403                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1404                     if (label == labelled.label) {
  1405                         // If jump is a continue, check that target is a loop.
  1406                         if (tag == CONTINUE) {
  1407                             if (!labelled.body.hasTag(DOLOOP) &&
  1408                                 !labelled.body.hasTag(WHILELOOP) &&
  1409                                 !labelled.body.hasTag(FORLOOP) &&
  1410                                 !labelled.body.hasTag(FOREACHLOOP))
  1411                                 log.error(pos, "not.loop.label", label);
  1412                             // Found labelled statement target, now go inwards
  1413                             // to next non-labelled tree.
  1414                             return TreeInfo.referencedStatement(labelled);
  1415                         } else {
  1416                             return labelled;
  1419                     break;
  1420                 case DOLOOP:
  1421                 case WHILELOOP:
  1422                 case FORLOOP:
  1423                 case FOREACHLOOP:
  1424                     if (label == null) return env1.tree;
  1425                     break;
  1426                 case SWITCH:
  1427                     if (label == null && tag == BREAK) return env1.tree;
  1428                     break;
  1429                 case METHODDEF:
  1430                 case CLASSDEF:
  1431                     break LOOP;
  1432                 default:
  1434                 env1 = env1.next;
  1436             if (label != null)
  1437                 log.error(pos, "undef.label", label);
  1438             else if (tag == CONTINUE)
  1439                 log.error(pos, "cont.outside.loop");
  1440             else
  1441                 log.error(pos, "break.outside.switch.loop");
  1442             return null;
  1445     public void visitReturn(JCReturn tree) {
  1446         // Check that there is an enclosing method which is
  1447         // nested within than the enclosing class.
  1448         if (env.enclMethod == null ||
  1449             env.enclMethod.sym.owner != env.enclClass.sym) {
  1450             log.error(tree.pos(), "ret.outside.meth");
  1452         } else {
  1453             // Attribute return expression, if it exists, and check that
  1454             // it conforms to result type of enclosing method.
  1455             Symbol m = env.enclMethod.sym;
  1456             if (m.type.getReturnType().tag == VOID) {
  1457                 if (tree.expr != null)
  1458                     log.error(tree.expr.pos(),
  1459                               "cant.ret.val.from.meth.decl.void");
  1460             } else if (tree.expr == null) {
  1461                 log.error(tree.pos(), "missing.ret.val");
  1462             } else {
  1463                 attribExpr(tree.expr, env, m.type.getReturnType());
  1466         result = null;
  1469     public void visitThrow(JCThrow tree) {
  1470         attribExpr(tree.expr, env, syms.throwableType);
  1471         result = null;
  1474     public void visitAssert(JCAssert tree) {
  1475         attribExpr(tree.cond, env, syms.booleanType);
  1476         if (tree.detail != null) {
  1477             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1479         result = null;
  1482      /** Visitor method for method invocations.
  1483      *  NOTE: The method part of an application will have in its type field
  1484      *        the return type of the method, not the method's type itself!
  1485      */
  1486     public void visitApply(JCMethodInvocation tree) {
  1487         // The local environment of a method application is
  1488         // a new environment nested in the current one.
  1489         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1491         // The types of the actual method arguments.
  1492         List<Type> argtypes;
  1494         // The types of the actual method type arguments.
  1495         List<Type> typeargtypes = null;
  1497         Name methName = TreeInfo.name(tree.meth);
  1499         boolean isConstructorCall =
  1500             methName == names._this || methName == names._super;
  1502         if (isConstructorCall) {
  1503             // We are seeing a ...this(...) or ...super(...) call.
  1504             // Check that this is the first statement in a constructor.
  1505             if (checkFirstConstructorStat(tree, env)) {
  1507                 // Record the fact
  1508                 // that this is a constructor call (using isSelfCall).
  1509                 localEnv.info.isSelfCall = true;
  1511                 // Attribute arguments, yielding list of argument types.
  1512                 argtypes = attribArgs(tree.args, localEnv);
  1513                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1515                 // Variable `site' points to the class in which the called
  1516                 // constructor is defined.
  1517                 Type site = env.enclClass.sym.type;
  1518                 if (methName == names._super) {
  1519                     if (site == syms.objectType) {
  1520                         log.error(tree.meth.pos(), "no.superclass", site);
  1521                         site = types.createErrorType(syms.objectType);
  1522                     } else {
  1523                         site = types.supertype(site);
  1527                 if (site.tag == CLASS) {
  1528                     Type encl = site.getEnclosingType();
  1529                     while (encl != null && encl.tag == TYPEVAR)
  1530                         encl = encl.getUpperBound();
  1531                     if (encl.tag == CLASS) {
  1532                         // we are calling a nested class
  1534                         if (tree.meth.hasTag(SELECT)) {
  1535                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1537                             // We are seeing a prefixed call, of the form
  1538                             //     <expr>.super(...).
  1539                             // Check that the prefix expression conforms
  1540                             // to the outer instance type of the class.
  1541                             chk.checkRefType(qualifier.pos(),
  1542                                              attribExpr(qualifier, localEnv,
  1543                                                         encl));
  1544                         } else if (methName == names._super) {
  1545                             // qualifier omitted; check for existence
  1546                             // of an appropriate implicit qualifier.
  1547                             rs.resolveImplicitThis(tree.meth.pos(),
  1548                                                    localEnv, site, true);
  1550                     } else if (tree.meth.hasTag(SELECT)) {
  1551                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1552                                   site.tsym);
  1555                     // if we're calling a java.lang.Enum constructor,
  1556                     // prefix the implicit String and int parameters
  1557                     if (site.tsym == syms.enumSym && allowEnums)
  1558                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1560                     // Resolve the called constructor under the assumption
  1561                     // that we are referring to a superclass instance of the
  1562                     // current instance (JLS ???).
  1563                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1564                     localEnv.info.selectSuper = true;
  1565                     localEnv.info.varArgs = false;
  1566                     Symbol sym = rs.resolveConstructor(
  1567                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1568                     localEnv.info.selectSuper = selectSuperPrev;
  1570                     // Set method symbol to resolved constructor...
  1571                     TreeInfo.setSymbol(tree.meth, sym);
  1573                     // ...and check that it is legal in the current context.
  1574                     // (this will also set the tree's type)
  1575                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1576                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt),
  1577                             tree.varargsElement != null);
  1579                 // Otherwise, `site' is an error type and we do nothing
  1581             result = tree.type = syms.voidType;
  1582         } else {
  1583             // Otherwise, we are seeing a regular method call.
  1584             // Attribute the arguments, yielding list of argument types, ...
  1585             argtypes = attribArgs(tree.args, localEnv);
  1586             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1588             // ... and attribute the method using as a prototype a methodtype
  1589             // whose formal argument types is exactly the list of actual
  1590             // arguments (this will also set the method symbol).
  1591             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1592             localEnv.info.varArgs = false;
  1593             Type mtype = attribExpr(tree.meth, localEnv, mpt);
  1595             // Compute the result type.
  1596             Type restype = mtype.getReturnType();
  1597             if (restype.tag == WILDCARD)
  1598                 throw new AssertionError(mtype);
  1600             // as a special case, array.clone() has a result that is
  1601             // the same as static type of the array being cloned
  1602             if (tree.meth.hasTag(SELECT) &&
  1603                 allowCovariantReturns &&
  1604                 methName == names.clone &&
  1605                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
  1606                 restype = ((JCFieldAccess) tree.meth).selected.type;
  1608             // as a special case, x.getClass() has type Class<? extends |X|>
  1609             if (allowGenerics &&
  1610                 methName == names.getClass && tree.args.isEmpty()) {
  1611                 Type qualifier = (tree.meth.hasTag(SELECT))
  1612                     ? ((JCFieldAccess) tree.meth).selected.type
  1613                     : env.enclClass.sym.type;
  1614                 restype = new
  1615                     ClassType(restype.getEnclosingType(),
  1616                               List.<Type>of(new WildcardType(types.erasure(qualifier),
  1617                                                                BoundKind.EXTENDS,
  1618                                                                syms.boundClass)),
  1619                               restype.tsym);
  1622             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1624             // Check that value of resulting type is admissible in the
  1625             // current context.  Also, capture the return type
  1626             result = check(tree, capture(restype), VAL, resultInfo);
  1628             if (localEnv.info.varArgs)
  1629                 Assert.check(result.isErroneous() || tree.varargsElement != null);
  1631         chk.validate(tree.typeargs, localEnv);
  1633     //where
  1634         /** Check that given application node appears as first statement
  1635          *  in a constructor call.
  1636          *  @param tree   The application node
  1637          *  @param env    The environment current at the application.
  1638          */
  1639         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1640             JCMethodDecl enclMethod = env.enclMethod;
  1641             if (enclMethod != null && enclMethod.name == names.init) {
  1642                 JCBlock body = enclMethod.body;
  1643                 if (body.stats.head.hasTag(EXEC) &&
  1644                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1645                     return true;
  1647             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1648                       TreeInfo.name(tree.meth));
  1649             return false;
  1652         /** Obtain a method type with given argument types.
  1653          */
  1654         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1655             MethodType mt = new MethodType(argtypes, restype, null, syms.methodClass);
  1656             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1659     public void visitNewClass(JCNewClass tree) {
  1660         Type owntype = types.createErrorType(tree.type);
  1662         // The local environment of a class creation is
  1663         // a new environment nested in the current one.
  1664         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1666         // The anonymous inner class definition of the new expression,
  1667         // if one is defined by it.
  1668         JCClassDecl cdef = tree.def;
  1670         // If enclosing class is given, attribute it, and
  1671         // complete class name to be fully qualified
  1672         JCExpression clazz = tree.clazz; // Class field following new
  1673         JCExpression clazzid =          // Identifier in class field
  1674             (clazz.hasTag(TYPEAPPLY))
  1675             ? ((JCTypeApply) clazz).clazz
  1676             : clazz;
  1678         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1680         if (tree.encl != null) {
  1681             // We are seeing a qualified new, of the form
  1682             //    <expr>.new C <...> (...) ...
  1683             // In this case, we let clazz stand for the name of the
  1684             // allocated class C prefixed with the type of the qualifier
  1685             // expression, so that we can
  1686             // resolve it with standard techniques later. I.e., if
  1687             // <expr> has type T, then <expr>.new C <...> (...)
  1688             // yields a clazz T.C.
  1689             Type encltype = chk.checkRefType(tree.encl.pos(),
  1690                                              attribExpr(tree.encl, env));
  1691             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1692                                                  ((JCIdent) clazzid).name);
  1693             if (clazz.hasTag(TYPEAPPLY))
  1694                 clazz = make.at(tree.pos).
  1695                     TypeApply(clazzid1,
  1696                               ((JCTypeApply) clazz).arguments);
  1697             else
  1698                 clazz = clazzid1;
  1701         // Attribute clazz expression and store
  1702         // symbol + type back into the attributed tree.
  1703         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1704             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1705             attribType(clazz, env);
  1707         clazztype = chk.checkDiamond(tree, clazztype);
  1708         chk.validate(clazz, localEnv);
  1709         if (tree.encl != null) {
  1710             // We have to work in this case to store
  1711             // symbol + type back into the attributed tree.
  1712             tree.clazz.type = clazztype;
  1713             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1714             clazzid.type = ((JCIdent) clazzid).sym.type;
  1715             if (!clazztype.isErroneous()) {
  1716                 if (cdef != null && clazztype.tsym.isInterface()) {
  1717                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1718                 } else if (clazztype.tsym.isStatic()) {
  1719                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1722         } else if (!clazztype.tsym.isInterface() &&
  1723                    clazztype.getEnclosingType().tag == CLASS) {
  1724             // Check for the existence of an apropos outer instance
  1725             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1728         // Attribute constructor arguments.
  1729         List<Type> argtypes = attribArgs(tree.args, localEnv);
  1730         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1732         if (TreeInfo.isDiamond(tree) && !clazztype.isErroneous()) {
  1733             Pair<Symbol, Type> diamondResult =
  1734                     attribDiamond(localEnv, tree, clazztype, argtypes, typeargtypes);
  1735             tree.clazz.type = types.createErrorType(clazztype);
  1736             tree.constructor = diamondResult.fst;
  1737             tree.constructorType = diamondResult.snd;
  1738             if (!diamondResult.snd.isErroneous()) {
  1739                 tree.clazz.type = clazztype = diamondResult.snd.getReturnType();
  1740                 tree.constructorType = types.createMethodTypeWithReturn(diamondResult.snd, syms.voidType);
  1742             clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  1745         // If we have made no mistakes in the class type...
  1746         if (clazztype.tag == CLASS) {
  1747             // Enums may not be instantiated except implicitly
  1748             if (allowEnums &&
  1749                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1750                 (!env.tree.hasTag(VARDEF) ||
  1751                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1752                  ((JCVariableDecl) env.tree).init != tree))
  1753                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1754             // Check that class is not abstract
  1755             if (cdef == null &&
  1756                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1757                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1758                           clazztype.tsym);
  1759             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1760                 // Check that no constructor arguments are given to
  1761                 // anonymous classes implementing an interface
  1762                 if (!argtypes.isEmpty())
  1763                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  1765                 if (!typeargtypes.isEmpty())
  1766                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  1768                 // Error recovery: pretend no arguments were supplied.
  1769                 argtypes = List.nil();
  1770                 typeargtypes = List.nil();
  1773             // Resolve the called constructor under the assumption
  1774             // that we are referring to a superclass instance of the
  1775             // current instance (JLS ???).
  1776             else if (!TreeInfo.isDiamond(tree)) {
  1777                 //the following code alters some of the fields in the current
  1778                 //AttrContext - hence, the current context must be dup'ed in
  1779                 //order to avoid downstream failures
  1780                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  1781                 rsEnv.info.selectSuper = cdef != null;
  1782                 rsEnv.info.varArgs = false;
  1783                 tree.constructor = rs.resolveConstructor(
  1784                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  1785                 if (cdef == null) { //do not check twice!
  1786                     tree.constructorType = checkId(tree,
  1787                             clazztype,
  1788                             tree.constructor,
  1789                             rsEnv,
  1790                             new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)),
  1791                             rsEnv.info.varArgs);
  1792                     if (rsEnv.info.varArgs)
  1793                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  1795                 if (tree.def == null &&
  1796                         !clazztype.isErroneous() &&
  1797                         clazztype.getTypeArguments().nonEmpty() &&
  1798                         findDiamonds) {
  1799                     boolean prevDeferDiags = log.deferDiagnostics;
  1800                     Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
  1801                     Type inferred = null;
  1802                     try {
  1803                         //disable diamond-related diagnostics
  1804                         log.deferDiagnostics = true;
  1805                         log.deferredDiagnostics = ListBuffer.lb();
  1806                         inferred = attribDiamond(localEnv,
  1807                                 tree,
  1808                                 clazztype,
  1809                                 argtypes,
  1810                                 typeargtypes).snd;
  1811                     } finally {
  1812                         log.deferDiagnostics = prevDeferDiags;
  1813                         log.deferredDiagnostics = prevDeferredDiags;
  1815                     if (!inferred.isErroneous()) {
  1816                         inferred = inferred.getReturnType();
  1818                     if (inferred != null &&
  1819                             types.isAssignable(inferred, pt().tag == NONE ? syms.objectType : pt(), Warner.noWarnings)) {
  1820                         String key = types.isSameType(clazztype, inferred) ?
  1821                             "diamond.redundant.args" :
  1822                             "diamond.redundant.args.1";
  1823                         log.warning(tree.clazz.pos(), key, clazztype, inferred);
  1828             if (cdef != null) {
  1829                 // We are seeing an anonymous class instance creation.
  1830                 // In this case, the class instance creation
  1831                 // expression
  1832                 //
  1833                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1834                 //
  1835                 // is represented internally as
  1836                 //
  1837                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  1838                 //
  1839                 // This expression is then *transformed* as follows:
  1840                 //
  1841                 // (1) add a STATIC flag to the class definition
  1842                 //     if the current environment is static
  1843                 // (2) add an extends or implements clause
  1844                 // (3) add a constructor.
  1845                 //
  1846                 // For instance, if C is a class, and ET is the type of E,
  1847                 // the expression
  1848                 //
  1849                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  1850                 //
  1851                 // is translated to (where X is a fresh name and typarams is the
  1852                 // parameter list of the super constructor):
  1853                 //
  1854                 //   new <typeargs1>X(<*nullchk*>E, args) where
  1855                 //     X extends C<typargs2> {
  1856                 //       <typarams> X(ET e, args) {
  1857                 //         e.<typeargs1>super(args)
  1858                 //       }
  1859                 //       ...
  1860                 //     }
  1861                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  1863                 if (clazztype.tsym.isInterface()) {
  1864                     cdef.implementing = List.of(clazz);
  1865                 } else {
  1866                     cdef.extending = clazz;
  1869                 attribStat(cdef, localEnv);
  1871                 // If an outer instance is given,
  1872                 // prefix it to the constructor arguments
  1873                 // and delete it from the new expression
  1874                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  1875                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  1876                     argtypes = argtypes.prepend(tree.encl.type);
  1877                     tree.encl = null;
  1880                 // Reassign clazztype and recompute constructor.
  1881                 clazztype = cdef.sym.type;
  1882                 Symbol sym = tree.constructor = rs.resolveConstructor(
  1883                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  1884                 Assert.check(sym.kind < AMBIGUOUS);
  1885                 tree.constructor = sym;
  1886                 tree.constructorType = checkId(tree,
  1887                     clazztype,
  1888                     tree.constructor,
  1889                     localEnv,
  1890                     new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)),
  1891                     localEnv.info.varArgs);
  1894             if (tree.constructor != null && tree.constructor.kind == MTH)
  1895                 owntype = clazztype;
  1897         result = check(tree, owntype, VAL, resultInfo);
  1898         chk.validate(tree.typeargs, localEnv);
  1901     Pair<Symbol, Type> attribDiamond(Env<AttrContext> env,
  1902                         final JCNewClass tree,
  1903                         final Type clazztype,
  1904                         List<Type> argtypes,
  1905                         List<Type> typeargtypes) {
  1906         if (clazztype.isErroneous() ||
  1907                 clazztype.isInterface()) {
  1908             //if the type of the instance creation expression is erroneous,
  1909             //or if it's an interface, or if something prevented us to form a valid
  1910             //mapping, return the (possibly erroneous) type unchanged
  1911             return new Pair<Symbol, Type>(syms.noSymbol, clazztype);
  1914         //dup attribution environment and augment the set of inference variables
  1915         Env<AttrContext> localEnv = env.dup(tree);
  1917         ClassType site = new ClassType(clazztype.getEnclosingType(),
  1918                     clazztype.tsym.type.getTypeArguments(),
  1919                     clazztype.tsym);
  1921         //if the type of the instance creation expression is a class type
  1922         //apply method resolution inference (JLS 15.12.2.7). The return type
  1923         //of the resolved constructor will be a partially instantiated type
  1924         Symbol constructor = rs.resolveDiamond(tree.pos(),
  1925                     localEnv,
  1926                     site,
  1927                     argtypes,
  1928                     typeargtypes);
  1930         Type constructorType = types.createErrorType(clazztype);
  1931         ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  1932             @Override
  1933             public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  1934                 enclosingContext.report(tree.clazz,
  1935                         diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", clazztype.tsym), details));
  1937         });
  1938         constructorType = checkId(tree, site,
  1939                 constructor,
  1940                 localEnv,
  1941                 diamondResult,
  1942                 localEnv.info.varArgs);
  1944         return new Pair<Symbol, Type>(constructor.baseSymbol(), constructorType);
  1947     /** Make an attributed null check tree.
  1948      */
  1949     public JCExpression makeNullCheck(JCExpression arg) {
  1950         // optimization: X.this is never null; skip null check
  1951         Name name = TreeInfo.name(arg);
  1952         if (name == names._this || name == names._super) return arg;
  1954         JCTree.Tag optag = NULLCHK;
  1955         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  1956         tree.operator = syms.nullcheck;
  1957         tree.type = arg.type;
  1958         return tree;
  1961     public void visitNewArray(JCNewArray tree) {
  1962         Type owntype = types.createErrorType(tree.type);
  1963         Type elemtype;
  1964         if (tree.elemtype != null) {
  1965             elemtype = attribType(tree.elemtype, env);
  1966             chk.validate(tree.elemtype, env);
  1967             owntype = elemtype;
  1968             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1969                 attribExpr(l.head, env, syms.intType);
  1970                 owntype = new ArrayType(owntype, syms.arrayClass);
  1972         } else {
  1973             // we are seeing an untyped aggregate { ... }
  1974             // this is allowed only if the prototype is an array
  1975             if (pt().tag == ARRAY) {
  1976                 elemtype = types.elemtype(pt());
  1977             } else {
  1978                 if (pt().tag != ERROR) {
  1979                     log.error(tree.pos(), "illegal.initializer.for.type",
  1980                               pt());
  1982                 elemtype = types.createErrorType(pt());
  1985         if (tree.elems != null) {
  1986             attribExprs(tree.elems, env, elemtype);
  1987             owntype = new ArrayType(elemtype, syms.arrayClass);
  1989         if (!types.isReifiable(elemtype))
  1990             log.error(tree.pos(), "generic.array.creation");
  1991         result = check(tree, owntype, VAL, resultInfo);
  1994     @Override
  1995     public void visitLambda(JCLambda that) {
  1996         throw new UnsupportedOperationException("Lambda expression not supported yet");
  1999     @Override
  2000     public void visitReference(JCMemberReference that) {
  2001         throw new UnsupportedOperationException("Member references not supported yet");
  2004     public void visitParens(JCParens tree) {
  2005         Type owntype = attribTree(tree.expr, env, resultInfo);
  2006         result = check(tree, owntype, pkind(), resultInfo);
  2007         Symbol sym = TreeInfo.symbol(tree);
  2008         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2009             log.error(tree.pos(), "illegal.start.of.type");
  2012     public void visitAssign(JCAssign tree) {
  2013         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2014         Type capturedType = capture(owntype);
  2015         attribExpr(tree.rhs, env, owntype);
  2016         result = check(tree, capturedType, VAL, resultInfo);
  2019     public void visitAssignop(JCAssignOp tree) {
  2020         // Attribute arguments.
  2021         Type owntype = attribTree(tree.lhs, env, varInfo);
  2022         Type operand = attribExpr(tree.rhs, env);
  2023         // Find operator.
  2024         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2025             tree.pos(), tree.getTag().noAssignOp(), env,
  2026             owntype, operand);
  2028         if (operator.kind == MTH &&
  2029                 !owntype.isErroneous() &&
  2030                 !operand.isErroneous()) {
  2031             chk.checkOperator(tree.pos(),
  2032                               (OperatorSymbol)operator,
  2033                               tree.getTag().noAssignOp(),
  2034                               owntype,
  2035                               operand);
  2036             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2037             chk.checkCastable(tree.rhs.pos(),
  2038                               operator.type.getReturnType(),
  2039                               owntype);
  2041         result = check(tree, owntype, VAL, resultInfo);
  2044     public void visitUnary(JCUnary tree) {
  2045         // Attribute arguments.
  2046         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2047             ? attribTree(tree.arg, env, varInfo)
  2048             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2050         // Find operator.
  2051         Symbol operator = tree.operator =
  2052             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2054         Type owntype = types.createErrorType(tree.type);
  2055         if (operator.kind == MTH &&
  2056                 !argtype.isErroneous()) {
  2057             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2058                 ? tree.arg.type
  2059                 : operator.type.getReturnType();
  2060             int opc = ((OperatorSymbol)operator).opcode;
  2062             // If the argument is constant, fold it.
  2063             if (argtype.constValue() != null) {
  2064                 Type ctype = cfolder.fold1(opc, argtype);
  2065                 if (ctype != null) {
  2066                     owntype = cfolder.coerce(ctype, owntype);
  2068                     // Remove constant types from arguments to
  2069                     // conserve space. The parser will fold concatenations
  2070                     // of string literals; the code here also
  2071                     // gets rid of intermediate results when some of the
  2072                     // operands are constant identifiers.
  2073                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2074                         tree.arg.type = syms.stringType;
  2079         result = check(tree, owntype, VAL, resultInfo);
  2082     public void visitBinary(JCBinary tree) {
  2083         // Attribute arguments.
  2084         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2085         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2087         // Find operator.
  2088         Symbol operator = tree.operator =
  2089             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2091         Type owntype = types.createErrorType(tree.type);
  2092         if (operator.kind == MTH &&
  2093                 !left.isErroneous() &&
  2094                 !right.isErroneous()) {
  2095             owntype = operator.type.getReturnType();
  2096             int opc = chk.checkOperator(tree.lhs.pos(),
  2097                                         (OperatorSymbol)operator,
  2098                                         tree.getTag(),
  2099                                         left,
  2100                                         right);
  2102             // If both arguments are constants, fold them.
  2103             if (left.constValue() != null && right.constValue() != null) {
  2104                 Type ctype = cfolder.fold2(opc, left, right);
  2105                 if (ctype != null) {
  2106                     owntype = cfolder.coerce(ctype, owntype);
  2108                     // Remove constant types from arguments to
  2109                     // conserve space. The parser will fold concatenations
  2110                     // of string literals; the code here also
  2111                     // gets rid of intermediate results when some of the
  2112                     // operands are constant identifiers.
  2113                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  2114                         tree.lhs.type = syms.stringType;
  2116                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  2117                         tree.rhs.type = syms.stringType;
  2122             // Check that argument types of a reference ==, != are
  2123             // castable to each other, (JLS???).
  2124             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  2125                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  2126                     log.error(tree.pos(), "incomparable.types", left, right);
  2130             chk.checkDivZero(tree.rhs.pos(), operator, right);
  2132         result = check(tree, owntype, VAL, resultInfo);
  2135     public void visitTypeCast(JCTypeCast tree) {
  2136         Type clazztype = attribType(tree.clazz, env);
  2137         chk.validate(tree.clazz, env, false);
  2138         //a fresh environment is required for 292 inference to work properly ---
  2139         //see Infer.instantiatePolymorphicSignatureInstance()
  2140         Env<AttrContext> localEnv = env.dup(tree);
  2141         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
  2142         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2143         if (exprtype.constValue() != null)
  2144             owntype = cfolder.coerce(exprtype, owntype);
  2145         result = check(tree, capture(owntype), VAL, resultInfo);
  2146         chk.checkRedundantCast(localEnv, tree);
  2149     public void visitTypeTest(JCInstanceOf tree) {
  2150         Type exprtype = chk.checkNullOrRefType(
  2151             tree.expr.pos(), attribExpr(tree.expr, env));
  2152         Type clazztype = chk.checkReifiableReferenceType(
  2153             tree.clazz.pos(), attribType(tree.clazz, env));
  2154         chk.validate(tree.clazz, env, false);
  2155         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  2156         result = check(tree, syms.booleanType, VAL, resultInfo);
  2159     public void visitIndexed(JCArrayAccess tree) {
  2160         Type owntype = types.createErrorType(tree.type);
  2161         Type atype = attribExpr(tree.indexed, env);
  2162         attribExpr(tree.index, env, syms.intType);
  2163         if (types.isArray(atype))
  2164             owntype = types.elemtype(atype);
  2165         else if (atype.tag != ERROR)
  2166             log.error(tree.pos(), "array.req.but.found", atype);
  2167         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  2168         result = check(tree, owntype, VAR, resultInfo);
  2171     public void visitIdent(JCIdent tree) {
  2172         Symbol sym;
  2173         boolean varArgs = false;
  2175         // Find symbol
  2176         if (pt().tag == METHOD || pt().tag == FORALL) {
  2177             // If we are looking for a method, the prototype `pt' will be a
  2178             // method type with the type of the call's arguments as parameters.
  2179             env.info.varArgs = false;
  2180             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  2181             varArgs = env.info.varArgs;
  2182         } else if (tree.sym != null && tree.sym.kind != VAR) {
  2183             sym = tree.sym;
  2184         } else {
  2185             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  2187         tree.sym = sym;
  2189         // (1) Also find the environment current for the class where
  2190         //     sym is defined (`symEnv').
  2191         // Only for pre-tiger versions (1.4 and earlier):
  2192         // (2) Also determine whether we access symbol out of an anonymous
  2193         //     class in a this or super call.  This is illegal for instance
  2194         //     members since such classes don't carry a this$n link.
  2195         //     (`noOuterThisPath').
  2196         Env<AttrContext> symEnv = env;
  2197         boolean noOuterThisPath = false;
  2198         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  2199             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  2200             sym.owner.kind == TYP &&
  2201             tree.name != names._this && tree.name != names._super) {
  2203             // Find environment in which identifier is defined.
  2204             while (symEnv.outer != null &&
  2205                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  2206                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  2207                     noOuterThisPath = !allowAnonOuterThis;
  2208                 symEnv = symEnv.outer;
  2212         // If symbol is a variable, ...
  2213         if (sym.kind == VAR) {
  2214             VarSymbol v = (VarSymbol)sym;
  2216             // ..., evaluate its initializer, if it has one, and check for
  2217             // illegal forward reference.
  2218             checkInit(tree, env, v, false);
  2220             // If we are expecting a variable (as opposed to a value), check
  2221             // that the variable is assignable in the current environment.
  2222             if (pkind() == VAR)
  2223                 checkAssignable(tree.pos(), v, null, env);
  2226         // In a constructor body,
  2227         // if symbol is a field or instance method, check that it is
  2228         // not accessed before the supertype constructor is called.
  2229         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  2230             (sym.kind & (VAR | MTH)) != 0 &&
  2231             sym.owner.kind == TYP &&
  2232             (sym.flags() & STATIC) == 0) {
  2233             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  2235         Env<AttrContext> env1 = env;
  2236         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  2237             // If the found symbol is inaccessible, then it is
  2238             // accessed through an enclosing instance.  Locate this
  2239             // enclosing instance:
  2240             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  2241                 env1 = env1.outer;
  2243         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo, varArgs);
  2246     public void visitSelect(JCFieldAccess tree) {
  2247         // Determine the expected kind of the qualifier expression.
  2248         int skind = 0;
  2249         if (tree.name == names._this || tree.name == names._super ||
  2250             tree.name == names._class)
  2252             skind = TYP;
  2253         } else {
  2254             if ((pkind() & PCK) != 0) skind = skind | PCK;
  2255             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  2256             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  2259         // Attribute the qualifier expression, and determine its symbol (if any).
  2260         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  2261         if ((pkind() & (PCK | TYP)) == 0)
  2262             site = capture(site); // Capture field access
  2264         // don't allow T.class T[].class, etc
  2265         if (skind == TYP) {
  2266             Type elt = site;
  2267             while (elt.tag == ARRAY)
  2268                 elt = ((ArrayType)elt).elemtype;
  2269             if (elt.tag == TYPEVAR) {
  2270                 log.error(tree.pos(), "type.var.cant.be.deref");
  2271                 result = types.createErrorType(tree.type);
  2272                 return;
  2276         // If qualifier symbol is a type or `super', assert `selectSuper'
  2277         // for the selection. This is relevant for determining whether
  2278         // protected symbols are accessible.
  2279         Symbol sitesym = TreeInfo.symbol(tree.selected);
  2280         boolean selectSuperPrev = env.info.selectSuper;
  2281         env.info.selectSuper =
  2282             sitesym != null &&
  2283             sitesym.name == names._super;
  2285         // Determine the symbol represented by the selection.
  2286         env.info.varArgs = false;
  2287         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  2288         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  2289             site = capture(site);
  2290             sym = selectSym(tree, sitesym, site, env, resultInfo);
  2292         boolean varArgs = env.info.varArgs;
  2293         tree.sym = sym;
  2295         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
  2296             while (site.tag == TYPEVAR) site = site.getUpperBound();
  2297             site = capture(site);
  2300         // If that symbol is a variable, ...
  2301         if (sym.kind == VAR) {
  2302             VarSymbol v = (VarSymbol)sym;
  2304             // ..., evaluate its initializer, if it has one, and check for
  2305             // illegal forward reference.
  2306             checkInit(tree, env, v, true);
  2308             // If we are expecting a variable (as opposed to a value), check
  2309             // that the variable is assignable in the current environment.
  2310             if (pkind() == VAR)
  2311                 checkAssignable(tree.pos(), v, tree.selected, env);
  2314         if (sitesym != null &&
  2315                 sitesym.kind == VAR &&
  2316                 ((VarSymbol)sitesym).isResourceVariable() &&
  2317                 sym.kind == MTH &&
  2318                 sym.name.equals(names.close) &&
  2319                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  2320                 env.info.lint.isEnabled(LintCategory.TRY)) {
  2321             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  2324         // Disallow selecting a type from an expression
  2325         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  2326             tree.type = check(tree.selected, pt(),
  2327                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  2330         if (isType(sitesym)) {
  2331             if (sym.name == names._this) {
  2332                 // If `C' is the currently compiled class, check that
  2333                 // C.this' does not appear in a call to a super(...)
  2334                 if (env.info.isSelfCall &&
  2335                     site.tsym == env.enclClass.sym) {
  2336                     chk.earlyRefError(tree.pos(), sym);
  2338             } else {
  2339                 // Check if type-qualified fields or methods are static (JLS)
  2340                 if ((sym.flags() & STATIC) == 0 &&
  2341                     sym.name != names._super &&
  2342                     (sym.kind == VAR || sym.kind == MTH)) {
  2343                     rs.access(rs.new StaticError(sym),
  2344                               tree.pos(), site, sym.name, true);
  2347         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  2348             // If the qualified item is not a type and the selected item is static, report
  2349             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  2350             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  2353         // If we are selecting an instance member via a `super', ...
  2354         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  2356             // Check that super-qualified symbols are not abstract (JLS)
  2357             rs.checkNonAbstract(tree.pos(), sym);
  2359             if (site.isRaw()) {
  2360                 // Determine argument types for site.
  2361                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  2362                 if (site1 != null) site = site1;
  2366         env.info.selectSuper = selectSuperPrev;
  2367         result = checkId(tree, site, sym, env, resultInfo, varArgs);
  2369     //where
  2370         /** Determine symbol referenced by a Select expression,
  2372          *  @param tree   The select tree.
  2373          *  @param site   The type of the selected expression,
  2374          *  @param env    The current environment.
  2375          *  @param resultInfo The current result.
  2376          */
  2377         private Symbol selectSym(JCFieldAccess tree,
  2378                                  Symbol location,
  2379                                  Type site,
  2380                                  Env<AttrContext> env,
  2381                                  ResultInfo resultInfo) {
  2382             DiagnosticPosition pos = tree.pos();
  2383             Name name = tree.name;
  2384             switch (site.tag) {
  2385             case PACKAGE:
  2386                 return rs.access(
  2387                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  2388                     pos, location, site, name, true);
  2389             case ARRAY:
  2390             case CLASS:
  2391                 if (resultInfo.pt.tag == METHOD || resultInfo.pt.tag == FORALL) {
  2392                     return rs.resolveQualifiedMethod(
  2393                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  2394                 } else if (name == names._this || name == names._super) {
  2395                     return rs.resolveSelf(pos, env, site.tsym, name);
  2396                 } else if (name == names._class) {
  2397                     // In this case, we have already made sure in
  2398                     // visitSelect that qualifier expression is a type.
  2399                     Type t = syms.classType;
  2400                     List<Type> typeargs = allowGenerics
  2401                         ? List.of(types.erasure(site))
  2402                         : List.<Type>nil();
  2403                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  2404                     return new VarSymbol(
  2405                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2406                 } else {
  2407                     // We are seeing a plain identifier as selector.
  2408                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  2409                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  2410                         sym = rs.access(sym, pos, location, site, name, true);
  2411                     return sym;
  2413             case WILDCARD:
  2414                 throw new AssertionError(tree);
  2415             case TYPEVAR:
  2416                 // Normally, site.getUpperBound() shouldn't be null.
  2417                 // It should only happen during memberEnter/attribBase
  2418                 // when determining the super type which *must* beac
  2419                 // done before attributing the type variables.  In
  2420                 // other words, we are seeing this illegal program:
  2421                 // class B<T> extends A<T.foo> {}
  2422                 Symbol sym = (site.getUpperBound() != null)
  2423                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  2424                     : null;
  2425                 if (sym == null) {
  2426                     log.error(pos, "type.var.cant.be.deref");
  2427                     return syms.errSymbol;
  2428                 } else {
  2429                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  2430                         rs.new AccessError(env, site, sym) :
  2431                                 sym;
  2432                     rs.access(sym2, pos, location, site, name, true);
  2433                     return sym;
  2435             case ERROR:
  2436                 // preserve identifier names through errors
  2437                 return types.createErrorType(name, site.tsym, site).tsym;
  2438             default:
  2439                 // The qualifier expression is of a primitive type -- only
  2440                 // .class is allowed for these.
  2441                 if (name == names._class) {
  2442                     // In this case, we have already made sure in Select that
  2443                     // qualifier expression is a type.
  2444                     Type t = syms.classType;
  2445                     Type arg = types.boxedClass(site).type;
  2446                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  2447                     return new VarSymbol(
  2448                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  2449                 } else {
  2450                     log.error(pos, "cant.deref", site);
  2451                     return syms.errSymbol;
  2456         /** Determine type of identifier or select expression and check that
  2457          *  (1) the referenced symbol is not deprecated
  2458          *  (2) the symbol's type is safe (@see checkSafe)
  2459          *  (3) if symbol is a variable, check that its type and kind are
  2460          *      compatible with the prototype and protokind.
  2461          *  (4) if symbol is an instance field of a raw type,
  2462          *      which is being assigned to, issue an unchecked warning if its
  2463          *      type changes under erasure.
  2464          *  (5) if symbol is an instance method of a raw type, issue an
  2465          *      unchecked warning if its argument types change under erasure.
  2466          *  If checks succeed:
  2467          *    If symbol is a constant, return its constant type
  2468          *    else if symbol is a method, return its result type
  2469          *    otherwise return its type.
  2470          *  Otherwise return errType.
  2472          *  @param tree       The syntax tree representing the identifier
  2473          *  @param site       If this is a select, the type of the selected
  2474          *                    expression, otherwise the type of the current class.
  2475          *  @param sym        The symbol representing the identifier.
  2476          *  @param env        The current environment.
  2477          *  @param resultInfo    The expected result
  2478          */
  2479         Type checkId(JCTree tree,
  2480                      Type site,
  2481                      Symbol sym,
  2482                      Env<AttrContext> env,
  2483                      ResultInfo resultInfo,
  2484                      boolean useVarargs) {
  2485             if (resultInfo.pt.isErroneous()) return types.createErrorType(site);
  2486             Type owntype; // The computed type of this identifier occurrence.
  2487             switch (sym.kind) {
  2488             case TYP:
  2489                 // For types, the computed type equals the symbol's type,
  2490                 // except for two situations:
  2491                 owntype = sym.type;
  2492                 if (owntype.tag == CLASS) {
  2493                     Type ownOuter = owntype.getEnclosingType();
  2495                     // (a) If the symbol's type is parameterized, erase it
  2496                     // because no type parameters were given.
  2497                     // We recover generic outer type later in visitTypeApply.
  2498                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  2499                         owntype = types.erasure(owntype);
  2502                     // (b) If the symbol's type is an inner class, then
  2503                     // we have to interpret its outer type as a superclass
  2504                     // of the site type. Example:
  2505                     //
  2506                     // class Tree<A> { class Visitor { ... } }
  2507                     // class PointTree extends Tree<Point> { ... }
  2508                     // ...PointTree.Visitor...
  2509                     //
  2510                     // Then the type of the last expression above is
  2511                     // Tree<Point>.Visitor.
  2512                     else if (ownOuter.tag == CLASS && site != ownOuter) {
  2513                         Type normOuter = site;
  2514                         if (normOuter.tag == CLASS)
  2515                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  2516                         if (normOuter == null) // perhaps from an import
  2517                             normOuter = types.erasure(ownOuter);
  2518                         if (normOuter != ownOuter)
  2519                             owntype = new ClassType(
  2520                                 normOuter, List.<Type>nil(), owntype.tsym);
  2523                 break;
  2524             case VAR:
  2525                 VarSymbol v = (VarSymbol)sym;
  2526                 // Test (4): if symbol is an instance field of a raw type,
  2527                 // which is being assigned to, issue an unchecked warning if
  2528                 // its type changes under erasure.
  2529                 if (allowGenerics &&
  2530                     resultInfo.pkind == VAR &&
  2531                     v.owner.kind == TYP &&
  2532                     (v.flags() & STATIC) == 0 &&
  2533                     (site.tag == CLASS || site.tag == TYPEVAR)) {
  2534                     Type s = types.asOuterSuper(site, v.owner);
  2535                     if (s != null &&
  2536                         s.isRaw() &&
  2537                         !types.isSameType(v.type, v.erasure(types))) {
  2538                         chk.warnUnchecked(tree.pos(),
  2539                                           "unchecked.assign.to.var",
  2540                                           v, s);
  2543                 // The computed type of a variable is the type of the
  2544                 // variable symbol, taken as a member of the site type.
  2545                 owntype = (sym.owner.kind == TYP &&
  2546                            sym.name != names._this && sym.name != names._super)
  2547                     ? types.memberType(site, sym)
  2548                     : sym.type;
  2550                 // If the variable is a constant, record constant value in
  2551                 // computed type.
  2552                 if (v.getConstValue() != null && isStaticReference(tree))
  2553                     owntype = owntype.constType(v.getConstValue());
  2555                 if (resultInfo.pkind == VAL) {
  2556                     owntype = capture(owntype); // capture "names as expressions"
  2558                 break;
  2559             case MTH: {
  2560                 owntype = checkMethod(site, sym,
  2561                         new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  2562                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  2563                         resultInfo.pt.getTypeArguments(), env.info.varArgs);
  2564                 break;
  2566             case PCK: case ERR:
  2567                 owntype = sym.type;
  2568                 break;
  2569             default:
  2570                 throw new AssertionError("unexpected kind: " + sym.kind +
  2571                                          " in tree " + tree);
  2574             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  2575             // (for constructors, the error was given when the constructor was
  2576             // resolved)
  2578             if (sym.name != names.init) {
  2579                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  2580                 chk.checkSunAPI(tree.pos(), sym);
  2583             // Test (3): if symbol is a variable, check that its type and
  2584             // kind are compatible with the prototype and protokind.
  2585             return check(tree, owntype, sym.kind, resultInfo);
  2588         /** Check that variable is initialized and evaluate the variable's
  2589          *  initializer, if not yet done. Also check that variable is not
  2590          *  referenced before it is defined.
  2591          *  @param tree    The tree making up the variable reference.
  2592          *  @param env     The current environment.
  2593          *  @param v       The variable's symbol.
  2594          */
  2595         private void checkInit(JCTree tree,
  2596                                Env<AttrContext> env,
  2597                                VarSymbol v,
  2598                                boolean onlyWarning) {
  2599 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  2600 //                             tree.pos + " " + v.pos + " " +
  2601 //                             Resolve.isStatic(env));//DEBUG
  2603             // A forward reference is diagnosed if the declaration position
  2604             // of the variable is greater than the current tree position
  2605             // and the tree and variable definition occur in the same class
  2606             // definition.  Note that writes don't count as references.
  2607             // This check applies only to class and instance
  2608             // variables.  Local variables follow different scope rules,
  2609             // and are subject to definite assignment checking.
  2610             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  2611                 v.owner.kind == TYP &&
  2612                 canOwnInitializer(owner(env)) &&
  2613                 v.owner == env.info.scope.owner.enclClass() &&
  2614                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  2615                 (!env.tree.hasTag(ASSIGN) ||
  2616                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  2617                 String suffix = (env.info.enclVar == v) ?
  2618                                 "self.ref" : "forward.ref";
  2619                 if (!onlyWarning || isStaticEnumField(v)) {
  2620                     log.error(tree.pos(), "illegal." + suffix);
  2621                 } else if (useBeforeDeclarationWarning) {
  2622                     log.warning(tree.pos(), suffix, v);
  2626             v.getConstValue(); // ensure initializer is evaluated
  2628             checkEnumInitializer(tree, env, v);
  2631         /**
  2632          * Check for illegal references to static members of enum.  In
  2633          * an enum type, constructors and initializers may not
  2634          * reference its static members unless they are constant.
  2636          * @param tree    The tree making up the variable reference.
  2637          * @param env     The current environment.
  2638          * @param v       The variable's symbol.
  2639          * @jls  section 8.9 Enums
  2640          */
  2641         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  2642             // JLS:
  2643             //
  2644             // "It is a compile-time error to reference a static field
  2645             // of an enum type that is not a compile-time constant
  2646             // (15.28) from constructors, instance initializer blocks,
  2647             // or instance variable initializer expressions of that
  2648             // type. It is a compile-time error for the constructors,
  2649             // instance initializer blocks, or instance variable
  2650             // initializer expressions of an enum constant e to refer
  2651             // to itself or to an enum constant of the same type that
  2652             // is declared to the right of e."
  2653             if (isStaticEnumField(v)) {
  2654                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  2656                 if (enclClass == null || enclClass.owner == null)
  2657                     return;
  2659                 // See if the enclosing class is the enum (or a
  2660                 // subclass thereof) declaring v.  If not, this
  2661                 // reference is OK.
  2662                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  2663                     return;
  2665                 // If the reference isn't from an initializer, then
  2666                 // the reference is OK.
  2667                 if (!Resolve.isInitializer(env))
  2668                     return;
  2670                 log.error(tree.pos(), "illegal.enum.static.ref");
  2674         /** Is the given symbol a static, non-constant field of an Enum?
  2675          *  Note: enum literals should not be regarded as such
  2676          */
  2677         private boolean isStaticEnumField(VarSymbol v) {
  2678             return Flags.isEnum(v.owner) &&
  2679                    Flags.isStatic(v) &&
  2680                    !Flags.isConstant(v) &&
  2681                    v.name != names._class;
  2684         /** Can the given symbol be the owner of code which forms part
  2685          *  if class initialization? This is the case if the symbol is
  2686          *  a type or field, or if the symbol is the synthetic method.
  2687          *  owning a block.
  2688          */
  2689         private boolean canOwnInitializer(Symbol sym) {
  2690             return
  2691                 (sym.kind & (VAR | TYP)) != 0 ||
  2692                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  2695     Warner noteWarner = new Warner();
  2697     /**
  2698      * Check that method arguments conform to its instantiation.
  2699      **/
  2700     public Type checkMethod(Type site,
  2701                             Symbol sym,
  2702                             ResultInfo resultInfo,
  2703                             Env<AttrContext> env,
  2704                             final List<JCExpression> argtrees,
  2705                             List<Type> argtypes,
  2706                             List<Type> typeargtypes,
  2707                             boolean useVarargs) {
  2708         // Test (5): if symbol is an instance method of a raw type, issue
  2709         // an unchecked warning if its argument types change under erasure.
  2710         if (allowGenerics &&
  2711             (sym.flags() & STATIC) == 0 &&
  2712             (site.tag == CLASS || site.tag == TYPEVAR)) {
  2713             Type s = types.asOuterSuper(site, sym.owner);
  2714             if (s != null && s.isRaw() &&
  2715                 !types.isSameTypes(sym.type.getParameterTypes(),
  2716                                    sym.erasure(types).getParameterTypes())) {
  2717                 chk.warnUnchecked(env.tree.pos(),
  2718                                   "unchecked.call.mbr.of.raw.type",
  2719                                   sym, s);
  2723         // Compute the identifier's instantiated type.
  2724         // For methods, we need to compute the instance type by
  2725         // Resolve.instantiate from the symbol's type as well as
  2726         // any type arguments and value arguments.
  2727         noteWarner.clear();
  2728         try {
  2729             Type owntype = rs.rawInstantiate(
  2730                     env,
  2731                     site,
  2732                     sym,
  2733                     resultInfo,
  2734                     argtypes,
  2735                     typeargtypes,
  2736                     allowBoxing,
  2737                     useVarargs,
  2738                     noteWarner);
  2740             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, useVarargs,
  2741                     noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
  2742         } catch (Infer.InferenceException ex) {
  2743             //invalid target type - propagate exception outwards or report error
  2744             //depending on the current check context
  2745             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  2746             return types.createErrorType(site);
  2747         } catch (Resolve.InapplicableMethodException ex) {
  2748             Assert.error();
  2749             return null;
  2753     public void visitLiteral(JCLiteral tree) {
  2754         result = check(
  2755             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  2757     //where
  2758     /** Return the type of a literal with given type tag.
  2759      */
  2760     Type litType(int tag) {
  2761         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
  2764     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  2765         result = check(tree, syms.typeOfTag[tree.typetag], TYP, resultInfo);
  2768     public void visitTypeArray(JCArrayTypeTree tree) {
  2769         Type etype = attribType(tree.elemtype, env);
  2770         Type type = new ArrayType(etype, syms.arrayClass);
  2771         result = check(tree, type, TYP, resultInfo);
  2774     /** Visitor method for parameterized types.
  2775      *  Bound checking is left until later, since types are attributed
  2776      *  before supertype structure is completely known
  2777      */
  2778     public void visitTypeApply(JCTypeApply tree) {
  2779         Type owntype = types.createErrorType(tree.type);
  2781         // Attribute functor part of application and make sure it's a class.
  2782         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  2784         // Attribute type parameters
  2785         List<Type> actuals = attribTypes(tree.arguments, env);
  2787         if (clazztype.tag == CLASS) {
  2788             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  2789             if (actuals.isEmpty()) //diamond
  2790                 actuals = formals;
  2792             if (actuals.length() == formals.length()) {
  2793                 List<Type> a = actuals;
  2794                 List<Type> f = formals;
  2795                 while (a.nonEmpty()) {
  2796                     a.head = a.head.withTypeVar(f.head);
  2797                     a = a.tail;
  2798                     f = f.tail;
  2800                 // Compute the proper generic outer
  2801                 Type clazzOuter = clazztype.getEnclosingType();
  2802                 if (clazzOuter.tag == CLASS) {
  2803                     Type site;
  2804                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  2805                     if (clazz.hasTag(IDENT)) {
  2806                         site = env.enclClass.sym.type;
  2807                     } else if (clazz.hasTag(SELECT)) {
  2808                         site = ((JCFieldAccess) clazz).selected.type;
  2809                     } else throw new AssertionError(""+tree);
  2810                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
  2811                         if (site.tag == CLASS)
  2812                             site = types.asOuterSuper(site, clazzOuter.tsym);
  2813                         if (site == null)
  2814                             site = types.erasure(clazzOuter);
  2815                         clazzOuter = site;
  2818                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  2819             } else {
  2820                 if (formals.length() != 0) {
  2821                     log.error(tree.pos(), "wrong.number.type.args",
  2822                               Integer.toString(formals.length()));
  2823                 } else {
  2824                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  2826                 owntype = types.createErrorType(tree.type);
  2829         result = check(tree, owntype, TYP, resultInfo);
  2832     public void visitTypeUnion(JCTypeUnion tree) {
  2833         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  2834         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  2835         for (JCExpression typeTree : tree.alternatives) {
  2836             Type ctype = attribType(typeTree, env);
  2837             ctype = chk.checkType(typeTree.pos(),
  2838                           chk.checkClassType(typeTree.pos(), ctype),
  2839                           syms.throwableType);
  2840             if (!ctype.isErroneous()) {
  2841                 //check that alternatives of a union type are pairwise
  2842                 //unrelated w.r.t. subtyping
  2843                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  2844                     for (Type t : multicatchTypes) {
  2845                         boolean sub = types.isSubtype(ctype, t);
  2846                         boolean sup = types.isSubtype(t, ctype);
  2847                         if (sub || sup) {
  2848                             //assume 'a' <: 'b'
  2849                             Type a = sub ? ctype : t;
  2850                             Type b = sub ? t : ctype;
  2851                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  2855                 multicatchTypes.append(ctype);
  2856                 if (all_multicatchTypes != null)
  2857                     all_multicatchTypes.append(ctype);
  2858             } else {
  2859                 if (all_multicatchTypes == null) {
  2860                     all_multicatchTypes = ListBuffer.lb();
  2861                     all_multicatchTypes.appendList(multicatchTypes);
  2863                 all_multicatchTypes.append(ctype);
  2866         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  2867         if (t.tag == CLASS) {
  2868             List<Type> alternatives =
  2869                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  2870             t = new UnionClassType((ClassType) t, alternatives);
  2872         tree.type = result = t;
  2875     public void visitTypeParameter(JCTypeParameter tree) {
  2876         TypeVar a = (TypeVar)tree.type;
  2877         Set<Type> boundSet = new HashSet<Type>();
  2878         if (a.bound.isErroneous())
  2879             return;
  2880         List<Type> bs = types.getBounds(a);
  2881         if (tree.bounds.nonEmpty()) {
  2882             // accept class or interface or typevar as first bound.
  2883             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
  2884             boundSet.add(types.erasure(b));
  2885             if (b.isErroneous()) {
  2886                 a.bound = b;
  2888             else if (b.tag == TYPEVAR) {
  2889                 // if first bound was a typevar, do not accept further bounds.
  2890                 if (tree.bounds.tail.nonEmpty()) {
  2891                     log.error(tree.bounds.tail.head.pos(),
  2892                               "type.var.may.not.be.followed.by.other.bounds");
  2893                     tree.bounds = List.of(tree.bounds.head);
  2894                     a.bound = bs.head;
  2896             } else {
  2897                 // if first bound was a class or interface, accept only interfaces
  2898                 // as further bounds.
  2899                 for (JCExpression bound : tree.bounds.tail) {
  2900                     bs = bs.tail;
  2901                     Type i = checkBase(bs.head, bound, env, false, true, false);
  2902                     if (i.isErroneous())
  2903                         a.bound = i;
  2904                     else if (i.tag == CLASS)
  2905                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
  2909         bs = types.getBounds(a);
  2911         // in case of multiple bounds ...
  2912         if (bs.length() > 1) {
  2913             // ... the variable's bound is a class type flagged COMPOUND
  2914             // (see comment for TypeVar.bound).
  2915             // In this case, generate a class tree that represents the
  2916             // bound class, ...
  2917             JCExpression extending;
  2918             List<JCExpression> implementing;
  2919             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
  2920                 extending = tree.bounds.head;
  2921                 implementing = tree.bounds.tail;
  2922             } else {
  2923                 extending = null;
  2924                 implementing = tree.bounds;
  2926             JCClassDecl cd = make.at(tree.pos).ClassDef(
  2927                 make.Modifiers(PUBLIC | ABSTRACT),
  2928                 tree.name, List.<JCTypeParameter>nil(),
  2929                 extending, implementing, List.<JCTree>nil());
  2931             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
  2932             Assert.check((c.flags() & COMPOUND) != 0);
  2933             cd.sym = c;
  2934             c.sourcefile = env.toplevel.sourcefile;
  2936             // ... and attribute the bound class
  2937             c.flags_field |= UNATTRIBUTED;
  2938             Env<AttrContext> cenv = enter.classEnv(cd, env);
  2939             enter.typeEnvs.put(c, cenv);
  2944     public void visitWildcard(JCWildcard tree) {
  2945         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  2946         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  2947             ? syms.objectType
  2948             : attribType(tree.inner, env);
  2949         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  2950                                               tree.kind.kind,
  2951                                               syms.boundClass),
  2952                        TYP, resultInfo);
  2955     public void visitAnnotation(JCAnnotation tree) {
  2956         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  2957         result = tree.type = syms.errType;
  2960     public void visitErroneous(JCErroneous tree) {
  2961         if (tree.errs != null)
  2962             for (JCTree err : tree.errs)
  2963                 attribTree(err, env, new ResultInfo(ERR, pt()));
  2964         result = tree.type = syms.errType;
  2967     /** Default visitor method for all other trees.
  2968      */
  2969     public void visitTree(JCTree tree) {
  2970         throw new AssertionError();
  2973     /**
  2974      * Attribute an env for either a top level tree or class declaration.
  2975      */
  2976     public void attrib(Env<AttrContext> env) {
  2977         if (env.tree.hasTag(TOPLEVEL))
  2978             attribTopLevel(env);
  2979         else
  2980             attribClass(env.tree.pos(), env.enclClass.sym);
  2983     /**
  2984      * Attribute a top level tree. These trees are encountered when the
  2985      * package declaration has annotations.
  2986      */
  2987     public void attribTopLevel(Env<AttrContext> env) {
  2988         JCCompilationUnit toplevel = env.toplevel;
  2989         try {
  2990             annotate.flush();
  2991             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  2992         } catch (CompletionFailure ex) {
  2993             chk.completionError(toplevel.pos(), ex);
  2997     /** Main method: attribute class definition associated with given class symbol.
  2998      *  reporting completion failures at the given position.
  2999      *  @param pos The source position at which completion errors are to be
  3000      *             reported.
  3001      *  @param c   The class symbol whose definition will be attributed.
  3002      */
  3003     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  3004         try {
  3005             annotate.flush();
  3006             attribClass(c);
  3007         } catch (CompletionFailure ex) {
  3008             chk.completionError(pos, ex);
  3012     /** Attribute class definition associated with given class symbol.
  3013      *  @param c   The class symbol whose definition will be attributed.
  3014      */
  3015     void attribClass(ClassSymbol c) throws CompletionFailure {
  3016         if (c.type.tag == ERROR) return;
  3018         // Check for cycles in the inheritance graph, which can arise from
  3019         // ill-formed class files.
  3020         chk.checkNonCyclic(null, c.type);
  3022         Type st = types.supertype(c.type);
  3023         if ((c.flags_field & Flags.COMPOUND) == 0) {
  3024             // First, attribute superclass.
  3025             if (st.tag == CLASS)
  3026                 attribClass((ClassSymbol)st.tsym);
  3028             // Next attribute owner, if it is a class.
  3029             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
  3030                 attribClass((ClassSymbol)c.owner);
  3033         // The previous operations might have attributed the current class
  3034         // if there was a cycle. So we test first whether the class is still
  3035         // UNATTRIBUTED.
  3036         if ((c.flags_field & UNATTRIBUTED) != 0) {
  3037             c.flags_field &= ~UNATTRIBUTED;
  3039             // Get environment current at the point of class definition.
  3040             Env<AttrContext> env = enter.typeEnvs.get(c);
  3042             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  3043             // because the annotations were not available at the time the env was created. Therefore,
  3044             // we look up the environment chain for the first enclosing environment for which the
  3045             // lint value is set. Typically, this is the parent env, but might be further if there
  3046             // are any envs created as a result of TypeParameter nodes.
  3047             Env<AttrContext> lintEnv = env;
  3048             while (lintEnv.info.lint == null)
  3049                 lintEnv = lintEnv.next;
  3051             // Having found the enclosing lint value, we can initialize the lint value for this class
  3052             env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
  3054             Lint prevLint = chk.setLint(env.info.lint);
  3055             JavaFileObject prev = log.useSource(c.sourcefile);
  3057             try {
  3058                 // java.lang.Enum may not be subclassed by a non-enum
  3059                 if (st.tsym == syms.enumSym &&
  3060                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  3061                     log.error(env.tree.pos(), "enum.no.subclassing");
  3063                 // Enums may not be extended by source-level classes
  3064                 if (st.tsym != null &&
  3065                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  3066                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
  3067                     !target.compilerBootstrap(c)) {
  3068                     log.error(env.tree.pos(), "enum.types.not.extensible");
  3070                 attribClassBody(env, c);
  3072                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  3073             } finally {
  3074                 log.useSource(prev);
  3075                 chk.setLint(prevLint);
  3081     public void visitImport(JCImport tree) {
  3082         // nothing to do
  3085     /** Finish the attribution of a class. */
  3086     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  3087         JCClassDecl tree = (JCClassDecl)env.tree;
  3088         Assert.check(c == tree.sym);
  3090         // Validate annotations
  3091         chk.validateAnnotations(tree.mods.annotations, c);
  3093         // Validate type parameters, supertype and interfaces.
  3094         attribBounds(tree.typarams);
  3095         if (!c.isAnonymous()) {
  3096             //already checked if anonymous
  3097             chk.validate(tree.typarams, env);
  3098             chk.validate(tree.extending, env);
  3099             chk.validate(tree.implementing, env);
  3102         // If this is a non-abstract class, check that it has no abstract
  3103         // methods or unimplemented methods of an implemented interface.
  3104         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  3105             if (!relax)
  3106                 chk.checkAllDefined(tree.pos(), c);
  3109         if ((c.flags() & ANNOTATION) != 0) {
  3110             if (tree.implementing.nonEmpty())
  3111                 log.error(tree.implementing.head.pos(),
  3112                           "cant.extend.intf.annotation");
  3113             if (tree.typarams.nonEmpty())
  3114                 log.error(tree.typarams.head.pos(),
  3115                           "intf.annotation.cant.have.type.params");
  3117             // If this annotation has a @ContainedBy, validate
  3118             Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym);
  3119             if (containedBy != null) {
  3120                 // get diagnositc position for error reporting
  3121                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type);
  3122                 Assert.checkNonNull(cbPos);
  3124                 chk.validateContainedBy(c, containedBy, cbPos);
  3127             // If this annotation has a @ContainerFor, validate
  3128             Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym);
  3129             if (containerFor != null) {
  3130                 // get diagnositc position for error reporting
  3131                 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type);
  3132                 Assert.checkNonNull(cfPos);
  3134                 chk.validateContainerFor(c, containerFor, cfPos);
  3136         } else {
  3137             // Check that all extended classes and interfaces
  3138             // are compatible (i.e. no two define methods with same arguments
  3139             // yet different return types).  (JLS 8.4.6.3)
  3140             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  3143         // Check that class does not import the same parameterized interface
  3144         // with two different argument lists.
  3145         chk.checkClassBounds(tree.pos(), c.type);
  3147         tree.type = c.type;
  3149         for (List<JCTypeParameter> l = tree.typarams;
  3150              l.nonEmpty(); l = l.tail) {
  3151              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  3154         // Check that a generic class doesn't extend Throwable
  3155         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  3156             log.error(tree.extending.pos(), "generic.throwable");
  3158         // Check that all methods which implement some
  3159         // method conform to the method they implement.
  3160         chk.checkImplementations(tree);
  3162         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  3163         checkAutoCloseable(tree.pos(), env, c.type);
  3165         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3166             // Attribute declaration
  3167             attribStat(l.head, env);
  3168             // Check that declarations in inner classes are not static (JLS 8.1.2)
  3169             // Make an exception for static constants.
  3170             if (c.owner.kind != PCK &&
  3171                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  3172                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  3173                 Symbol sym = null;
  3174                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  3175                 if (sym == null ||
  3176                     sym.kind != VAR ||
  3177                     ((VarSymbol) sym).getConstValue() == null)
  3178                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  3182         // Check for cycles among non-initial constructors.
  3183         chk.checkCyclicConstructors(tree);
  3185         // Check for cycles among annotation elements.
  3186         chk.checkNonCyclicElements(tree);
  3188         // Check for proper use of serialVersionUID
  3189         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  3190             isSerializable(c) &&
  3191             (c.flags() & Flags.ENUM) == 0 &&
  3192             (c.flags() & ABSTRACT) == 0) {
  3193             checkSerialVersionUID(tree, c);
  3196         // where
  3197         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  3198         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  3199             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  3200                 if (types.isSameType(al.head.annotationType.type, t))
  3201                     return al.head.pos();
  3204             return null;
  3207         /** check if a class is a subtype of Serializable, if that is available. */
  3208         private boolean isSerializable(ClassSymbol c) {
  3209             try {
  3210                 syms.serializableType.complete();
  3212             catch (CompletionFailure e) {
  3213                 return false;
  3215             return types.isSubtype(c.type, syms.serializableType);
  3218         /** Check that an appropriate serialVersionUID member is defined. */
  3219         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  3221             // check for presence of serialVersionUID
  3222             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  3223             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  3224             if (e.scope == null) {
  3225                 log.warning(LintCategory.SERIAL,
  3226                         tree.pos(), "missing.SVUID", c);
  3227                 return;
  3230             // check that it is static final
  3231             VarSymbol svuid = (VarSymbol)e.sym;
  3232             if ((svuid.flags() & (STATIC | FINAL)) !=
  3233                 (STATIC | FINAL))
  3234                 log.warning(LintCategory.SERIAL,
  3235                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  3237             // check that it is long
  3238             else if (svuid.type.tag != TypeTags.LONG)
  3239                 log.warning(LintCategory.SERIAL,
  3240                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  3242             // check constant
  3243             else if (svuid.getConstValue() == null)
  3244                 log.warning(LintCategory.SERIAL,
  3245                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  3248     private Type capture(Type type) {
  3249         return types.capture(type);
  3252     // <editor-fold desc="post-attribution visitor">
  3254     /**
  3255      * Handle missing types/symbols in an AST. This routine is useful when
  3256      * the compiler has encountered some errors (which might have ended up
  3257      * terminating attribution abruptly); if the compiler is used in fail-over
  3258      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  3259      * prevents NPE to be progagated during subsequent compilation steps.
  3260      */
  3261     public void postAttr(Env<AttrContext> env) {
  3262         new PostAttrAnalyzer().scan(env.tree);
  3265     class PostAttrAnalyzer extends TreeScanner {
  3267         private void initTypeIfNeeded(JCTree that) {
  3268             if (that.type == null) {
  3269                 that.type = syms.unknownType;
  3273         @Override
  3274         public void scan(JCTree tree) {
  3275             if (tree == null) return;
  3276             if (tree instanceof JCExpression) {
  3277                 initTypeIfNeeded(tree);
  3279             super.scan(tree);
  3282         @Override
  3283         public void visitIdent(JCIdent that) {
  3284             if (that.sym == null) {
  3285                 that.sym = syms.unknownSymbol;
  3289         @Override
  3290         public void visitSelect(JCFieldAccess that) {
  3291             if (that.sym == null) {
  3292                 that.sym = syms.unknownSymbol;
  3294             super.visitSelect(that);
  3297         @Override
  3298         public void visitClassDef(JCClassDecl that) {
  3299             initTypeIfNeeded(that);
  3300             if (that.sym == null) {
  3301                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  3303             super.visitClassDef(that);
  3306         @Override
  3307         public void visitMethodDef(JCMethodDecl that) {
  3308             initTypeIfNeeded(that);
  3309             if (that.sym == null) {
  3310                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  3312             super.visitMethodDef(that);
  3315         @Override
  3316         public void visitVarDef(JCVariableDecl that) {
  3317             initTypeIfNeeded(that);
  3318             if (that.sym == null) {
  3319                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  3320                 that.sym.adr = 0;
  3322             super.visitVarDef(that);
  3325         @Override
  3326         public void visitNewClass(JCNewClass that) {
  3327             if (that.constructor == null) {
  3328                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  3330             if (that.constructorType == null) {
  3331                 that.constructorType = syms.unknownType;
  3333             super.visitNewClass(that);
  3336         @Override
  3337         public void visitAssignop(JCAssignOp that) {
  3338             if (that.operator == null)
  3339                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3340             super.visitAssignop(that);
  3343         @Override
  3344         public void visitBinary(JCBinary that) {
  3345             if (that.operator == null)
  3346                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3347             super.visitBinary(that);
  3350         @Override
  3351         public void visitUnary(JCUnary that) {
  3352             if (that.operator == null)
  3353                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  3354             super.visitUnary(that);
  3357     // </editor-fold>

mercurial