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

Wed, 17 Jul 2013 14:09:46 +0100

author
mcimadamore
date
Wed, 17 Jul 2013 14:09:46 +0100
changeset 1897
866c87c01285
parent 1890
bfbedbfc522a
child 1898
a204cf7aab7e
permissions
-rw-r--r--

8016175: Add bottom-up type-checking support for unambiguous method references
Summary: Type-checking of non-overloaded method references should be independent from target-type
Reviewed-by: jjg, vromero

     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         }
   558     }
   560     final ResultInfo statInfo;
   561     final ResultInfo varInfo;
   562     final ResultInfo unknownAnyPolyInfo;
   563     final ResultInfo unknownExprInfo;
   564     final ResultInfo unknownTypeInfo;
   565     final ResultInfo unknownTypeExprInfo;
   566     final ResultInfo recoveryInfo;
   568     Type pt() {
   569         return resultInfo.pt;
   570     }
   572     int pkind() {
   573         return resultInfo.pkind;
   574     }
   576 /* ************************************************************************
   577  * Visitor methods
   578  *************************************************************************/
   580     /** Visitor argument: the current environment.
   581      */
   582     Env<AttrContext> env;
   584     /** Visitor argument: the currently expected attribution result.
   585      */
   586     ResultInfo resultInfo;
   588     /** Visitor result: the computed type.
   589      */
   590     Type result;
   592     /** Visitor method: attribute a tree, catching any completion failure
   593      *  exceptions. Return the tree's type.
   594      *
   595      *  @param tree    The tree to be visited.
   596      *  @param env     The environment visitor argument.
   597      *  @param resultInfo   The result info visitor argument.
   598      */
   599     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   600         Env<AttrContext> prevEnv = this.env;
   601         ResultInfo prevResult = this.resultInfo;
   602         try {
   603             this.env = env;
   604             this.resultInfo = resultInfo;
   605             tree.accept(this);
   606             if (tree == breakTree &&
   607                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   608                 throw new BreakAttr(env);
   609             }
   610             return result;
   611         } catch (CompletionFailure ex) {
   612             tree.type = syms.errType;
   613             return chk.completionError(tree.pos(), ex);
   614         } finally {
   615             this.env = prevEnv;
   616             this.resultInfo = prevResult;
   617         }
   618     }
   620     /** Derived visitor method: attribute an expression tree.
   621      */
   622     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   623         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   624     }
   626     /** Derived visitor method: attribute an expression tree with
   627      *  no constraints on the computed type.
   628      */
   629     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   630         return attribTree(tree, env, unknownExprInfo);
   631     }
   633     /** Derived visitor method: attribute a type tree.
   634      */
   635     public Type attribType(JCTree tree, Env<AttrContext> env) {
   636         Type result = attribType(tree, env, Type.noType);
   637         return result;
   638     }
   640     /** Derived visitor method: attribute a type tree.
   641      */
   642     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   643         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   644         return result;
   645     }
   647     /** Derived visitor method: attribute a statement or definition tree.
   648      */
   649     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   650         return attribTree(tree, env, statInfo);
   651     }
   653     /** Attribute a list of expressions, returning a list of types.
   654      */
   655     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   656         ListBuffer<Type> ts = new ListBuffer<Type>();
   657         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   658             ts.append(attribExpr(l.head, env, pt));
   659         return ts.toList();
   660     }
   662     /** Attribute a list of statements, returning nothing.
   663      */
   664     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   665         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   666             attribStat(l.head, env);
   667     }
   669     /** Attribute the arguments in a method call, returning the method kind.
   670      */
   671     int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   672         int kind = VAL;
   673         for (JCExpression arg : trees) {
   674             Type argtype;
   675             if (allowPoly && deferredAttr.isDeferred(env, arg)) {
   676                 argtype = deferredAttr.new DeferredType(arg, env);
   677                 kind |= POLY;
   678             } else {
   679                 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
   680             }
   681             argtypes.append(argtype);
   682         }
   683         return kind;
   684     }
   686     /** Attribute a type argument list, returning a list of types.
   687      *  Caller is responsible for calling checkRefTypes.
   688      */
   689     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   690         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   691         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   692             argtypes.append(attribType(l.head, env));
   693         return argtypes.toList();
   694     }
   696     /** Attribute a type argument list, returning a list of types.
   697      *  Check that all the types are references.
   698      */
   699     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   700         List<Type> types = attribAnyTypes(trees, env);
   701         return chk.checkRefTypes(trees, types);
   702     }
   704     /**
   705      * Attribute type variables (of generic classes or methods).
   706      * Compound types are attributed later in attribBounds.
   707      * @param typarams the type variables to enter
   708      * @param env      the current environment
   709      */
   710     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   711         for (JCTypeParameter tvar : typarams) {
   712             TypeVar a = (TypeVar)tvar.type;
   713             a.tsym.flags_field |= UNATTRIBUTED;
   714             a.bound = Type.noType;
   715             if (!tvar.bounds.isEmpty()) {
   716                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   717                 for (JCExpression bound : tvar.bounds.tail)
   718                     bounds = bounds.prepend(attribType(bound, env));
   719                 types.setBounds(a, bounds.reverse());
   720             } else {
   721                 // if no bounds are given, assume a single bound of
   722                 // java.lang.Object.
   723                 types.setBounds(a, List.of(syms.objectType));
   724             }
   725             a.tsym.flags_field &= ~UNATTRIBUTED;
   726         }
   727         for (JCTypeParameter tvar : typarams) {
   728             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   729         }
   730     }
   732     /**
   733      * Attribute the type references in a list of annotations.
   734      */
   735     void attribAnnotationTypes(List<JCAnnotation> annotations,
   736                                Env<AttrContext> env) {
   737         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   738             JCAnnotation a = al.head;
   739             attribType(a.annotationType, env);
   740         }
   741     }
   743     /**
   744      * Attribute a "lazy constant value".
   745      *  @param env         The env for the const value
   746      *  @param initializer The initializer for the const value
   747      *  @param type        The expected type, or null
   748      *  @see VarSymbol#setLazyConstValue
   749      */
   750     public Object attribLazyConstantValue(Env<AttrContext> env,
   751                                       JCTree.JCExpression initializer,
   752                                       Type type) {
   754         /*  When this env was created, it didn't have the correct lint nor had
   755          *  annotations has been processed.
   756          *  But now at this phase we have already processed annotations and the
   757          *  correct lint must have been set in chk, so we should use that one to
   758          *  attribute the initializer.
   759          */
   760         Lint prevLint = env.info.lint;
   761         env.info.lint = chk.getLint();
   763         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   765         try {
   766             // Use null as symbol to not attach the type annotation to any symbol.
   767             // The initializer will later also be visited and then we'll attach
   768             // to the symbol.
   769             // This prevents having multiple type annotations, just because of
   770             // lazy constant value evaluation.
   771             memberEnter.typeAnnotate(initializer, env, null);
   772             annotate.flush();
   773             Type itype = attribExpr(initializer, env, type);
   774             if (itype.constValue() != null) {
   775                 return coerce(itype, type).constValue();
   776             } else {
   777                 return null;
   778             }
   779         } finally {
   780             env.info.lint = prevLint;
   781             log.useSource(prevSource);
   782         }
   783     }
   785     /** Attribute type reference in an `extends' or `implements' clause.
   786      *  Supertypes of anonymous inner classes are usually already attributed.
   787      *
   788      *  @param tree              The tree making up the type reference.
   789      *  @param env               The environment current at the reference.
   790      *  @param classExpected     true if only a class is expected here.
   791      *  @param interfaceExpected true if only an interface is expected here.
   792      */
   793     Type attribBase(JCTree tree,
   794                     Env<AttrContext> env,
   795                     boolean classExpected,
   796                     boolean interfaceExpected,
   797                     boolean checkExtensible) {
   798         Type t = tree.type != null ?
   799             tree.type :
   800             attribType(tree, env);
   801         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   802     }
   803     Type checkBase(Type t,
   804                    JCTree tree,
   805                    Env<AttrContext> env,
   806                    boolean classExpected,
   807                    boolean interfaceExpected,
   808                    boolean checkExtensible) {
   809         if (t.isErroneous())
   810             return t;
   811         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   812             // check that type variable is already visible
   813             if (t.getUpperBound() == null) {
   814                 log.error(tree.pos(), "illegal.forward.ref");
   815                 return types.createErrorType(t);
   816             }
   817         } else {
   818             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   819         }
   820         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   821             log.error(tree.pos(), "intf.expected.here");
   822             // return errType is necessary since otherwise there might
   823             // be undetected cycles which cause attribution to loop
   824             return types.createErrorType(t);
   825         } else if (checkExtensible &&
   826                    classExpected &&
   827                    (t.tsym.flags() & INTERFACE) != 0) {
   828                 log.error(tree.pos(), "no.intf.expected.here");
   829             return types.createErrorType(t);
   830         }
   831         if (checkExtensible &&
   832             ((t.tsym.flags() & FINAL) != 0)) {
   833             log.error(tree.pos(),
   834                       "cant.inherit.from.final", t.tsym);
   835         }
   836         chk.checkNonCyclic(tree.pos(), t);
   837         return t;
   838     }
   840     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   841         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   842         id.type = env.info.scope.owner.type;
   843         id.sym = env.info.scope.owner;
   844         return id.type;
   845     }
   847     public void visitClassDef(JCClassDecl tree) {
   848         // Local classes have not been entered yet, so we need to do it now:
   849         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   850             enter.classEnter(tree, env);
   852         ClassSymbol c = tree.sym;
   853         if (c == null) {
   854             // exit in case something drastic went wrong during enter.
   855             result = null;
   856         } else {
   857             // make sure class has been completed:
   858             c.complete();
   860             // If this class appears as an anonymous class
   861             // in a superclass constructor call where
   862             // no explicit outer instance is given,
   863             // disable implicit outer instance from being passed.
   864             // (This would be an illegal access to "this before super").
   865             if (env.info.isSelfCall &&
   866                 env.tree.hasTag(NEWCLASS) &&
   867                 ((JCNewClass) env.tree).encl == null)
   868             {
   869                 c.flags_field |= NOOUTERTHIS;
   870             }
   871             attribClass(tree.pos(), c);
   872             result = tree.type = c.type;
   873         }
   874     }
   876     public void visitMethodDef(JCMethodDecl tree) {
   877         MethodSymbol m = tree.sym;
   878         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   880         Lint lint = env.info.lint.augment(m);
   881         Lint prevLint = chk.setLint(lint);
   882         MethodSymbol prevMethod = chk.setMethod(m);
   883         try {
   884             deferredLintHandler.flush(tree.pos());
   885             chk.checkDeprecatedAnnotation(tree.pos(), m);
   888             // Create a new environment with local scope
   889             // for attributing the method.
   890             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   891             localEnv.info.lint = lint;
   893             attribStats(tree.typarams, localEnv);
   895             // If we override any other methods, check that we do so properly.
   896             // JLS ???
   897             if (m.isStatic()) {
   898                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   899             } else {
   900                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   901             }
   902             chk.checkOverride(tree, m);
   904             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   905                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   906             }
   908             // Enter all type parameters into the local method scope.
   909             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   910                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   912             ClassSymbol owner = env.enclClass.sym;
   913             if ((owner.flags() & ANNOTATION) != 0 &&
   914                 tree.params.nonEmpty())
   915                 log.error(tree.params.head.pos(),
   916                           "intf.annotation.members.cant.have.params");
   918             // Attribute all value parameters.
   919             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   920                 attribStat(l.head, localEnv);
   921             }
   923             chk.checkVarargsMethodDecl(localEnv, tree);
   925             // Check that type parameters are well-formed.
   926             chk.validate(tree.typarams, localEnv);
   928             // Check that result type is well-formed.
   929             chk.validate(tree.restype, localEnv);
   931             // Check that receiver type is well-formed.
   932             if (tree.recvparam != null) {
   933                 // Use a new environment to check the receiver parameter.
   934                 // Otherwise I get "might not have been initialized" errors.
   935                 // Is there a better way?
   936                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   937                 attribType(tree.recvparam, newEnv);
   938                 chk.validate(tree.recvparam, newEnv);
   939             }
   941             // annotation method checks
   942             if ((owner.flags() & ANNOTATION) != 0) {
   943                 // annotation method cannot have throws clause
   944                 if (tree.thrown.nonEmpty()) {
   945                     log.error(tree.thrown.head.pos(),
   946                             "throws.not.allowed.in.intf.annotation");
   947                 }
   948                 // annotation method cannot declare type-parameters
   949                 if (tree.typarams.nonEmpty()) {
   950                     log.error(tree.typarams.head.pos(),
   951                             "intf.annotation.members.cant.have.type.params");
   952                 }
   953                 // validate annotation method's return type (could be an annotation type)
   954                 chk.validateAnnotationType(tree.restype);
   955                 // ensure that annotation method does not clash with members of Object/Annotation
   956                 chk.validateAnnotationMethod(tree.pos(), m);
   958                 if (tree.defaultValue != null) {
   959                     // if default value is an annotation, check it is a well-formed
   960                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   961                     chk.validateAnnotationTree(tree.defaultValue);
   962                 }
   963             }
   965             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   966                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   968             if (tree.body == null) {
   969                 // Empty bodies are only allowed for
   970                 // abstract, native, or interface methods, or for methods
   971                 // in a retrofit signature class.
   972                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   973                     !relax)
   974                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   975                 if (tree.defaultValue != null) {
   976                     if ((owner.flags() & ANNOTATION) == 0)
   977                         log.error(tree.pos(),
   978                                   "default.allowed.in.intf.annotation.member");
   979                 }
   980             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   981                 if ((owner.flags() & INTERFACE) != 0) {
   982                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   983                 } else {
   984                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   985                 }
   986             } else if ((tree.mods.flags & NATIVE) != 0) {
   987                 log.error(tree.pos(), "native.meth.cant.have.body");
   988             } else {
   989                 // Add an implicit super() call unless an explicit call to
   990                 // super(...) or this(...) is given
   991                 // or we are compiling class java.lang.Object.
   992                 if (tree.name == names.init && owner.type != syms.objectType) {
   993                     JCBlock body = tree.body;
   994                     if (body.stats.isEmpty() ||
   995                         !TreeInfo.isSelfCall(body.stats.head)) {
   996                         body.stats = body.stats.
   997                             prepend(memberEnter.SuperCall(make.at(body.pos),
   998                                                           List.<Type>nil(),
   999                                                           List.<JCVariableDecl>nil(),
  1000                                                           false));
  1001                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1002                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1003                                TreeInfo.isSuperCall(body.stats.head)) {
  1004                         // enum constructors are not allowed to call super
  1005                         // directly, so make sure there aren't any super calls
  1006                         // in enum constructors, except in the compiler
  1007                         // generated one.
  1008                         log.error(tree.body.stats.head.pos(),
  1009                                   "call.to.super.not.allowed.in.enum.ctor",
  1010                                   env.enclClass.sym);
  1014                 // Attribute all type annotations in the body
  1015                 memberEnter.typeAnnotate(tree.body, localEnv, m);
  1016                 annotate.flush();
  1018                 // Attribute method body.
  1019                 attribStat(tree.body, localEnv);
  1022             localEnv.info.scope.leave();
  1023             result = tree.type = m.type;
  1024             chk.validateAnnotations(tree.mods.annotations, m);
  1026         finally {
  1027             chk.setLint(prevLint);
  1028             chk.setMethod(prevMethod);
  1032     public void visitVarDef(JCVariableDecl tree) {
  1033         // Local variables have not been entered yet, so we need to do it now:
  1034         if (env.info.scope.owner.kind == MTH) {
  1035             if (tree.sym != null) {
  1036                 // parameters have already been entered
  1037                 env.info.scope.enter(tree.sym);
  1038             } else {
  1039                 memberEnter.memberEnter(tree, env);
  1040                 annotate.flush();
  1042         } else {
  1043             if (tree.init != null) {
  1044                 // Field initializer expression need to be entered.
  1045                 memberEnter.typeAnnotate(tree.init, env, tree.sym);
  1046                 annotate.flush();
  1050         VarSymbol v = tree.sym;
  1051         Lint lint = env.info.lint.augment(v);
  1052         Lint prevLint = chk.setLint(lint);
  1054         // Check that the variable's declared type is well-formed.
  1055         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1056                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1057                 (tree.sym.flags() & PARAMETER) != 0;
  1058         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1059         deferredLintHandler.flush(tree.pos());
  1061         try {
  1062             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1064             if (tree.init != null) {
  1065                 if ((v.flags_field & FINAL) != 0 &&
  1066                         !tree.init.hasTag(NEWCLASS) &&
  1067                         !tree.init.hasTag(LAMBDA) &&
  1068                         !tree.init.hasTag(REFERENCE)) {
  1069                     // In this case, `v' is final.  Ensure that it's initializer is
  1070                     // evaluated.
  1071                     v.getConstValue(); // ensure initializer is evaluated
  1072                 } else {
  1073                     // Attribute initializer in a new environment
  1074                     // with the declared variable as owner.
  1075                     // Check that initializer conforms to variable's declared type.
  1076                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1077                     initEnv.info.lint = lint;
  1078                     // In order to catch self-references, we set the variable's
  1079                     // declaration position to maximal possible value, effectively
  1080                     // marking the variable as undefined.
  1081                     initEnv.info.enclVar = v;
  1082                     attribExpr(tree.init, initEnv, v.type);
  1085             result = tree.type = v.type;
  1086             chk.validateAnnotations(tree.mods.annotations, v);
  1088         finally {
  1089             chk.setLint(prevLint);
  1093     public void visitSkip(JCSkip tree) {
  1094         result = null;
  1097     public void visitBlock(JCBlock tree) {
  1098         if (env.info.scope.owner.kind == TYP) {
  1099             // Block is a static or instance initializer;
  1100             // let the owner of the environment be a freshly
  1101             // created BLOCK-method.
  1102             Env<AttrContext> localEnv =
  1103                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1104             localEnv.info.scope.owner =
  1105                 new MethodSymbol(tree.flags | BLOCK |
  1106                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1107                     env.info.scope.owner);
  1108             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1110             // Attribute all type annotations in the block
  1111             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner);
  1112             annotate.flush();
  1115                 // Store init and clinit type annotations with the ClassSymbol
  1116                 // to allow output in Gen.normalizeDefs.
  1117                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1118                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1119                 if ((tree.flags & STATIC) != 0) {
  1120                     cs.appendClassInitTypeAttributes(tas);
  1121                 } else {
  1122                     cs.appendInitTypeAttributes(tas);
  1126             attribStats(tree.stats, localEnv);
  1127         } else {
  1128             // Create a new local environment with a local scope.
  1129             Env<AttrContext> localEnv =
  1130                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1131             try {
  1132                 attribStats(tree.stats, localEnv);
  1133             } finally {
  1134                 localEnv.info.scope.leave();
  1137         result = null;
  1140     public void visitDoLoop(JCDoWhileLoop tree) {
  1141         attribStat(tree.body, env.dup(tree));
  1142         attribExpr(tree.cond, env, syms.booleanType);
  1143         result = null;
  1146     public void visitWhileLoop(JCWhileLoop tree) {
  1147         attribExpr(tree.cond, env, syms.booleanType);
  1148         attribStat(tree.body, env.dup(tree));
  1149         result = null;
  1152     public void visitForLoop(JCForLoop tree) {
  1153         Env<AttrContext> loopEnv =
  1154             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1155         try {
  1156             attribStats(tree.init, loopEnv);
  1157             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1158             loopEnv.tree = tree; // before, we were not in loop!
  1159             attribStats(tree.step, loopEnv);
  1160             attribStat(tree.body, loopEnv);
  1161             result = null;
  1163         finally {
  1164             loopEnv.info.scope.leave();
  1168     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1169         Env<AttrContext> loopEnv =
  1170             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1171         try {
  1172             //the Formal Parameter of a for-each loop is not in the scope when
  1173             //attributing the for-each expression; we mimick this by attributing
  1174             //the for-each expression first (against original scope).
  1175             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1176             attribStat(tree.var, loopEnv);
  1177             chk.checkNonVoid(tree.pos(), exprType);
  1178             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1179             if (elemtype == null) {
  1180                 // or perhaps expr implements Iterable<T>?
  1181                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1182                 if (base == null) {
  1183                     log.error(tree.expr.pos(),
  1184                             "foreach.not.applicable.to.type",
  1185                             exprType,
  1186                             diags.fragment("type.req.array.or.iterable"));
  1187                     elemtype = types.createErrorType(exprType);
  1188                 } else {
  1189                     List<Type> iterableParams = base.allparams();
  1190                     elemtype = iterableParams.isEmpty()
  1191                         ? syms.objectType
  1192                         : types.upperBound(iterableParams.head);
  1195             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1196             loopEnv.tree = tree; // before, we were not in loop!
  1197             attribStat(tree.body, loopEnv);
  1198             result = null;
  1200         finally {
  1201             loopEnv.info.scope.leave();
  1205     public void visitLabelled(JCLabeledStatement tree) {
  1206         // Check that label is not used in an enclosing statement
  1207         Env<AttrContext> env1 = env;
  1208         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1209             if (env1.tree.hasTag(LABELLED) &&
  1210                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1211                 log.error(tree.pos(), "label.already.in.use",
  1212                           tree.label);
  1213                 break;
  1215             env1 = env1.next;
  1218         attribStat(tree.body, env.dup(tree));
  1219         result = null;
  1222     public void visitSwitch(JCSwitch tree) {
  1223         Type seltype = attribExpr(tree.selector, env);
  1225         Env<AttrContext> switchEnv =
  1226             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1228         try {
  1230             boolean enumSwitch =
  1231                 allowEnums &&
  1232                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1233             boolean stringSwitch = false;
  1234             if (types.isSameType(seltype, syms.stringType)) {
  1235                 if (allowStringsInSwitch) {
  1236                     stringSwitch = true;
  1237                 } else {
  1238                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1241             if (!enumSwitch && !stringSwitch)
  1242                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1244             // Attribute all cases and
  1245             // check that there are no duplicate case labels or default clauses.
  1246             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1247             boolean hasDefault = false;      // Is there a default label?
  1248             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1249                 JCCase c = l.head;
  1250                 Env<AttrContext> caseEnv =
  1251                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1252                 try {
  1253                     if (c.pat != null) {
  1254                         if (enumSwitch) {
  1255                             Symbol sym = enumConstant(c.pat, seltype);
  1256                             if (sym == null) {
  1257                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1258                             } else if (!labels.add(sym)) {
  1259                                 log.error(c.pos(), "duplicate.case.label");
  1261                         } else {
  1262                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1263                             if (!pattype.hasTag(ERROR)) {
  1264                                 if (pattype.constValue() == null) {
  1265                                     log.error(c.pat.pos(),
  1266                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1267                                 } else if (labels.contains(pattype.constValue())) {
  1268                                     log.error(c.pos(), "duplicate.case.label");
  1269                                 } else {
  1270                                     labels.add(pattype.constValue());
  1274                     } else if (hasDefault) {
  1275                         log.error(c.pos(), "duplicate.default.label");
  1276                     } else {
  1277                         hasDefault = true;
  1279                     attribStats(c.stats, caseEnv);
  1280                 } finally {
  1281                     caseEnv.info.scope.leave();
  1282                     addVars(c.stats, switchEnv.info.scope);
  1286             result = null;
  1288         finally {
  1289             switchEnv.info.scope.leave();
  1292     // where
  1293         /** Add any variables defined in stats to the switch scope. */
  1294         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1295             for (;stats.nonEmpty(); stats = stats.tail) {
  1296                 JCTree stat = stats.head;
  1297                 if (stat.hasTag(VARDEF))
  1298                     switchScope.enter(((JCVariableDecl) stat).sym);
  1301     // where
  1302     /** Return the selected enumeration constant symbol, or null. */
  1303     private Symbol enumConstant(JCTree tree, Type enumType) {
  1304         if (!tree.hasTag(IDENT)) {
  1305             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1306             return syms.errSymbol;
  1308         JCIdent ident = (JCIdent)tree;
  1309         Name name = ident.name;
  1310         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1311              e.scope != null; e = e.next()) {
  1312             if (e.sym.kind == VAR) {
  1313                 Symbol s = ident.sym = e.sym;
  1314                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1315                 ident.type = s.type;
  1316                 return ((s.flags_field & Flags.ENUM) == 0)
  1317                     ? null : s;
  1320         return null;
  1323     public void visitSynchronized(JCSynchronized tree) {
  1324         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1325         attribStat(tree.body, env);
  1326         result = null;
  1329     public void visitTry(JCTry tree) {
  1330         // Create a new local environment with a local
  1331         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1332         try {
  1333             boolean isTryWithResource = tree.resources.nonEmpty();
  1334             // Create a nested environment for attributing the try block if needed
  1335             Env<AttrContext> tryEnv = isTryWithResource ?
  1336                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1337                 localEnv;
  1338             try {
  1339                 // Attribute resource declarations
  1340                 for (JCTree resource : tree.resources) {
  1341                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1342                         @Override
  1343                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1344                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1346                     };
  1347                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1348                     if (resource.hasTag(VARDEF)) {
  1349                         attribStat(resource, tryEnv);
  1350                         twrResult.check(resource, resource.type);
  1352                         //check that resource type cannot throw InterruptedException
  1353                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1355                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1356                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1357                     } else {
  1358                         attribTree(resource, tryEnv, twrResult);
  1361                 // Attribute body
  1362                 attribStat(tree.body, tryEnv);
  1363             } finally {
  1364                 if (isTryWithResource)
  1365                     tryEnv.info.scope.leave();
  1368             // Attribute catch clauses
  1369             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1370                 JCCatch c = l.head;
  1371                 Env<AttrContext> catchEnv =
  1372                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1373                 try {
  1374                     Type ctype = attribStat(c.param, catchEnv);
  1375                     if (TreeInfo.isMultiCatch(c)) {
  1376                         //multi-catch parameter is implicitly marked as final
  1377                         c.param.sym.flags_field |= FINAL | UNION;
  1379                     if (c.param.sym.kind == Kinds.VAR) {
  1380                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1382                     chk.checkType(c.param.vartype.pos(),
  1383                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1384                                   syms.throwableType);
  1385                     attribStat(c.body, catchEnv);
  1386                 } finally {
  1387                     catchEnv.info.scope.leave();
  1391             // Attribute finalizer
  1392             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1393             result = null;
  1395         finally {
  1396             localEnv.info.scope.leave();
  1400     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1401         if (!resource.isErroneous() &&
  1402             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1403             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1404             Symbol close = syms.noSymbol;
  1405             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1406             try {
  1407                 close = rs.resolveQualifiedMethod(pos,
  1408                         env,
  1409                         resource,
  1410                         names.close,
  1411                         List.<Type>nil(),
  1412                         List.<Type>nil());
  1414             finally {
  1415                 log.popDiagnosticHandler(discardHandler);
  1417             if (close.kind == MTH &&
  1418                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1419                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1420                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1421                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1426     public void visitConditional(JCConditional tree) {
  1427         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1429         tree.polyKind = (!allowPoly ||
  1430                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1431                 isBooleanOrNumeric(env, tree)) ?
  1432                 PolyKind.STANDALONE : PolyKind.POLY;
  1434         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1435             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1436             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1437             result = tree.type = types.createErrorType(resultInfo.pt);
  1438             return;
  1441         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1442                 unknownExprInfo :
  1443                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1444                     //this will use enclosing check context to check compatibility of
  1445                     //subexpression against target type; if we are in a method check context,
  1446                     //depending on whether boxing is allowed, we could have incompatibilities
  1447                     @Override
  1448                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1449                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1451                 });
  1453         Type truetype = attribTree(tree.truepart, env, condInfo);
  1454         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1456         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1457         if (condtype.constValue() != null &&
  1458                 truetype.constValue() != null &&
  1459                 falsetype.constValue() != null &&
  1460                 !owntype.hasTag(NONE)) {
  1461             //constant folding
  1462             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1464         result = check(tree, owntype, VAL, resultInfo);
  1466     //where
  1467         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1468             switch (tree.getTag()) {
  1469                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1470                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1471                               ((JCLiteral)tree).typetag == BOT;
  1472                 case LAMBDA: case REFERENCE: return false;
  1473                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1474                 case CONDEXPR:
  1475                     JCConditional condTree = (JCConditional)tree;
  1476                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1477                             isBooleanOrNumeric(env, condTree.falsepart);
  1478                 case APPLY:
  1479                     JCMethodInvocation speculativeMethodTree =
  1480                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1481                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1482                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1483                 case NEWCLASS:
  1484                     JCExpression className =
  1485                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1486                     JCExpression speculativeNewClassTree =
  1487                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1488                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1489                 default:
  1490                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1491                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1492                     return speculativeType.isPrimitive();
  1495         //where
  1496             TreeTranslator removeClassParams = new TreeTranslator() {
  1497                 @Override
  1498                 public void visitTypeApply(JCTypeApply tree) {
  1499                     result = translate(tree.clazz);
  1501             };
  1503         /** Compute the type of a conditional expression, after
  1504          *  checking that it exists.  See JLS 15.25. Does not take into
  1505          *  account the special case where condition and both arms
  1506          *  are constants.
  1508          *  @param pos      The source position to be used for error
  1509          *                  diagnostics.
  1510          *  @param thentype The type of the expression's then-part.
  1511          *  @param elsetype The type of the expression's else-part.
  1512          */
  1513         private Type condType(DiagnosticPosition pos,
  1514                                Type thentype, Type elsetype) {
  1515             // If same type, that is the result
  1516             if (types.isSameType(thentype, elsetype))
  1517                 return thentype.baseType();
  1519             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1520                 ? thentype : types.unboxedType(thentype);
  1521             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1522                 ? elsetype : types.unboxedType(elsetype);
  1524             // Otherwise, if both arms can be converted to a numeric
  1525             // type, return the least numeric type that fits both arms
  1526             // (i.e. return larger of the two, or return int if one
  1527             // arm is short, the other is char).
  1528             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1529                 // If one arm has an integer subrange type (i.e., byte,
  1530                 // short, or char), and the other is an integer constant
  1531                 // that fits into the subrange, return the subrange type.
  1532                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1533                     elseUnboxed.hasTag(INT) &&
  1534                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1535                     return thenUnboxed.baseType();
  1537                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1538                     thenUnboxed.hasTag(INT) &&
  1539                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1540                     return elseUnboxed.baseType();
  1543                 for (TypeTag tag : primitiveTags) {
  1544                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1545                     if (types.isSubtype(thenUnboxed, candidate) &&
  1546                         types.isSubtype(elseUnboxed, candidate)) {
  1547                         return candidate;
  1552             // Those were all the cases that could result in a primitive
  1553             if (allowBoxing) {
  1554                 if (thentype.isPrimitive())
  1555                     thentype = types.boxedClass(thentype).type;
  1556                 if (elsetype.isPrimitive())
  1557                     elsetype = types.boxedClass(elsetype).type;
  1560             if (types.isSubtype(thentype, elsetype))
  1561                 return elsetype.baseType();
  1562             if (types.isSubtype(elsetype, thentype))
  1563                 return thentype.baseType();
  1565             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1566                 log.error(pos, "neither.conditional.subtype",
  1567                           thentype, elsetype);
  1568                 return thentype.baseType();
  1571             // both are known to be reference types.  The result is
  1572             // lub(thentype,elsetype). This cannot fail, as it will
  1573             // always be possible to infer "Object" if nothing better.
  1574             return types.lub(thentype.baseType(), elsetype.baseType());
  1577     final static TypeTag[] primitiveTags = new TypeTag[]{
  1578         BYTE,
  1579         CHAR,
  1580         SHORT,
  1581         INT,
  1582         LONG,
  1583         FLOAT,
  1584         DOUBLE,
  1585         BOOLEAN,
  1586     };
  1588     public void visitIf(JCIf tree) {
  1589         attribExpr(tree.cond, env, syms.booleanType);
  1590         attribStat(tree.thenpart, env);
  1591         if (tree.elsepart != null)
  1592             attribStat(tree.elsepart, env);
  1593         chk.checkEmptyIf(tree);
  1594         result = null;
  1597     public void visitExec(JCExpressionStatement tree) {
  1598         //a fresh environment is required for 292 inference to work properly ---
  1599         //see Infer.instantiatePolymorphicSignatureInstance()
  1600         Env<AttrContext> localEnv = env.dup(tree);
  1601         attribExpr(tree.expr, localEnv);
  1602         result = null;
  1605     public void visitBreak(JCBreak tree) {
  1606         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1607         result = null;
  1610     public void visitContinue(JCContinue tree) {
  1611         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1612         result = null;
  1614     //where
  1615         /** Return the target of a break or continue statement, if it exists,
  1616          *  report an error if not.
  1617          *  Note: The target of a labelled break or continue is the
  1618          *  (non-labelled) statement tree referred to by the label,
  1619          *  not the tree representing the labelled statement itself.
  1621          *  @param pos     The position to be used for error diagnostics
  1622          *  @param tag     The tag of the jump statement. This is either
  1623          *                 Tree.BREAK or Tree.CONTINUE.
  1624          *  @param label   The label of the jump statement, or null if no
  1625          *                 label is given.
  1626          *  @param env     The environment current at the jump statement.
  1627          */
  1628         private JCTree findJumpTarget(DiagnosticPosition pos,
  1629                                     JCTree.Tag tag,
  1630                                     Name label,
  1631                                     Env<AttrContext> env) {
  1632             // Search environments outwards from the point of jump.
  1633             Env<AttrContext> env1 = env;
  1634             LOOP:
  1635             while (env1 != null) {
  1636                 switch (env1.tree.getTag()) {
  1637                     case LABELLED:
  1638                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1639                         if (label == labelled.label) {
  1640                             // If jump is a continue, check that target is a loop.
  1641                             if (tag == CONTINUE) {
  1642                                 if (!labelled.body.hasTag(DOLOOP) &&
  1643                                         !labelled.body.hasTag(WHILELOOP) &&
  1644                                         !labelled.body.hasTag(FORLOOP) &&
  1645                                         !labelled.body.hasTag(FOREACHLOOP))
  1646                                     log.error(pos, "not.loop.label", label);
  1647                                 // Found labelled statement target, now go inwards
  1648                                 // to next non-labelled tree.
  1649                                 return TreeInfo.referencedStatement(labelled);
  1650                             } else {
  1651                                 return labelled;
  1654                         break;
  1655                     case DOLOOP:
  1656                     case WHILELOOP:
  1657                     case FORLOOP:
  1658                     case FOREACHLOOP:
  1659                         if (label == null) return env1.tree;
  1660                         break;
  1661                     case SWITCH:
  1662                         if (label == null && tag == BREAK) return env1.tree;
  1663                         break;
  1664                     case LAMBDA:
  1665                     case METHODDEF:
  1666                     case CLASSDEF:
  1667                         break LOOP;
  1668                     default:
  1670                 env1 = env1.next;
  1672             if (label != null)
  1673                 log.error(pos, "undef.label", label);
  1674             else if (tag == CONTINUE)
  1675                 log.error(pos, "cont.outside.loop");
  1676             else
  1677                 log.error(pos, "break.outside.switch.loop");
  1678             return null;
  1681     public void visitReturn(JCReturn tree) {
  1682         // Check that there is an enclosing method which is
  1683         // nested within than the enclosing class.
  1684         if (env.info.returnResult == null) {
  1685             log.error(tree.pos(), "ret.outside.meth");
  1686         } else {
  1687             // Attribute return expression, if it exists, and check that
  1688             // it conforms to result type of enclosing method.
  1689             if (tree.expr != null) {
  1690                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1691                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1692                               diags.fragment("unexpected.ret.val"));
  1694                 attribTree(tree.expr, env, env.info.returnResult);
  1695             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1696                     !env.info.returnResult.pt.hasTag(NONE)) {
  1697                 env.info.returnResult.checkContext.report(tree.pos(),
  1698                               diags.fragment("missing.ret.val"));
  1701         result = null;
  1704     public void visitThrow(JCThrow tree) {
  1705         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1706         if (allowPoly) {
  1707             chk.checkType(tree, owntype, syms.throwableType);
  1709         result = null;
  1712     public void visitAssert(JCAssert tree) {
  1713         attribExpr(tree.cond, env, syms.booleanType);
  1714         if (tree.detail != null) {
  1715             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1717         result = null;
  1720      /** Visitor method for method invocations.
  1721      *  NOTE: The method part of an application will have in its type field
  1722      *        the return type of the method, not the method's type itself!
  1723      */
  1724     public void visitApply(JCMethodInvocation tree) {
  1725         // The local environment of a method application is
  1726         // a new environment nested in the current one.
  1727         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1729         // The types of the actual method arguments.
  1730         List<Type> argtypes;
  1732         // The types of the actual method type arguments.
  1733         List<Type> typeargtypes = null;
  1735         Name methName = TreeInfo.name(tree.meth);
  1737         boolean isConstructorCall =
  1738             methName == names._this || methName == names._super;
  1740         ListBuffer<Type> argtypesBuf = ListBuffer.lb();
  1741         if (isConstructorCall) {
  1742             // We are seeing a ...this(...) or ...super(...) call.
  1743             // Check that this is the first statement in a constructor.
  1744             if (checkFirstConstructorStat(tree, env)) {
  1746                 // Record the fact
  1747                 // that this is a constructor call (using isSelfCall).
  1748                 localEnv.info.isSelfCall = true;
  1750                 // Attribute arguments, yielding list of argument types.
  1751                 attribArgs(tree.args, localEnv, argtypesBuf);
  1752                 argtypes = argtypesBuf.toList();
  1753                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1755                 // Variable `site' points to the class in which the called
  1756                 // constructor is defined.
  1757                 Type site = env.enclClass.sym.type;
  1758                 if (methName == names._super) {
  1759                     if (site == syms.objectType) {
  1760                         log.error(tree.meth.pos(), "no.superclass", site);
  1761                         site = types.createErrorType(syms.objectType);
  1762                     } else {
  1763                         site = types.supertype(site);
  1767                 if (site.hasTag(CLASS)) {
  1768                     Type encl = site.getEnclosingType();
  1769                     while (encl != null && encl.hasTag(TYPEVAR))
  1770                         encl = encl.getUpperBound();
  1771                     if (encl.hasTag(CLASS)) {
  1772                         // we are calling a nested class
  1774                         if (tree.meth.hasTag(SELECT)) {
  1775                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1777                             // We are seeing a prefixed call, of the form
  1778                             //     <expr>.super(...).
  1779                             // Check that the prefix expression conforms
  1780                             // to the outer instance type of the class.
  1781                             chk.checkRefType(qualifier.pos(),
  1782                                              attribExpr(qualifier, localEnv,
  1783                                                         encl));
  1784                         } else if (methName == names._super) {
  1785                             // qualifier omitted; check for existence
  1786                             // of an appropriate implicit qualifier.
  1787                             rs.resolveImplicitThis(tree.meth.pos(),
  1788                                                    localEnv, site, true);
  1790                     } else if (tree.meth.hasTag(SELECT)) {
  1791                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1792                                   site.tsym);
  1795                     // if we're calling a java.lang.Enum constructor,
  1796                     // prefix the implicit String and int parameters
  1797                     if (site.tsym == syms.enumSym && allowEnums)
  1798                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1800                     // Resolve the called constructor under the assumption
  1801                     // that we are referring to a superclass instance of the
  1802                     // current instance (JLS ???).
  1803                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1804                     localEnv.info.selectSuper = true;
  1805                     localEnv.info.pendingResolutionPhase = null;
  1806                     Symbol sym = rs.resolveConstructor(
  1807                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1808                     localEnv.info.selectSuper = selectSuperPrev;
  1810                     // Set method symbol to resolved constructor...
  1811                     TreeInfo.setSymbol(tree.meth, sym);
  1813                     // ...and check that it is legal in the current context.
  1814                     // (this will also set the tree's type)
  1815                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1816                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1818                 // Otherwise, `site' is an error type and we do nothing
  1820             result = tree.type = syms.voidType;
  1821         } else {
  1822             // Otherwise, we are seeing a regular method call.
  1823             // Attribute the arguments, yielding list of argument types, ...
  1824             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1825             argtypes = argtypesBuf.toList();
  1826             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1828             // ... and attribute the method using as a prototype a methodtype
  1829             // whose formal argument types is exactly the list of actual
  1830             // arguments (this will also set the method symbol).
  1831             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1832             localEnv.info.pendingResolutionPhase = null;
  1833             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1835             // Compute the result type.
  1836             Type restype = mtype.getReturnType();
  1837             if (restype.hasTag(WILDCARD))
  1838                 throw new AssertionError(mtype);
  1840             Type qualifier = (tree.meth.hasTag(SELECT))
  1841                     ? ((JCFieldAccess) tree.meth).selected.type
  1842                     : env.enclClass.sym.type;
  1843             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1845             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1847             // Check that value of resulting type is admissible in the
  1848             // current context.  Also, capture the return type
  1849             result = check(tree, capture(restype), VAL, resultInfo);
  1851         chk.validate(tree.typeargs, localEnv);
  1853     //where
  1854         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1855             if (allowCovariantReturns &&
  1856                     methodName == names.clone &&
  1857                 types.isArray(qualifierType)) {
  1858                 // as a special case, array.clone() has a result that is
  1859                 // the same as static type of the array being cloned
  1860                 return qualifierType;
  1861             } else if (allowGenerics &&
  1862                     methodName == names.getClass &&
  1863                     argtypes.isEmpty()) {
  1864                 // as a special case, x.getClass() has type Class<? extends |X|>
  1865                 return new ClassType(restype.getEnclosingType(),
  1866                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1867                                                                BoundKind.EXTENDS,
  1868                                                                syms.boundClass)),
  1869                               restype.tsym);
  1870             } else {
  1871                 return restype;
  1875         /** Check that given application node appears as first statement
  1876          *  in a constructor call.
  1877          *  @param tree   The application node
  1878          *  @param env    The environment current at the application.
  1879          */
  1880         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1881             JCMethodDecl enclMethod = env.enclMethod;
  1882             if (enclMethod != null && enclMethod.name == names.init) {
  1883                 JCBlock body = enclMethod.body;
  1884                 if (body.stats.head.hasTag(EXEC) &&
  1885                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1886                     return true;
  1888             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1889                       TreeInfo.name(tree.meth));
  1890             return false;
  1893         /** Obtain a method type with given argument types.
  1894          */
  1895         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1896             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1897             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1900     public void visitNewClass(final JCNewClass tree) {
  1901         Type owntype = types.createErrorType(tree.type);
  1903         // The local environment of a class creation is
  1904         // a new environment nested in the current one.
  1905         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1907         // The anonymous inner class definition of the new expression,
  1908         // if one is defined by it.
  1909         JCClassDecl cdef = tree.def;
  1911         // If enclosing class is given, attribute it, and
  1912         // complete class name to be fully qualified
  1913         JCExpression clazz = tree.clazz; // Class field following new
  1914         JCExpression clazzid;            // Identifier in class field
  1915         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1916         annoclazzid = null;
  1918         if (clazz.hasTag(TYPEAPPLY)) {
  1919             clazzid = ((JCTypeApply) clazz).clazz;
  1920             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1921                 annoclazzid = (JCAnnotatedType) clazzid;
  1922                 clazzid = annoclazzid.underlyingType;
  1924         } else {
  1925             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1926                 annoclazzid = (JCAnnotatedType) clazz;
  1927                 clazzid = annoclazzid.underlyingType;
  1928             } else {
  1929                 clazzid = clazz;
  1933         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1935         if (tree.encl != null) {
  1936             // We are seeing a qualified new, of the form
  1937             //    <expr>.new C <...> (...) ...
  1938             // In this case, we let clazz stand for the name of the
  1939             // allocated class C prefixed with the type of the qualifier
  1940             // expression, so that we can
  1941             // resolve it with standard techniques later. I.e., if
  1942             // <expr> has type T, then <expr>.new C <...> (...)
  1943             // yields a clazz T.C.
  1944             Type encltype = chk.checkRefType(tree.encl.pos(),
  1945                                              attribExpr(tree.encl, env));
  1946             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1947             // from expr to the combined type, or not? Yes, do this.
  1948             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1949                                                  ((JCIdent) clazzid).name);
  1951             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1952                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1953                 List<JCAnnotation> annos = annoType.annotations;
  1955                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1956                     clazzid1 = make.at(tree.pos).
  1957                         TypeApply(clazzid1,
  1958                                   ((JCTypeApply) clazz).arguments);
  1961                 clazzid1 = make.at(tree.pos).
  1962                     AnnotatedType(annos, clazzid1);
  1963             } else if (clazz.hasTag(TYPEAPPLY)) {
  1964                 clazzid1 = make.at(tree.pos).
  1965                     TypeApply(clazzid1,
  1966                               ((JCTypeApply) clazz).arguments);
  1969             clazz = clazzid1;
  1972         // Attribute clazz expression and store
  1973         // symbol + type back into the attributed tree.
  1974         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1975             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1976             attribType(clazz, env);
  1978         clazztype = chk.checkDiamond(tree, clazztype);
  1979         chk.validate(clazz, localEnv);
  1980         if (tree.encl != null) {
  1981             // We have to work in this case to store
  1982             // symbol + type back into the attributed tree.
  1983             tree.clazz.type = clazztype;
  1984             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1985             clazzid.type = ((JCIdent) clazzid).sym.type;
  1986             if (annoclazzid != null) {
  1987                 annoclazzid.type = clazzid.type;
  1989             if (!clazztype.isErroneous()) {
  1990                 if (cdef != null && clazztype.tsym.isInterface()) {
  1991                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1992                 } else if (clazztype.tsym.isStatic()) {
  1993                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1996         } else if (!clazztype.tsym.isInterface() &&
  1997                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1998             // Check for the existence of an apropos outer instance
  1999             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  2002         // Attribute constructor arguments.
  2003         ListBuffer<Type> argtypesBuf = ListBuffer.lb();
  2004         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  2005         List<Type> argtypes = argtypesBuf.toList();
  2006         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  2008         // If we have made no mistakes in the class type...
  2009         if (clazztype.hasTag(CLASS)) {
  2010             // Enums may not be instantiated except implicitly
  2011             if (allowEnums &&
  2012                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  2013                 (!env.tree.hasTag(VARDEF) ||
  2014                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  2015                  ((JCVariableDecl) env.tree).init != tree))
  2016                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2017             // Check that class is not abstract
  2018             if (cdef == null &&
  2019                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2020                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2021                           clazztype.tsym);
  2022             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2023                 // Check that no constructor arguments are given to
  2024                 // anonymous classes implementing an interface
  2025                 if (!argtypes.isEmpty())
  2026                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2028                 if (!typeargtypes.isEmpty())
  2029                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2031                 // Error recovery: pretend no arguments were supplied.
  2032                 argtypes = List.nil();
  2033                 typeargtypes = List.nil();
  2034             } else if (TreeInfo.isDiamond(tree)) {
  2035                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2036                             clazztype.tsym.type.getTypeArguments(),
  2037                             clazztype.tsym);
  2039                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2040                 diamondEnv.info.selectSuper = cdef != null;
  2041                 diamondEnv.info.pendingResolutionPhase = null;
  2043                 //if the type of the instance creation expression is a class type
  2044                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2045                 //of the resolved constructor will be a partially instantiated type
  2046                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2047                             diamondEnv,
  2048                             site,
  2049                             argtypes,
  2050                             typeargtypes);
  2051                 tree.constructor = constructor.baseSymbol();
  2053                 final TypeSymbol csym = clazztype.tsym;
  2054                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2055                     @Override
  2056                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2057                         enclosingContext.report(tree.clazz,
  2058                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2060                 });
  2061                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2062                 constructorType = checkId(tree, site,
  2063                         constructor,
  2064                         diamondEnv,
  2065                         diamondResult);
  2067                 tree.clazz.type = types.createErrorType(clazztype);
  2068                 if (!constructorType.isErroneous()) {
  2069                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2070                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2072                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2075             // Resolve the called constructor under the assumption
  2076             // that we are referring to a superclass instance of the
  2077             // current instance (JLS ???).
  2078             else {
  2079                 //the following code alters some of the fields in the current
  2080                 //AttrContext - hence, the current context must be dup'ed in
  2081                 //order to avoid downstream failures
  2082                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2083                 rsEnv.info.selectSuper = cdef != null;
  2084                 rsEnv.info.pendingResolutionPhase = null;
  2085                 tree.constructor = rs.resolveConstructor(
  2086                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2087                 if (cdef == null) { //do not check twice!
  2088                     tree.constructorType = checkId(tree,
  2089                             clazztype,
  2090                             tree.constructor,
  2091                             rsEnv,
  2092                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2093                     if (rsEnv.info.lastResolveVarargs())
  2094                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2096                 if (cdef == null &&
  2097                         !clazztype.isErroneous() &&
  2098                         clazztype.getTypeArguments().nonEmpty() &&
  2099                         findDiamonds) {
  2100                     findDiamond(localEnv, tree, clazztype);
  2104             if (cdef != null) {
  2105                 // We are seeing an anonymous class instance creation.
  2106                 // In this case, the class instance creation
  2107                 // expression
  2108                 //
  2109                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2110                 //
  2111                 // is represented internally as
  2112                 //
  2113                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2114                 //
  2115                 // This expression is then *transformed* as follows:
  2116                 //
  2117                 // (1) add a STATIC flag to the class definition
  2118                 //     if the current environment is static
  2119                 // (2) add an extends or implements clause
  2120                 // (3) add a constructor.
  2121                 //
  2122                 // For instance, if C is a class, and ET is the type of E,
  2123                 // the expression
  2124                 //
  2125                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2126                 //
  2127                 // is translated to (where X is a fresh name and typarams is the
  2128                 // parameter list of the super constructor):
  2129                 //
  2130                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2131                 //     X extends C<typargs2> {
  2132                 //       <typarams> X(ET e, args) {
  2133                 //         e.<typeargs1>super(args)
  2134                 //       }
  2135                 //       ...
  2136                 //     }
  2137                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2139                 if (clazztype.tsym.isInterface()) {
  2140                     cdef.implementing = List.of(clazz);
  2141                 } else {
  2142                     cdef.extending = clazz;
  2145                 attribStat(cdef, localEnv);
  2147                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2149                 // If an outer instance is given,
  2150                 // prefix it to the constructor arguments
  2151                 // and delete it from the new expression
  2152                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2153                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2154                     argtypes = argtypes.prepend(tree.encl.type);
  2155                     tree.encl = null;
  2158                 // Reassign clazztype and recompute constructor.
  2159                 clazztype = cdef.sym.type;
  2160                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2161                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2162                 Assert.check(sym.kind < AMBIGUOUS);
  2163                 tree.constructor = sym;
  2164                 tree.constructorType = checkId(tree,
  2165                     clazztype,
  2166                     tree.constructor,
  2167                     localEnv,
  2168                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2169             } else {
  2170                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  2171                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  2172                             tree.clazz.type.tsym);
  2176             if (tree.constructor != null && tree.constructor.kind == MTH)
  2177                 owntype = clazztype;
  2179         result = check(tree, owntype, VAL, resultInfo);
  2180         chk.validate(tree.typeargs, localEnv);
  2182     //where
  2183         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2184             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2185             List<JCExpression> prevTypeargs = ta.arguments;
  2186             try {
  2187                 //create a 'fake' diamond AST node by removing type-argument trees
  2188                 ta.arguments = List.nil();
  2189                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2190                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2191                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2192                 Type polyPt = allowPoly ?
  2193                         syms.objectType :
  2194                         clazztype;
  2195                 if (!inferred.isErroneous() &&
  2196                     types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings)) {
  2197                     String key = types.isSameType(clazztype, inferred) ?
  2198                         "diamond.redundant.args" :
  2199                         "diamond.redundant.args.1";
  2200                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2202             } finally {
  2203                 ta.arguments = prevTypeargs;
  2207             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2208                 if (allowLambda &&
  2209                         identifyLambdaCandidate &&
  2210                         clazztype.hasTag(CLASS) &&
  2211                         !pt().hasTag(NONE) &&
  2212                         types.isFunctionalInterface(clazztype.tsym)) {
  2213                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2214                     int count = 0;
  2215                     boolean found = false;
  2216                     for (Symbol sym : csym.members().getElements()) {
  2217                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2218                                 sym.isConstructor()) continue;
  2219                         count++;
  2220                         if (sym.kind != MTH ||
  2221                                 !sym.name.equals(descriptor.name)) continue;
  2222                         Type mtype = types.memberType(clazztype, sym);
  2223                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2224                             found = true;
  2227                     if (found && count == 1) {
  2228                         log.note(tree.def, "potential.lambda.found");
  2233     private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  2234             Symbol sym) {
  2235         // Ensure that no declaration annotations are present.
  2236         // Note that a tree type might be an AnnotatedType with
  2237         // empty annotations, if only declaration annotations were given.
  2238         // This method will raise an error for such a type.
  2239         for (JCAnnotation ai : annotations) {
  2240             if (TypeAnnotations.annotationType(syms, names, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  2241                 log.error(ai.pos(), "annotation.type.not.applicable");
  2247     /** Make an attributed null check tree.
  2248      */
  2249     public JCExpression makeNullCheck(JCExpression arg) {
  2250         // optimization: X.this is never null; skip null check
  2251         Name name = TreeInfo.name(arg);
  2252         if (name == names._this || name == names._super) return arg;
  2254         JCTree.Tag optag = NULLCHK;
  2255         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2256         tree.operator = syms.nullcheck;
  2257         tree.type = arg.type;
  2258         return tree;
  2261     public void visitNewArray(JCNewArray tree) {
  2262         Type owntype = types.createErrorType(tree.type);
  2263         Env<AttrContext> localEnv = env.dup(tree);
  2264         Type elemtype;
  2265         if (tree.elemtype != null) {
  2266             elemtype = attribType(tree.elemtype, localEnv);
  2267             chk.validate(tree.elemtype, localEnv);
  2268             owntype = elemtype;
  2269             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2270                 attribExpr(l.head, localEnv, syms.intType);
  2271                 owntype = new ArrayType(owntype, syms.arrayClass);
  2273             if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  2274                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  2275                         tree.elemtype.type.tsym);
  2277         } else {
  2278             // we are seeing an untyped aggregate { ... }
  2279             // this is allowed only if the prototype is an array
  2280             if (pt().hasTag(ARRAY)) {
  2281                 elemtype = types.elemtype(pt());
  2282             } else {
  2283                 if (!pt().hasTag(ERROR)) {
  2284                     log.error(tree.pos(), "illegal.initializer.for.type",
  2285                               pt());
  2287                 elemtype = types.createErrorType(pt());
  2290         if (tree.elems != null) {
  2291             attribExprs(tree.elems, localEnv, elemtype);
  2292             owntype = new ArrayType(elemtype, syms.arrayClass);
  2294         if (!types.isReifiable(elemtype))
  2295             log.error(tree.pos(), "generic.array.creation");
  2296         result = check(tree, owntype, VAL, resultInfo);
  2299     /*
  2300      * A lambda expression can only be attributed when a target-type is available.
  2301      * In addition, if the target-type is that of a functional interface whose
  2302      * descriptor contains inference variables in argument position the lambda expression
  2303      * is 'stuck' (see DeferredAttr).
  2304      */
  2305     @Override
  2306     public void visitLambda(final JCLambda that) {
  2307         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2308             if (pt().hasTag(NONE)) {
  2309                 //lambda only allowed in assignment or method invocation/cast context
  2310                 log.error(that.pos(), "unexpected.lambda");
  2312             result = that.type = types.createErrorType(pt());
  2313             return;
  2315         //create an environment for attribution of the lambda expression
  2316         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2317         boolean needsRecovery =
  2318                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2319         try {
  2320             Type target = pt();
  2321             List<Type> explicitParamTypes = null;
  2322             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2323                 //attribute lambda parameters
  2324                 attribStats(that.params, localEnv);
  2325                 explicitParamTypes = TreeInfo.types(that.params);
  2326                 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
  2329             Type lambdaType;
  2330             if (pt() != Type.recoveryType) {
  2331                 target = targetChecker.visit(target, that);
  2332                 lambdaType = types.findDescriptorType(target);
  2333                 chk.checkFunctionalInterface(that, target);
  2334             } else {
  2335                 target = Type.recoveryType;
  2336                 lambdaType = fallbackDescriptorType(that);
  2339             setFunctionalInfo(that, pt(), lambdaType, target, resultInfo.checkContext.inferenceContext());
  2341             if (lambdaType.hasTag(FORALL)) {
  2342                 //lambda expression target desc cannot be a generic method
  2343                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2344                         lambdaType, kindName(target.tsym), target.tsym));
  2345                 result = that.type = types.createErrorType(pt());
  2346                 return;
  2349             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2350                 //add param type info in the AST
  2351                 List<Type> actuals = lambdaType.getParameterTypes();
  2352                 List<JCVariableDecl> params = that.params;
  2354                 boolean arityMismatch = false;
  2356                 while (params.nonEmpty()) {
  2357                     if (actuals.isEmpty()) {
  2358                         //not enough actuals to perform lambda parameter inference
  2359                         arityMismatch = true;
  2361                     //reset previously set info
  2362                     Type argType = arityMismatch ?
  2363                             syms.errType :
  2364                             actuals.head;
  2365                     params.head.vartype = make.at(params.head).Type(argType);
  2366                     params.head.sym = null;
  2367                     actuals = actuals.isEmpty() ?
  2368                             actuals :
  2369                             actuals.tail;
  2370                     params = params.tail;
  2373                 //attribute lambda parameters
  2374                 attribStats(that.params, localEnv);
  2376                 if (arityMismatch) {
  2377                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2378                         result = that.type = types.createErrorType(target);
  2379                         return;
  2383             //from this point on, no recovery is needed; if we are in assignment context
  2384             //we will be able to attribute the whole lambda body, regardless of errors;
  2385             //if we are in a 'check' method context, and the lambda is not compatible
  2386             //with the target-type, it will be recovered anyway in Attr.checkId
  2387             needsRecovery = false;
  2389             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2390                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2391                     new FunctionalReturnContext(resultInfo.checkContext);
  2393             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2394                 recoveryInfo :
  2395                 new LambdaResultInfo(lambdaType.getReturnType(), funcContext);
  2396             localEnv.info.returnResult = bodyResultInfo;
  2398             Log.DeferredDiagnosticHandler lambdaDeferredHandler = new Log.DeferredDiagnosticHandler(log);
  2399             try {
  2400                 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2401                     attribTree(that.getBody(), localEnv, bodyResultInfo);
  2402                 } else {
  2403                     JCBlock body = (JCBlock)that.body;
  2404                     attribStats(body.stats, localEnv);
  2407                 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.SPECULATIVE) {
  2408                     //check for errors in lambda body
  2409                     for (JCDiagnostic deferredDiag : lambdaDeferredHandler.getDiagnostics()) {
  2410                         if (deferredDiag.getKind() == JCDiagnostic.Kind.ERROR) {
  2411                             resultInfo.checkContext
  2412                                     .report(that, diags.fragment("bad.arg.types.in.lambda", TreeInfo.types(that.params),
  2413                                     deferredDiag)); //hidden diag parameter
  2414                             //we mark the lambda as erroneous - this is crucial in the recovery step
  2415                             //as parameter-dependent type error won't be reported in that stage,
  2416                             //meaning that a lambda will be deemed erroeneous only if there is
  2417                             //a target-independent error (which will cause method diagnostic
  2418                             //to be skipped).
  2419                             result = that.type = types.createErrorType(target);
  2420                             return;
  2424             } finally {
  2425                 lambdaDeferredHandler.reportDeferredDiagnostics();
  2426                 log.popDiagnosticHandler(lambdaDeferredHandler);
  2429             result = check(that, target, VAL, resultInfo);
  2431             boolean isSpeculativeRound =
  2432                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2434             postAttr(that);
  2435             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2437             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
  2439             if (!isSpeculativeRound) {
  2440                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
  2442             result = check(that, target, VAL, resultInfo);
  2443         } catch (Types.FunctionDescriptorLookupError ex) {
  2444             JCDiagnostic cause = ex.getDiagnostic();
  2445             resultInfo.checkContext.report(that, cause);
  2446             result = that.type = types.createErrorType(pt());
  2447             return;
  2448         } finally {
  2449             localEnv.info.scope.leave();
  2450             if (needsRecovery) {
  2451                 attribTree(that, env, recoveryInfo);
  2455     //where
  2456         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2458             @Override
  2459             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2460                 return t.isCompound() ?
  2461                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2464             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2465                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2466                 Type target = null;
  2467                 for (Type bound : ict.getExplicitComponents()) {
  2468                     TypeSymbol boundSym = bound.tsym;
  2469                     if (types.isFunctionalInterface(boundSym) &&
  2470                             types.findDescriptorSymbol(boundSym) == desc) {
  2471                         target = bound;
  2472                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2473                         //bound must be an interface
  2474                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2477                 return target != null ?
  2478                         target :
  2479                         ict.getExplicitComponents().head; //error recovery
  2482             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2483                 ListBuffer<Type> targs = ListBuffer.lb();
  2484                 ListBuffer<Type> supertypes = ListBuffer.lb();
  2485                 for (Type i : ict.interfaces_field) {
  2486                     if (i.isParameterized()) {
  2487                         targs.appendList(i.tsym.type.allparams());
  2489                     supertypes.append(i.tsym.type);
  2491                 IntersectionClassType notionalIntf =
  2492                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2493                 notionalIntf.allparams_field = targs.toList();
  2494                 notionalIntf.tsym.flags_field |= INTERFACE;
  2495                 return notionalIntf.tsym;
  2498             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2499                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2500                         diags.fragment(key, args)));
  2502         };
  2504         private Type fallbackDescriptorType(JCExpression tree) {
  2505             switch (tree.getTag()) {
  2506                 case LAMBDA:
  2507                     JCLambda lambda = (JCLambda)tree;
  2508                     List<Type> argtypes = List.nil();
  2509                     for (JCVariableDecl param : lambda.params) {
  2510                         argtypes = param.vartype != null ?
  2511                                 argtypes.append(param.vartype.type) :
  2512                                 argtypes.append(syms.errType);
  2514                     return new MethodType(argtypes, Type.recoveryType,
  2515                             List.of(syms.throwableType), syms.methodClass);
  2516                 case REFERENCE:
  2517                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2518                             List.of(syms.throwableType), syms.methodClass);
  2519                 default:
  2520                     Assert.error("Cannot get here!");
  2522             return null;
  2525         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2526                 final InferenceContext inferenceContext, final Type... ts) {
  2527             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2530         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2531                 final InferenceContext inferenceContext, final List<Type> ts) {
  2532             if (inferenceContext.free(ts)) {
  2533                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2534                     @Override
  2535                     public void typesInferred(InferenceContext inferenceContext) {
  2536                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2538                 });
  2539             } else {
  2540                 for (Type t : ts) {
  2541                     rs.checkAccessibleType(env, t);
  2546         /**
  2547          * Lambda/method reference have a special check context that ensures
  2548          * that i.e. a lambda return type is compatible with the expected
  2549          * type according to both the inherited context and the assignment
  2550          * context.
  2551          */
  2552         class FunctionalReturnContext extends Check.NestedCheckContext {
  2554             FunctionalReturnContext(CheckContext enclosingContext) {
  2555                 super(enclosingContext);
  2558             @Override
  2559             public boolean compatible(Type found, Type req, Warner warn) {
  2560                 //return type must be compatible in both current context and assignment context
  2561                 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
  2564             @Override
  2565             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2566                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2570         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2572             JCExpression expr;
  2574             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2575                 super(enclosingContext);
  2576                 this.expr = expr;
  2579             @Override
  2580             public boolean compatible(Type found, Type req, Warner warn) {
  2581                 //a void return is compatible with an expression statement lambda
  2582                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2583                         super.compatible(found, req, warn);
  2587         class LambdaResultInfo extends ResultInfo {
  2589             LambdaResultInfo(Type pt, CheckContext checkContext) {
  2590                 super(VAL, pt, checkContext);
  2593             @Override
  2594             protected Type check(DiagnosticPosition pos, Type found) {
  2595                 return super.check(pos, found.baseType());
  2598             @Override
  2599             protected ResultInfo dup(CheckContext newContext) {
  2600                 return new LambdaResultInfo(pt, newContext);
  2603             @Override
  2604             protected ResultInfo dup(Type newPt) {
  2605                 return new LambdaResultInfo(newPt, checkContext);
  2609         /**
  2610         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2611         * are compatible with the expected functional interface descriptor. This means that:
  2612         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2613         * types must be compatible with the return type of the expected descriptor;
  2614         * (iii) thrown types must be 'included' in the thrown types list of the expected
  2615         * descriptor.
  2616         */
  2617         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
  2618             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2620             //return values have already been checked - but if lambda has no return
  2621             //values, we must ensure that void/value compatibility is correct;
  2622             //this amounts at checking that, if a lambda body can complete normally,
  2623             //the descriptor's return type must be void
  2624             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2625                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2626                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2627                         diags.fragment("missing.ret.val", returnType)));
  2630             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
  2631             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2632                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2635             if (!speculativeAttr) {
  2636                 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2637                 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
  2638                     log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
  2643         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2644             Env<AttrContext> lambdaEnv;
  2645             Symbol owner = env.info.scope.owner;
  2646             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2647                 //field initializer
  2648                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2649                 lambdaEnv.info.scope.owner =
  2650                     new MethodSymbol((owner.flags() & STATIC) | BLOCK, names.empty, null,
  2651                                      env.info.scope.owner);
  2652             } else {
  2653                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2655             return lambdaEnv;
  2658     @Override
  2659     public void visitReference(final JCMemberReference that) {
  2660         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2661             if (pt().hasTag(NONE)) {
  2662                 //method reference only allowed in assignment or method invocation/cast context
  2663                 log.error(that.pos(), "unexpected.mref");
  2665             result = that.type = types.createErrorType(pt());
  2666             return;
  2668         final Env<AttrContext> localEnv = env.dup(that);
  2669         try {
  2670             //attribute member reference qualifier - if this is a constructor
  2671             //reference, the expected kind must be a type
  2672             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2674             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2675                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2678             if (exprType.isErroneous()) {
  2679                 //if the qualifier expression contains problems,
  2680                 //give up attribution of method reference
  2681                 result = that.type = exprType;
  2682                 return;
  2685             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2686                 //if the qualifier is a type, validate it; raw warning check is
  2687                 //omitted as we don't know at this stage as to whether this is a
  2688                 //raw selector (because of inference)
  2689                 chk.validate(that.expr, env, false);
  2692             //attrib type-arguments
  2693             List<Type> typeargtypes = List.nil();
  2694             if (that.typeargs != null) {
  2695                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2698             Type target;
  2699             Type desc;
  2700             if (pt() != Type.recoveryType) {
  2701                 target = targetChecker.visit(pt(), that);
  2702                 desc = types.findDescriptorType(target);
  2703                 chk.checkFunctionalInterface(that, target);
  2704             } else {
  2705                 target = Type.recoveryType;
  2706                 desc = fallbackDescriptorType(that);
  2709             setFunctionalInfo(that, pt(), desc, target, resultInfo.checkContext.inferenceContext());
  2710             List<Type> argtypes = desc.getParameterTypes();
  2711             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2713             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2714                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2717             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2718             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2719             try {
  2720                 refResult = rs.resolveMemberReference(that.pos(), localEnv, that, that.expr.type,
  2721                         that.name, argtypes, typeargtypes, true, referenceCheck,
  2722                         resultInfo.checkContext.inferenceContext());
  2723             } finally {
  2724                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2727             Symbol refSym = refResult.fst;
  2728             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2730             if (refSym.kind != MTH) {
  2731                 boolean targetError;
  2732                 switch (refSym.kind) {
  2733                     case ABSENT_MTH:
  2734                         targetError = false;
  2735                         break;
  2736                     case WRONG_MTH:
  2737                     case WRONG_MTHS:
  2738                     case AMBIGUOUS:
  2739                     case HIDDEN:
  2740                     case STATICERR:
  2741                     case MISSING_ENCL:
  2742                         targetError = true;
  2743                         break;
  2744                     default:
  2745                         Assert.error("unexpected result kind " + refSym.kind);
  2746                         targetError = false;
  2749                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2750                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2752                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2753                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2755                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2756                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2758                 if (targetError && target == Type.recoveryType) {
  2759                     //a target error doesn't make sense during recovery stage
  2760                     //as we don't know what actual parameter types are
  2761                     result = that.type = target;
  2762                     return;
  2763                 } else {
  2764                     if (targetError) {
  2765                         resultInfo.checkContext.report(that, diag);
  2766                     } else {
  2767                         log.report(diag);
  2769                     result = that.type = types.createErrorType(target);
  2770                     return;
  2774             that.sym = refSym.baseSymbol();
  2775             that.kind = lookupHelper.referenceKind(that.sym);
  2776             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2778             if (desc.getReturnType() == Type.recoveryType) {
  2779                 // stop here
  2780                 result = that.type = target;
  2781                 return;
  2784             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2786                 if (that.getMode() == ReferenceMode.INVOKE &&
  2787                         TreeInfo.isStaticSelector(that.expr, names) &&
  2788                         that.kind.isUnbound() &&
  2789                         !desc.getParameterTypes().head.isParameterized()) {
  2790                     chk.checkRaw(that.expr, localEnv);
  2793                 if (!that.kind.isUnbound() &&
  2794                         that.getMode() == ReferenceMode.INVOKE &&
  2795                         TreeInfo.isStaticSelector(that.expr, names) &&
  2796                         !that.sym.isStatic()) {
  2797                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2798                             diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym));
  2799                     result = that.type = types.createErrorType(target);
  2800                     return;
  2803                 if (that.kind.isUnbound() &&
  2804                         that.getMode() == ReferenceMode.INVOKE &&
  2805                         TreeInfo.isStaticSelector(that.expr, names) &&
  2806                         that.sym.isStatic()) {
  2807                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2808                             diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym));
  2809                     result = that.type = types.createErrorType(target);
  2810                     return;
  2813                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2814                         exprType.getTypeArguments().nonEmpty()) {
  2815                     //static ref with class type-args
  2816                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2817                             diags.fragment("static.mref.with.targs"));
  2818                     result = that.type = types.createErrorType(target);
  2819                     return;
  2822                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2823                         !that.kind.isUnbound()) {
  2824                     //no static bound mrefs
  2825                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2826                             diags.fragment("static.bound.mref"));
  2827                     result = that.type = types.createErrorType(target);
  2828                     return;
  2831                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2832                     // Check that super-qualified symbols are not abstract (JLS)
  2833                     rs.checkNonAbstract(that.pos(), that.sym);
  2837             ResultInfo checkInfo =
  2838                     resultInfo.dup(newMethodTemplate(
  2839                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2840                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes));
  2842             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2844             if (that.kind.isUnbound() &&
  2845                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2846                 //re-generate inference constraints for unbound receiver
  2847                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asFree(argtypes.head), exprType)) {
  2848                     //cannot happen as this has already been checked - we just need
  2849                     //to regenerate the inference constraints, as that has been lost
  2850                     //as a result of the call to inferenceContext.save()
  2851                     Assert.error("Can't get here");
  2855             if (!refType.isErroneous()) {
  2856                 refType = types.createMethodTypeWithReturn(refType,
  2857                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2860             //go ahead with standard method reference compatibility check - note that param check
  2861             //is a no-op (as this has been taken care during method applicability)
  2862             boolean isSpeculativeRound =
  2863                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2864             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2865             if (!isSpeculativeRound) {
  2866                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2868             result = check(that, target, VAL, resultInfo);
  2869         } catch (Types.FunctionDescriptorLookupError ex) {
  2870             JCDiagnostic cause = ex.getDiagnostic();
  2871             resultInfo.checkContext.report(that, cause);
  2872             result = that.type = types.createErrorType(pt());
  2873             return;
  2876     //where
  2877         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2878             //if this is a constructor reference, the expected kind must be a type
  2879             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2883     @SuppressWarnings("fallthrough")
  2884     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2885         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2887         Type resType;
  2888         switch (tree.getMode()) {
  2889             case NEW:
  2890                 if (!tree.expr.type.isRaw()) {
  2891                     resType = tree.expr.type;
  2892                     break;
  2894             default:
  2895                 resType = refType.getReturnType();
  2898         Type incompatibleReturnType = resType;
  2900         if (returnType.hasTag(VOID)) {
  2901             incompatibleReturnType = null;
  2904         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2905             if (resType.isErroneous() ||
  2906                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2907                 incompatibleReturnType = null;
  2911         if (incompatibleReturnType != null) {
  2912             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2913                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2916         if (!speculativeAttr) {
  2917             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2918             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2919                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2924     /**
  2925      * Set functional type info on the underlying AST. Note: as the target descriptor
  2926      * might contain inference variables, we might need to register an hook in the
  2927      * current inference context.
  2928      */
  2929     private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt,
  2930             final Type descriptorType, final Type primaryTarget, InferenceContext inferenceContext) {
  2931         if (inferenceContext.free(descriptorType)) {
  2932             inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2933                 public void typesInferred(InferenceContext inferenceContext) {
  2934                     setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType),
  2935                             inferenceContext.asInstType(primaryTarget), inferenceContext);
  2937             });
  2938         } else {
  2939             ListBuffer<TypeSymbol> targets = ListBuffer.lb();
  2940             if (pt.hasTag(CLASS)) {
  2941                 if (pt.isCompound()) {
  2942                     targets.append(primaryTarget.tsym); //this goes first
  2943                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2944                         if (t != primaryTarget) {
  2945                             targets.append(t.tsym);
  2948                 } else {
  2949                     targets.append(pt.tsym);
  2952             fExpr.targets = targets.toList();
  2953             fExpr.descriptorType = descriptorType;
  2957     public void visitParens(JCParens tree) {
  2958         Type owntype = attribTree(tree.expr, env, resultInfo);
  2959         result = check(tree, owntype, pkind(), resultInfo);
  2960         Symbol sym = TreeInfo.symbol(tree);
  2961         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2962             log.error(tree.pos(), "illegal.start.of.type");
  2965     public void visitAssign(JCAssign tree) {
  2966         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2967         Type capturedType = capture(owntype);
  2968         attribExpr(tree.rhs, env, owntype);
  2969         result = check(tree, capturedType, VAL, resultInfo);
  2972     public void visitAssignop(JCAssignOp tree) {
  2973         // Attribute arguments.
  2974         Type owntype = attribTree(tree.lhs, env, varInfo);
  2975         Type operand = attribExpr(tree.rhs, env);
  2976         // Find operator.
  2977         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2978             tree.pos(), tree.getTag().noAssignOp(), env,
  2979             owntype, operand);
  2981         if (operator.kind == MTH &&
  2982                 !owntype.isErroneous() &&
  2983                 !operand.isErroneous()) {
  2984             chk.checkOperator(tree.pos(),
  2985                               (OperatorSymbol)operator,
  2986                               tree.getTag().noAssignOp(),
  2987                               owntype,
  2988                               operand);
  2989             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2990             chk.checkCastable(tree.rhs.pos(),
  2991                               operator.type.getReturnType(),
  2992                               owntype);
  2994         result = check(tree, owntype, VAL, resultInfo);
  2997     public void visitUnary(JCUnary tree) {
  2998         // Attribute arguments.
  2999         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  3000             ? attribTree(tree.arg, env, varInfo)
  3001             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  3003         // Find operator.
  3004         Symbol operator = tree.operator =
  3005             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  3007         Type owntype = types.createErrorType(tree.type);
  3008         if (operator.kind == MTH &&
  3009                 !argtype.isErroneous()) {
  3010             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3011                 ? tree.arg.type
  3012                 : operator.type.getReturnType();
  3013             int opc = ((OperatorSymbol)operator).opcode;
  3015             // If the argument is constant, fold it.
  3016             if (argtype.constValue() != null) {
  3017                 Type ctype = cfolder.fold1(opc, argtype);
  3018                 if (ctype != null) {
  3019                     owntype = cfolder.coerce(ctype, owntype);
  3021                     // Remove constant types from arguments to
  3022                     // conserve space. The parser will fold concatenations
  3023                     // of string literals; the code here also
  3024                     // gets rid of intermediate results when some of the
  3025                     // operands are constant identifiers.
  3026                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  3027                         tree.arg.type = syms.stringType;
  3032         result = check(tree, owntype, VAL, resultInfo);
  3035     public void visitBinary(JCBinary tree) {
  3036         // Attribute arguments.
  3037         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3038         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3040         // Find operator.
  3041         Symbol operator = tree.operator =
  3042             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3044         Type owntype = types.createErrorType(tree.type);
  3045         if (operator.kind == MTH &&
  3046                 !left.isErroneous() &&
  3047                 !right.isErroneous()) {
  3048             owntype = operator.type.getReturnType();
  3049             // This will figure out when unboxing can happen and
  3050             // choose the right comparison operator.
  3051             int opc = chk.checkOperator(tree.lhs.pos(),
  3052                                         (OperatorSymbol)operator,
  3053                                         tree.getTag(),
  3054                                         left,
  3055                                         right);
  3057             // If both arguments are constants, fold them.
  3058             if (left.constValue() != null && right.constValue() != null) {
  3059                 Type ctype = cfolder.fold2(opc, left, right);
  3060                 if (ctype != null) {
  3061                     owntype = cfolder.coerce(ctype, owntype);
  3063                     // Remove constant types from arguments to
  3064                     // conserve space. The parser will fold concatenations
  3065                     // of string literals; the code here also
  3066                     // gets rid of intermediate results when some of the
  3067                     // operands are constant identifiers.
  3068                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  3069                         tree.lhs.type = syms.stringType;
  3071                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  3072                         tree.rhs.type = syms.stringType;
  3077             // Check that argument types of a reference ==, != are
  3078             // castable to each other, (JLS 15.21).  Note: unboxing
  3079             // comparisons will not have an acmp* opc at this point.
  3080             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3081                 if (!types.isEqualityComparable(left, right,
  3082                                                 new Warner(tree.pos()))) {
  3083                     log.error(tree.pos(), "incomparable.types", left, right);
  3087             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3089         result = check(tree, owntype, VAL, resultInfo);
  3092     public void visitTypeCast(final JCTypeCast tree) {
  3093         Type clazztype = attribType(tree.clazz, env);
  3094         chk.validate(tree.clazz, env, false);
  3095         //a fresh environment is required for 292 inference to work properly ---
  3096         //see Infer.instantiatePolymorphicSignatureInstance()
  3097         Env<AttrContext> localEnv = env.dup(tree);
  3098         //should we propagate the target type?
  3099         final ResultInfo castInfo;
  3100         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3101         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3102         if (isPoly) {
  3103             //expression is a poly - we need to propagate target type info
  3104             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3105                 @Override
  3106                 public boolean compatible(Type found, Type req, Warner warn) {
  3107                     return types.isCastable(found, req, warn);
  3109             });
  3110         } else {
  3111             //standalone cast - target-type info is not propagated
  3112             castInfo = unknownExprInfo;
  3114         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3115         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3116         if (exprtype.constValue() != null)
  3117             owntype = cfolder.coerce(exprtype, owntype);
  3118         result = check(tree, capture(owntype), VAL, resultInfo);
  3119         if (!isPoly)
  3120             chk.checkRedundantCast(localEnv, tree);
  3123     public void visitTypeTest(JCInstanceOf tree) {
  3124         Type exprtype = chk.checkNullOrRefType(
  3125             tree.expr.pos(), attribExpr(tree.expr, env));
  3126         Type clazztype = chk.checkReifiableReferenceType(
  3127             tree.clazz.pos(), attribType(tree.clazz, env));
  3128         chk.validate(tree.clazz, env, false);
  3129         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3130         result = check(tree, syms.booleanType, VAL, resultInfo);
  3133     public void visitIndexed(JCArrayAccess tree) {
  3134         Type owntype = types.createErrorType(tree.type);
  3135         Type atype = attribExpr(tree.indexed, env);
  3136         attribExpr(tree.index, env, syms.intType);
  3137         if (types.isArray(atype))
  3138             owntype = types.elemtype(atype);
  3139         else if (!atype.hasTag(ERROR))
  3140             log.error(tree.pos(), "array.req.but.found", atype);
  3141         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3142         result = check(tree, owntype, VAR, resultInfo);
  3145     public void visitIdent(JCIdent tree) {
  3146         Symbol sym;
  3148         // Find symbol
  3149         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3150             // If we are looking for a method, the prototype `pt' will be a
  3151             // method type with the type of the call's arguments as parameters.
  3152             env.info.pendingResolutionPhase = null;
  3153             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3154         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3155             sym = tree.sym;
  3156         } else {
  3157             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3159         tree.sym = sym;
  3161         // (1) Also find the environment current for the class where
  3162         //     sym is defined (`symEnv').
  3163         // Only for pre-tiger versions (1.4 and earlier):
  3164         // (2) Also determine whether we access symbol out of an anonymous
  3165         //     class in a this or super call.  This is illegal for instance
  3166         //     members since such classes don't carry a this$n link.
  3167         //     (`noOuterThisPath').
  3168         Env<AttrContext> symEnv = env;
  3169         boolean noOuterThisPath = false;
  3170         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3171             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3172             sym.owner.kind == TYP &&
  3173             tree.name != names._this && tree.name != names._super) {
  3175             // Find environment in which identifier is defined.
  3176             while (symEnv.outer != null &&
  3177                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3178                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3179                     noOuterThisPath = !allowAnonOuterThis;
  3180                 symEnv = symEnv.outer;
  3184         // If symbol is a variable, ...
  3185         if (sym.kind == VAR) {
  3186             VarSymbol v = (VarSymbol)sym;
  3188             // ..., evaluate its initializer, if it has one, and check for
  3189             // illegal forward reference.
  3190             checkInit(tree, env, v, false);
  3192             // If we are expecting a variable (as opposed to a value), check
  3193             // that the variable is assignable in the current environment.
  3194             if (pkind() == VAR)
  3195                 checkAssignable(tree.pos(), v, null, env);
  3198         // In a constructor body,
  3199         // if symbol is a field or instance method, check that it is
  3200         // not accessed before the supertype constructor is called.
  3201         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3202             (sym.kind & (VAR | MTH)) != 0 &&
  3203             sym.owner.kind == TYP &&
  3204             (sym.flags() & STATIC) == 0) {
  3205             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3207         Env<AttrContext> env1 = env;
  3208         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3209             // If the found symbol is inaccessible, then it is
  3210             // accessed through an enclosing instance.  Locate this
  3211             // enclosing instance:
  3212             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3213                 env1 = env1.outer;
  3215         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3218     public void visitSelect(JCFieldAccess tree) {
  3219         // Determine the expected kind of the qualifier expression.
  3220         int skind = 0;
  3221         if (tree.name == names._this || tree.name == names._super ||
  3222             tree.name == names._class)
  3224             skind = TYP;
  3225         } else {
  3226             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3227             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3228             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3231         // Attribute the qualifier expression, and determine its symbol (if any).
  3232         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3233         if ((pkind() & (PCK | TYP)) == 0)
  3234             site = capture(site); // Capture field access
  3236         // don't allow T.class T[].class, etc
  3237         if (skind == TYP) {
  3238             Type elt = site;
  3239             while (elt.hasTag(ARRAY))
  3240                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3241             if (elt.hasTag(TYPEVAR)) {
  3242                 log.error(tree.pos(), "type.var.cant.be.deref");
  3243                 result = types.createErrorType(tree.type);
  3244                 return;
  3248         // If qualifier symbol is a type or `super', assert `selectSuper'
  3249         // for the selection. This is relevant for determining whether
  3250         // protected symbols are accessible.
  3251         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3252         boolean selectSuperPrev = env.info.selectSuper;
  3253         env.info.selectSuper =
  3254             sitesym != null &&
  3255             sitesym.name == names._super;
  3257         // Determine the symbol represented by the selection.
  3258         env.info.pendingResolutionPhase = null;
  3259         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3260         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3261             site = capture(site);
  3262             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3264         boolean varArgs = env.info.lastResolveVarargs();
  3265         tree.sym = sym;
  3267         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3268             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3269             site = capture(site);
  3272         // If that symbol is a variable, ...
  3273         if (sym.kind == VAR) {
  3274             VarSymbol v = (VarSymbol)sym;
  3276             // ..., evaluate its initializer, if it has one, and check for
  3277             // illegal forward reference.
  3278             checkInit(tree, env, v, true);
  3280             // If we are expecting a variable (as opposed to a value), check
  3281             // that the variable is assignable in the current environment.
  3282             if (pkind() == VAR)
  3283                 checkAssignable(tree.pos(), v, tree.selected, env);
  3286         if (sitesym != null &&
  3287                 sitesym.kind == VAR &&
  3288                 ((VarSymbol)sitesym).isResourceVariable() &&
  3289                 sym.kind == MTH &&
  3290                 sym.name.equals(names.close) &&
  3291                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3292                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3293             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3296         // Disallow selecting a type from an expression
  3297         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3298             tree.type = check(tree.selected, pt(),
  3299                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3302         if (isType(sitesym)) {
  3303             if (sym.name == names._this) {
  3304                 // If `C' is the currently compiled class, check that
  3305                 // C.this' does not appear in a call to a super(...)
  3306                 if (env.info.isSelfCall &&
  3307                     site.tsym == env.enclClass.sym) {
  3308                     chk.earlyRefError(tree.pos(), sym);
  3310             } else {
  3311                 // Check if type-qualified fields or methods are static (JLS)
  3312                 if ((sym.flags() & STATIC) == 0 &&
  3313                     !env.next.tree.hasTag(REFERENCE) &&
  3314                     sym.name != names._super &&
  3315                     (sym.kind == VAR || sym.kind == MTH)) {
  3316                     rs.accessBase(rs.new StaticError(sym),
  3317                               tree.pos(), site, sym.name, true);
  3320         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3321             // If the qualified item is not a type and the selected item is static, report
  3322             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3323             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3326         // If we are selecting an instance member via a `super', ...
  3327         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3329             // Check that super-qualified symbols are not abstract (JLS)
  3330             rs.checkNonAbstract(tree.pos(), sym);
  3332             if (site.isRaw()) {
  3333                 // Determine argument types for site.
  3334                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3335                 if (site1 != null) site = site1;
  3339         env.info.selectSuper = selectSuperPrev;
  3340         result = checkId(tree, site, sym, env, resultInfo);
  3342     //where
  3343         /** Determine symbol referenced by a Select expression,
  3345          *  @param tree   The select tree.
  3346          *  @param site   The type of the selected expression,
  3347          *  @param env    The current environment.
  3348          *  @param resultInfo The current result.
  3349          */
  3350         private Symbol selectSym(JCFieldAccess tree,
  3351                                  Symbol location,
  3352                                  Type site,
  3353                                  Env<AttrContext> env,
  3354                                  ResultInfo resultInfo) {
  3355             DiagnosticPosition pos = tree.pos();
  3356             Name name = tree.name;
  3357             switch (site.getTag()) {
  3358             case PACKAGE:
  3359                 return rs.accessBase(
  3360                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3361                     pos, location, site, name, true);
  3362             case ARRAY:
  3363             case CLASS:
  3364                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3365                     return rs.resolveQualifiedMethod(
  3366                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3367                 } else if (name == names._this || name == names._super) {
  3368                     return rs.resolveSelf(pos, env, site.tsym, name);
  3369                 } else if (name == names._class) {
  3370                     // In this case, we have already made sure in
  3371                     // visitSelect that qualifier expression is a type.
  3372                     Type t = syms.classType;
  3373                     List<Type> typeargs = allowGenerics
  3374                         ? List.of(types.erasure(site))
  3375                         : List.<Type>nil();
  3376                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3377                     return new VarSymbol(
  3378                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3379                 } else {
  3380                     // We are seeing a plain identifier as selector.
  3381                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3382                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3383                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3384                     return sym;
  3386             case WILDCARD:
  3387                 throw new AssertionError(tree);
  3388             case TYPEVAR:
  3389                 // Normally, site.getUpperBound() shouldn't be null.
  3390                 // It should only happen during memberEnter/attribBase
  3391                 // when determining the super type which *must* beac
  3392                 // done before attributing the type variables.  In
  3393                 // other words, we are seeing this illegal program:
  3394                 // class B<T> extends A<T.foo> {}
  3395                 Symbol sym = (site.getUpperBound() != null)
  3396                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3397                     : null;
  3398                 if (sym == null) {
  3399                     log.error(pos, "type.var.cant.be.deref");
  3400                     return syms.errSymbol;
  3401                 } else {
  3402                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3403                         rs.new AccessError(env, site, sym) :
  3404                                 sym;
  3405                     rs.accessBase(sym2, pos, location, site, name, true);
  3406                     return sym;
  3408             case ERROR:
  3409                 // preserve identifier names through errors
  3410                 return types.createErrorType(name, site.tsym, site).tsym;
  3411             default:
  3412                 // The qualifier expression is of a primitive type -- only
  3413                 // .class is allowed for these.
  3414                 if (name == names._class) {
  3415                     // In this case, we have already made sure in Select that
  3416                     // qualifier expression is a type.
  3417                     Type t = syms.classType;
  3418                     Type arg = types.boxedClass(site).type;
  3419                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3420                     return new VarSymbol(
  3421                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3422                 } else {
  3423                     log.error(pos, "cant.deref", site);
  3424                     return syms.errSymbol;
  3429         /** Determine type of identifier or select expression and check that
  3430          *  (1) the referenced symbol is not deprecated
  3431          *  (2) the symbol's type is safe (@see checkSafe)
  3432          *  (3) if symbol is a variable, check that its type and kind are
  3433          *      compatible with the prototype and protokind.
  3434          *  (4) if symbol is an instance field of a raw type,
  3435          *      which is being assigned to, issue an unchecked warning if its
  3436          *      type changes under erasure.
  3437          *  (5) if symbol is an instance method of a raw type, issue an
  3438          *      unchecked warning if its argument types change under erasure.
  3439          *  If checks succeed:
  3440          *    If symbol is a constant, return its constant type
  3441          *    else if symbol is a method, return its result type
  3442          *    otherwise return its type.
  3443          *  Otherwise return errType.
  3445          *  @param tree       The syntax tree representing the identifier
  3446          *  @param site       If this is a select, the type of the selected
  3447          *                    expression, otherwise the type of the current class.
  3448          *  @param sym        The symbol representing the identifier.
  3449          *  @param env        The current environment.
  3450          *  @param resultInfo    The expected result
  3451          */
  3452         Type checkId(JCTree tree,
  3453                      Type site,
  3454                      Symbol sym,
  3455                      Env<AttrContext> env,
  3456                      ResultInfo resultInfo) {
  3457             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3458                     checkMethodId(tree, site, sym, env, resultInfo) :
  3459                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3462         Type checkMethodId(JCTree tree,
  3463                      Type site,
  3464                      Symbol sym,
  3465                      Env<AttrContext> env,
  3466                      ResultInfo resultInfo) {
  3467             boolean isPolymorhicSignature =
  3468                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3469             return isPolymorhicSignature ?
  3470                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3471                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3474         Type checkSigPolyMethodId(JCTree tree,
  3475                      Type site,
  3476                      Symbol sym,
  3477                      Env<AttrContext> env,
  3478                      ResultInfo resultInfo) {
  3479             //recover original symbol for signature polymorphic methods
  3480             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3481             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3482             return sym.type;
  3485         Type checkMethodIdInternal(JCTree tree,
  3486                      Type site,
  3487                      Symbol sym,
  3488                      Env<AttrContext> env,
  3489                      ResultInfo resultInfo) {
  3490             if ((resultInfo.pkind & POLY) != 0) {
  3491                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3492                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3493                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3494                 return owntype;
  3495             } else {
  3496                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3500         Type checkIdInternal(JCTree tree,
  3501                      Type site,
  3502                      Symbol sym,
  3503                      Type pt,
  3504                      Env<AttrContext> env,
  3505                      ResultInfo resultInfo) {
  3506             if (pt.isErroneous()) {
  3507                 return types.createErrorType(site);
  3509             Type owntype; // The computed type of this identifier occurrence.
  3510             switch (sym.kind) {
  3511             case TYP:
  3512                 // For types, the computed type equals the symbol's type,
  3513                 // except for two situations:
  3514                 owntype = sym.type;
  3515                 if (owntype.hasTag(CLASS)) {
  3516                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3517                     Type ownOuter = owntype.getEnclosingType();
  3519                     // (a) If the symbol's type is parameterized, erase it
  3520                     // because no type parameters were given.
  3521                     // We recover generic outer type later in visitTypeApply.
  3522                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3523                         owntype = types.erasure(owntype);
  3526                     // (b) If the symbol's type is an inner class, then
  3527                     // we have to interpret its outer type as a superclass
  3528                     // of the site type. Example:
  3529                     //
  3530                     // class Tree<A> { class Visitor { ... } }
  3531                     // class PointTree extends Tree<Point> { ... }
  3532                     // ...PointTree.Visitor...
  3533                     //
  3534                     // Then the type of the last expression above is
  3535                     // Tree<Point>.Visitor.
  3536                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3537                         Type normOuter = site;
  3538                         if (normOuter.hasTag(CLASS)) {
  3539                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3540                             if (site.isAnnotated()) {
  3541                                 // Propagate any type annotations.
  3542                                 // TODO: should asEnclosingSuper do this?
  3543                                 // Note that the type annotations in site will be updated
  3544                                 // by annotateType. Therefore, modify site instead
  3545                                 // of creating a new AnnotatedType.
  3546                                 ((AnnotatedType)site).underlyingType = normOuter;
  3547                                 normOuter = site;
  3550                         if (normOuter == null) // perhaps from an import
  3551                             normOuter = types.erasure(ownOuter);
  3552                         if (normOuter != ownOuter)
  3553                             owntype = new ClassType(
  3554                                 normOuter, List.<Type>nil(), owntype.tsym);
  3557                 break;
  3558             case VAR:
  3559                 VarSymbol v = (VarSymbol)sym;
  3560                 // Test (4): if symbol is an instance field of a raw type,
  3561                 // which is being assigned to, issue an unchecked warning if
  3562                 // its type changes under erasure.
  3563                 if (allowGenerics &&
  3564                     resultInfo.pkind == VAR &&
  3565                     v.owner.kind == TYP &&
  3566                     (v.flags() & STATIC) == 0 &&
  3567                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3568                     Type s = types.asOuterSuper(site, v.owner);
  3569                     if (s != null &&
  3570                         s.isRaw() &&
  3571                         !types.isSameType(v.type, v.erasure(types))) {
  3572                         chk.warnUnchecked(tree.pos(),
  3573                                           "unchecked.assign.to.var",
  3574                                           v, s);
  3577                 // The computed type of a variable is the type of the
  3578                 // variable symbol, taken as a member of the site type.
  3579                 owntype = (sym.owner.kind == TYP &&
  3580                            sym.name != names._this && sym.name != names._super)
  3581                     ? types.memberType(site, sym)
  3582                     : sym.type;
  3584                 // If the variable is a constant, record constant value in
  3585                 // computed type.
  3586                 if (v.getConstValue() != null && isStaticReference(tree))
  3587                     owntype = owntype.constType(v.getConstValue());
  3589                 if (resultInfo.pkind == VAL) {
  3590                     owntype = capture(owntype); // capture "names as expressions"
  3592                 break;
  3593             case MTH: {
  3594                 owntype = checkMethod(site, sym,
  3595                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3596                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3597                         resultInfo.pt.getTypeArguments());
  3598                 break;
  3600             case PCK: case ERR:
  3601                 owntype = sym.type;
  3602                 break;
  3603             default:
  3604                 throw new AssertionError("unexpected kind: " + sym.kind +
  3605                                          " in tree " + tree);
  3608             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3609             // (for constructors, the error was given when the constructor was
  3610             // resolved)
  3612             if (sym.name != names.init) {
  3613                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3614                 chk.checkSunAPI(tree.pos(), sym);
  3615                 chk.checkProfile(tree.pos(), sym);
  3618             // Test (3): if symbol is a variable, check that its type and
  3619             // kind are compatible with the prototype and protokind.
  3620             return check(tree, owntype, sym.kind, resultInfo);
  3623         /** Check that variable is initialized and evaluate the variable's
  3624          *  initializer, if not yet done. Also check that variable is not
  3625          *  referenced before it is defined.
  3626          *  @param tree    The tree making up the variable reference.
  3627          *  @param env     The current environment.
  3628          *  @param v       The variable's symbol.
  3629          */
  3630         private void checkInit(JCTree tree,
  3631                                Env<AttrContext> env,
  3632                                VarSymbol v,
  3633                                boolean onlyWarning) {
  3634 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3635 //                             tree.pos + " " + v.pos + " " +
  3636 //                             Resolve.isStatic(env));//DEBUG
  3638             // A forward reference is diagnosed if the declaration position
  3639             // of the variable is greater than the current tree position
  3640             // and the tree and variable definition occur in the same class
  3641             // definition.  Note that writes don't count as references.
  3642             // This check applies only to class and instance
  3643             // variables.  Local variables follow different scope rules,
  3644             // and are subject to definite assignment checking.
  3645             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3646                 v.owner.kind == TYP &&
  3647                 canOwnInitializer(owner(env)) &&
  3648                 v.owner == env.info.scope.owner.enclClass() &&
  3649                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3650                 (!env.tree.hasTag(ASSIGN) ||
  3651                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3652                 String suffix = (env.info.enclVar == v) ?
  3653                                 "self.ref" : "forward.ref";
  3654                 if (!onlyWarning || isStaticEnumField(v)) {
  3655                     log.error(tree.pos(), "illegal." + suffix);
  3656                 } else if (useBeforeDeclarationWarning) {
  3657                     log.warning(tree.pos(), suffix, v);
  3661             v.getConstValue(); // ensure initializer is evaluated
  3663             checkEnumInitializer(tree, env, v);
  3666         /**
  3667          * Check for illegal references to static members of enum.  In
  3668          * an enum type, constructors and initializers may not
  3669          * reference its static members unless they are constant.
  3671          * @param tree    The tree making up the variable reference.
  3672          * @param env     The current environment.
  3673          * @param v       The variable's symbol.
  3674          * @jls  section 8.9 Enums
  3675          */
  3676         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3677             // JLS:
  3678             //
  3679             // "It is a compile-time error to reference a static field
  3680             // of an enum type that is not a compile-time constant
  3681             // (15.28) from constructors, instance initializer blocks,
  3682             // or instance variable initializer expressions of that
  3683             // type. It is a compile-time error for the constructors,
  3684             // instance initializer blocks, or instance variable
  3685             // initializer expressions of an enum constant e to refer
  3686             // to itself or to an enum constant of the same type that
  3687             // is declared to the right of e."
  3688             if (isStaticEnumField(v)) {
  3689                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3691                 if (enclClass == null || enclClass.owner == null)
  3692                     return;
  3694                 // See if the enclosing class is the enum (or a
  3695                 // subclass thereof) declaring v.  If not, this
  3696                 // reference is OK.
  3697                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3698                     return;
  3700                 // If the reference isn't from an initializer, then
  3701                 // the reference is OK.
  3702                 if (!Resolve.isInitializer(env))
  3703                     return;
  3705                 log.error(tree.pos(), "illegal.enum.static.ref");
  3709         /** Is the given symbol a static, non-constant field of an Enum?
  3710          *  Note: enum literals should not be regarded as such
  3711          */
  3712         private boolean isStaticEnumField(VarSymbol v) {
  3713             return Flags.isEnum(v.owner) &&
  3714                    Flags.isStatic(v) &&
  3715                    !Flags.isConstant(v) &&
  3716                    v.name != names._class;
  3719         /** Can the given symbol be the owner of code which forms part
  3720          *  if class initialization? This is the case if the symbol is
  3721          *  a type or field, or if the symbol is the synthetic method.
  3722          *  owning a block.
  3723          */
  3724         private boolean canOwnInitializer(Symbol sym) {
  3725             return
  3726                 (sym.kind & (VAR | TYP)) != 0 ||
  3727                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3730     Warner noteWarner = new Warner();
  3732     /**
  3733      * Check that method arguments conform to its instantiation.
  3734      **/
  3735     public Type checkMethod(Type site,
  3736                             Symbol sym,
  3737                             ResultInfo resultInfo,
  3738                             Env<AttrContext> env,
  3739                             final List<JCExpression> argtrees,
  3740                             List<Type> argtypes,
  3741                             List<Type> typeargtypes) {
  3742         // Test (5): if symbol is an instance method of a raw type, issue
  3743         // an unchecked warning if its argument types change under erasure.
  3744         if (allowGenerics &&
  3745             (sym.flags() & STATIC) == 0 &&
  3746             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3747             Type s = types.asOuterSuper(site, sym.owner);
  3748             if (s != null && s.isRaw() &&
  3749                 !types.isSameTypes(sym.type.getParameterTypes(),
  3750                                    sym.erasure(types).getParameterTypes())) {
  3751                 chk.warnUnchecked(env.tree.pos(),
  3752                                   "unchecked.call.mbr.of.raw.type",
  3753                                   sym, s);
  3757         if (env.info.defaultSuperCallSite != null) {
  3758             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3759                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3760                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3761                 List<MethodSymbol> icand_sup =
  3762                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3763                 if (icand_sup.nonEmpty() &&
  3764                         icand_sup.head != sym &&
  3765                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3766                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3767                         diags.fragment("overridden.default", sym, sup));
  3768                     break;
  3771             env.info.defaultSuperCallSite = null;
  3774         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3775             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3776             if (app.meth.hasTag(SELECT) &&
  3777                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3778                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3782         // Compute the identifier's instantiated type.
  3783         // For methods, we need to compute the instance type by
  3784         // Resolve.instantiate from the symbol's type as well as
  3785         // any type arguments and value arguments.
  3786         noteWarner.clear();
  3787         try {
  3788             Type owntype = rs.checkMethod(
  3789                     env,
  3790                     site,
  3791                     sym,
  3792                     resultInfo,
  3793                     argtypes,
  3794                     typeargtypes,
  3795                     noteWarner);
  3797             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3798                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3800             argtypes = Type.map(argtypes, checkDeferredMap);
  3802             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3803                 chk.warnUnchecked(env.tree.pos(),
  3804                         "unchecked.meth.invocation.applied",
  3805                         kindName(sym),
  3806                         sym.name,
  3807                         rs.methodArguments(sym.type.getParameterTypes()),
  3808                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3809                         kindName(sym.location()),
  3810                         sym.location());
  3811                owntype = new MethodType(owntype.getParameterTypes(),
  3812                        types.erasure(owntype.getReturnType()),
  3813                        types.erasure(owntype.getThrownTypes()),
  3814                        syms.methodClass);
  3817             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3818                     resultInfo.checkContext.inferenceContext());
  3819         } catch (Infer.InferenceException ex) {
  3820             //invalid target type - propagate exception outwards or report error
  3821             //depending on the current check context
  3822             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3823             return types.createErrorType(site);
  3824         } catch (Resolve.InapplicableMethodException ex) {
  3825             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
  3826             return null;
  3830     public void visitLiteral(JCLiteral tree) {
  3831         result = check(
  3832             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3834     //where
  3835     /** Return the type of a literal with given type tag.
  3836      */
  3837     Type litType(TypeTag tag) {
  3838         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3841     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3842         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3845     public void visitTypeArray(JCArrayTypeTree tree) {
  3846         Type etype = attribType(tree.elemtype, env);
  3847         Type type = new ArrayType(etype, syms.arrayClass);
  3848         result = check(tree, type, TYP, resultInfo);
  3851     /** Visitor method for parameterized types.
  3852      *  Bound checking is left until later, since types are attributed
  3853      *  before supertype structure is completely known
  3854      */
  3855     public void visitTypeApply(JCTypeApply tree) {
  3856         Type owntype = types.createErrorType(tree.type);
  3858         // Attribute functor part of application and make sure it's a class.
  3859         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3861         // Attribute type parameters
  3862         List<Type> actuals = attribTypes(tree.arguments, env);
  3864         if (clazztype.hasTag(CLASS)) {
  3865             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3866             if (actuals.isEmpty()) //diamond
  3867                 actuals = formals;
  3869             if (actuals.length() == formals.length()) {
  3870                 List<Type> a = actuals;
  3871                 List<Type> f = formals;
  3872                 while (a.nonEmpty()) {
  3873                     a.head = a.head.withTypeVar(f.head);
  3874                     a = a.tail;
  3875                     f = f.tail;
  3877                 // Compute the proper generic outer
  3878                 Type clazzOuter = clazztype.getEnclosingType();
  3879                 if (clazzOuter.hasTag(CLASS)) {
  3880                     Type site;
  3881                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3882                     if (clazz.hasTag(IDENT)) {
  3883                         site = env.enclClass.sym.type;
  3884                     } else if (clazz.hasTag(SELECT)) {
  3885                         site = ((JCFieldAccess) clazz).selected.type;
  3886                     } else throw new AssertionError(""+tree);
  3887                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3888                         if (site.hasTag(CLASS))
  3889                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3890                         if (site == null)
  3891                             site = types.erasure(clazzOuter);
  3892                         clazzOuter = site;
  3895                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3896                 if (clazztype.isAnnotated()) {
  3897                     // Use the same AnnotatedType, because it will have
  3898                     // its annotations set later.
  3899                     ((AnnotatedType)clazztype).underlyingType = owntype;
  3900                     owntype = clazztype;
  3902             } else {
  3903                 if (formals.length() != 0) {
  3904                     log.error(tree.pos(), "wrong.number.type.args",
  3905                               Integer.toString(formals.length()));
  3906                 } else {
  3907                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3909                 owntype = types.createErrorType(tree.type);
  3912         result = check(tree, owntype, TYP, resultInfo);
  3915     public void visitTypeUnion(JCTypeUnion tree) {
  3916         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  3917         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3918         for (JCExpression typeTree : tree.alternatives) {
  3919             Type ctype = attribType(typeTree, env);
  3920             ctype = chk.checkType(typeTree.pos(),
  3921                           chk.checkClassType(typeTree.pos(), ctype),
  3922                           syms.throwableType);
  3923             if (!ctype.isErroneous()) {
  3924                 //check that alternatives of a union type are pairwise
  3925                 //unrelated w.r.t. subtyping
  3926                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3927                     for (Type t : multicatchTypes) {
  3928                         boolean sub = types.isSubtype(ctype, t);
  3929                         boolean sup = types.isSubtype(t, ctype);
  3930                         if (sub || sup) {
  3931                             //assume 'a' <: 'b'
  3932                             Type a = sub ? ctype : t;
  3933                             Type b = sub ? t : ctype;
  3934                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3938                 multicatchTypes.append(ctype);
  3939                 if (all_multicatchTypes != null)
  3940                     all_multicatchTypes.append(ctype);
  3941             } else {
  3942                 if (all_multicatchTypes == null) {
  3943                     all_multicatchTypes = ListBuffer.lb();
  3944                     all_multicatchTypes.appendList(multicatchTypes);
  3946                 all_multicatchTypes.append(ctype);
  3949         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3950         if (t.hasTag(CLASS)) {
  3951             List<Type> alternatives =
  3952                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3953             t = new UnionClassType((ClassType) t, alternatives);
  3955         tree.type = result = t;
  3958     public void visitTypeIntersection(JCTypeIntersection tree) {
  3959         attribTypes(tree.bounds, env);
  3960         tree.type = result = checkIntersection(tree, tree.bounds);
  3963     public void visitTypeParameter(JCTypeParameter tree) {
  3964         TypeVar typeVar = (TypeVar) tree.type;
  3966         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3967             AnnotatedType antype = new AnnotatedType(typeVar);
  3968             annotateType(antype, tree.annotations);
  3969             tree.type = antype;
  3972         if (!typeVar.bound.isErroneous()) {
  3973             //fixup type-parameter bound computed in 'attribTypeVariables'
  3974             typeVar.bound = checkIntersection(tree, tree.bounds);
  3978     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3979         Set<Type> boundSet = new HashSet<Type>();
  3980         if (bounds.nonEmpty()) {
  3981             // accept class or interface or typevar as first bound.
  3982             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3983             boundSet.add(types.erasure(bounds.head.type));
  3984             if (bounds.head.type.isErroneous()) {
  3985                 return bounds.head.type;
  3987             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3988                 // if first bound was a typevar, do not accept further bounds.
  3989                 if (bounds.tail.nonEmpty()) {
  3990                     log.error(bounds.tail.head.pos(),
  3991                               "type.var.may.not.be.followed.by.other.bounds");
  3992                     return bounds.head.type;
  3994             } else {
  3995                 // if first bound was a class or interface, accept only interfaces
  3996                 // as further bounds.
  3997                 for (JCExpression bound : bounds.tail) {
  3998                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  3999                     if (bound.type.isErroneous()) {
  4000                         bounds = List.of(bound);
  4002                     else if (bound.type.hasTag(CLASS)) {
  4003                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4009         if (bounds.length() == 0) {
  4010             return syms.objectType;
  4011         } else if (bounds.length() == 1) {
  4012             return bounds.head.type;
  4013         } else {
  4014             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4015             if (tree.hasTag(TYPEINTERSECTION)) {
  4016                 ((IntersectionClassType)owntype).intersectionKind =
  4017                         IntersectionClassType.IntersectionKind.EXPLICIT;
  4019             // ... the variable's bound is a class type flagged COMPOUND
  4020             // (see comment for TypeVar.bound).
  4021             // In this case, generate a class tree that represents the
  4022             // bound class, ...
  4023             JCExpression extending;
  4024             List<JCExpression> implementing;
  4025             if (!bounds.head.type.isInterface()) {
  4026                 extending = bounds.head;
  4027                 implementing = bounds.tail;
  4028             } else {
  4029                 extending = null;
  4030                 implementing = bounds;
  4032             JCClassDecl cd = make.at(tree).ClassDef(
  4033                 make.Modifiers(PUBLIC | ABSTRACT),
  4034                 names.empty, List.<JCTypeParameter>nil(),
  4035                 extending, implementing, List.<JCTree>nil());
  4037             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4038             Assert.check((c.flags() & COMPOUND) != 0);
  4039             cd.sym = c;
  4040             c.sourcefile = env.toplevel.sourcefile;
  4042             // ... and attribute the bound class
  4043             c.flags_field |= UNATTRIBUTED;
  4044             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4045             enter.typeEnvs.put(c, cenv);
  4046             attribClass(c);
  4047             return owntype;
  4051     public void visitWildcard(JCWildcard tree) {
  4052         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4053         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4054             ? syms.objectType
  4055             : attribType(tree.inner, env);
  4056         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4057                                               tree.kind.kind,
  4058                                               syms.boundClass),
  4059                        TYP, resultInfo);
  4062     public void visitAnnotation(JCAnnotation tree) {
  4063         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  4064         result = tree.type = syms.errType;
  4067     public void visitAnnotatedType(JCAnnotatedType tree) {
  4068         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4069         this.attribAnnotationTypes(tree.annotations, env);
  4070         AnnotatedType antype = new AnnotatedType(underlyingType);
  4071         annotateType(antype, tree.annotations);
  4072         result = tree.type = antype;
  4075     /**
  4076      * Apply the annotations to the particular type.
  4077      */
  4078     public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
  4079         if (annotations.isEmpty())
  4080             return;
  4081         annotate.typeAnnotation(new Annotate.Annotator() {
  4082             @Override
  4083             public String toString() {
  4084                 return "annotate " + annotations + " onto " + type;
  4086             @Override
  4087             public void enterAnnotation() {
  4088                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4089                 type.typeAnnotations = compounds;
  4091         });
  4094     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4095         if (annotations.isEmpty())
  4096             return List.nil();
  4098         ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
  4099         for (JCAnnotation anno : annotations) {
  4100             if (anno.attribute != null) {
  4101                 // TODO: this null-check is only needed for an obscure
  4102                 // ordering issue, where annotate.flush is called when
  4103                 // the attribute is not set yet. For an example failure
  4104                 // try the referenceinfos/NestedTypes.java test.
  4105                 // Any better solutions?
  4106                 buf.append((Attribute.TypeCompound) anno.attribute);
  4109         return buf.toList();
  4112     public void visitErroneous(JCErroneous tree) {
  4113         if (tree.errs != null)
  4114             for (JCTree err : tree.errs)
  4115                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4116         result = tree.type = syms.errType;
  4119     /** Default visitor method for all other trees.
  4120      */
  4121     public void visitTree(JCTree tree) {
  4122         throw new AssertionError();
  4125     /**
  4126      * Attribute an env for either a top level tree or class declaration.
  4127      */
  4128     public void attrib(Env<AttrContext> env) {
  4129         if (env.tree.hasTag(TOPLEVEL))
  4130             attribTopLevel(env);
  4131         else
  4132             attribClass(env.tree.pos(), env.enclClass.sym);
  4135     /**
  4136      * Attribute a top level tree. These trees are encountered when the
  4137      * package declaration has annotations.
  4138      */
  4139     public void attribTopLevel(Env<AttrContext> env) {
  4140         JCCompilationUnit toplevel = env.toplevel;
  4141         try {
  4142             annotate.flush();
  4143             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  4144         } catch (CompletionFailure ex) {
  4145             chk.completionError(toplevel.pos(), ex);
  4149     /** Main method: attribute class definition associated with given class symbol.
  4150      *  reporting completion failures at the given position.
  4151      *  @param pos The source position at which completion errors are to be
  4152      *             reported.
  4153      *  @param c   The class symbol whose definition will be attributed.
  4154      */
  4155     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4156         try {
  4157             annotate.flush();
  4158             attribClass(c);
  4159         } catch (CompletionFailure ex) {
  4160             chk.completionError(pos, ex);
  4164     /** Attribute class definition associated with given class symbol.
  4165      *  @param c   The class symbol whose definition will be attributed.
  4166      */
  4167     void attribClass(ClassSymbol c) throws CompletionFailure {
  4168         if (c.type.hasTag(ERROR)) return;
  4170         // Check for cycles in the inheritance graph, which can arise from
  4171         // ill-formed class files.
  4172         chk.checkNonCyclic(null, c.type);
  4174         Type st = types.supertype(c.type);
  4175         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4176             // First, attribute superclass.
  4177             if (st.hasTag(CLASS))
  4178                 attribClass((ClassSymbol)st.tsym);
  4180             // Next attribute owner, if it is a class.
  4181             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4182                 attribClass((ClassSymbol)c.owner);
  4185         // The previous operations might have attributed the current class
  4186         // if there was a cycle. So we test first whether the class is still
  4187         // UNATTRIBUTED.
  4188         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4189             c.flags_field &= ~UNATTRIBUTED;
  4191             // Get environment current at the point of class definition.
  4192             Env<AttrContext> env = enter.typeEnvs.get(c);
  4194             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4195             // because the annotations were not available at the time the env was created. Therefore,
  4196             // we look up the environment chain for the first enclosing environment for which the
  4197             // lint value is set. Typically, this is the parent env, but might be further if there
  4198             // are any envs created as a result of TypeParameter nodes.
  4199             Env<AttrContext> lintEnv = env;
  4200             while (lintEnv.info.lint == null)
  4201                 lintEnv = lintEnv.next;
  4203             // Having found the enclosing lint value, we can initialize the lint value for this class
  4204             env.info.lint = lintEnv.info.lint.augment(c);
  4206             Lint prevLint = chk.setLint(env.info.lint);
  4207             JavaFileObject prev = log.useSource(c.sourcefile);
  4208             ResultInfo prevReturnRes = env.info.returnResult;
  4210             try {
  4211                 env.info.returnResult = null;
  4212                 // java.lang.Enum may not be subclassed by a non-enum
  4213                 if (st.tsym == syms.enumSym &&
  4214                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4215                     log.error(env.tree.pos(), "enum.no.subclassing");
  4217                 // Enums may not be extended by source-level classes
  4218                 if (st.tsym != null &&
  4219                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4220                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4221                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4223                 attribClassBody(env, c);
  4225                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4226                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4227             } finally {
  4228                 env.info.returnResult = prevReturnRes;
  4229                 log.useSource(prev);
  4230                 chk.setLint(prevLint);
  4236     public void visitImport(JCImport tree) {
  4237         // nothing to do
  4240     /** Finish the attribution of a class. */
  4241     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4242         JCClassDecl tree = (JCClassDecl)env.tree;
  4243         Assert.check(c == tree.sym);
  4245         // Validate annotations
  4246         chk.validateAnnotations(tree.mods.annotations, c);
  4248         // Validate type parameters, supertype and interfaces.
  4249         attribStats(tree.typarams, env);
  4250         if (!c.isAnonymous()) {
  4251             //already checked if anonymous
  4252             chk.validate(tree.typarams, env);
  4253             chk.validate(tree.extending, env);
  4254             chk.validate(tree.implementing, env);
  4257         // If this is a non-abstract class, check that it has no abstract
  4258         // methods or unimplemented methods of an implemented interface.
  4259         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4260             if (!relax)
  4261                 chk.checkAllDefined(tree.pos(), c);
  4264         if ((c.flags() & ANNOTATION) != 0) {
  4265             if (tree.implementing.nonEmpty())
  4266                 log.error(tree.implementing.head.pos(),
  4267                           "cant.extend.intf.annotation");
  4268             if (tree.typarams.nonEmpty())
  4269                 log.error(tree.typarams.head.pos(),
  4270                           "intf.annotation.cant.have.type.params");
  4272             // If this annotation has a @Repeatable, validate
  4273             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4274             if (repeatable != null) {
  4275                 // get diagnostic position for error reporting
  4276                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4277                 Assert.checkNonNull(cbPos);
  4279                 chk.validateRepeatable(c, repeatable, cbPos);
  4281         } else {
  4282             // Check that all extended classes and interfaces
  4283             // are compatible (i.e. no two define methods with same arguments
  4284             // yet different return types).  (JLS 8.4.6.3)
  4285             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4286             if (allowDefaultMethods) {
  4287                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4291         // Check that class does not import the same parameterized interface
  4292         // with two different argument lists.
  4293         chk.checkClassBounds(tree.pos(), c.type);
  4295         tree.type = c.type;
  4297         for (List<JCTypeParameter> l = tree.typarams;
  4298              l.nonEmpty(); l = l.tail) {
  4299              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4302         // Check that a generic class doesn't extend Throwable
  4303         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4304             log.error(tree.extending.pos(), "generic.throwable");
  4306         // Check that all methods which implement some
  4307         // method conform to the method they implement.
  4308         chk.checkImplementations(tree);
  4310         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4311         checkAutoCloseable(tree.pos(), env, c.type);
  4313         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4314             // Attribute declaration
  4315             attribStat(l.head, env);
  4316             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4317             // Make an exception for static constants.
  4318             if (c.owner.kind != PCK &&
  4319                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4320                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4321                 Symbol sym = null;
  4322                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4323                 if (sym == null ||
  4324                     sym.kind != VAR ||
  4325                     ((VarSymbol) sym).getConstValue() == null)
  4326                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4330         // Check for cycles among non-initial constructors.
  4331         chk.checkCyclicConstructors(tree);
  4333         // Check for cycles among annotation elements.
  4334         chk.checkNonCyclicElements(tree);
  4336         // Check for proper use of serialVersionUID
  4337         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4338             isSerializable(c) &&
  4339             (c.flags() & Flags.ENUM) == 0 &&
  4340             checkForSerial(c)) {
  4341             checkSerialVersionUID(tree, c);
  4343         if (allowTypeAnnos) {
  4344             // Correctly organize the postions of the type annotations
  4345             TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
  4347             // Check type annotations applicability rules
  4348             validateTypeAnnotations(tree);
  4351         // where
  4352         boolean checkForSerial(ClassSymbol c) {
  4353             if ((c.flags() & ABSTRACT) == 0) {
  4354                 return true;
  4355             } else {
  4356                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4360         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4361             @Override
  4362             public boolean accepts(Symbol s) {
  4363                 return s.kind == Kinds.MTH &&
  4364                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4366         };
  4368         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4369         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4370             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4371                 if (types.isSameType(al.head.annotationType.type, t))
  4372                     return al.head.pos();
  4375             return null;
  4378         /** check if a class is a subtype of Serializable, if that is available. */
  4379         private boolean isSerializable(ClassSymbol c) {
  4380             try {
  4381                 syms.serializableType.complete();
  4383             catch (CompletionFailure e) {
  4384                 return false;
  4386             return types.isSubtype(c.type, syms.serializableType);
  4389         /** Check that an appropriate serialVersionUID member is defined. */
  4390         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4392             // check for presence of serialVersionUID
  4393             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4394             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4395             if (e.scope == null) {
  4396                 log.warning(LintCategory.SERIAL,
  4397                         tree.pos(), "missing.SVUID", c);
  4398                 return;
  4401             // check that it is static final
  4402             VarSymbol svuid = (VarSymbol)e.sym;
  4403             if ((svuid.flags() & (STATIC | FINAL)) !=
  4404                 (STATIC | FINAL))
  4405                 log.warning(LintCategory.SERIAL,
  4406                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4408             // check that it is long
  4409             else if (!svuid.type.hasTag(LONG))
  4410                 log.warning(LintCategory.SERIAL,
  4411                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4413             // check constant
  4414             else if (svuid.getConstValue() == null)
  4415                 log.warning(LintCategory.SERIAL,
  4416                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4419     private Type capture(Type type) {
  4420         //do not capture free types
  4421         return resultInfo.checkContext.inferenceContext().free(type) ?
  4422                 type : types.capture(type);
  4425     private void validateTypeAnnotations(JCTree tree) {
  4426         tree.accept(typeAnnotationsValidator);
  4428     //where
  4429     private final JCTree.Visitor typeAnnotationsValidator = new TreeScanner() {
  4431         private boolean checkAllAnnotations = false;
  4433         public void visitAnnotation(JCAnnotation tree) {
  4434             if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
  4435                 chk.validateTypeAnnotation(tree, false);
  4437             super.visitAnnotation(tree);
  4439         public void visitTypeParameter(JCTypeParameter tree) {
  4440             chk.validateTypeAnnotations(tree.annotations, true);
  4441             scan(tree.bounds);
  4442             // Don't call super.
  4443             // This is needed because above we call validateTypeAnnotation with
  4444             // false, which would forbid annotations on type parameters.
  4445             // super.visitTypeParameter(tree);
  4447         public void visitMethodDef(JCMethodDecl tree) {
  4448             if (tree.recvparam != null &&
  4449                     tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
  4450                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4451                         tree.recvparam.vartype.type.tsym);
  4453             if (tree.restype != null && tree.restype.type != null) {
  4454                 validateAnnotatedType(tree.restype, tree.restype.type);
  4456             super.visitMethodDef(tree);
  4458         public void visitVarDef(final JCVariableDecl tree) {
  4459             if (tree.sym != null && tree.sym.type != null)
  4460                 validateAnnotatedType(tree, tree.sym.type);
  4461             super.visitVarDef(tree);
  4463         public void visitTypeCast(JCTypeCast tree) {
  4464             if (tree.clazz != null && tree.clazz.type != null)
  4465                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4466             super.visitTypeCast(tree);
  4468         public void visitTypeTest(JCInstanceOf tree) {
  4469             if (tree.clazz != null && tree.clazz.type != null)
  4470                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4471             super.visitTypeTest(tree);
  4473         public void visitNewClass(JCNewClass tree) {
  4474             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4475                 boolean prevCheck = this.checkAllAnnotations;
  4476                 try {
  4477                     this.checkAllAnnotations = true;
  4478                     scan(((JCAnnotatedType)tree.clazz).annotations);
  4479                 } finally {
  4480                     this.checkAllAnnotations = prevCheck;
  4483             super.visitNewClass(tree);
  4485         public void visitNewArray(JCNewArray tree) {
  4486             if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4487                 boolean prevCheck = this.checkAllAnnotations;
  4488                 try {
  4489                     this.checkAllAnnotations = true;
  4490                     scan(((JCAnnotatedType)tree.elemtype).annotations);
  4491                 } finally {
  4492                     this.checkAllAnnotations = prevCheck;
  4495             super.visitNewArray(tree);
  4498         /* I would want to model this after
  4499          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4500          * and override visitSelect and visitTypeApply.
  4501          * However, we only set the annotated type in the top-level type
  4502          * of the symbol.
  4503          * Therefore, we need to override each individual location where a type
  4504          * can occur.
  4505          */
  4506         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4507             if (type.getEnclosingType() != null &&
  4508                     type != type.getEnclosingType()) {
  4509                 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
  4511             for (Type targ : type.getTypeArguments()) {
  4512                 validateAnnotatedType(errtree, targ);
  4515         private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
  4516             validateAnnotatedType(errtree, type);
  4517             if (type.tsym != null &&
  4518                     type.tsym.isStatic() &&
  4519                     type.getAnnotationMirrors().nonEmpty()) {
  4520                     // Enclosing static classes cannot have type annotations.
  4521                 log.error(errtree.pos(), "cant.annotate.static.class");
  4524     };
  4526     // <editor-fold desc="post-attribution visitor">
  4528     /**
  4529      * Handle missing types/symbols in an AST. This routine is useful when
  4530      * the compiler has encountered some errors (which might have ended up
  4531      * terminating attribution abruptly); if the compiler is used in fail-over
  4532      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4533      * prevents NPE to be progagated during subsequent compilation steps.
  4534      */
  4535     public void postAttr(JCTree tree) {
  4536         new PostAttrAnalyzer().scan(tree);
  4539     class PostAttrAnalyzer extends TreeScanner {
  4541         private void initTypeIfNeeded(JCTree that) {
  4542             if (that.type == null) {
  4543                 that.type = syms.unknownType;
  4547         @Override
  4548         public void scan(JCTree tree) {
  4549             if (tree == null) return;
  4550             if (tree instanceof JCExpression) {
  4551                 initTypeIfNeeded(tree);
  4553             super.scan(tree);
  4556         @Override
  4557         public void visitIdent(JCIdent that) {
  4558             if (that.sym == null) {
  4559                 that.sym = syms.unknownSymbol;
  4563         @Override
  4564         public void visitSelect(JCFieldAccess that) {
  4565             if (that.sym == null) {
  4566                 that.sym = syms.unknownSymbol;
  4568             super.visitSelect(that);
  4571         @Override
  4572         public void visitClassDef(JCClassDecl that) {
  4573             initTypeIfNeeded(that);
  4574             if (that.sym == null) {
  4575                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4577             super.visitClassDef(that);
  4580         @Override
  4581         public void visitMethodDef(JCMethodDecl that) {
  4582             initTypeIfNeeded(that);
  4583             if (that.sym == null) {
  4584                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4586             super.visitMethodDef(that);
  4589         @Override
  4590         public void visitVarDef(JCVariableDecl that) {
  4591             initTypeIfNeeded(that);
  4592             if (that.sym == null) {
  4593                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4594                 that.sym.adr = 0;
  4596             super.visitVarDef(that);
  4599         @Override
  4600         public void visitNewClass(JCNewClass that) {
  4601             if (that.constructor == null) {
  4602                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  4604             if (that.constructorType == null) {
  4605                 that.constructorType = syms.unknownType;
  4607             super.visitNewClass(that);
  4610         @Override
  4611         public void visitAssignop(JCAssignOp that) {
  4612             if (that.operator == null)
  4613                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4614             super.visitAssignop(that);
  4617         @Override
  4618         public void visitBinary(JCBinary that) {
  4619             if (that.operator == null)
  4620                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4621             super.visitBinary(that);
  4624         @Override
  4625         public void visitUnary(JCUnary that) {
  4626             if (that.operator == null)
  4627                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4628             super.visitUnary(that);
  4631         @Override
  4632         public void visitLambda(JCLambda that) {
  4633             super.visitLambda(that);
  4634             if (that.descriptorType == null) {
  4635                 that.descriptorType = syms.unknownType;
  4637             if (that.targets == null) {
  4638                 that.targets = List.nil();
  4642         @Override
  4643         public void visitReference(JCMemberReference that) {
  4644             super.visitReference(that);
  4645             if (that.sym == null) {
  4646                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  4648             if (that.descriptorType == null) {
  4649                 that.descriptorType = syms.unknownType;
  4651             if (that.targets == null) {
  4652                 that.targets = List.nil();
  4656     // </editor-fold>

mercurial