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

Thu, 27 Jun 2013 16:04:05 +0100

author
vromero
date
Thu, 27 Jun 2013 16:04:05 +0100
changeset 1864
e42c27026290
parent 1851
e9ebff1840e5
child 1869
5c548a8542b8
permissions
-rw-r--r--

8016099: Some @SuppressWarnings annotations ignored ( unchecked, rawtypes )
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, 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.*;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.lang.model.type.TypeKind;
    32 import javax.tools.JavaFileObject;
    34 import com.sun.source.tree.IdentifierTree;
    35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    36 import com.sun.source.tree.MemberSelectTree;
    37 import com.sun.source.tree.TreeVisitor;
    38 import com.sun.source.util.SimpleTreeVisitor;
    39 import com.sun.tools.javac.code.*;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.comp.Check.CheckContext;
    44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    45 import com.sun.tools.javac.comp.Infer.InferenceContext;
    46 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    47 import com.sun.tools.javac.jvm.*;
    48 import com.sun.tools.javac.tree.*;
    49 import com.sun.tools.javac.tree.JCTree.*;
    50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    51 import com.sun.tools.javac.util.*;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    53 import com.sun.tools.javac.util.List;
    54 import static com.sun.tools.javac.code.Flags.*;
    55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    56 import static com.sun.tools.javac.code.Flags.BLOCK;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    59 import static com.sun.tools.javac.code.TypeTag.*;
    60 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    61 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    63 /** This is the main context-dependent analysis phase in GJC. It
    64  *  encompasses name resolution, type checking and constant folding as
    65  *  subtasks. Some subtasks involve auxiliary classes.
    66  *  @see Check
    67  *  @see Resolve
    68  *  @see ConstFold
    69  *  @see Infer
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class Attr extends JCTree.Visitor {
    77     protected static final Context.Key<Attr> attrKey =
    78         new Context.Key<Attr>();
    80     final Names names;
    81     final Log log;
    82     final Symtab syms;
    83     final Resolve rs;
    84     final Infer infer;
    85     final DeferredAttr deferredAttr;
    86     final Check chk;
    87     final Flow flow;
    88     final MemberEnter memberEnter;
    89     final TreeMaker make;
    90     final ConstFold cfolder;
    91     final Enter enter;
    92     final Target target;
    93     final Types types;
    94     final JCDiagnostic.Factory diags;
    95     final Annotate annotate;
    96     final DeferredLintHandler deferredLintHandler;
    98     public static Attr instance(Context context) {
    99         Attr instance = context.get(attrKey);
   100         if (instance == null)
   101             instance = new Attr(context);
   102         return instance;
   103     }
   105     protected Attr(Context context) {
   106         context.put(attrKey, this);
   108         names = Names.instance(context);
   109         log = Log.instance(context);
   110         syms = Symtab.instance(context);
   111         rs = Resolve.instance(context);
   112         chk = Check.instance(context);
   113         flow = Flow.instance(context);
   114         memberEnter = MemberEnter.instance(context);
   115         make = TreeMaker.instance(context);
   116         enter = Enter.instance(context);
   117         infer = Infer.instance(context);
   118         deferredAttr = DeferredAttr.instance(context);
   119         cfolder = ConstFold.instance(context);
   120         target = Target.instance(context);
   121         types = Types.instance(context);
   122         diags = JCDiagnostic.Factory.instance(context);
   123         annotate = Annotate.instance(context);
   124         deferredLintHandler = DeferredLintHandler.instance(context);
   126         Options options = Options.instance(context);
   128         Source source = Source.instance(context);
   129         allowGenerics = source.allowGenerics();
   130         allowVarargs = source.allowVarargs();
   131         allowEnums = source.allowEnums();
   132         allowBoxing = source.allowBoxing();
   133         allowCovariantReturns = source.allowCovariantReturns();
   134         allowAnonOuterThis = source.allowAnonOuterThis();
   135         allowStringsInSwitch = source.allowStringsInSwitch();
   136         allowPoly = source.allowPoly();
   137         allowTypeAnnos = source.allowTypeAnnotations();
   138         allowLambda = source.allowLambda();
   139         allowDefaultMethods = source.allowDefaultMethods();
   140         sourceName = source.name;
   141         relax = (options.isSet("-retrofit") ||
   142                  options.isSet("-relax"));
   143         findDiamonds = options.get("findDiamond") != null &&
   144                  source.allowDiamond();
   145         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   146         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   148         statInfo = new ResultInfo(NIL, Type.noType);
   149         varInfo = new ResultInfo(VAR, Type.noType);
   150         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   151         unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly);
   152         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   153         unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
   154         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   155     }
   157     /** Switch: relax some constraints for retrofit mode.
   158      */
   159     boolean relax;
   161     /** Switch: support target-typing inference
   162      */
   163     boolean allowPoly;
   165     /** Switch: support type annotations.
   166      */
   167     boolean allowTypeAnnos;
   169     /** Switch: support generics?
   170      */
   171     boolean allowGenerics;
   173     /** Switch: allow variable-arity methods.
   174      */
   175     boolean allowVarargs;
   177     /** Switch: support enums?
   178      */
   179     boolean allowEnums;
   181     /** Switch: support boxing and unboxing?
   182      */
   183     boolean allowBoxing;
   185     /** Switch: support covariant result types?
   186      */
   187     boolean allowCovariantReturns;
   189     /** Switch: support lambda expressions ?
   190      */
   191     boolean allowLambda;
   193     /** Switch: support default methods ?
   194      */
   195     boolean allowDefaultMethods;
   197     /** Switch: allow references to surrounding object from anonymous
   198      * objects during constructor call?
   199      */
   200     boolean allowAnonOuterThis;
   202     /** Switch: generates a warning if diamond can be safely applied
   203      *  to a given new expression
   204      */
   205     boolean findDiamonds;
   207     /**
   208      * Internally enables/disables diamond finder feature
   209      */
   210     static final boolean allowDiamondFinder = true;
   212     /**
   213      * Switch: warn about use of variable before declaration?
   214      * RFE: 6425594
   215      */
   216     boolean useBeforeDeclarationWarning;
   218     /**
   219      * Switch: generate warnings whenever an anonymous inner class that is convertible
   220      * to a lambda expression is found
   221      */
   222     boolean identifyLambdaCandidate;
   224     /**
   225      * Switch: allow strings in switch?
   226      */
   227     boolean allowStringsInSwitch;
   229     /**
   230      * Switch: name of source level; used for error reporting.
   231      */
   232     String sourceName;
   234     /** Check kind and type of given tree against protokind and prototype.
   235      *  If check succeeds, store type in tree and return it.
   236      *  If check fails, store errType in tree and return it.
   237      *  No checks are performed if the prototype is a method type.
   238      *  It is not necessary in this case since we know that kind and type
   239      *  are correct.
   240      *
   241      *  @param tree     The tree whose kind and type is checked
   242      *  @param ownkind  The computed kind of the tree
   243      *  @param resultInfo  The expected result of the tree
   244      */
   245     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   246         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   247         Type owntype = found;
   248         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   249             if (allowPoly && inferenceContext.free(found)) {
   250                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   251                     @Override
   252                     public void typesInferred(InferenceContext inferenceContext) {
   253                         ResultInfo pendingResult =
   254                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   255                         check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   256                     }
   257                 });
   258                 return tree.type = resultInfo.pt;
   259             } else {
   260                 if ((ownkind & ~resultInfo.pkind) == 0) {
   261                     owntype = resultInfo.check(tree, owntype);
   262                 } else {
   263                     log.error(tree.pos(), "unexpected.type",
   264                             kindNames(resultInfo.pkind),
   265                             kindName(ownkind));
   266                     owntype = types.createErrorType(owntype);
   267                 }
   268             }
   269         }
   270         tree.type = owntype;
   271         return owntype;
   272     }
   274     /** Is given blank final variable assignable, i.e. in a scope where it
   275      *  may be assigned to even though it is final?
   276      *  @param v      The blank final variable.
   277      *  @param env    The current environment.
   278      */
   279     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   280         Symbol owner = owner(env);
   281            // owner refers to the innermost variable, method or
   282            // initializer block declaration at this point.
   283         return
   284             v.owner == owner
   285             ||
   286             ((owner.name == names.init ||    // i.e. we are in a constructor
   287               owner.kind == VAR ||           // i.e. we are in a variable initializer
   288               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   289              &&
   290              v.owner == owner.owner
   291              &&
   292              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   293     }
   295     /**
   296      * Return the innermost enclosing owner symbol in a given attribution context
   297      */
   298     Symbol owner(Env<AttrContext> env) {
   299         while (true) {
   300             switch (env.tree.getTag()) {
   301                 case VARDEF:
   302                     //a field can be owner
   303                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   304                     if (vsym.owner.kind == TYP) {
   305                         return vsym;
   306                     }
   307                     break;
   308                 case METHODDEF:
   309                     //method def is always an owner
   310                     return ((JCMethodDecl)env.tree).sym;
   311                 case CLASSDEF:
   312                     //class def is always an owner
   313                     return ((JCClassDecl)env.tree).sym;
   314                 case LAMBDA:
   315                     //a lambda is an owner - return a fresh synthetic method symbol
   316                     return new MethodSymbol(0, names.empty, null, syms.methodClass);
   317                 case BLOCK:
   318                     //static/instance init blocks are owner
   319                     Symbol blockSym = env.info.scope.owner;
   320                     if ((blockSym.flags() & BLOCK) != 0) {
   321                         return blockSym;
   322                     }
   323                     break;
   324                 case TOPLEVEL:
   325                     //toplevel is always an owner (for pkge decls)
   326                     return env.info.scope.owner;
   327             }
   328             Assert.checkNonNull(env.next);
   329             env = env.next;
   330         }
   331     }
   333     /** Check that variable can be assigned to.
   334      *  @param pos    The current source code position.
   335      *  @param v      The assigned varaible
   336      *  @param base   If the variable is referred to in a Select, the part
   337      *                to the left of the `.', null otherwise.
   338      *  @param env    The current environment.
   339      */
   340     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   341         if ((v.flags() & FINAL) != 0 &&
   342             ((v.flags() & HASINIT) != 0
   343              ||
   344              !((base == null ||
   345                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   346                isAssignableAsBlankFinal(v, env)))) {
   347             if (v.isResourceVariable()) { //TWR resource
   348                 log.error(pos, "try.resource.may.not.be.assigned", v);
   349             } else {
   350                 log.error(pos, "cant.assign.val.to.final.var", v);
   351             }
   352         }
   353     }
   355     /** Does tree represent a static reference to an identifier?
   356      *  It is assumed that tree is either a SELECT or an IDENT.
   357      *  We have to weed out selects from non-type names here.
   358      *  @param tree    The candidate tree.
   359      */
   360     boolean isStaticReference(JCTree tree) {
   361         if (tree.hasTag(SELECT)) {
   362             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   363             if (lsym == null || lsym.kind != TYP) {
   364                 return false;
   365             }
   366         }
   367         return true;
   368     }
   370     /** Is this symbol a type?
   371      */
   372     static boolean isType(Symbol sym) {
   373         return sym != null && sym.kind == TYP;
   374     }
   376     /** The current `this' symbol.
   377      *  @param env    The current environment.
   378      */
   379     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   380         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   381     }
   383     /** Attribute a parsed identifier.
   384      * @param tree Parsed identifier name
   385      * @param topLevel The toplevel to use
   386      */
   387     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   388         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   389         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   390                                            syms.errSymbol.name,
   391                                            null, null, null, null);
   392         localEnv.enclClass.sym = syms.errSymbol;
   393         return tree.accept(identAttributer, localEnv);
   394     }
   395     // where
   396         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   397         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   398             @Override
   399             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   400                 Symbol site = visit(node.getExpression(), env);
   401                 if (site.kind == ERR)
   402                     return site;
   403                 Name name = (Name)node.getIdentifier();
   404                 if (site.kind == PCK) {
   405                     env.toplevel.packge = (PackageSymbol)site;
   406                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   407                 } else {
   408                     env.enclClass.sym = (ClassSymbol)site;
   409                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   410                 }
   411             }
   413             @Override
   414             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   415                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   416             }
   417         }
   419     public Type coerce(Type etype, Type ttype) {
   420         return cfolder.coerce(etype, ttype);
   421     }
   423     public Type attribType(JCTree node, TypeSymbol sym) {
   424         Env<AttrContext> env = enter.typeEnvs.get(sym);
   425         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   426         return attribTree(node, localEnv, unknownTypeInfo);
   427     }
   429     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   430         // Attribute qualifying package or class.
   431         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   432         return attribTree(s.selected,
   433                        env,
   434                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   435                        Type.noType));
   436     }
   438     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   439         breakTree = tree;
   440         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   441         try {
   442             attribExpr(expr, env);
   443         } catch (BreakAttr b) {
   444             return b.env;
   445         } catch (AssertionError ae) {
   446             if (ae.getCause() instanceof BreakAttr) {
   447                 return ((BreakAttr)(ae.getCause())).env;
   448             } else {
   449                 throw ae;
   450             }
   451         } finally {
   452             breakTree = null;
   453             log.useSource(prev);
   454         }
   455         return env;
   456     }
   458     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   459         breakTree = tree;
   460         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   461         try {
   462             attribStat(stmt, env);
   463         } catch (BreakAttr b) {
   464             return b.env;
   465         } catch (AssertionError ae) {
   466             if (ae.getCause() instanceof BreakAttr) {
   467                 return ((BreakAttr)(ae.getCause())).env;
   468             } else {
   469                 throw ae;
   470             }
   471         } finally {
   472             breakTree = null;
   473             log.useSource(prev);
   474         }
   475         return env;
   476     }
   478     private JCTree breakTree = null;
   480     private static class BreakAttr extends RuntimeException {
   481         static final long serialVersionUID = -6924771130405446405L;
   482         private Env<AttrContext> env;
   483         private BreakAttr(Env<AttrContext> env) {
   484             this.env = copyEnv(env);
   485         }
   487         private Env<AttrContext> copyEnv(Env<AttrContext> env) {
   488             Env<AttrContext> newEnv =
   489                     env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   490             if (newEnv.outer != null) {
   491                 newEnv.outer = copyEnv(newEnv.outer);
   492             }
   493             return newEnv;
   494         }
   496         private Scope copyScope(Scope sc) {
   497             Scope newScope = new Scope(sc.owner);
   498             List<Symbol> elemsList = List.nil();
   499             while (sc != null) {
   500                 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   501                     elemsList = elemsList.prepend(e.sym);
   502                 }
   503                 sc = sc.next;
   504             }
   505             for (Symbol s : elemsList) {
   506                 newScope.enter(s);
   507             }
   508             return newScope;
   509         }
   510     }
   512     class ResultInfo {
   513         final int pkind;
   514         final Type pt;
   515         final CheckContext checkContext;
   517         ResultInfo(int pkind, Type pt) {
   518             this(pkind, pt, chk.basicHandler);
   519         }
   521         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   522             this.pkind = pkind;
   523             this.pt = pt;
   524             this.checkContext = checkContext;
   525         }
   527         protected Type check(final DiagnosticPosition pos, final Type found) {
   528             return chk.checkType(pos, found, pt, checkContext);
   529         }
   531         protected ResultInfo dup(Type newPt) {
   532             return new ResultInfo(pkind, newPt, checkContext);
   533         }
   535         protected ResultInfo dup(CheckContext newContext) {
   536             return new ResultInfo(pkind, pt, newContext);
   537         }
   538     }
   540     class RecoveryInfo extends ResultInfo {
   542         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   543             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   544                 @Override
   545                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   546                     return deferredAttrContext;
   547                 }
   548                 @Override
   549                 public boolean compatible(Type found, Type req, Warner warn) {
   550                     return true;
   551                 }
   552                 @Override
   553                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   554                     chk.basicHandler.report(pos, details);
   555                 }
   556             });
   557         }
   559         @Override
   560         protected Type check(DiagnosticPosition pos, Type found) {
   561             return chk.checkNonVoid(pos, super.check(pos, found));
   562         }
   563     }
   565     final ResultInfo statInfo;
   566     final ResultInfo varInfo;
   567     final ResultInfo unknownAnyPolyInfo;
   568     final ResultInfo unknownExprInfo;
   569     final ResultInfo unknownTypeInfo;
   570     final ResultInfo unknownTypeExprInfo;
   571     final ResultInfo recoveryInfo;
   573     Type pt() {
   574         return resultInfo.pt;
   575     }
   577     int pkind() {
   578         return resultInfo.pkind;
   579     }
   581 /* ************************************************************************
   582  * Visitor methods
   583  *************************************************************************/
   585     /** Visitor argument: the current environment.
   586      */
   587     Env<AttrContext> env;
   589     /** Visitor argument: the currently expected attribution result.
   590      */
   591     ResultInfo resultInfo;
   593     /** Visitor result: the computed type.
   594      */
   595     Type result;
   597     /** Visitor method: attribute a tree, catching any completion failure
   598      *  exceptions. Return the tree's type.
   599      *
   600      *  @param tree    The tree to be visited.
   601      *  @param env     The environment visitor argument.
   602      *  @param resultInfo   The result info visitor argument.
   603      */
   604     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   605         Env<AttrContext> prevEnv = this.env;
   606         ResultInfo prevResult = this.resultInfo;
   607         try {
   608             this.env = env;
   609             this.resultInfo = resultInfo;
   610             tree.accept(this);
   611             if (tree == breakTree &&
   612                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   613                 throw new BreakAttr(env);
   614             }
   615             return result;
   616         } catch (CompletionFailure ex) {
   617             tree.type = syms.errType;
   618             return chk.completionError(tree.pos(), ex);
   619         } finally {
   620             this.env = prevEnv;
   621             this.resultInfo = prevResult;
   622         }
   623     }
   625     /** Derived visitor method: attribute an expression tree.
   626      */
   627     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   628         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   629     }
   631     /** Derived visitor method: attribute an expression tree with
   632      *  no constraints on the computed type.
   633      */
   634     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   635         return attribTree(tree, env, unknownExprInfo);
   636     }
   638     /** Derived visitor method: attribute a type tree.
   639      */
   640     public Type attribType(JCTree tree, Env<AttrContext> env) {
   641         Type result = attribType(tree, env, Type.noType);
   642         return result;
   643     }
   645     /** Derived visitor method: attribute a type tree.
   646      */
   647     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   648         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   649         return result;
   650     }
   652     /** Derived visitor method: attribute a statement or definition tree.
   653      */
   654     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   655         return attribTree(tree, env, statInfo);
   656     }
   658     /** Attribute a list of expressions, returning a list of types.
   659      */
   660     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   661         ListBuffer<Type> ts = new ListBuffer<Type>();
   662         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   663             ts.append(attribExpr(l.head, env, pt));
   664         return ts.toList();
   665     }
   667     /** Attribute a list of statements, returning nothing.
   668      */
   669     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   670         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   671             attribStat(l.head, env);
   672     }
   674     /** Attribute the arguments in a method call, returning the method kind.
   675      */
   676     int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   677         int kind = VAL;
   678         for (JCExpression arg : trees) {
   679             Type argtype;
   680             if (allowPoly && deferredAttr.isDeferred(env, arg)) {
   681                 argtype = deferredAttr.new DeferredType(arg, env);
   682                 kind |= POLY;
   683             } else {
   684                 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
   685             }
   686             argtypes.append(argtype);
   687         }
   688         return kind;
   689     }
   691     /** Attribute a type argument list, returning a list of types.
   692      *  Caller is responsible for calling checkRefTypes.
   693      */
   694     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   695         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   696         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   697             argtypes.append(attribType(l.head, env));
   698         return argtypes.toList();
   699     }
   701     /** Attribute a type argument list, returning a list of types.
   702      *  Check that all the types are references.
   703      */
   704     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   705         List<Type> types = attribAnyTypes(trees, env);
   706         return chk.checkRefTypes(trees, types);
   707     }
   709     /**
   710      * Attribute type variables (of generic classes or methods).
   711      * Compound types are attributed later in attribBounds.
   712      * @param typarams the type variables to enter
   713      * @param env      the current environment
   714      */
   715     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   716         for (JCTypeParameter tvar : typarams) {
   717             TypeVar a = (TypeVar)tvar.type;
   718             a.tsym.flags_field |= UNATTRIBUTED;
   719             a.bound = Type.noType;
   720             if (!tvar.bounds.isEmpty()) {
   721                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   722                 for (JCExpression bound : tvar.bounds.tail)
   723                     bounds = bounds.prepend(attribType(bound, env));
   724                 types.setBounds(a, bounds.reverse());
   725             } else {
   726                 // if no bounds are given, assume a single bound of
   727                 // java.lang.Object.
   728                 types.setBounds(a, List.of(syms.objectType));
   729             }
   730             a.tsym.flags_field &= ~UNATTRIBUTED;
   731         }
   732         for (JCTypeParameter tvar : typarams) {
   733             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   734         }
   735     }
   737     /**
   738      * Attribute the type references in a list of annotations.
   739      */
   740     void attribAnnotationTypes(List<JCAnnotation> annotations,
   741                                Env<AttrContext> env) {
   742         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   743             JCAnnotation a = al.head;
   744             attribType(a.annotationType, env);
   745         }
   746     }
   748     /**
   749      * Attribute a "lazy constant value".
   750      *  @param env         The env for the const value
   751      *  @param initializer The initializer for the const value
   752      *  @param type        The expected type, or null
   753      *  @see VarSymbol#setLazyConstValue
   754      */
   755     public Object attribLazyConstantValue(Env<AttrContext> env,
   756                                       JCTree.JCExpression initializer,
   757                                       Type type) {
   759         /*  When this env was created, it didn't have the correct lint nor had
   760          *  annotations has been processed.
   761          *  But now at this phase we have already processed annotations and the
   762          *  correct lint must have been set in chk, so we should use that one to
   763          *  attribute the initializer.
   764          */
   765         Lint prevLint = env.info.lint;
   766         env.info.lint = chk.getLint();
   768         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   770         try {
   771             // Use null as symbol to not attach the type annotation to any symbol.
   772             // The initializer will later also be visited and then we'll attach
   773             // to the symbol.
   774             // This prevents having multiple type annotations, just because of
   775             // lazy constant value evaluation.
   776             memberEnter.typeAnnotate(initializer, env, null);
   777             annotate.flush();
   778             Type itype = attribExpr(initializer, env, type);
   779             if (itype.constValue() != null) {
   780                 return coerce(itype, type).constValue();
   781             } else {
   782                 return null;
   783             }
   784         } finally {
   785             env.info.lint = prevLint;
   786             log.useSource(prevSource);
   787         }
   788     }
   790     /** Attribute type reference in an `extends' or `implements' clause.
   791      *  Supertypes of anonymous inner classes are usually already attributed.
   792      *
   793      *  @param tree              The tree making up the type reference.
   794      *  @param env               The environment current at the reference.
   795      *  @param classExpected     true if only a class is expected here.
   796      *  @param interfaceExpected true if only an interface is expected here.
   797      */
   798     Type attribBase(JCTree tree,
   799                     Env<AttrContext> env,
   800                     boolean classExpected,
   801                     boolean interfaceExpected,
   802                     boolean checkExtensible) {
   803         Type t = tree.type != null ?
   804             tree.type :
   805             attribType(tree, env);
   806         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   807     }
   808     Type checkBase(Type t,
   809                    JCTree tree,
   810                    Env<AttrContext> env,
   811                    boolean classExpected,
   812                    boolean interfaceExpected,
   813                    boolean checkExtensible) {
   814         if (t.isErroneous())
   815             return t;
   816         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   817             // check that type variable is already visible
   818             if (t.getUpperBound() == null) {
   819                 log.error(tree.pos(), "illegal.forward.ref");
   820                 return types.createErrorType(t);
   821             }
   822         } else {
   823             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   824         }
   825         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   826             log.error(tree.pos(), "intf.expected.here");
   827             // return errType is necessary since otherwise there might
   828             // be undetected cycles which cause attribution to loop
   829             return types.createErrorType(t);
   830         } else if (checkExtensible &&
   831                    classExpected &&
   832                    (t.tsym.flags() & INTERFACE) != 0) {
   833                 log.error(tree.pos(), "no.intf.expected.here");
   834             return types.createErrorType(t);
   835         }
   836         if (checkExtensible &&
   837             ((t.tsym.flags() & FINAL) != 0)) {
   838             log.error(tree.pos(),
   839                       "cant.inherit.from.final", t.tsym);
   840         }
   841         chk.checkNonCyclic(tree.pos(), t);
   842         return t;
   843     }
   845     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   846         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   847         id.type = env.info.scope.owner.type;
   848         id.sym = env.info.scope.owner;
   849         return id.type;
   850     }
   852     public void visitClassDef(JCClassDecl tree) {
   853         // Local classes have not been entered yet, so we need to do it now:
   854         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   855             enter.classEnter(tree, env);
   857         ClassSymbol c = tree.sym;
   858         if (c == null) {
   859             // exit in case something drastic went wrong during enter.
   860             result = null;
   861         } else {
   862             // make sure class has been completed:
   863             c.complete();
   865             // If this class appears as an anonymous class
   866             // in a superclass constructor call where
   867             // no explicit outer instance is given,
   868             // disable implicit outer instance from being passed.
   869             // (This would be an illegal access to "this before super").
   870             if (env.info.isSelfCall &&
   871                 env.tree.hasTag(NEWCLASS) &&
   872                 ((JCNewClass) env.tree).encl == null)
   873             {
   874                 c.flags_field |= NOOUTERTHIS;
   875             }
   876             attribClass(tree.pos(), c);
   877             result = tree.type = c.type;
   878         }
   879     }
   881     public void visitMethodDef(JCMethodDecl tree) {
   882         MethodSymbol m = tree.sym;
   883         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   885         Lint lint = env.info.lint.augment(m);
   886         Lint prevLint = chk.setLint(lint);
   887         MethodSymbol prevMethod = chk.setMethod(m);
   888         try {
   889             deferredLintHandler.flush(tree.pos());
   890             chk.checkDeprecatedAnnotation(tree.pos(), m);
   893             // Create a new environment with local scope
   894             // for attributing the method.
   895             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   896             localEnv.info.lint = lint;
   898             attribStats(tree.typarams, localEnv);
   900             // If we override any other methods, check that we do so properly.
   901             // JLS ???
   902             if (m.isStatic()) {
   903                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   904             } else {
   905                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   906             }
   907             chk.checkOverride(tree, m);
   909             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   910                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   911             }
   913             // Enter all type parameters into the local method scope.
   914             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   915                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   917             ClassSymbol owner = env.enclClass.sym;
   918             if ((owner.flags() & ANNOTATION) != 0 &&
   919                 tree.params.nonEmpty())
   920                 log.error(tree.params.head.pos(),
   921                           "intf.annotation.members.cant.have.params");
   923             // Attribute all value parameters.
   924             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   925                 attribStat(l.head, localEnv);
   926             }
   928             chk.checkVarargsMethodDecl(localEnv, tree);
   930             // Check that type parameters are well-formed.
   931             chk.validate(tree.typarams, localEnv);
   933             // Check that result type is well-formed.
   934             chk.validate(tree.restype, localEnv);
   936             // Check that receiver type is well-formed.
   937             if (tree.recvparam != null) {
   938                 // Use a new environment to check the receiver parameter.
   939                 // Otherwise I get "might not have been initialized" errors.
   940                 // Is there a better way?
   941                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   942                 attribType(tree.recvparam, newEnv);
   943                 chk.validate(tree.recvparam, newEnv);
   944             }
   946             // annotation method checks
   947             if ((owner.flags() & ANNOTATION) != 0) {
   948                 // annotation method cannot have throws clause
   949                 if (tree.thrown.nonEmpty()) {
   950                     log.error(tree.thrown.head.pos(),
   951                             "throws.not.allowed.in.intf.annotation");
   952                 }
   953                 // annotation method cannot declare type-parameters
   954                 if (tree.typarams.nonEmpty()) {
   955                     log.error(tree.typarams.head.pos(),
   956                             "intf.annotation.members.cant.have.type.params");
   957                 }
   958                 // validate annotation method's return type (could be an annotation type)
   959                 chk.validateAnnotationType(tree.restype);
   960                 // ensure that annotation method does not clash with members of Object/Annotation
   961                 chk.validateAnnotationMethod(tree.pos(), m);
   963                 if (tree.defaultValue != null) {
   964                     // if default value is an annotation, check it is a well-formed
   965                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   966                     chk.validateAnnotationTree(tree.defaultValue);
   967                 }
   968             }
   970             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   971                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   973             if (tree.body == null) {
   974                 // Empty bodies are only allowed for
   975                 // abstract, native, or interface methods, or for methods
   976                 // in a retrofit signature class.
   977                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   978                     !relax)
   979                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   980                 if (tree.defaultValue != null) {
   981                     if ((owner.flags() & ANNOTATION) == 0)
   982                         log.error(tree.pos(),
   983                                   "default.allowed.in.intf.annotation.member");
   984                 }
   985             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   986                 if ((owner.flags() & INTERFACE) != 0) {
   987                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   988                 } else {
   989                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   990                 }
   991             } else if ((tree.mods.flags & NATIVE) != 0) {
   992                 log.error(tree.pos(), "native.meth.cant.have.body");
   993             } else {
   994                 // Add an implicit super() call unless an explicit call to
   995                 // super(...) or this(...) is given
   996                 // or we are compiling class java.lang.Object.
   997                 if (tree.name == names.init && owner.type != syms.objectType) {
   998                     JCBlock body = tree.body;
   999                     if (body.stats.isEmpty() ||
  1000                         !TreeInfo.isSelfCall(body.stats.head)) {
  1001                         body.stats = body.stats.
  1002                             prepend(memberEnter.SuperCall(make.at(body.pos),
  1003                                                           List.<Type>nil(),
  1004                                                           List.<JCVariableDecl>nil(),
  1005                                                           false));
  1006                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1007                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1008                                TreeInfo.isSuperCall(body.stats.head)) {
  1009                         // enum constructors are not allowed to call super
  1010                         // directly, so make sure there aren't any super calls
  1011                         // in enum constructors, except in the compiler
  1012                         // generated one.
  1013                         log.error(tree.body.stats.head.pos(),
  1014                                   "call.to.super.not.allowed.in.enum.ctor",
  1015                                   env.enclClass.sym);
  1019                 // Attribute all type annotations in the body
  1020                 memberEnter.typeAnnotate(tree.body, localEnv, m);
  1021                 annotate.flush();
  1023                 // Attribute method body.
  1024                 attribStat(tree.body, localEnv);
  1027             localEnv.info.scope.leave();
  1028             result = tree.type = m.type;
  1029             chk.validateAnnotations(tree.mods.annotations, m);
  1031         finally {
  1032             chk.setLint(prevLint);
  1033             chk.setMethod(prevMethod);
  1037     public void visitVarDef(JCVariableDecl tree) {
  1038         // Local variables have not been entered yet, so we need to do it now:
  1039         if (env.info.scope.owner.kind == MTH) {
  1040             if (tree.sym != null) {
  1041                 // parameters have already been entered
  1042                 env.info.scope.enter(tree.sym);
  1043             } else {
  1044                 memberEnter.memberEnter(tree, env);
  1045                 annotate.flush();
  1047         } else {
  1048             if (tree.init != null) {
  1049                 // Field initializer expression need to be entered.
  1050                 memberEnter.typeAnnotate(tree.init, env, tree.sym);
  1051                 annotate.flush();
  1055         VarSymbol v = tree.sym;
  1056         Lint lint = env.info.lint.augment(v);
  1057         Lint prevLint = chk.setLint(lint);
  1059         // Check that the variable's declared type is well-formed.
  1060         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1061                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1062                 (tree.sym.flags() & PARAMETER) != 0;
  1063         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1064         deferredLintHandler.flush(tree.pos());
  1066         try {
  1067             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1069             if (tree.init != null) {
  1070                 if ((v.flags_field & FINAL) != 0 &&
  1071                         !tree.init.hasTag(NEWCLASS) &&
  1072                         !tree.init.hasTag(LAMBDA) &&
  1073                         !tree.init.hasTag(REFERENCE)) {
  1074                     // In this case, `v' is final.  Ensure that it's initializer is
  1075                     // evaluated.
  1076                     v.getConstValue(); // ensure initializer is evaluated
  1077                 } else {
  1078                     // Attribute initializer in a new environment
  1079                     // with the declared variable as owner.
  1080                     // Check that initializer conforms to variable's declared type.
  1081                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1082                     initEnv.info.lint = lint;
  1083                     // In order to catch self-references, we set the variable's
  1084                     // declaration position to maximal possible value, effectively
  1085                     // marking the variable as undefined.
  1086                     initEnv.info.enclVar = v;
  1087                     attribExpr(tree.init, initEnv, v.type);
  1090             result = tree.type = v.type;
  1091             chk.validateAnnotations(tree.mods.annotations, v);
  1093         finally {
  1094             chk.setLint(prevLint);
  1098     public void visitSkip(JCSkip tree) {
  1099         result = null;
  1102     public void visitBlock(JCBlock tree) {
  1103         if (env.info.scope.owner.kind == TYP) {
  1104             // Block is a static or instance initializer;
  1105             // let the owner of the environment be a freshly
  1106             // created BLOCK-method.
  1107             Env<AttrContext> localEnv =
  1108                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1109             localEnv.info.scope.owner =
  1110                 new MethodSymbol(tree.flags | BLOCK |
  1111                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1112                     env.info.scope.owner);
  1113             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1115             // Attribute all type annotations in the block
  1116             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner);
  1117             annotate.flush();
  1120                 // Store init and clinit type annotations with the ClassSymbol
  1121                 // to allow output in Gen.normalizeDefs.
  1122                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1123                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1124                 if ((tree.flags & STATIC) != 0) {
  1125                     cs.appendClassInitTypeAttributes(tas);
  1126                 } else {
  1127                     cs.appendInitTypeAttributes(tas);
  1131             attribStats(tree.stats, localEnv);
  1132         } else {
  1133             // Create a new local environment with a local scope.
  1134             Env<AttrContext> localEnv =
  1135                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1136             try {
  1137                 attribStats(tree.stats, localEnv);
  1138             } finally {
  1139                 localEnv.info.scope.leave();
  1142         result = null;
  1145     public void visitDoLoop(JCDoWhileLoop tree) {
  1146         attribStat(tree.body, env.dup(tree));
  1147         attribExpr(tree.cond, env, syms.booleanType);
  1148         result = null;
  1151     public void visitWhileLoop(JCWhileLoop tree) {
  1152         attribExpr(tree.cond, env, syms.booleanType);
  1153         attribStat(tree.body, env.dup(tree));
  1154         result = null;
  1157     public void visitForLoop(JCForLoop tree) {
  1158         Env<AttrContext> loopEnv =
  1159             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1160         try {
  1161             attribStats(tree.init, loopEnv);
  1162             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1163             loopEnv.tree = tree; // before, we were not in loop!
  1164             attribStats(tree.step, loopEnv);
  1165             attribStat(tree.body, loopEnv);
  1166             result = null;
  1168         finally {
  1169             loopEnv.info.scope.leave();
  1173     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1174         Env<AttrContext> loopEnv =
  1175             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1176         try {
  1177             //the Formal Parameter of a for-each loop is not in the scope when
  1178             //attributing the for-each expression; we mimick this by attributing
  1179             //the for-each expression first (against original scope).
  1180             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1181             attribStat(tree.var, loopEnv);
  1182             chk.checkNonVoid(tree.pos(), exprType);
  1183             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1184             if (elemtype == null) {
  1185                 // or perhaps expr implements Iterable<T>?
  1186                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1187                 if (base == null) {
  1188                     log.error(tree.expr.pos(),
  1189                             "foreach.not.applicable.to.type",
  1190                             exprType,
  1191                             diags.fragment("type.req.array.or.iterable"));
  1192                     elemtype = types.createErrorType(exprType);
  1193                 } else {
  1194                     List<Type> iterableParams = base.allparams();
  1195                     elemtype = iterableParams.isEmpty()
  1196                         ? syms.objectType
  1197                         : types.upperBound(iterableParams.head);
  1200             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1201             loopEnv.tree = tree; // before, we were not in loop!
  1202             attribStat(tree.body, loopEnv);
  1203             result = null;
  1205         finally {
  1206             loopEnv.info.scope.leave();
  1210     public void visitLabelled(JCLabeledStatement tree) {
  1211         // Check that label is not used in an enclosing statement
  1212         Env<AttrContext> env1 = env;
  1213         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1214             if (env1.tree.hasTag(LABELLED) &&
  1215                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1216                 log.error(tree.pos(), "label.already.in.use",
  1217                           tree.label);
  1218                 break;
  1220             env1 = env1.next;
  1223         attribStat(tree.body, env.dup(tree));
  1224         result = null;
  1227     public void visitSwitch(JCSwitch tree) {
  1228         Type seltype = attribExpr(tree.selector, env);
  1230         Env<AttrContext> switchEnv =
  1231             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1233         try {
  1235             boolean enumSwitch =
  1236                 allowEnums &&
  1237                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1238             boolean stringSwitch = false;
  1239             if (types.isSameType(seltype, syms.stringType)) {
  1240                 if (allowStringsInSwitch) {
  1241                     stringSwitch = true;
  1242                 } else {
  1243                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1246             if (!enumSwitch && !stringSwitch)
  1247                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1249             // Attribute all cases and
  1250             // check that there are no duplicate case labels or default clauses.
  1251             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1252             boolean hasDefault = false;      // Is there a default label?
  1253             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1254                 JCCase c = l.head;
  1255                 Env<AttrContext> caseEnv =
  1256                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1257                 try {
  1258                     if (c.pat != null) {
  1259                         if (enumSwitch) {
  1260                             Symbol sym = enumConstant(c.pat, seltype);
  1261                             if (sym == null) {
  1262                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1263                             } else if (!labels.add(sym)) {
  1264                                 log.error(c.pos(), "duplicate.case.label");
  1266                         } else {
  1267                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1268                             if (!pattype.hasTag(ERROR)) {
  1269                                 if (pattype.constValue() == null) {
  1270                                     log.error(c.pat.pos(),
  1271                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1272                                 } else if (labels.contains(pattype.constValue())) {
  1273                                     log.error(c.pos(), "duplicate.case.label");
  1274                                 } else {
  1275                                     labels.add(pattype.constValue());
  1279                     } else if (hasDefault) {
  1280                         log.error(c.pos(), "duplicate.default.label");
  1281                     } else {
  1282                         hasDefault = true;
  1284                     attribStats(c.stats, caseEnv);
  1285                 } finally {
  1286                     caseEnv.info.scope.leave();
  1287                     addVars(c.stats, switchEnv.info.scope);
  1291             result = null;
  1293         finally {
  1294             switchEnv.info.scope.leave();
  1297     // where
  1298         /** Add any variables defined in stats to the switch scope. */
  1299         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1300             for (;stats.nonEmpty(); stats = stats.tail) {
  1301                 JCTree stat = stats.head;
  1302                 if (stat.hasTag(VARDEF))
  1303                     switchScope.enter(((JCVariableDecl) stat).sym);
  1306     // where
  1307     /** Return the selected enumeration constant symbol, or null. */
  1308     private Symbol enumConstant(JCTree tree, Type enumType) {
  1309         if (!tree.hasTag(IDENT)) {
  1310             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1311             return syms.errSymbol;
  1313         JCIdent ident = (JCIdent)tree;
  1314         Name name = ident.name;
  1315         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1316              e.scope != null; e = e.next()) {
  1317             if (e.sym.kind == VAR) {
  1318                 Symbol s = ident.sym = e.sym;
  1319                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1320                 ident.type = s.type;
  1321                 return ((s.flags_field & Flags.ENUM) == 0)
  1322                     ? null : s;
  1325         return null;
  1328     public void visitSynchronized(JCSynchronized tree) {
  1329         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1330         attribStat(tree.body, env);
  1331         result = null;
  1334     public void visitTry(JCTry tree) {
  1335         // Create a new local environment with a local
  1336         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1337         try {
  1338             boolean isTryWithResource = tree.resources.nonEmpty();
  1339             // Create a nested environment for attributing the try block if needed
  1340             Env<AttrContext> tryEnv = isTryWithResource ?
  1341                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1342                 localEnv;
  1343             try {
  1344                 // Attribute resource declarations
  1345                 for (JCTree resource : tree.resources) {
  1346                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1347                         @Override
  1348                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1349                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1351                     };
  1352                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1353                     if (resource.hasTag(VARDEF)) {
  1354                         attribStat(resource, tryEnv);
  1355                         twrResult.check(resource, resource.type);
  1357                         //check that resource type cannot throw InterruptedException
  1358                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1360                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1361                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1362                     } else {
  1363                         attribTree(resource, tryEnv, twrResult);
  1366                 // Attribute body
  1367                 attribStat(tree.body, tryEnv);
  1368             } finally {
  1369                 if (isTryWithResource)
  1370                     tryEnv.info.scope.leave();
  1373             // Attribute catch clauses
  1374             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1375                 JCCatch c = l.head;
  1376                 Env<AttrContext> catchEnv =
  1377                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1378                 try {
  1379                     Type ctype = attribStat(c.param, catchEnv);
  1380                     if (TreeInfo.isMultiCatch(c)) {
  1381                         //multi-catch parameter is implicitly marked as final
  1382                         c.param.sym.flags_field |= FINAL | UNION;
  1384                     if (c.param.sym.kind == Kinds.VAR) {
  1385                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1387                     chk.checkType(c.param.vartype.pos(),
  1388                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1389                                   syms.throwableType);
  1390                     attribStat(c.body, catchEnv);
  1391                 } finally {
  1392                     catchEnv.info.scope.leave();
  1396             // Attribute finalizer
  1397             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1398             result = null;
  1400         finally {
  1401             localEnv.info.scope.leave();
  1405     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1406         if (!resource.isErroneous() &&
  1407             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1408             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1409             Symbol close = syms.noSymbol;
  1410             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1411             try {
  1412                 close = rs.resolveQualifiedMethod(pos,
  1413                         env,
  1414                         resource,
  1415                         names.close,
  1416                         List.<Type>nil(),
  1417                         List.<Type>nil());
  1419             finally {
  1420                 log.popDiagnosticHandler(discardHandler);
  1422             if (close.kind == MTH &&
  1423                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1424                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1425                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1426                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1431     public void visitConditional(JCConditional tree) {
  1432         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1434         tree.polyKind = (!allowPoly ||
  1435                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1436                 isBooleanOrNumeric(env, tree)) ?
  1437                 PolyKind.STANDALONE : PolyKind.POLY;
  1439         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1440             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1441             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1442             result = tree.type = types.createErrorType(resultInfo.pt);
  1443             return;
  1446         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1447                 unknownExprInfo :
  1448                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1449                     //this will use enclosing check context to check compatibility of
  1450                     //subexpression against target type; if we are in a method check context,
  1451                     //depending on whether boxing is allowed, we could have incompatibilities
  1452                     @Override
  1453                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1454                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1456                 });
  1458         Type truetype = attribTree(tree.truepart, env, condInfo);
  1459         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1461         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1462         if (condtype.constValue() != null &&
  1463                 truetype.constValue() != null &&
  1464                 falsetype.constValue() != null &&
  1465                 !owntype.hasTag(NONE)) {
  1466             //constant folding
  1467             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1469         result = check(tree, owntype, VAL, resultInfo);
  1471     //where
  1472         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1473             switch (tree.getTag()) {
  1474                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1475                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1476                               ((JCLiteral)tree).typetag == BOT;
  1477                 case LAMBDA: case REFERENCE: return false;
  1478                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1479                 case CONDEXPR:
  1480                     JCConditional condTree = (JCConditional)tree;
  1481                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1482                             isBooleanOrNumeric(env, condTree.falsepart);
  1483                 case APPLY:
  1484                     JCMethodInvocation speculativeMethodTree =
  1485                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1486                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1487                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1488                 case NEWCLASS:
  1489                     JCExpression className =
  1490                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1491                     JCExpression speculativeNewClassTree =
  1492                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1493                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1494                 default:
  1495                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1496                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1497                     return speculativeType.isPrimitive();
  1500         //where
  1501             TreeTranslator removeClassParams = new TreeTranslator() {
  1502                 @Override
  1503                 public void visitTypeApply(JCTypeApply tree) {
  1504                     result = translate(tree.clazz);
  1506             };
  1508         /** Compute the type of a conditional expression, after
  1509          *  checking that it exists.  See JLS 15.25. Does not take into
  1510          *  account the special case where condition and both arms
  1511          *  are constants.
  1513          *  @param pos      The source position to be used for error
  1514          *                  diagnostics.
  1515          *  @param thentype The type of the expression's then-part.
  1516          *  @param elsetype The type of the expression's else-part.
  1517          */
  1518         private Type condType(DiagnosticPosition pos,
  1519                                Type thentype, Type elsetype) {
  1520             // If same type, that is the result
  1521             if (types.isSameType(thentype, elsetype))
  1522                 return thentype.baseType();
  1524             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1525                 ? thentype : types.unboxedType(thentype);
  1526             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1527                 ? elsetype : types.unboxedType(elsetype);
  1529             // Otherwise, if both arms can be converted to a numeric
  1530             // type, return the least numeric type that fits both arms
  1531             // (i.e. return larger of the two, or return int if one
  1532             // arm is short, the other is char).
  1533             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1534                 // If one arm has an integer subrange type (i.e., byte,
  1535                 // short, or char), and the other is an integer constant
  1536                 // that fits into the subrange, return the subrange type.
  1537                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1538                     elseUnboxed.hasTag(INT) &&
  1539                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1540                     return thenUnboxed.baseType();
  1542                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1543                     thenUnboxed.hasTag(INT) &&
  1544                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1545                     return elseUnboxed.baseType();
  1548                 for (TypeTag tag : primitiveTags) {
  1549                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1550                     if (types.isSubtype(thenUnboxed, candidate) &&
  1551                         types.isSubtype(elseUnboxed, candidate)) {
  1552                         return candidate;
  1557             // Those were all the cases that could result in a primitive
  1558             if (allowBoxing) {
  1559                 if (thentype.isPrimitive())
  1560                     thentype = types.boxedClass(thentype).type;
  1561                 if (elsetype.isPrimitive())
  1562                     elsetype = types.boxedClass(elsetype).type;
  1565             if (types.isSubtype(thentype, elsetype))
  1566                 return elsetype.baseType();
  1567             if (types.isSubtype(elsetype, thentype))
  1568                 return thentype.baseType();
  1570             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1571                 log.error(pos, "neither.conditional.subtype",
  1572                           thentype, elsetype);
  1573                 return thentype.baseType();
  1576             // both are known to be reference types.  The result is
  1577             // lub(thentype,elsetype). This cannot fail, as it will
  1578             // always be possible to infer "Object" if nothing better.
  1579             return types.lub(thentype.baseType(), elsetype.baseType());
  1582     final static TypeTag[] primitiveTags = new TypeTag[]{
  1583         BYTE,
  1584         CHAR,
  1585         SHORT,
  1586         INT,
  1587         LONG,
  1588         FLOAT,
  1589         DOUBLE,
  1590         BOOLEAN,
  1591     };
  1593     public void visitIf(JCIf tree) {
  1594         attribExpr(tree.cond, env, syms.booleanType);
  1595         attribStat(tree.thenpart, env);
  1596         if (tree.elsepart != null)
  1597             attribStat(tree.elsepart, env);
  1598         chk.checkEmptyIf(tree);
  1599         result = null;
  1602     public void visitExec(JCExpressionStatement tree) {
  1603         //a fresh environment is required for 292 inference to work properly ---
  1604         //see Infer.instantiatePolymorphicSignatureInstance()
  1605         Env<AttrContext> localEnv = env.dup(tree);
  1606         attribExpr(tree.expr, localEnv);
  1607         result = null;
  1610     public void visitBreak(JCBreak tree) {
  1611         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1612         result = null;
  1615     public void visitContinue(JCContinue tree) {
  1616         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1617         result = null;
  1619     //where
  1620         /** Return the target of a break or continue statement, if it exists,
  1621          *  report an error if not.
  1622          *  Note: The target of a labelled break or continue is the
  1623          *  (non-labelled) statement tree referred to by the label,
  1624          *  not the tree representing the labelled statement itself.
  1626          *  @param pos     The position to be used for error diagnostics
  1627          *  @param tag     The tag of the jump statement. This is either
  1628          *                 Tree.BREAK or Tree.CONTINUE.
  1629          *  @param label   The label of the jump statement, or null if no
  1630          *                 label is given.
  1631          *  @param env     The environment current at the jump statement.
  1632          */
  1633         private JCTree findJumpTarget(DiagnosticPosition pos,
  1634                                     JCTree.Tag tag,
  1635                                     Name label,
  1636                                     Env<AttrContext> env) {
  1637             // Search environments outwards from the point of jump.
  1638             Env<AttrContext> env1 = env;
  1639             LOOP:
  1640             while (env1 != null) {
  1641                 switch (env1.tree.getTag()) {
  1642                     case LABELLED:
  1643                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1644                         if (label == labelled.label) {
  1645                             // If jump is a continue, check that target is a loop.
  1646                             if (tag == CONTINUE) {
  1647                                 if (!labelled.body.hasTag(DOLOOP) &&
  1648                                         !labelled.body.hasTag(WHILELOOP) &&
  1649                                         !labelled.body.hasTag(FORLOOP) &&
  1650                                         !labelled.body.hasTag(FOREACHLOOP))
  1651                                     log.error(pos, "not.loop.label", label);
  1652                                 // Found labelled statement target, now go inwards
  1653                                 // to next non-labelled tree.
  1654                                 return TreeInfo.referencedStatement(labelled);
  1655                             } else {
  1656                                 return labelled;
  1659                         break;
  1660                     case DOLOOP:
  1661                     case WHILELOOP:
  1662                     case FORLOOP:
  1663                     case FOREACHLOOP:
  1664                         if (label == null) return env1.tree;
  1665                         break;
  1666                     case SWITCH:
  1667                         if (label == null && tag == BREAK) return env1.tree;
  1668                         break;
  1669                     case LAMBDA:
  1670                     case METHODDEF:
  1671                     case CLASSDEF:
  1672                         break LOOP;
  1673                     default:
  1675                 env1 = env1.next;
  1677             if (label != null)
  1678                 log.error(pos, "undef.label", label);
  1679             else if (tag == CONTINUE)
  1680                 log.error(pos, "cont.outside.loop");
  1681             else
  1682                 log.error(pos, "break.outside.switch.loop");
  1683             return null;
  1686     public void visitReturn(JCReturn tree) {
  1687         // Check that there is an enclosing method which is
  1688         // nested within than the enclosing class.
  1689         if (env.info.returnResult == null) {
  1690             log.error(tree.pos(), "ret.outside.meth");
  1691         } else {
  1692             // Attribute return expression, if it exists, and check that
  1693             // it conforms to result type of enclosing method.
  1694             if (tree.expr != null) {
  1695                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1696                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1697                               diags.fragment("unexpected.ret.val"));
  1699                 attribTree(tree.expr, env, env.info.returnResult);
  1700             } else if (!env.info.returnResult.pt.hasTag(VOID)) {
  1701                 env.info.returnResult.checkContext.report(tree.pos(),
  1702                               diags.fragment("missing.ret.val"));
  1705         result = null;
  1708     public void visitThrow(JCThrow tree) {
  1709         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1710         if (allowPoly) {
  1711             chk.checkType(tree, owntype, syms.throwableType);
  1713         result = null;
  1716     public void visitAssert(JCAssert tree) {
  1717         attribExpr(tree.cond, env, syms.booleanType);
  1718         if (tree.detail != null) {
  1719             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1721         result = null;
  1724      /** Visitor method for method invocations.
  1725      *  NOTE: The method part of an application will have in its type field
  1726      *        the return type of the method, not the method's type itself!
  1727      */
  1728     public void visitApply(JCMethodInvocation tree) {
  1729         // The local environment of a method application is
  1730         // a new environment nested in the current one.
  1731         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1733         // The types of the actual method arguments.
  1734         List<Type> argtypes;
  1736         // The types of the actual method type arguments.
  1737         List<Type> typeargtypes = null;
  1739         Name methName = TreeInfo.name(tree.meth);
  1741         boolean isConstructorCall =
  1742             methName == names._this || methName == names._super;
  1744         ListBuffer<Type> argtypesBuf = ListBuffer.lb();
  1745         if (isConstructorCall) {
  1746             // We are seeing a ...this(...) or ...super(...) call.
  1747             // Check that this is the first statement in a constructor.
  1748             if (checkFirstConstructorStat(tree, env)) {
  1750                 // Record the fact
  1751                 // that this is a constructor call (using isSelfCall).
  1752                 localEnv.info.isSelfCall = true;
  1754                 // Attribute arguments, yielding list of argument types.
  1755                 attribArgs(tree.args, localEnv, argtypesBuf);
  1756                 argtypes = argtypesBuf.toList();
  1757                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1759                 // Variable `site' points to the class in which the called
  1760                 // constructor is defined.
  1761                 Type site = env.enclClass.sym.type;
  1762                 if (methName == names._super) {
  1763                     if (site == syms.objectType) {
  1764                         log.error(tree.meth.pos(), "no.superclass", site);
  1765                         site = types.createErrorType(syms.objectType);
  1766                     } else {
  1767                         site = types.supertype(site);
  1771                 if (site.hasTag(CLASS)) {
  1772                     Type encl = site.getEnclosingType();
  1773                     while (encl != null && encl.hasTag(TYPEVAR))
  1774                         encl = encl.getUpperBound();
  1775                     if (encl.hasTag(CLASS)) {
  1776                         // we are calling a nested class
  1778                         if (tree.meth.hasTag(SELECT)) {
  1779                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1781                             // We are seeing a prefixed call, of the form
  1782                             //     <expr>.super(...).
  1783                             // Check that the prefix expression conforms
  1784                             // to the outer instance type of the class.
  1785                             chk.checkRefType(qualifier.pos(),
  1786                                              attribExpr(qualifier, localEnv,
  1787                                                         encl));
  1788                         } else if (methName == names._super) {
  1789                             // qualifier omitted; check for existence
  1790                             // of an appropriate implicit qualifier.
  1791                             rs.resolveImplicitThis(tree.meth.pos(),
  1792                                                    localEnv, site, true);
  1794                     } else if (tree.meth.hasTag(SELECT)) {
  1795                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1796                                   site.tsym);
  1799                     // if we're calling a java.lang.Enum constructor,
  1800                     // prefix the implicit String and int parameters
  1801                     if (site.tsym == syms.enumSym && allowEnums)
  1802                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1804                     // Resolve the called constructor under the assumption
  1805                     // that we are referring to a superclass instance of the
  1806                     // current instance (JLS ???).
  1807                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1808                     localEnv.info.selectSuper = true;
  1809                     localEnv.info.pendingResolutionPhase = null;
  1810                     Symbol sym = rs.resolveConstructor(
  1811                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1812                     localEnv.info.selectSuper = selectSuperPrev;
  1814                     // Set method symbol to resolved constructor...
  1815                     TreeInfo.setSymbol(tree.meth, sym);
  1817                     // ...and check that it is legal in the current context.
  1818                     // (this will also set the tree's type)
  1819                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1820                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1822                 // Otherwise, `site' is an error type and we do nothing
  1824             result = tree.type = syms.voidType;
  1825         } else {
  1826             // Otherwise, we are seeing a regular method call.
  1827             // Attribute the arguments, yielding list of argument types, ...
  1828             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1829             argtypes = argtypesBuf.toList();
  1830             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1832             // ... and attribute the method using as a prototype a methodtype
  1833             // whose formal argument types is exactly the list of actual
  1834             // arguments (this will also set the method symbol).
  1835             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1836             localEnv.info.pendingResolutionPhase = null;
  1837             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1839             // Compute the result type.
  1840             Type restype = mtype.getReturnType();
  1841             if (restype.hasTag(WILDCARD))
  1842                 throw new AssertionError(mtype);
  1844             Type qualifier = (tree.meth.hasTag(SELECT))
  1845                     ? ((JCFieldAccess) tree.meth).selected.type
  1846                     : env.enclClass.sym.type;
  1847             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1849             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1851             // Check that value of resulting type is admissible in the
  1852             // current context.  Also, capture the return type
  1853             result = check(tree, capture(restype), VAL, resultInfo);
  1855         chk.validate(tree.typeargs, localEnv);
  1857     //where
  1858         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1859             if (allowCovariantReturns &&
  1860                     methodName == names.clone &&
  1861                 types.isArray(qualifierType)) {
  1862                 // as a special case, array.clone() has a result that is
  1863                 // the same as static type of the array being cloned
  1864                 return qualifierType;
  1865             } else if (allowGenerics &&
  1866                     methodName == names.getClass &&
  1867                     argtypes.isEmpty()) {
  1868                 // as a special case, x.getClass() has type Class<? extends |X|>
  1869                 return new ClassType(restype.getEnclosingType(),
  1870                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1871                                                                BoundKind.EXTENDS,
  1872                                                                syms.boundClass)),
  1873                               restype.tsym);
  1874             } else {
  1875                 return restype;
  1879         /** Check that given application node appears as first statement
  1880          *  in a constructor call.
  1881          *  @param tree   The application node
  1882          *  @param env    The environment current at the application.
  1883          */
  1884         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1885             JCMethodDecl enclMethod = env.enclMethod;
  1886             if (enclMethod != null && enclMethod.name == names.init) {
  1887                 JCBlock body = enclMethod.body;
  1888                 if (body.stats.head.hasTag(EXEC) &&
  1889                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1890                     return true;
  1892             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1893                       TreeInfo.name(tree.meth));
  1894             return false;
  1897         /** Obtain a method type with given argument types.
  1898          */
  1899         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1900             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1901             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1904     public void visitNewClass(final JCNewClass tree) {
  1905         Type owntype = types.createErrorType(tree.type);
  1907         // The local environment of a class creation is
  1908         // a new environment nested in the current one.
  1909         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1911         // The anonymous inner class definition of the new expression,
  1912         // if one is defined by it.
  1913         JCClassDecl cdef = tree.def;
  1915         // If enclosing class is given, attribute it, and
  1916         // complete class name to be fully qualified
  1917         JCExpression clazz = tree.clazz; // Class field following new
  1918         JCExpression clazzid;            // Identifier in class field
  1919         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1920         annoclazzid = null;
  1922         if (clazz.hasTag(TYPEAPPLY)) {
  1923             clazzid = ((JCTypeApply) clazz).clazz;
  1924             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1925                 annoclazzid = (JCAnnotatedType) clazzid;
  1926                 clazzid = annoclazzid.underlyingType;
  1928         } else {
  1929             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1930                 annoclazzid = (JCAnnotatedType) clazz;
  1931                 clazzid = annoclazzid.underlyingType;
  1932             } else {
  1933                 clazzid = clazz;
  1937         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1939         if (tree.encl != null) {
  1940             // We are seeing a qualified new, of the form
  1941             //    <expr>.new C <...> (...) ...
  1942             // In this case, we let clazz stand for the name of the
  1943             // allocated class C prefixed with the type of the qualifier
  1944             // expression, so that we can
  1945             // resolve it with standard techniques later. I.e., if
  1946             // <expr> has type T, then <expr>.new C <...> (...)
  1947             // yields a clazz T.C.
  1948             Type encltype = chk.checkRefType(tree.encl.pos(),
  1949                                              attribExpr(tree.encl, env));
  1950             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1951             // from expr to the combined type, or not? Yes, do this.
  1952             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1953                                                  ((JCIdent) clazzid).name);
  1955             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1956                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1957                 List<JCAnnotation> annos = annoType.annotations;
  1959                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1960                     clazzid1 = make.at(tree.pos).
  1961                         TypeApply(clazzid1,
  1962                                   ((JCTypeApply) clazz).arguments);
  1965                 clazzid1 = make.at(tree.pos).
  1966                     AnnotatedType(annos, clazzid1);
  1967             } else if (clazz.hasTag(TYPEAPPLY)) {
  1968                 clazzid1 = make.at(tree.pos).
  1969                     TypeApply(clazzid1,
  1970                               ((JCTypeApply) clazz).arguments);
  1973             clazz = clazzid1;
  1976         // Attribute clazz expression and store
  1977         // symbol + type back into the attributed tree.
  1978         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1979             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1980             attribType(clazz, env);
  1982         clazztype = chk.checkDiamond(tree, clazztype);
  1983         chk.validate(clazz, localEnv);
  1984         if (tree.encl != null) {
  1985             // We have to work in this case to store
  1986             // symbol + type back into the attributed tree.
  1987             tree.clazz.type = clazztype;
  1988             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1989             clazzid.type = ((JCIdent) clazzid).sym.type;
  1990             if (annoclazzid != null) {
  1991                 annoclazzid.type = clazzid.type;
  1993             if (!clazztype.isErroneous()) {
  1994                 if (cdef != null && clazztype.tsym.isInterface()) {
  1995                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1996                 } else if (clazztype.tsym.isStatic()) {
  1997                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  2000         } else if (!clazztype.tsym.isInterface() &&
  2001                    clazztype.getEnclosingType().hasTag(CLASS)) {
  2002             // Check for the existence of an apropos outer instance
  2003             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  2006         // Attribute constructor arguments.
  2007         ListBuffer<Type> argtypesBuf = ListBuffer.lb();
  2008         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  2009         List<Type> argtypes = argtypesBuf.toList();
  2010         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  2012         // If we have made no mistakes in the class type...
  2013         if (clazztype.hasTag(CLASS)) {
  2014             // Enums may not be instantiated except implicitly
  2015             if (allowEnums &&
  2016                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  2017                 (!env.tree.hasTag(VARDEF) ||
  2018                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  2019                  ((JCVariableDecl) env.tree).init != tree))
  2020                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2021             // Check that class is not abstract
  2022             if (cdef == null &&
  2023                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2024                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2025                           clazztype.tsym);
  2026             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2027                 // Check that no constructor arguments are given to
  2028                 // anonymous classes implementing an interface
  2029                 if (!argtypes.isEmpty())
  2030                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2032                 if (!typeargtypes.isEmpty())
  2033                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2035                 // Error recovery: pretend no arguments were supplied.
  2036                 argtypes = List.nil();
  2037                 typeargtypes = List.nil();
  2038             } else if (TreeInfo.isDiamond(tree)) {
  2039                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2040                             clazztype.tsym.type.getTypeArguments(),
  2041                             clazztype.tsym);
  2043                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2044                 diamondEnv.info.selectSuper = cdef != null;
  2045                 diamondEnv.info.pendingResolutionPhase = null;
  2047                 //if the type of the instance creation expression is a class type
  2048                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2049                 //of the resolved constructor will be a partially instantiated type
  2050                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2051                             diamondEnv,
  2052                             site,
  2053                             argtypes,
  2054                             typeargtypes);
  2055                 tree.constructor = constructor.baseSymbol();
  2057                 final TypeSymbol csym = clazztype.tsym;
  2058                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2059                     @Override
  2060                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2061                         enclosingContext.report(tree.clazz,
  2062                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2064                 });
  2065                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2066                 constructorType = checkId(tree, site,
  2067                         constructor,
  2068                         diamondEnv,
  2069                         diamondResult);
  2071                 tree.clazz.type = types.createErrorType(clazztype);
  2072                 if (!constructorType.isErroneous()) {
  2073                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2074                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2076                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2079             // Resolve the called constructor under the assumption
  2080             // that we are referring to a superclass instance of the
  2081             // current instance (JLS ???).
  2082             else {
  2083                 //the following code alters some of the fields in the current
  2084                 //AttrContext - hence, the current context must be dup'ed in
  2085                 //order to avoid downstream failures
  2086                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2087                 rsEnv.info.selectSuper = cdef != null;
  2088                 rsEnv.info.pendingResolutionPhase = null;
  2089                 tree.constructor = rs.resolveConstructor(
  2090                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2091                 if (cdef == null) { //do not check twice!
  2092                     tree.constructorType = checkId(tree,
  2093                             clazztype,
  2094                             tree.constructor,
  2095                             rsEnv,
  2096                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2097                     if (rsEnv.info.lastResolveVarargs())
  2098                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2100                 if (cdef == null &&
  2101                         !clazztype.isErroneous() &&
  2102                         clazztype.getTypeArguments().nonEmpty() &&
  2103                         findDiamonds) {
  2104                     findDiamond(localEnv, tree, clazztype);
  2108             if (cdef != null) {
  2109                 // We are seeing an anonymous class instance creation.
  2110                 // In this case, the class instance creation
  2111                 // expression
  2112                 //
  2113                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2114                 //
  2115                 // is represented internally as
  2116                 //
  2117                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2118                 //
  2119                 // This expression is then *transformed* as follows:
  2120                 //
  2121                 // (1) add a STATIC flag to the class definition
  2122                 //     if the current environment is static
  2123                 // (2) add an extends or implements clause
  2124                 // (3) add a constructor.
  2125                 //
  2126                 // For instance, if C is a class, and ET is the type of E,
  2127                 // the expression
  2128                 //
  2129                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2130                 //
  2131                 // is translated to (where X is a fresh name and typarams is the
  2132                 // parameter list of the super constructor):
  2133                 //
  2134                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2135                 //     X extends C<typargs2> {
  2136                 //       <typarams> X(ET e, args) {
  2137                 //         e.<typeargs1>super(args)
  2138                 //       }
  2139                 //       ...
  2140                 //     }
  2141                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2143                 if (clazztype.tsym.isInterface()) {
  2144                     cdef.implementing = List.of(clazz);
  2145                 } else {
  2146                     cdef.extending = clazz;
  2149                 attribStat(cdef, localEnv);
  2151                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2153                 // If an outer instance is given,
  2154                 // prefix it to the constructor arguments
  2155                 // and delete it from the new expression
  2156                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2157                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2158                     argtypes = argtypes.prepend(tree.encl.type);
  2159                     tree.encl = null;
  2162                 // Reassign clazztype and recompute constructor.
  2163                 clazztype = cdef.sym.type;
  2164                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2165                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2166                 Assert.check(sym.kind < AMBIGUOUS);
  2167                 tree.constructor = sym;
  2168                 tree.constructorType = checkId(tree,
  2169                     clazztype,
  2170                     tree.constructor,
  2171                     localEnv,
  2172                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2173             } else {
  2174                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  2175                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  2176                             tree.clazz.type.tsym);
  2180             if (tree.constructor != null && tree.constructor.kind == MTH)
  2181                 owntype = clazztype;
  2183         result = check(tree, owntype, VAL, resultInfo);
  2184         chk.validate(tree.typeargs, localEnv);
  2186     //where
  2187         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2188             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2189             List<JCExpression> prevTypeargs = ta.arguments;
  2190             try {
  2191                 //create a 'fake' diamond AST node by removing type-argument trees
  2192                 ta.arguments = List.nil();
  2193                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2194                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2195                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2196                 Type polyPt = allowPoly ?
  2197                         syms.objectType :
  2198                         clazztype;
  2199                 if (!inferred.isErroneous() &&
  2200                     types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings)) {
  2201                     String key = types.isSameType(clazztype, inferred) ?
  2202                         "diamond.redundant.args" :
  2203                         "diamond.redundant.args.1";
  2204                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2206             } finally {
  2207                 ta.arguments = prevTypeargs;
  2211             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2212                 if (allowLambda &&
  2213                         identifyLambdaCandidate &&
  2214                         clazztype.hasTag(CLASS) &&
  2215                         !pt().hasTag(NONE) &&
  2216                         types.isFunctionalInterface(clazztype.tsym)) {
  2217                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2218                     int count = 0;
  2219                     boolean found = false;
  2220                     for (Symbol sym : csym.members().getElements()) {
  2221                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2222                                 sym.isConstructor()) continue;
  2223                         count++;
  2224                         if (sym.kind != MTH ||
  2225                                 !sym.name.equals(descriptor.name)) continue;
  2226                         Type mtype = types.memberType(clazztype, sym);
  2227                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2228                             found = true;
  2231                     if (found && count == 1) {
  2232                         log.note(tree.def, "potential.lambda.found");
  2237     private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  2238             Symbol sym) {
  2239         // Ensure that no declaration annotations are present.
  2240         // Note that a tree type might be an AnnotatedType with
  2241         // empty annotations, if only declaration annotations were given.
  2242         // This method will raise an error for such a type.
  2243         for (JCAnnotation ai : annotations) {
  2244             if (TypeAnnotations.annotationType(syms, names, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  2245                 log.error(ai.pos(), "annotation.type.not.applicable");
  2251     /** Make an attributed null check tree.
  2252      */
  2253     public JCExpression makeNullCheck(JCExpression arg) {
  2254         // optimization: X.this is never null; skip null check
  2255         Name name = TreeInfo.name(arg);
  2256         if (name == names._this || name == names._super) return arg;
  2258         JCTree.Tag optag = NULLCHK;
  2259         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2260         tree.operator = syms.nullcheck;
  2261         tree.type = arg.type;
  2262         return tree;
  2265     public void visitNewArray(JCNewArray tree) {
  2266         Type owntype = types.createErrorType(tree.type);
  2267         Env<AttrContext> localEnv = env.dup(tree);
  2268         Type elemtype;
  2269         if (tree.elemtype != null) {
  2270             elemtype = attribType(tree.elemtype, localEnv);
  2271             chk.validate(tree.elemtype, localEnv);
  2272             owntype = elemtype;
  2273             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2274                 attribExpr(l.head, localEnv, syms.intType);
  2275                 owntype = new ArrayType(owntype, syms.arrayClass);
  2277             if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  2278                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  2279                         tree.elemtype.type.tsym);
  2281         } else {
  2282             // we are seeing an untyped aggregate { ... }
  2283             // this is allowed only if the prototype is an array
  2284             if (pt().hasTag(ARRAY)) {
  2285                 elemtype = types.elemtype(pt());
  2286             } else {
  2287                 if (!pt().hasTag(ERROR)) {
  2288                     log.error(tree.pos(), "illegal.initializer.for.type",
  2289                               pt());
  2291                 elemtype = types.createErrorType(pt());
  2294         if (tree.elems != null) {
  2295             attribExprs(tree.elems, localEnv, elemtype);
  2296             owntype = new ArrayType(elemtype, syms.arrayClass);
  2298         if (!types.isReifiable(elemtype))
  2299             log.error(tree.pos(), "generic.array.creation");
  2300         result = check(tree, owntype, VAL, resultInfo);
  2303     /*
  2304      * A lambda expression can only be attributed when a target-type is available.
  2305      * In addition, if the target-type is that of a functional interface whose
  2306      * descriptor contains inference variables in argument position the lambda expression
  2307      * is 'stuck' (see DeferredAttr).
  2308      */
  2309     @Override
  2310     public void visitLambda(final JCLambda that) {
  2311         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2312             if (pt().hasTag(NONE)) {
  2313                 //lambda only allowed in assignment or method invocation/cast context
  2314                 log.error(that.pos(), "unexpected.lambda");
  2316             result = that.type = types.createErrorType(pt());
  2317             return;
  2319         //create an environment for attribution of the lambda expression
  2320         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2321         boolean needsRecovery =
  2322                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2323         try {
  2324             Type target = pt();
  2325             List<Type> explicitParamTypes = null;
  2326             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2327                 //attribute lambda parameters
  2328                 attribStats(that.params, localEnv);
  2329                 explicitParamTypes = TreeInfo.types(that.params);
  2330                 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
  2333             Type lambdaType;
  2334             if (pt() != Type.recoveryType) {
  2335                 target = targetChecker.visit(target, that);
  2336                 lambdaType = types.findDescriptorType(target);
  2337                 chk.checkFunctionalInterface(that, target);
  2338             } else {
  2339                 target = Type.recoveryType;
  2340                 lambdaType = fallbackDescriptorType(that);
  2343             setFunctionalInfo(that, pt(), lambdaType, target, resultInfo.checkContext.inferenceContext());
  2345             if (lambdaType.hasTag(FORALL)) {
  2346                 //lambda expression target desc cannot be a generic method
  2347                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2348                         lambdaType, kindName(target.tsym), target.tsym));
  2349                 result = that.type = types.createErrorType(pt());
  2350                 return;
  2353             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2354                 //add param type info in the AST
  2355                 List<Type> actuals = lambdaType.getParameterTypes();
  2356                 List<JCVariableDecl> params = that.params;
  2358                 boolean arityMismatch = false;
  2360                 while (params.nonEmpty()) {
  2361                     if (actuals.isEmpty()) {
  2362                         //not enough actuals to perform lambda parameter inference
  2363                         arityMismatch = true;
  2365                     //reset previously set info
  2366                     Type argType = arityMismatch ?
  2367                             syms.errType :
  2368                             actuals.head;
  2369                     params.head.vartype = make.at(params.head).Type(argType);
  2370                     params.head.sym = null;
  2371                     actuals = actuals.isEmpty() ?
  2372                             actuals :
  2373                             actuals.tail;
  2374                     params = params.tail;
  2377                 //attribute lambda parameters
  2378                 attribStats(that.params, localEnv);
  2380                 if (arityMismatch) {
  2381                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2382                         result = that.type = types.createErrorType(target);
  2383                         return;
  2387             //from this point on, no recovery is needed; if we are in assignment context
  2388             //we will be able to attribute the whole lambda body, regardless of errors;
  2389             //if we are in a 'check' method context, and the lambda is not compatible
  2390             //with the target-type, it will be recovered anyway in Attr.checkId
  2391             needsRecovery = false;
  2393             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2394                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2395                     new FunctionalReturnContext(resultInfo.checkContext);
  2397             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2398                 recoveryInfo :
  2399                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2400             localEnv.info.returnResult = bodyResultInfo;
  2402             Log.DeferredDiagnosticHandler lambdaDeferredHandler = new Log.DeferredDiagnosticHandler(log);
  2403             try {
  2404                 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2405                     attribTree(that.getBody(), localEnv, bodyResultInfo);
  2406                 } else {
  2407                     JCBlock body = (JCBlock)that.body;
  2408                     attribStats(body.stats, localEnv);
  2411                 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.SPECULATIVE) {
  2412                     //check for errors in lambda body
  2413                     for (JCDiagnostic deferredDiag : lambdaDeferredHandler.getDiagnostics()) {
  2414                         if (deferredDiag.getKind() == JCDiagnostic.Kind.ERROR) {
  2415                             resultInfo.checkContext
  2416                                     .report(that, diags.fragment("bad.arg.types.in.lambda", TreeInfo.types(that.params),
  2417                                     deferredDiag)); //hidden diag parameter
  2418                             //we mark the lambda as erroneous - this is crucial in the recovery step
  2419                             //as parameter-dependent type error won't be reported in that stage,
  2420                             //meaning that a lambda will be deemed erroeneous only if there is
  2421                             //a target-independent error (which will cause method diagnostic
  2422                             //to be skipped).
  2423                             result = that.type = types.createErrorType(target);
  2424                             return;
  2428             } finally {
  2429                 lambdaDeferredHandler.reportDeferredDiagnostics();
  2430                 log.popDiagnosticHandler(lambdaDeferredHandler);
  2433             result = check(that, target, VAL, resultInfo);
  2435             boolean isSpeculativeRound =
  2436                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2438             postAttr(that);
  2439             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2441             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
  2443             if (!isSpeculativeRound) {
  2444                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
  2446             result = check(that, target, VAL, resultInfo);
  2447         } catch (Types.FunctionDescriptorLookupError ex) {
  2448             JCDiagnostic cause = ex.getDiagnostic();
  2449             resultInfo.checkContext.report(that, cause);
  2450             result = that.type = types.createErrorType(pt());
  2451             return;
  2452         } finally {
  2453             localEnv.info.scope.leave();
  2454             if (needsRecovery) {
  2455                 attribTree(that, env, recoveryInfo);
  2459     //where
  2460         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2462             @Override
  2463             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2464                 return t.isCompound() ?
  2465                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2468             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2469                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2470                 Type target = null;
  2471                 for (Type bound : ict.getExplicitComponents()) {
  2472                     TypeSymbol boundSym = bound.tsym;
  2473                     if (types.isFunctionalInterface(boundSym) &&
  2474                             types.findDescriptorSymbol(boundSym) == desc) {
  2475                         target = bound;
  2476                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2477                         //bound must be an interface
  2478                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2481                 return target != null ?
  2482                         target :
  2483                         ict.getExplicitComponents().head; //error recovery
  2486             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2487                 ListBuffer<Type> targs = ListBuffer.lb();
  2488                 ListBuffer<Type> supertypes = ListBuffer.lb();
  2489                 for (Type i : ict.interfaces_field) {
  2490                     if (i.isParameterized()) {
  2491                         targs.appendList(i.tsym.type.allparams());
  2493                     supertypes.append(i.tsym.type);
  2495                 IntersectionClassType notionalIntf =
  2496                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2497                 notionalIntf.allparams_field = targs.toList();
  2498                 notionalIntf.tsym.flags_field |= INTERFACE;
  2499                 return notionalIntf.tsym;
  2502             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2503                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2504                         diags.fragment(key, args)));
  2506         };
  2508         private Type fallbackDescriptorType(JCExpression tree) {
  2509             switch (tree.getTag()) {
  2510                 case LAMBDA:
  2511                     JCLambda lambda = (JCLambda)tree;
  2512                     List<Type> argtypes = List.nil();
  2513                     for (JCVariableDecl param : lambda.params) {
  2514                         argtypes = param.vartype != null ?
  2515                                 argtypes.append(param.vartype.type) :
  2516                                 argtypes.append(syms.errType);
  2518                     return new MethodType(argtypes, Type.recoveryType,
  2519                             List.of(syms.throwableType), syms.methodClass);
  2520                 case REFERENCE:
  2521                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2522                             List.of(syms.throwableType), syms.methodClass);
  2523                 default:
  2524                     Assert.error("Cannot get here!");
  2526             return null;
  2529         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2530                 final InferenceContext inferenceContext, final Type... ts) {
  2531             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2534         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2535                 final InferenceContext inferenceContext, final List<Type> ts) {
  2536             if (inferenceContext.free(ts)) {
  2537                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2538                     @Override
  2539                     public void typesInferred(InferenceContext inferenceContext) {
  2540                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2542                 });
  2543             } else {
  2544                 for (Type t : ts) {
  2545                     rs.checkAccessibleType(env, t);
  2550         /**
  2551          * Lambda/method reference have a special check context that ensures
  2552          * that i.e. a lambda return type is compatible with the expected
  2553          * type according to both the inherited context and the assignment
  2554          * context.
  2555          */
  2556         class FunctionalReturnContext extends Check.NestedCheckContext {
  2558             FunctionalReturnContext(CheckContext enclosingContext) {
  2559                 super(enclosingContext);
  2562             @Override
  2563             public boolean compatible(Type found, Type req, Warner warn) {
  2564                 //return type must be compatible in both current context and assignment context
  2565                 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
  2568             @Override
  2569             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2570                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2574         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2576             JCExpression expr;
  2578             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2579                 super(enclosingContext);
  2580                 this.expr = expr;
  2583             @Override
  2584             public boolean compatible(Type found, Type req, Warner warn) {
  2585                 //a void return is compatible with an expression statement lambda
  2586                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2587                         super.compatible(found, req, warn);
  2591         /**
  2592         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2593         * are compatible with the expected functional interface descriptor. This means that:
  2594         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2595         * types must be compatible with the return type of the expected descriptor;
  2596         * (iii) thrown types must be 'included' in the thrown types list of the expected
  2597         * descriptor.
  2598         */
  2599         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
  2600             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2602             //return values have already been checked - but if lambda has no return
  2603             //values, we must ensure that void/value compatibility is correct;
  2604             //this amounts at checking that, if a lambda body can complete normally,
  2605             //the descriptor's return type must be void
  2606             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2607                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2608                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2609                         diags.fragment("missing.ret.val", returnType)));
  2612             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
  2613             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2614                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2617             if (!speculativeAttr) {
  2618                 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2619                 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
  2620                     log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
  2625         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2626             Env<AttrContext> lambdaEnv;
  2627             Symbol owner = env.info.scope.owner;
  2628             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2629                 //field initializer
  2630                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2631                 lambdaEnv.info.scope.owner =
  2632                     new MethodSymbol((owner.flags() & STATIC) | BLOCK, names.empty, null,
  2633                                      env.info.scope.owner);
  2634             } else {
  2635                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2637             return lambdaEnv;
  2640     @Override
  2641     public void visitReference(final JCMemberReference that) {
  2642         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2643             if (pt().hasTag(NONE)) {
  2644                 //method reference only allowed in assignment or method invocation/cast context
  2645                 log.error(that.pos(), "unexpected.mref");
  2647             result = that.type = types.createErrorType(pt());
  2648             return;
  2650         final Env<AttrContext> localEnv = env.dup(that);
  2651         try {
  2652             //attribute member reference qualifier - if this is a constructor
  2653             //reference, the expected kind must be a type
  2654             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2656             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2657                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2660             if (exprType.isErroneous()) {
  2661                 //if the qualifier expression contains problems,
  2662                 //give up attribution of method reference
  2663                 result = that.type = exprType;
  2664                 return;
  2667             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2668                 //if the qualifier is a type, validate it; raw warning check is
  2669                 //omitted as we don't know at this stage as to whether this is a
  2670                 //raw selector (because of inference)
  2671                 chk.validate(that.expr, env, false);
  2674             //attrib type-arguments
  2675             List<Type> typeargtypes = List.nil();
  2676             if (that.typeargs != null) {
  2677                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2680             Type target;
  2681             Type desc;
  2682             if (pt() != Type.recoveryType) {
  2683                 target = targetChecker.visit(pt(), that);
  2684                 desc = types.findDescriptorType(target);
  2685                 chk.checkFunctionalInterface(that, target);
  2686             } else {
  2687                 target = Type.recoveryType;
  2688                 desc = fallbackDescriptorType(that);
  2691             setFunctionalInfo(that, pt(), desc, target, resultInfo.checkContext.inferenceContext());
  2692             List<Type> argtypes = desc.getParameterTypes();
  2694             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult =
  2695                     rs.resolveMemberReference(that.pos(), localEnv, that,
  2696                         that.expr.type, that.name, argtypes, typeargtypes, true, rs.resolveMethodCheck);
  2698             Symbol refSym = refResult.fst;
  2699             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2701             if (refSym.kind != MTH) {
  2702                 boolean targetError;
  2703                 switch (refSym.kind) {
  2704                     case ABSENT_MTH:
  2705                         targetError = false;
  2706                         break;
  2707                     case WRONG_MTH:
  2708                     case WRONG_MTHS:
  2709                     case AMBIGUOUS:
  2710                     case HIDDEN:
  2711                     case STATICERR:
  2712                     case MISSING_ENCL:
  2713                         targetError = true;
  2714                         break;
  2715                     default:
  2716                         Assert.error("unexpected result kind " + refSym.kind);
  2717                         targetError = false;
  2720                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2721                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2723                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2724                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2726                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2727                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2729                 if (targetError && target == Type.recoveryType) {
  2730                     //a target error doesn't make sense during recovery stage
  2731                     //as we don't know what actual parameter types are
  2732                     result = that.type = target;
  2733                     return;
  2734                 } else {
  2735                     if (targetError) {
  2736                         resultInfo.checkContext.report(that, diag);
  2737                     } else {
  2738                         log.report(diag);
  2740                     result = that.type = types.createErrorType(target);
  2741                     return;
  2745             that.sym = refSym.baseSymbol();
  2746             that.kind = lookupHelper.referenceKind(that.sym);
  2747             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2749             if (desc.getReturnType() == Type.recoveryType) {
  2750                 // stop here
  2751                 result = that.type = target;
  2752                 return;
  2755             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2757                 if (that.getMode() == ReferenceMode.INVOKE &&
  2758                         TreeInfo.isStaticSelector(that.expr, names) &&
  2759                         that.kind.isUnbound() &&
  2760                         !desc.getParameterTypes().head.isParameterized()) {
  2761                     chk.checkRaw(that.expr, localEnv);
  2764                 if (!that.kind.isUnbound() &&
  2765                         that.getMode() == ReferenceMode.INVOKE &&
  2766                         TreeInfo.isStaticSelector(that.expr, names) &&
  2767                         !that.sym.isStatic()) {
  2768                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2769                             diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym));
  2770                     result = that.type = types.createErrorType(target);
  2771                     return;
  2774                 if (that.kind.isUnbound() &&
  2775                         that.getMode() == ReferenceMode.INVOKE &&
  2776                         TreeInfo.isStaticSelector(that.expr, names) &&
  2777                         that.sym.isStatic()) {
  2778                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2779                             diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym));
  2780                     result = that.type = types.createErrorType(target);
  2781                     return;
  2784                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2785                         exprType.getTypeArguments().nonEmpty()) {
  2786                     //static ref with class type-args
  2787                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2788                             diags.fragment("static.mref.with.targs"));
  2789                     result = that.type = types.createErrorType(target);
  2790                     return;
  2793                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2794                         !that.kind.isUnbound()) {
  2795                     //no static bound mrefs
  2796                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2797                             diags.fragment("static.bound.mref"));
  2798                     result = that.type = types.createErrorType(target);
  2799                     return;
  2802                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2803                     // Check that super-qualified symbols are not abstract (JLS)
  2804                     rs.checkNonAbstract(that.pos(), that.sym);
  2808             that.sym = refSym.baseSymbol();
  2809             that.kind = lookupHelper.referenceKind(that.sym);
  2811             ResultInfo checkInfo =
  2812                     resultInfo.dup(newMethodTemplate(
  2813                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2814                         lookupHelper.argtypes,
  2815                         typeargtypes));
  2817             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2819             if (!refType.isErroneous()) {
  2820                 refType = types.createMethodTypeWithReturn(refType,
  2821                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2824             //go ahead with standard method reference compatibility check - note that param check
  2825             //is a no-op (as this has been taken care during method applicability)
  2826             boolean isSpeculativeRound =
  2827                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2828             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2829             if (!isSpeculativeRound) {
  2830                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2832             result = check(that, target, VAL, resultInfo);
  2833         } catch (Types.FunctionDescriptorLookupError ex) {
  2834             JCDiagnostic cause = ex.getDiagnostic();
  2835             resultInfo.checkContext.report(that, cause);
  2836             result = that.type = types.createErrorType(pt());
  2837             return;
  2840     //where
  2841         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2842             //if this is a constructor reference, the expected kind must be a type
  2843             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2847     @SuppressWarnings("fallthrough")
  2848     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2849         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2851         Type resType;
  2852         switch (tree.getMode()) {
  2853             case NEW:
  2854                 if (!tree.expr.type.isRaw()) {
  2855                     resType = tree.expr.type;
  2856                     break;
  2858             default:
  2859                 resType = refType.getReturnType();
  2862         Type incompatibleReturnType = resType;
  2864         if (returnType.hasTag(VOID)) {
  2865             incompatibleReturnType = null;
  2868         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2869             if (resType.isErroneous() ||
  2870                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2871                 incompatibleReturnType = null;
  2875         if (incompatibleReturnType != null) {
  2876             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2877                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2880         if (!speculativeAttr) {
  2881             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2882             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2883                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2888     /**
  2889      * Set functional type info on the underlying AST. Note: as the target descriptor
  2890      * might contain inference variables, we might need to register an hook in the
  2891      * current inference context.
  2892      */
  2893     private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt,
  2894             final Type descriptorType, final Type primaryTarget, InferenceContext inferenceContext) {
  2895         if (inferenceContext.free(descriptorType)) {
  2896             inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2897                 public void typesInferred(InferenceContext inferenceContext) {
  2898                     setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType),
  2899                             inferenceContext.asInstType(primaryTarget), inferenceContext);
  2901             });
  2902         } else {
  2903             ListBuffer<TypeSymbol> targets = ListBuffer.lb();
  2904             if (pt.hasTag(CLASS)) {
  2905                 if (pt.isCompound()) {
  2906                     targets.append(primaryTarget.tsym); //this goes first
  2907                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2908                         if (t != primaryTarget) {
  2909                             targets.append(t.tsym);
  2912                 } else {
  2913                     targets.append(pt.tsym);
  2916             fExpr.targets = targets.toList();
  2917             fExpr.descriptorType = descriptorType;
  2921     public void visitParens(JCParens tree) {
  2922         Type owntype = attribTree(tree.expr, env, resultInfo);
  2923         result = check(tree, owntype, pkind(), resultInfo);
  2924         Symbol sym = TreeInfo.symbol(tree);
  2925         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2926             log.error(tree.pos(), "illegal.start.of.type");
  2929     public void visitAssign(JCAssign tree) {
  2930         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2931         Type capturedType = capture(owntype);
  2932         attribExpr(tree.rhs, env, owntype);
  2933         result = check(tree, capturedType, VAL, resultInfo);
  2936     public void visitAssignop(JCAssignOp tree) {
  2937         // Attribute arguments.
  2938         Type owntype = attribTree(tree.lhs, env, varInfo);
  2939         Type operand = attribExpr(tree.rhs, env);
  2940         // Find operator.
  2941         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2942             tree.pos(), tree.getTag().noAssignOp(), env,
  2943             owntype, operand);
  2945         if (operator.kind == MTH &&
  2946                 !owntype.isErroneous() &&
  2947                 !operand.isErroneous()) {
  2948             chk.checkOperator(tree.pos(),
  2949                               (OperatorSymbol)operator,
  2950                               tree.getTag().noAssignOp(),
  2951                               owntype,
  2952                               operand);
  2953             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2954             chk.checkCastable(tree.rhs.pos(),
  2955                               operator.type.getReturnType(),
  2956                               owntype);
  2958         result = check(tree, owntype, VAL, resultInfo);
  2961     public void visitUnary(JCUnary tree) {
  2962         // Attribute arguments.
  2963         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2964             ? attribTree(tree.arg, env, varInfo)
  2965             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2967         // Find operator.
  2968         Symbol operator = tree.operator =
  2969             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2971         Type owntype = types.createErrorType(tree.type);
  2972         if (operator.kind == MTH &&
  2973                 !argtype.isErroneous()) {
  2974             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2975                 ? tree.arg.type
  2976                 : operator.type.getReturnType();
  2977             int opc = ((OperatorSymbol)operator).opcode;
  2979             // If the argument is constant, fold it.
  2980             if (argtype.constValue() != null) {
  2981                 Type ctype = cfolder.fold1(opc, argtype);
  2982                 if (ctype != null) {
  2983                     owntype = cfolder.coerce(ctype, owntype);
  2985                     // Remove constant types from arguments to
  2986                     // conserve space. The parser will fold concatenations
  2987                     // of string literals; the code here also
  2988                     // gets rid of intermediate results when some of the
  2989                     // operands are constant identifiers.
  2990                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2991                         tree.arg.type = syms.stringType;
  2996         result = check(tree, owntype, VAL, resultInfo);
  2999     public void visitBinary(JCBinary tree) {
  3000         // Attribute arguments.
  3001         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3002         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3004         // Find operator.
  3005         Symbol operator = tree.operator =
  3006             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3008         Type owntype = types.createErrorType(tree.type);
  3009         if (operator.kind == MTH &&
  3010                 !left.isErroneous() &&
  3011                 !right.isErroneous()) {
  3012             owntype = operator.type.getReturnType();
  3013             int opc = chk.checkOperator(tree.lhs.pos(),
  3014                                         (OperatorSymbol)operator,
  3015                                         tree.getTag(),
  3016                                         left,
  3017                                         right);
  3019             // If both arguments are constants, fold them.
  3020             if (left.constValue() != null && right.constValue() != null) {
  3021                 Type ctype = cfolder.fold2(opc, left, right);
  3022                 if (ctype != null) {
  3023                     owntype = cfolder.coerce(ctype, owntype);
  3025                     // Remove constant types from arguments to
  3026                     // conserve space. The parser will fold concatenations
  3027                     // of string literals; the code here also
  3028                     // gets rid of intermediate results when some of the
  3029                     // operands are constant identifiers.
  3030                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  3031                         tree.lhs.type = syms.stringType;
  3033                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  3034                         tree.rhs.type = syms.stringType;
  3039             // Check that argument types of a reference ==, != are
  3040             // castable to each other, (JLS???).
  3041             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3042                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  3043                     log.error(tree.pos(), "incomparable.types", left, right);
  3047             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3049         result = check(tree, owntype, VAL, resultInfo);
  3052     public void visitTypeCast(final JCTypeCast tree) {
  3053         Type clazztype = attribType(tree.clazz, env);
  3054         chk.validate(tree.clazz, env, false);
  3055         //a fresh environment is required for 292 inference to work properly ---
  3056         //see Infer.instantiatePolymorphicSignatureInstance()
  3057         Env<AttrContext> localEnv = env.dup(tree);
  3058         //should we propagate the target type?
  3059         final ResultInfo castInfo;
  3060         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3061         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3062         if (isPoly) {
  3063             //expression is a poly - we need to propagate target type info
  3064             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3065                 @Override
  3066                 public boolean compatible(Type found, Type req, Warner warn) {
  3067                     return types.isCastable(found, req, warn);
  3069             });
  3070         } else {
  3071             //standalone cast - target-type info is not propagated
  3072             castInfo = unknownExprInfo;
  3074         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3075         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3076         if (exprtype.constValue() != null)
  3077             owntype = cfolder.coerce(exprtype, owntype);
  3078         result = check(tree, capture(owntype), VAL, resultInfo);
  3079         if (!isPoly)
  3080             chk.checkRedundantCast(localEnv, tree);
  3083     public void visitTypeTest(JCInstanceOf tree) {
  3084         Type exprtype = chk.checkNullOrRefType(
  3085             tree.expr.pos(), attribExpr(tree.expr, env));
  3086         Type clazztype = chk.checkReifiableReferenceType(
  3087             tree.clazz.pos(), attribType(tree.clazz, env));
  3088         chk.validate(tree.clazz, env, false);
  3089         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3090         result = check(tree, syms.booleanType, VAL, resultInfo);
  3093     public void visitIndexed(JCArrayAccess tree) {
  3094         Type owntype = types.createErrorType(tree.type);
  3095         Type atype = attribExpr(tree.indexed, env);
  3096         attribExpr(tree.index, env, syms.intType);
  3097         if (types.isArray(atype))
  3098             owntype = types.elemtype(atype);
  3099         else if (!atype.hasTag(ERROR))
  3100             log.error(tree.pos(), "array.req.but.found", atype);
  3101         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3102         result = check(tree, owntype, VAR, resultInfo);
  3105     public void visitIdent(JCIdent tree) {
  3106         Symbol sym;
  3108         // Find symbol
  3109         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3110             // If we are looking for a method, the prototype `pt' will be a
  3111             // method type with the type of the call's arguments as parameters.
  3112             env.info.pendingResolutionPhase = null;
  3113             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3114         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3115             sym = tree.sym;
  3116         } else {
  3117             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3119         tree.sym = sym;
  3121         // (1) Also find the environment current for the class where
  3122         //     sym is defined (`symEnv').
  3123         // Only for pre-tiger versions (1.4 and earlier):
  3124         // (2) Also determine whether we access symbol out of an anonymous
  3125         //     class in a this or super call.  This is illegal for instance
  3126         //     members since such classes don't carry a this$n link.
  3127         //     (`noOuterThisPath').
  3128         Env<AttrContext> symEnv = env;
  3129         boolean noOuterThisPath = false;
  3130         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3131             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3132             sym.owner.kind == TYP &&
  3133             tree.name != names._this && tree.name != names._super) {
  3135             // Find environment in which identifier is defined.
  3136             while (symEnv.outer != null &&
  3137                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3138                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3139                     noOuterThisPath = !allowAnonOuterThis;
  3140                 symEnv = symEnv.outer;
  3144         // If symbol is a variable, ...
  3145         if (sym.kind == VAR) {
  3146             VarSymbol v = (VarSymbol)sym;
  3148             // ..., evaluate its initializer, if it has one, and check for
  3149             // illegal forward reference.
  3150             checkInit(tree, env, v, false);
  3152             // If we are expecting a variable (as opposed to a value), check
  3153             // that the variable is assignable in the current environment.
  3154             if (pkind() == VAR)
  3155                 checkAssignable(tree.pos(), v, null, env);
  3158         // In a constructor body,
  3159         // if symbol is a field or instance method, check that it is
  3160         // not accessed before the supertype constructor is called.
  3161         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3162             (sym.kind & (VAR | MTH)) != 0 &&
  3163             sym.owner.kind == TYP &&
  3164             (sym.flags() & STATIC) == 0) {
  3165             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3167         Env<AttrContext> env1 = env;
  3168         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3169             // If the found symbol is inaccessible, then it is
  3170             // accessed through an enclosing instance.  Locate this
  3171             // enclosing instance:
  3172             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3173                 env1 = env1.outer;
  3175         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3178     public void visitSelect(JCFieldAccess tree) {
  3179         // Determine the expected kind of the qualifier expression.
  3180         int skind = 0;
  3181         if (tree.name == names._this || tree.name == names._super ||
  3182             tree.name == names._class)
  3184             skind = TYP;
  3185         } else {
  3186             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3187             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3188             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3191         // Attribute the qualifier expression, and determine its symbol (if any).
  3192         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3193         if ((pkind() & (PCK | TYP)) == 0)
  3194             site = capture(site); // Capture field access
  3196         // don't allow T.class T[].class, etc
  3197         if (skind == TYP) {
  3198             Type elt = site;
  3199             while (elt.hasTag(ARRAY))
  3200                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3201             if (elt.hasTag(TYPEVAR)) {
  3202                 log.error(tree.pos(), "type.var.cant.be.deref");
  3203                 result = types.createErrorType(tree.type);
  3204                 return;
  3208         // If qualifier symbol is a type or `super', assert `selectSuper'
  3209         // for the selection. This is relevant for determining whether
  3210         // protected symbols are accessible.
  3211         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3212         boolean selectSuperPrev = env.info.selectSuper;
  3213         env.info.selectSuper =
  3214             sitesym != null &&
  3215             sitesym.name == names._super;
  3217         // Determine the symbol represented by the selection.
  3218         env.info.pendingResolutionPhase = null;
  3219         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3220         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3221             site = capture(site);
  3222             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3224         boolean varArgs = env.info.lastResolveVarargs();
  3225         tree.sym = sym;
  3227         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3228             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3229             site = capture(site);
  3232         // If that symbol is a variable, ...
  3233         if (sym.kind == VAR) {
  3234             VarSymbol v = (VarSymbol)sym;
  3236             // ..., evaluate its initializer, if it has one, and check for
  3237             // illegal forward reference.
  3238             checkInit(tree, env, v, true);
  3240             // If we are expecting a variable (as opposed to a value), check
  3241             // that the variable is assignable in the current environment.
  3242             if (pkind() == VAR)
  3243                 checkAssignable(tree.pos(), v, tree.selected, env);
  3246         if (sitesym != null &&
  3247                 sitesym.kind == VAR &&
  3248                 ((VarSymbol)sitesym).isResourceVariable() &&
  3249                 sym.kind == MTH &&
  3250                 sym.name.equals(names.close) &&
  3251                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3252                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3253             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3256         // Disallow selecting a type from an expression
  3257         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3258             tree.type = check(tree.selected, pt(),
  3259                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3262         if (isType(sitesym)) {
  3263             if (sym.name == names._this) {
  3264                 // If `C' is the currently compiled class, check that
  3265                 // C.this' does not appear in a call to a super(...)
  3266                 if (env.info.isSelfCall &&
  3267                     site.tsym == env.enclClass.sym) {
  3268                     chk.earlyRefError(tree.pos(), sym);
  3270             } else {
  3271                 // Check if type-qualified fields or methods are static (JLS)
  3272                 if ((sym.flags() & STATIC) == 0 &&
  3273                     !env.next.tree.hasTag(REFERENCE) &&
  3274                     sym.name != names._super &&
  3275                     (sym.kind == VAR || sym.kind == MTH)) {
  3276                     rs.accessBase(rs.new StaticError(sym),
  3277                               tree.pos(), site, sym.name, true);
  3280         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3281             // If the qualified item is not a type and the selected item is static, report
  3282             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3283             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3286         // If we are selecting an instance member via a `super', ...
  3287         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3289             // Check that super-qualified symbols are not abstract (JLS)
  3290             rs.checkNonAbstract(tree.pos(), sym);
  3292             if (site.isRaw()) {
  3293                 // Determine argument types for site.
  3294                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3295                 if (site1 != null) site = site1;
  3299         env.info.selectSuper = selectSuperPrev;
  3300         result = checkId(tree, site, sym, env, resultInfo);
  3302     //where
  3303         /** Determine symbol referenced by a Select expression,
  3305          *  @param tree   The select tree.
  3306          *  @param site   The type of the selected expression,
  3307          *  @param env    The current environment.
  3308          *  @param resultInfo The current result.
  3309          */
  3310         private Symbol selectSym(JCFieldAccess tree,
  3311                                  Symbol location,
  3312                                  Type site,
  3313                                  Env<AttrContext> env,
  3314                                  ResultInfo resultInfo) {
  3315             DiagnosticPosition pos = tree.pos();
  3316             Name name = tree.name;
  3317             switch (site.getTag()) {
  3318             case PACKAGE:
  3319                 return rs.accessBase(
  3320                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3321                     pos, location, site, name, true);
  3322             case ARRAY:
  3323             case CLASS:
  3324                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3325                     return rs.resolveQualifiedMethod(
  3326                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3327                 } else if (name == names._this || name == names._super) {
  3328                     return rs.resolveSelf(pos, env, site.tsym, name);
  3329                 } else if (name == names._class) {
  3330                     // In this case, we have already made sure in
  3331                     // visitSelect that qualifier expression is a type.
  3332                     Type t = syms.classType;
  3333                     List<Type> typeargs = allowGenerics
  3334                         ? List.of(types.erasure(site))
  3335                         : List.<Type>nil();
  3336                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3337                     return new VarSymbol(
  3338                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3339                 } else {
  3340                     // We are seeing a plain identifier as selector.
  3341                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3342                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3343                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3344                     return sym;
  3346             case WILDCARD:
  3347                 throw new AssertionError(tree);
  3348             case TYPEVAR:
  3349                 // Normally, site.getUpperBound() shouldn't be null.
  3350                 // It should only happen during memberEnter/attribBase
  3351                 // when determining the super type which *must* beac
  3352                 // done before attributing the type variables.  In
  3353                 // other words, we are seeing this illegal program:
  3354                 // class B<T> extends A<T.foo> {}
  3355                 Symbol sym = (site.getUpperBound() != null)
  3356                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3357                     : null;
  3358                 if (sym == null) {
  3359                     log.error(pos, "type.var.cant.be.deref");
  3360                     return syms.errSymbol;
  3361                 } else {
  3362                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3363                         rs.new AccessError(env, site, sym) :
  3364                                 sym;
  3365                     rs.accessBase(sym2, pos, location, site, name, true);
  3366                     return sym;
  3368             case ERROR:
  3369                 // preserve identifier names through errors
  3370                 return types.createErrorType(name, site.tsym, site).tsym;
  3371             default:
  3372                 // The qualifier expression is of a primitive type -- only
  3373                 // .class is allowed for these.
  3374                 if (name == names._class) {
  3375                     // In this case, we have already made sure in Select that
  3376                     // qualifier expression is a type.
  3377                     Type t = syms.classType;
  3378                     Type arg = types.boxedClass(site).type;
  3379                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3380                     return new VarSymbol(
  3381                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3382                 } else {
  3383                     log.error(pos, "cant.deref", site);
  3384                     return syms.errSymbol;
  3389         /** Determine type of identifier or select expression and check that
  3390          *  (1) the referenced symbol is not deprecated
  3391          *  (2) the symbol's type is safe (@see checkSafe)
  3392          *  (3) if symbol is a variable, check that its type and kind are
  3393          *      compatible with the prototype and protokind.
  3394          *  (4) if symbol is an instance field of a raw type,
  3395          *      which is being assigned to, issue an unchecked warning if its
  3396          *      type changes under erasure.
  3397          *  (5) if symbol is an instance method of a raw type, issue an
  3398          *      unchecked warning if its argument types change under erasure.
  3399          *  If checks succeed:
  3400          *    If symbol is a constant, return its constant type
  3401          *    else if symbol is a method, return its result type
  3402          *    otherwise return its type.
  3403          *  Otherwise return errType.
  3405          *  @param tree       The syntax tree representing the identifier
  3406          *  @param site       If this is a select, the type of the selected
  3407          *                    expression, otherwise the type of the current class.
  3408          *  @param sym        The symbol representing the identifier.
  3409          *  @param env        The current environment.
  3410          *  @param resultInfo    The expected result
  3411          */
  3412         Type checkId(JCTree tree,
  3413                      Type site,
  3414                      Symbol sym,
  3415                      Env<AttrContext> env,
  3416                      ResultInfo resultInfo) {
  3417             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3418                     checkMethodId(tree, site, sym, env, resultInfo) :
  3419                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3422         Type checkMethodId(JCTree tree,
  3423                      Type site,
  3424                      Symbol sym,
  3425                      Env<AttrContext> env,
  3426                      ResultInfo resultInfo) {
  3427             boolean isPolymorhicSignature =
  3428                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3429             return isPolymorhicSignature ?
  3430                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3431                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3434         Type checkSigPolyMethodId(JCTree tree,
  3435                      Type site,
  3436                      Symbol sym,
  3437                      Env<AttrContext> env,
  3438                      ResultInfo resultInfo) {
  3439             //recover original symbol for signature polymorphic methods
  3440             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3441             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3442             return sym.type;
  3445         Type checkMethodIdInternal(JCTree tree,
  3446                      Type site,
  3447                      Symbol sym,
  3448                      Env<AttrContext> env,
  3449                      ResultInfo resultInfo) {
  3450             if ((resultInfo.pkind & POLY) != 0) {
  3451                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3452                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3453                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3454                 return owntype;
  3455             } else {
  3456                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3460         Type checkIdInternal(JCTree tree,
  3461                      Type site,
  3462                      Symbol sym,
  3463                      Type pt,
  3464                      Env<AttrContext> env,
  3465                      ResultInfo resultInfo) {
  3466             if (pt.isErroneous()) {
  3467                 return types.createErrorType(site);
  3469             Type owntype; // The computed type of this identifier occurrence.
  3470             switch (sym.kind) {
  3471             case TYP:
  3472                 // For types, the computed type equals the symbol's type,
  3473                 // except for two situations:
  3474                 owntype = sym.type;
  3475                 if (owntype.hasTag(CLASS)) {
  3476                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3477                     Type ownOuter = owntype.getEnclosingType();
  3479                     // (a) If the symbol's type is parameterized, erase it
  3480                     // because no type parameters were given.
  3481                     // We recover generic outer type later in visitTypeApply.
  3482                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3483                         owntype = types.erasure(owntype);
  3486                     // (b) If the symbol's type is an inner class, then
  3487                     // we have to interpret its outer type as a superclass
  3488                     // of the site type. Example:
  3489                     //
  3490                     // class Tree<A> { class Visitor { ... } }
  3491                     // class PointTree extends Tree<Point> { ... }
  3492                     // ...PointTree.Visitor...
  3493                     //
  3494                     // Then the type of the last expression above is
  3495                     // Tree<Point>.Visitor.
  3496                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3497                         Type normOuter = site;
  3498                         if (normOuter.hasTag(CLASS)) {
  3499                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3500                             if (site.isAnnotated()) {
  3501                                 // Propagate any type annotations.
  3502                                 // TODO: should asEnclosingSuper do this?
  3503                                 // Note that the type annotations in site will be updated
  3504                                 // by annotateType. Therefore, modify site instead
  3505                                 // of creating a new AnnotatedType.
  3506                                 ((AnnotatedType)site).underlyingType = normOuter;
  3507                                 normOuter = site;
  3510                         if (normOuter == null) // perhaps from an import
  3511                             normOuter = types.erasure(ownOuter);
  3512                         if (normOuter != ownOuter)
  3513                             owntype = new ClassType(
  3514                                 normOuter, List.<Type>nil(), owntype.tsym);
  3517                 break;
  3518             case VAR:
  3519                 VarSymbol v = (VarSymbol)sym;
  3520                 // Test (4): if symbol is an instance field of a raw type,
  3521                 // which is being assigned to, issue an unchecked warning if
  3522                 // its type changes under erasure.
  3523                 if (allowGenerics &&
  3524                     resultInfo.pkind == VAR &&
  3525                     v.owner.kind == TYP &&
  3526                     (v.flags() & STATIC) == 0 &&
  3527                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3528                     Type s = types.asOuterSuper(site, v.owner);
  3529                     if (s != null &&
  3530                         s.isRaw() &&
  3531                         !types.isSameType(v.type, v.erasure(types))) {
  3532                         chk.warnUnchecked(tree.pos(),
  3533                                           "unchecked.assign.to.var",
  3534                                           v, s);
  3537                 // The computed type of a variable is the type of the
  3538                 // variable symbol, taken as a member of the site type.
  3539                 owntype = (sym.owner.kind == TYP &&
  3540                            sym.name != names._this && sym.name != names._super)
  3541                     ? types.memberType(site, sym)
  3542                     : sym.type;
  3544                 // If the variable is a constant, record constant value in
  3545                 // computed type.
  3546                 if (v.getConstValue() != null && isStaticReference(tree))
  3547                     owntype = owntype.constType(v.getConstValue());
  3549                 if (resultInfo.pkind == VAL) {
  3550                     owntype = capture(owntype); // capture "names as expressions"
  3552                 break;
  3553             case MTH: {
  3554                 owntype = checkMethod(site, sym,
  3555                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3556                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3557                         resultInfo.pt.getTypeArguments());
  3558                 break;
  3560             case PCK: case ERR:
  3561                 owntype = sym.type;
  3562                 break;
  3563             default:
  3564                 throw new AssertionError("unexpected kind: " + sym.kind +
  3565                                          " in tree " + tree);
  3568             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3569             // (for constructors, the error was given when the constructor was
  3570             // resolved)
  3572             if (sym.name != names.init) {
  3573                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3574                 chk.checkSunAPI(tree.pos(), sym);
  3575                 chk.checkProfile(tree.pos(), sym);
  3578             // Test (3): if symbol is a variable, check that its type and
  3579             // kind are compatible with the prototype and protokind.
  3580             return check(tree, owntype, sym.kind, resultInfo);
  3583         /** Check that variable is initialized and evaluate the variable's
  3584          *  initializer, if not yet done. Also check that variable is not
  3585          *  referenced before it is defined.
  3586          *  @param tree    The tree making up the variable reference.
  3587          *  @param env     The current environment.
  3588          *  @param v       The variable's symbol.
  3589          */
  3590         private void checkInit(JCTree tree,
  3591                                Env<AttrContext> env,
  3592                                VarSymbol v,
  3593                                boolean onlyWarning) {
  3594 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3595 //                             tree.pos + " " + v.pos + " " +
  3596 //                             Resolve.isStatic(env));//DEBUG
  3598             // A forward reference is diagnosed if the declaration position
  3599             // of the variable is greater than the current tree position
  3600             // and the tree and variable definition occur in the same class
  3601             // definition.  Note that writes don't count as references.
  3602             // This check applies only to class and instance
  3603             // variables.  Local variables follow different scope rules,
  3604             // and are subject to definite assignment checking.
  3605             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3606                 v.owner.kind == TYP &&
  3607                 canOwnInitializer(owner(env)) &&
  3608                 v.owner == env.info.scope.owner.enclClass() &&
  3609                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3610                 (!env.tree.hasTag(ASSIGN) ||
  3611                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3612                 String suffix = (env.info.enclVar == v) ?
  3613                                 "self.ref" : "forward.ref";
  3614                 if (!onlyWarning || isStaticEnumField(v)) {
  3615                     log.error(tree.pos(), "illegal." + suffix);
  3616                 } else if (useBeforeDeclarationWarning) {
  3617                     log.warning(tree.pos(), suffix, v);
  3621             v.getConstValue(); // ensure initializer is evaluated
  3623             checkEnumInitializer(tree, env, v);
  3626         /**
  3627          * Check for illegal references to static members of enum.  In
  3628          * an enum type, constructors and initializers may not
  3629          * reference its static members unless they are constant.
  3631          * @param tree    The tree making up the variable reference.
  3632          * @param env     The current environment.
  3633          * @param v       The variable's symbol.
  3634          * @jls  section 8.9 Enums
  3635          */
  3636         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3637             // JLS:
  3638             //
  3639             // "It is a compile-time error to reference a static field
  3640             // of an enum type that is not a compile-time constant
  3641             // (15.28) from constructors, instance initializer blocks,
  3642             // or instance variable initializer expressions of that
  3643             // type. It is a compile-time error for the constructors,
  3644             // instance initializer blocks, or instance variable
  3645             // initializer expressions of an enum constant e to refer
  3646             // to itself or to an enum constant of the same type that
  3647             // is declared to the right of e."
  3648             if (isStaticEnumField(v)) {
  3649                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3651                 if (enclClass == null || enclClass.owner == null)
  3652                     return;
  3654                 // See if the enclosing class is the enum (or a
  3655                 // subclass thereof) declaring v.  If not, this
  3656                 // reference is OK.
  3657                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3658                     return;
  3660                 // If the reference isn't from an initializer, then
  3661                 // the reference is OK.
  3662                 if (!Resolve.isInitializer(env))
  3663                     return;
  3665                 log.error(tree.pos(), "illegal.enum.static.ref");
  3669         /** Is the given symbol a static, non-constant field of an Enum?
  3670          *  Note: enum literals should not be regarded as such
  3671          */
  3672         private boolean isStaticEnumField(VarSymbol v) {
  3673             return Flags.isEnum(v.owner) &&
  3674                    Flags.isStatic(v) &&
  3675                    !Flags.isConstant(v) &&
  3676                    v.name != names._class;
  3679         /** Can the given symbol be the owner of code which forms part
  3680          *  if class initialization? This is the case if the symbol is
  3681          *  a type or field, or if the symbol is the synthetic method.
  3682          *  owning a block.
  3683          */
  3684         private boolean canOwnInitializer(Symbol sym) {
  3685             return
  3686                 (sym.kind & (VAR | TYP)) != 0 ||
  3687                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3690     Warner noteWarner = new Warner();
  3692     /**
  3693      * Check that method arguments conform to its instantiation.
  3694      **/
  3695     public Type checkMethod(Type site,
  3696                             Symbol sym,
  3697                             ResultInfo resultInfo,
  3698                             Env<AttrContext> env,
  3699                             final List<JCExpression> argtrees,
  3700                             List<Type> argtypes,
  3701                             List<Type> typeargtypes) {
  3702         // Test (5): if symbol is an instance method of a raw type, issue
  3703         // an unchecked warning if its argument types change under erasure.
  3704         if (allowGenerics &&
  3705             (sym.flags() & STATIC) == 0 &&
  3706             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3707             Type s = types.asOuterSuper(site, sym.owner);
  3708             if (s != null && s.isRaw() &&
  3709                 !types.isSameTypes(sym.type.getParameterTypes(),
  3710                                    sym.erasure(types).getParameterTypes())) {
  3711                 chk.warnUnchecked(env.tree.pos(),
  3712                                   "unchecked.call.mbr.of.raw.type",
  3713                                   sym, s);
  3717         if (env.info.defaultSuperCallSite != null) {
  3718             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3719                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3720                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3721                 List<MethodSymbol> icand_sup =
  3722                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3723                 if (icand_sup.nonEmpty() &&
  3724                         icand_sup.head != sym &&
  3725                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3726                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3727                         diags.fragment("overridden.default", sym, sup));
  3728                     break;
  3731             env.info.defaultSuperCallSite = null;
  3734         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3735             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3736             if (app.meth.hasTag(SELECT) &&
  3737                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3738                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3742         // Compute the identifier's instantiated type.
  3743         // For methods, we need to compute the instance type by
  3744         // Resolve.instantiate from the symbol's type as well as
  3745         // any type arguments and value arguments.
  3746         noteWarner.clear();
  3747         try {
  3748             Type owntype = rs.checkMethod(
  3749                     env,
  3750                     site,
  3751                     sym,
  3752                     resultInfo,
  3753                     argtypes,
  3754                     typeargtypes,
  3755                     noteWarner);
  3757             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3758                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3760             argtypes = Type.map(argtypes, checkDeferredMap);
  3762             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3763                 chk.warnUnchecked(env.tree.pos(),
  3764                         "unchecked.meth.invocation.applied",
  3765                         kindName(sym),
  3766                         sym.name,
  3767                         rs.methodArguments(sym.type.getParameterTypes()),
  3768                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3769                         kindName(sym.location()),
  3770                         sym.location());
  3771                owntype = new MethodType(owntype.getParameterTypes(),
  3772                        types.erasure(owntype.getReturnType()),
  3773                        types.erasure(owntype.getThrownTypes()),
  3774                        syms.methodClass);
  3777             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3778                     resultInfo.checkContext.inferenceContext());
  3779         } catch (Infer.InferenceException ex) {
  3780             //invalid target type - propagate exception outwards or report error
  3781             //depending on the current check context
  3782             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3783             return types.createErrorType(site);
  3784         } catch (Resolve.InapplicableMethodException ex) {
  3785             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
  3786             return null;
  3790     public void visitLiteral(JCLiteral tree) {
  3791         result = check(
  3792             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3794     //where
  3795     /** Return the type of a literal with given type tag.
  3796      */
  3797     Type litType(TypeTag tag) {
  3798         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3801     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3802         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3805     public void visitTypeArray(JCArrayTypeTree tree) {
  3806         Type etype = attribType(tree.elemtype, env);
  3807         Type type = new ArrayType(etype, syms.arrayClass);
  3808         result = check(tree, type, TYP, resultInfo);
  3811     /** Visitor method for parameterized types.
  3812      *  Bound checking is left until later, since types are attributed
  3813      *  before supertype structure is completely known
  3814      */
  3815     public void visitTypeApply(JCTypeApply tree) {
  3816         Type owntype = types.createErrorType(tree.type);
  3818         // Attribute functor part of application and make sure it's a class.
  3819         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3821         // Attribute type parameters
  3822         List<Type> actuals = attribTypes(tree.arguments, env);
  3824         if (clazztype.hasTag(CLASS)) {
  3825             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3826             if (actuals.isEmpty()) //diamond
  3827                 actuals = formals;
  3829             if (actuals.length() == formals.length()) {
  3830                 List<Type> a = actuals;
  3831                 List<Type> f = formals;
  3832                 while (a.nonEmpty()) {
  3833                     a.head = a.head.withTypeVar(f.head);
  3834                     a = a.tail;
  3835                     f = f.tail;
  3837                 // Compute the proper generic outer
  3838                 Type clazzOuter = clazztype.getEnclosingType();
  3839                 if (clazzOuter.hasTag(CLASS)) {
  3840                     Type site;
  3841                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3842                     if (clazz.hasTag(IDENT)) {
  3843                         site = env.enclClass.sym.type;
  3844                     } else if (clazz.hasTag(SELECT)) {
  3845                         site = ((JCFieldAccess) clazz).selected.type;
  3846                     } else throw new AssertionError(""+tree);
  3847                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3848                         if (site.hasTag(CLASS))
  3849                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3850                         if (site == null)
  3851                             site = types.erasure(clazzOuter);
  3852                         clazzOuter = site;
  3855                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3856                 if (clazztype.isAnnotated()) {
  3857                     // Use the same AnnotatedType, because it will have
  3858                     // its annotations set later.
  3859                     ((AnnotatedType)clazztype).underlyingType = owntype;
  3860                     owntype = clazztype;
  3862             } else {
  3863                 if (formals.length() != 0) {
  3864                     log.error(tree.pos(), "wrong.number.type.args",
  3865                               Integer.toString(formals.length()));
  3866                 } else {
  3867                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3869                 owntype = types.createErrorType(tree.type);
  3872         result = check(tree, owntype, TYP, resultInfo);
  3875     public void visitTypeUnion(JCTypeUnion tree) {
  3876         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  3877         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3878         for (JCExpression typeTree : tree.alternatives) {
  3879             Type ctype = attribType(typeTree, env);
  3880             ctype = chk.checkType(typeTree.pos(),
  3881                           chk.checkClassType(typeTree.pos(), ctype),
  3882                           syms.throwableType);
  3883             if (!ctype.isErroneous()) {
  3884                 //check that alternatives of a union type are pairwise
  3885                 //unrelated w.r.t. subtyping
  3886                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3887                     for (Type t : multicatchTypes) {
  3888                         boolean sub = types.isSubtype(ctype, t);
  3889                         boolean sup = types.isSubtype(t, ctype);
  3890                         if (sub || sup) {
  3891                             //assume 'a' <: 'b'
  3892                             Type a = sub ? ctype : t;
  3893                             Type b = sub ? t : ctype;
  3894                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3898                 multicatchTypes.append(ctype);
  3899                 if (all_multicatchTypes != null)
  3900                     all_multicatchTypes.append(ctype);
  3901             } else {
  3902                 if (all_multicatchTypes == null) {
  3903                     all_multicatchTypes = ListBuffer.lb();
  3904                     all_multicatchTypes.appendList(multicatchTypes);
  3906                 all_multicatchTypes.append(ctype);
  3909         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3910         if (t.hasTag(CLASS)) {
  3911             List<Type> alternatives =
  3912                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3913             t = new UnionClassType((ClassType) t, alternatives);
  3915         tree.type = result = t;
  3918     public void visitTypeIntersection(JCTypeIntersection tree) {
  3919         attribTypes(tree.bounds, env);
  3920         tree.type = result = checkIntersection(tree, tree.bounds);
  3923     public void visitTypeParameter(JCTypeParameter tree) {
  3924         TypeVar typeVar = (TypeVar) tree.type;
  3926         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3927             AnnotatedType antype = new AnnotatedType(typeVar);
  3928             annotateType(antype, tree.annotations);
  3929             tree.type = antype;
  3932         if (!typeVar.bound.isErroneous()) {
  3933             //fixup type-parameter bound computed in 'attribTypeVariables'
  3934             typeVar.bound = checkIntersection(tree, tree.bounds);
  3938     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3939         Set<Type> boundSet = new HashSet<Type>();
  3940         if (bounds.nonEmpty()) {
  3941             // accept class or interface or typevar as first bound.
  3942             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3943             boundSet.add(types.erasure(bounds.head.type));
  3944             if (bounds.head.type.isErroneous()) {
  3945                 return bounds.head.type;
  3947             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3948                 // if first bound was a typevar, do not accept further bounds.
  3949                 if (bounds.tail.nonEmpty()) {
  3950                     log.error(bounds.tail.head.pos(),
  3951                               "type.var.may.not.be.followed.by.other.bounds");
  3952                     return bounds.head.type;
  3954             } else {
  3955                 // if first bound was a class or interface, accept only interfaces
  3956                 // as further bounds.
  3957                 for (JCExpression bound : bounds.tail) {
  3958                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  3959                     if (bound.type.isErroneous()) {
  3960                         bounds = List.of(bound);
  3962                     else if (bound.type.hasTag(CLASS)) {
  3963                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  3969         if (bounds.length() == 0) {
  3970             return syms.objectType;
  3971         } else if (bounds.length() == 1) {
  3972             return bounds.head.type;
  3973         } else {
  3974             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  3975             if (tree.hasTag(TYPEINTERSECTION)) {
  3976                 ((IntersectionClassType)owntype).intersectionKind =
  3977                         IntersectionClassType.IntersectionKind.EXPLICIT;
  3979             // ... the variable's bound is a class type flagged COMPOUND
  3980             // (see comment for TypeVar.bound).
  3981             // In this case, generate a class tree that represents the
  3982             // bound class, ...
  3983             JCExpression extending;
  3984             List<JCExpression> implementing;
  3985             if (!bounds.head.type.isInterface()) {
  3986                 extending = bounds.head;
  3987                 implementing = bounds.tail;
  3988             } else {
  3989                 extending = null;
  3990                 implementing = bounds;
  3992             JCClassDecl cd = make.at(tree).ClassDef(
  3993                 make.Modifiers(PUBLIC | ABSTRACT),
  3994                 names.empty, List.<JCTypeParameter>nil(),
  3995                 extending, implementing, List.<JCTree>nil());
  3997             ClassSymbol c = (ClassSymbol)owntype.tsym;
  3998             Assert.check((c.flags() & COMPOUND) != 0);
  3999             cd.sym = c;
  4000             c.sourcefile = env.toplevel.sourcefile;
  4002             // ... and attribute the bound class
  4003             c.flags_field |= UNATTRIBUTED;
  4004             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4005             enter.typeEnvs.put(c, cenv);
  4006             attribClass(c);
  4007             return owntype;
  4011     public void visitWildcard(JCWildcard tree) {
  4012         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4013         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4014             ? syms.objectType
  4015             : attribType(tree.inner, env);
  4016         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4017                                               tree.kind.kind,
  4018                                               syms.boundClass),
  4019                        TYP, resultInfo);
  4022     public void visitAnnotation(JCAnnotation tree) {
  4023         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  4024         result = tree.type = syms.errType;
  4027     public void visitAnnotatedType(JCAnnotatedType tree) {
  4028         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4029         this.attribAnnotationTypes(tree.annotations, env);
  4030         AnnotatedType antype = new AnnotatedType(underlyingType);
  4031         annotateType(antype, tree.annotations);
  4032         result = tree.type = antype;
  4035     /**
  4036      * Apply the annotations to the particular type.
  4037      */
  4038     public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
  4039         if (annotations.isEmpty())
  4040             return;
  4041         annotate.typeAnnotation(new Annotate.Annotator() {
  4042             @Override
  4043             public String toString() {
  4044                 return "annotate " + annotations + " onto " + type;
  4046             @Override
  4047             public void enterAnnotation() {
  4048                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4049                 type.typeAnnotations = compounds;
  4051         });
  4054     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4055         if (annotations.isEmpty())
  4056             return List.nil();
  4058         ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
  4059         for (JCAnnotation anno : annotations) {
  4060             if (anno.attribute != null) {
  4061                 // TODO: this null-check is only needed for an obscure
  4062                 // ordering issue, where annotate.flush is called when
  4063                 // the attribute is not set yet. For an example failure
  4064                 // try the referenceinfos/NestedTypes.java test.
  4065                 // Any better solutions?
  4066                 buf.append((Attribute.TypeCompound) anno.attribute);
  4069         return buf.toList();
  4072     public void visitErroneous(JCErroneous tree) {
  4073         if (tree.errs != null)
  4074             for (JCTree err : tree.errs)
  4075                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4076         result = tree.type = syms.errType;
  4079     /** Default visitor method for all other trees.
  4080      */
  4081     public void visitTree(JCTree tree) {
  4082         throw new AssertionError();
  4085     /**
  4086      * Attribute an env for either a top level tree or class declaration.
  4087      */
  4088     public void attrib(Env<AttrContext> env) {
  4089         if (env.tree.hasTag(TOPLEVEL))
  4090             attribTopLevel(env);
  4091         else
  4092             attribClass(env.tree.pos(), env.enclClass.sym);
  4095     /**
  4096      * Attribute a top level tree. These trees are encountered when the
  4097      * package declaration has annotations.
  4098      */
  4099     public void attribTopLevel(Env<AttrContext> env) {
  4100         JCCompilationUnit toplevel = env.toplevel;
  4101         try {
  4102             annotate.flush();
  4103             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  4104         } catch (CompletionFailure ex) {
  4105             chk.completionError(toplevel.pos(), ex);
  4109     /** Main method: attribute class definition associated with given class symbol.
  4110      *  reporting completion failures at the given position.
  4111      *  @param pos The source position at which completion errors are to be
  4112      *             reported.
  4113      *  @param c   The class symbol whose definition will be attributed.
  4114      */
  4115     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4116         try {
  4117             annotate.flush();
  4118             attribClass(c);
  4119         } catch (CompletionFailure ex) {
  4120             chk.completionError(pos, ex);
  4124     /** Attribute class definition associated with given class symbol.
  4125      *  @param c   The class symbol whose definition will be attributed.
  4126      */
  4127     void attribClass(ClassSymbol c) throws CompletionFailure {
  4128         if (c.type.hasTag(ERROR)) return;
  4130         // Check for cycles in the inheritance graph, which can arise from
  4131         // ill-formed class files.
  4132         chk.checkNonCyclic(null, c.type);
  4134         Type st = types.supertype(c.type);
  4135         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4136             // First, attribute superclass.
  4137             if (st.hasTag(CLASS))
  4138                 attribClass((ClassSymbol)st.tsym);
  4140             // Next attribute owner, if it is a class.
  4141             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4142                 attribClass((ClassSymbol)c.owner);
  4145         // The previous operations might have attributed the current class
  4146         // if there was a cycle. So we test first whether the class is still
  4147         // UNATTRIBUTED.
  4148         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4149             c.flags_field &= ~UNATTRIBUTED;
  4151             // Get environment current at the point of class definition.
  4152             Env<AttrContext> env = enter.typeEnvs.get(c);
  4154             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4155             // because the annotations were not available at the time the env was created. Therefore,
  4156             // we look up the environment chain for the first enclosing environment for which the
  4157             // lint value is set. Typically, this is the parent env, but might be further if there
  4158             // are any envs created as a result of TypeParameter nodes.
  4159             Env<AttrContext> lintEnv = env;
  4160             while (lintEnv.info.lint == null)
  4161                 lintEnv = lintEnv.next;
  4163             // Having found the enclosing lint value, we can initialize the lint value for this class
  4164             env.info.lint = lintEnv.info.lint.augment(c);
  4166             Lint prevLint = chk.setLint(env.info.lint);
  4167             JavaFileObject prev = log.useSource(c.sourcefile);
  4168             ResultInfo prevReturnRes = env.info.returnResult;
  4170             try {
  4171                 env.info.returnResult = null;
  4172                 // java.lang.Enum may not be subclassed by a non-enum
  4173                 if (st.tsym == syms.enumSym &&
  4174                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4175                     log.error(env.tree.pos(), "enum.no.subclassing");
  4177                 // Enums may not be extended by source-level classes
  4178                 if (st.tsym != null &&
  4179                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4180                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4181                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4183                 attribClassBody(env, c);
  4185                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4186                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4187             } finally {
  4188                 env.info.returnResult = prevReturnRes;
  4189                 log.useSource(prev);
  4190                 chk.setLint(prevLint);
  4196     public void visitImport(JCImport tree) {
  4197         // nothing to do
  4200     /** Finish the attribution of a class. */
  4201     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4202         JCClassDecl tree = (JCClassDecl)env.tree;
  4203         Assert.check(c == tree.sym);
  4205         // Validate annotations
  4206         chk.validateAnnotations(tree.mods.annotations, c);
  4208         // Validate type parameters, supertype and interfaces.
  4209         attribStats(tree.typarams, env);
  4210         if (!c.isAnonymous()) {
  4211             //already checked if anonymous
  4212             chk.validate(tree.typarams, env);
  4213             chk.validate(tree.extending, env);
  4214             chk.validate(tree.implementing, env);
  4217         // If this is a non-abstract class, check that it has no abstract
  4218         // methods or unimplemented methods of an implemented interface.
  4219         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4220             if (!relax)
  4221                 chk.checkAllDefined(tree.pos(), c);
  4224         if ((c.flags() & ANNOTATION) != 0) {
  4225             if (tree.implementing.nonEmpty())
  4226                 log.error(tree.implementing.head.pos(),
  4227                           "cant.extend.intf.annotation");
  4228             if (tree.typarams.nonEmpty())
  4229                 log.error(tree.typarams.head.pos(),
  4230                           "intf.annotation.cant.have.type.params");
  4232             // If this annotation has a @Repeatable, validate
  4233             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4234             if (repeatable != null) {
  4235                 // get diagnostic position for error reporting
  4236                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4237                 Assert.checkNonNull(cbPos);
  4239                 chk.validateRepeatable(c, repeatable, cbPos);
  4241         } else {
  4242             // Check that all extended classes and interfaces
  4243             // are compatible (i.e. no two define methods with same arguments
  4244             // yet different return types).  (JLS 8.4.6.3)
  4245             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4246             if (allowDefaultMethods) {
  4247                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4251         // Check that class does not import the same parameterized interface
  4252         // with two different argument lists.
  4253         chk.checkClassBounds(tree.pos(), c.type);
  4255         tree.type = c.type;
  4257         for (List<JCTypeParameter> l = tree.typarams;
  4258              l.nonEmpty(); l = l.tail) {
  4259              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4262         // Check that a generic class doesn't extend Throwable
  4263         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4264             log.error(tree.extending.pos(), "generic.throwable");
  4266         // Check that all methods which implement some
  4267         // method conform to the method they implement.
  4268         chk.checkImplementations(tree);
  4270         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4271         checkAutoCloseable(tree.pos(), env, c.type);
  4273         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4274             // Attribute declaration
  4275             attribStat(l.head, env);
  4276             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4277             // Make an exception for static constants.
  4278             if (c.owner.kind != PCK &&
  4279                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4280                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4281                 Symbol sym = null;
  4282                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4283                 if (sym == null ||
  4284                     sym.kind != VAR ||
  4285                     ((VarSymbol) sym).getConstValue() == null)
  4286                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4290         // Check for cycles among non-initial constructors.
  4291         chk.checkCyclicConstructors(tree);
  4293         // Check for cycles among annotation elements.
  4294         chk.checkNonCyclicElements(tree);
  4296         // Check for proper use of serialVersionUID
  4297         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4298             isSerializable(c) &&
  4299             (c.flags() & Flags.ENUM) == 0 &&
  4300             (c.flags() & ABSTRACT) == 0) {
  4301             checkSerialVersionUID(tree, c);
  4303         if (allowTypeAnnos) {
  4304             // Correctly organize the postions of the type annotations
  4305             TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
  4307             // Check type annotations applicability rules
  4308             validateTypeAnnotations(tree);
  4311         // where
  4312         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4313         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4314             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4315                 if (types.isSameType(al.head.annotationType.type, t))
  4316                     return al.head.pos();
  4319             return null;
  4322         /** check if a class is a subtype of Serializable, if that is available. */
  4323         private boolean isSerializable(ClassSymbol c) {
  4324             try {
  4325                 syms.serializableType.complete();
  4327             catch (CompletionFailure e) {
  4328                 return false;
  4330             return types.isSubtype(c.type, syms.serializableType);
  4333         /** Check that an appropriate serialVersionUID member is defined. */
  4334         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4336             // check for presence of serialVersionUID
  4337             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4338             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4339             if (e.scope == null) {
  4340                 log.warning(LintCategory.SERIAL,
  4341                         tree.pos(), "missing.SVUID", c);
  4342                 return;
  4345             // check that it is static final
  4346             VarSymbol svuid = (VarSymbol)e.sym;
  4347             if ((svuid.flags() & (STATIC | FINAL)) !=
  4348                 (STATIC | FINAL))
  4349                 log.warning(LintCategory.SERIAL,
  4350                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4352             // check that it is long
  4353             else if (!svuid.type.hasTag(LONG))
  4354                 log.warning(LintCategory.SERIAL,
  4355                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4357             // check constant
  4358             else if (svuid.getConstValue() == null)
  4359                 log.warning(LintCategory.SERIAL,
  4360                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4363     private Type capture(Type type) {
  4364         //do not capture free types
  4365         return resultInfo.checkContext.inferenceContext().free(type) ?
  4366                 type : types.capture(type);
  4369     private void validateTypeAnnotations(JCTree tree) {
  4370         tree.accept(typeAnnotationsValidator);
  4372     //where
  4373     private final JCTree.Visitor typeAnnotationsValidator = new TreeScanner() {
  4375         private boolean checkAllAnnotations = false;
  4377         public void visitAnnotation(JCAnnotation tree) {
  4378             if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
  4379                 chk.validateTypeAnnotation(tree, false);
  4381             super.visitAnnotation(tree);
  4383         public void visitTypeParameter(JCTypeParameter tree) {
  4384             chk.validateTypeAnnotations(tree.annotations, true);
  4385             scan(tree.bounds);
  4386             // Don't call super.
  4387             // This is needed because above we call validateTypeAnnotation with
  4388             // false, which would forbid annotations on type parameters.
  4389             // super.visitTypeParameter(tree);
  4391         public void visitMethodDef(JCMethodDecl tree) {
  4392             if (tree.recvparam != null &&
  4393                     tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
  4394                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4395                         tree.recvparam.vartype.type.tsym);
  4397             if (tree.restype != null && tree.restype.type != null) {
  4398                 validateAnnotatedType(tree.restype, tree.restype.type);
  4400             super.visitMethodDef(tree);
  4402         public void visitVarDef(final JCVariableDecl tree) {
  4403             if (tree.sym != null && tree.sym.type != null)
  4404                 validateAnnotatedType(tree, tree.sym.type);
  4405             super.visitVarDef(tree);
  4407         public void visitTypeCast(JCTypeCast tree) {
  4408             if (tree.clazz != null && tree.clazz.type != null)
  4409                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4410             super.visitTypeCast(tree);
  4412         public void visitTypeTest(JCInstanceOf tree) {
  4413             if (tree.clazz != null && tree.clazz.type != null)
  4414                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4415             super.visitTypeTest(tree);
  4417         public void visitNewClass(JCNewClass tree) {
  4418             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4419                 boolean prevCheck = this.checkAllAnnotations;
  4420                 try {
  4421                     this.checkAllAnnotations = true;
  4422                     scan(((JCAnnotatedType)tree.clazz).annotations);
  4423                 } finally {
  4424                     this.checkAllAnnotations = prevCheck;
  4427             super.visitNewClass(tree);
  4429         public void visitNewArray(JCNewArray tree) {
  4430             if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4431                 boolean prevCheck = this.checkAllAnnotations;
  4432                 try {
  4433                     this.checkAllAnnotations = true;
  4434                     scan(((JCAnnotatedType)tree.elemtype).annotations);
  4435                 } finally {
  4436                     this.checkAllAnnotations = prevCheck;
  4439             super.visitNewArray(tree);
  4442         /* I would want to model this after
  4443          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4444          * and override visitSelect and visitTypeApply.
  4445          * However, we only set the annotated type in the top-level type
  4446          * of the symbol.
  4447          * Therefore, we need to override each individual location where a type
  4448          * can occur.
  4449          */
  4450         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4451             if (type.getEnclosingType() != null &&
  4452                     type != type.getEnclosingType()) {
  4453                 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
  4455             for (Type targ : type.getTypeArguments()) {
  4456                 validateAnnotatedType(errtree, targ);
  4459         private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
  4460             validateAnnotatedType(errtree, type);
  4461             if (type.tsym != null &&
  4462                     type.tsym.isStatic() &&
  4463                     type.getAnnotationMirrors().nonEmpty()) {
  4464                     // Enclosing static classes cannot have type annotations.
  4465                 log.error(errtree.pos(), "cant.annotate.static.class");
  4468     };
  4470     // <editor-fold desc="post-attribution visitor">
  4472     /**
  4473      * Handle missing types/symbols in an AST. This routine is useful when
  4474      * the compiler has encountered some errors (which might have ended up
  4475      * terminating attribution abruptly); if the compiler is used in fail-over
  4476      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4477      * prevents NPE to be progagated during subsequent compilation steps.
  4478      */
  4479     public void postAttr(JCTree tree) {
  4480         new PostAttrAnalyzer().scan(tree);
  4483     class PostAttrAnalyzer extends TreeScanner {
  4485         private void initTypeIfNeeded(JCTree that) {
  4486             if (that.type == null) {
  4487                 that.type = syms.unknownType;
  4491         @Override
  4492         public void scan(JCTree tree) {
  4493             if (tree == null) return;
  4494             if (tree instanceof JCExpression) {
  4495                 initTypeIfNeeded(tree);
  4497             super.scan(tree);
  4500         @Override
  4501         public void visitIdent(JCIdent that) {
  4502             if (that.sym == null) {
  4503                 that.sym = syms.unknownSymbol;
  4507         @Override
  4508         public void visitSelect(JCFieldAccess that) {
  4509             if (that.sym == null) {
  4510                 that.sym = syms.unknownSymbol;
  4512             super.visitSelect(that);
  4515         @Override
  4516         public void visitClassDef(JCClassDecl that) {
  4517             initTypeIfNeeded(that);
  4518             if (that.sym == null) {
  4519                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4521             super.visitClassDef(that);
  4524         @Override
  4525         public void visitMethodDef(JCMethodDecl that) {
  4526             initTypeIfNeeded(that);
  4527             if (that.sym == null) {
  4528                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4530             super.visitMethodDef(that);
  4533         @Override
  4534         public void visitVarDef(JCVariableDecl that) {
  4535             initTypeIfNeeded(that);
  4536             if (that.sym == null) {
  4537                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4538                 that.sym.adr = 0;
  4540             super.visitVarDef(that);
  4543         @Override
  4544         public void visitNewClass(JCNewClass that) {
  4545             if (that.constructor == null) {
  4546                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  4548             if (that.constructorType == null) {
  4549                 that.constructorType = syms.unknownType;
  4551             super.visitNewClass(that);
  4554         @Override
  4555         public void visitAssignop(JCAssignOp that) {
  4556             if (that.operator == null)
  4557                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4558             super.visitAssignop(that);
  4561         @Override
  4562         public void visitBinary(JCBinary that) {
  4563             if (that.operator == null)
  4564                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4565             super.visitBinary(that);
  4568         @Override
  4569         public void visitUnary(JCUnary that) {
  4570             if (that.operator == null)
  4571                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4572             super.visitUnary(that);
  4575         @Override
  4576         public void visitLambda(JCLambda that) {
  4577             super.visitLambda(that);
  4578             if (that.descriptorType == null) {
  4579                 that.descriptorType = syms.unknownType;
  4581             if (that.targets == null) {
  4582                 that.targets = List.nil();
  4586         @Override
  4587         public void visitReference(JCMemberReference that) {
  4588             super.visitReference(that);
  4589             if (that.sym == null) {
  4590                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  4592             if (that.descriptorType == null) {
  4593                 that.descriptorType = syms.unknownType;
  4595             if (that.targets == null) {
  4596                 that.targets = List.nil();
  4600     // </editor-fold>

mercurial