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

Mon, 23 Sep 2013 18:29:27 +0400

author
kizune
date
Mon, 23 Sep 2013 18:29:27 +0400
changeset 2049
64e79d38bd07
parent 2047
5f915a0c9615
child 2056
5043e7056be8
permissions
-rw-r--r--

4881267: improve diagnostic for "instanceof T" for type parameter T
Reviewed-by: vromero, jjg

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.lang.model.type.TypeKind;
    32 import javax.tools.JavaFileObject;
    34 import com.sun.source.tree.IdentifierTree;
    35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    36 import com.sun.source.tree.MemberSelectTree;
    37 import com.sun.source.tree.TreeVisitor;
    38 import com.sun.source.util.SimpleTreeVisitor;
    39 import com.sun.tools.javac.code.*;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.comp.Check.CheckContext;
    44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    45 import com.sun.tools.javac.comp.Infer.InferenceContext;
    46 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    47 import com.sun.tools.javac.jvm.*;
    48 import com.sun.tools.javac.tree.*;
    49 import com.sun.tools.javac.tree.JCTree.*;
    50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    51 import com.sun.tools.javac.util.*;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    53 import com.sun.tools.javac.util.List;
    54 import static com.sun.tools.javac.code.Flags.*;
    55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    56 import static com.sun.tools.javac.code.Flags.BLOCK;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    59 import static com.sun.tools.javac.code.TypeTag.*;
    60 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    61 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    63 /** This is the main context-dependent analysis phase in GJC. It
    64  *  encompasses name resolution, type checking and constant folding as
    65  *  subtasks. Some subtasks involve auxiliary classes.
    66  *  @see Check
    67  *  @see Resolve
    68  *  @see ConstFold
    69  *  @see Infer
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class Attr extends JCTree.Visitor {
    77     protected static final Context.Key<Attr> attrKey =
    78         new Context.Key<Attr>();
    80     final Names names;
    81     final Log log;
    82     final Symtab syms;
    83     final Resolve rs;
    84     final Infer infer;
    85     final DeferredAttr deferredAttr;
    86     final Check chk;
    87     final Flow flow;
    88     final MemberEnter memberEnter;
    89     final TreeMaker make;
    90     final ConstFold cfolder;
    91     final Enter enter;
    92     final Target target;
    93     final Types types;
    94     final JCDiagnostic.Factory diags;
    95     final Annotate annotate;
    96     final DeferredLintHandler deferredLintHandler;
    98     public static Attr instance(Context context) {
    99         Attr instance = context.get(attrKey);
   100         if (instance == null)
   101             instance = new Attr(context);
   102         return instance;
   103     }
   105     protected Attr(Context context) {
   106         context.put(attrKey, this);
   108         names = Names.instance(context);
   109         log = Log.instance(context);
   110         syms = Symtab.instance(context);
   111         rs = Resolve.instance(context);
   112         chk = Check.instance(context);
   113         flow = Flow.instance(context);
   114         memberEnter = MemberEnter.instance(context);
   115         make = TreeMaker.instance(context);
   116         enter = Enter.instance(context);
   117         infer = Infer.instance(context);
   118         deferredAttr = DeferredAttr.instance(context);
   119         cfolder = ConstFold.instance(context);
   120         target = Target.instance(context);
   121         types = Types.instance(context);
   122         diags = JCDiagnostic.Factory.instance(context);
   123         annotate = Annotate.instance(context);
   124         deferredLintHandler = DeferredLintHandler.instance(context);
   126         Options options = Options.instance(context);
   128         Source source = Source.instance(context);
   129         allowGenerics = source.allowGenerics();
   130         allowVarargs = source.allowVarargs();
   131         allowEnums = source.allowEnums();
   132         allowBoxing = source.allowBoxing();
   133         allowCovariantReturns = source.allowCovariantReturns();
   134         allowAnonOuterThis = source.allowAnonOuterThis();
   135         allowStringsInSwitch = source.allowStringsInSwitch();
   136         allowPoly = source.allowPoly();
   137         allowTypeAnnos = source.allowTypeAnnotations();
   138         allowLambda = source.allowLambda();
   139         allowDefaultMethods = source.allowDefaultMethods();
   140         sourceName = source.name;
   141         relax = (options.isSet("-retrofit") ||
   142                  options.isSet("-relax"));
   143         findDiamonds = options.get("findDiamond") != null &&
   144                  source.allowDiamond();
   145         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   146         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   148         statInfo = new ResultInfo(NIL, Type.noType);
   149         varInfo = new ResultInfo(VAR, Type.noType);
   150         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   151         unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly);
   152         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   153         unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
   154         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   155     }
   157     /** Switch: relax some constraints for retrofit mode.
   158      */
   159     boolean relax;
   161     /** Switch: support target-typing inference
   162      */
   163     boolean allowPoly;
   165     /** Switch: support type annotations.
   166      */
   167     boolean allowTypeAnnos;
   169     /** Switch: support generics?
   170      */
   171     boolean allowGenerics;
   173     /** Switch: allow variable-arity methods.
   174      */
   175     boolean allowVarargs;
   177     /** Switch: support enums?
   178      */
   179     boolean allowEnums;
   181     /** Switch: support boxing and unboxing?
   182      */
   183     boolean allowBoxing;
   185     /** Switch: support covariant result types?
   186      */
   187     boolean allowCovariantReturns;
   189     /** Switch: support lambda expressions ?
   190      */
   191     boolean allowLambda;
   193     /** Switch: support default methods ?
   194      */
   195     boolean allowDefaultMethods;
   197     /** Switch: allow references to surrounding object from anonymous
   198      * objects during constructor call?
   199      */
   200     boolean allowAnonOuterThis;
   202     /** Switch: generates a warning if diamond can be safely applied
   203      *  to a given new expression
   204      */
   205     boolean findDiamonds;
   207     /**
   208      * Internally enables/disables diamond finder feature
   209      */
   210     static final boolean allowDiamondFinder = true;
   212     /**
   213      * Switch: warn about use of variable before declaration?
   214      * RFE: 6425594
   215      */
   216     boolean useBeforeDeclarationWarning;
   218     /**
   219      * Switch: generate warnings whenever an anonymous inner class that is convertible
   220      * to a lambda expression is found
   221      */
   222     boolean identifyLambdaCandidate;
   224     /**
   225      * Switch: allow strings in switch?
   226      */
   227     boolean allowStringsInSwitch;
   229     /**
   230      * Switch: name of source level; used for error reporting.
   231      */
   232     String sourceName;
   234     /** Check kind and type of given tree against protokind and prototype.
   235      *  If check succeeds, store type in tree and return it.
   236      *  If check fails, store errType in tree and return it.
   237      *  No checks are performed if the prototype is a method type.
   238      *  It is not necessary in this case since we know that kind and type
   239      *  are correct.
   240      *
   241      *  @param tree     The tree whose kind and type is checked
   242      *  @param ownkind  The computed kind of the tree
   243      *  @param resultInfo  The expected result of the tree
   244      */
   245     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   246         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   247         Type owntype = found;
   248         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   249             if (allowPoly && inferenceContext.free(found)) {
   250                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   251                     @Override
   252                     public void typesInferred(InferenceContext inferenceContext) {
   253                         ResultInfo pendingResult =
   254                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   255                         check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   256                     }
   257                 });
   258                 return tree.type = resultInfo.pt;
   259             } else {
   260                 if ((ownkind & ~resultInfo.pkind) == 0) {
   261                     owntype = resultInfo.check(tree, owntype);
   262                 } else {
   263                     log.error(tree.pos(), "unexpected.type",
   264                             kindNames(resultInfo.pkind),
   265                             kindName(ownkind));
   266                     owntype = types.createErrorType(owntype);
   267                 }
   268             }
   269         }
   270         tree.type = owntype;
   271         return owntype;
   272     }
   274     /** Is given blank final variable assignable, i.e. in a scope where it
   275      *  may be assigned to even though it is final?
   276      *  @param v      The blank final variable.
   277      *  @param env    The current environment.
   278      */
   279     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   280         Symbol owner = owner(env);
   281            // owner refers to the innermost variable, method or
   282            // initializer block declaration at this point.
   283         return
   284             v.owner == owner
   285             ||
   286             ((owner.name == names.init ||    // i.e. we are in a constructor
   287               owner.kind == VAR ||           // i.e. we are in a variable initializer
   288               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   289              &&
   290              v.owner == owner.owner
   291              &&
   292              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   293     }
   295     /**
   296      * Return the innermost enclosing owner symbol in a given attribution context
   297      */
   298     Symbol owner(Env<AttrContext> env) {
   299         while (true) {
   300             switch (env.tree.getTag()) {
   301                 case VARDEF:
   302                     //a field can be owner
   303                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   304                     if (vsym.owner.kind == TYP) {
   305                         return vsym;
   306                     }
   307                     break;
   308                 case METHODDEF:
   309                     //method def is always an owner
   310                     return ((JCMethodDecl)env.tree).sym;
   311                 case CLASSDEF:
   312                     //class def is always an owner
   313                     return ((JCClassDecl)env.tree).sym;
   314                 case LAMBDA:
   315                     //a lambda is an owner - return a fresh synthetic method symbol
   316                     return new MethodSymbol(0, names.empty, null, syms.methodClass);
   317                 case BLOCK:
   318                     //static/instance init blocks are owner
   319                     Symbol blockSym = env.info.scope.owner;
   320                     if ((blockSym.flags() & BLOCK) != 0) {
   321                         return blockSym;
   322                     }
   323                     break;
   324                 case TOPLEVEL:
   325                     //toplevel is always an owner (for pkge decls)
   326                     return env.info.scope.owner;
   327             }
   328             Assert.checkNonNull(env.next);
   329             env = env.next;
   330         }
   331     }
   333     /** Check that variable can be assigned to.
   334      *  @param pos    The current source code position.
   335      *  @param v      The assigned varaible
   336      *  @param base   If the variable is referred to in a Select, the part
   337      *                to the left of the `.', null otherwise.
   338      *  @param env    The current environment.
   339      */
   340     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   341         if ((v.flags() & FINAL) != 0 &&
   342             ((v.flags() & HASINIT) != 0
   343              ||
   344              !((base == null ||
   345                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   346                isAssignableAsBlankFinal(v, env)))) {
   347             if (v.isResourceVariable()) { //TWR resource
   348                 log.error(pos, "try.resource.may.not.be.assigned", v);
   349             } else {
   350                 log.error(pos, "cant.assign.val.to.final.var", v);
   351             }
   352         }
   353     }
   355     /** Does tree represent a static reference to an identifier?
   356      *  It is assumed that tree is either a SELECT or an IDENT.
   357      *  We have to weed out selects from non-type names here.
   358      *  @param tree    The candidate tree.
   359      */
   360     boolean isStaticReference(JCTree tree) {
   361         if (tree.hasTag(SELECT)) {
   362             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   363             if (lsym == null || lsym.kind != TYP) {
   364                 return false;
   365             }
   366         }
   367         return true;
   368     }
   370     /** Is this symbol a type?
   371      */
   372     static boolean isType(Symbol sym) {
   373         return sym != null && sym.kind == TYP;
   374     }
   376     /** The current `this' symbol.
   377      *  @param env    The current environment.
   378      */
   379     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   380         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   381     }
   383     /** Attribute a parsed identifier.
   384      * @param tree Parsed identifier name
   385      * @param topLevel The toplevel to use
   386      */
   387     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   388         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   389         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   390                                            syms.errSymbol.name,
   391                                            null, null, null, null);
   392         localEnv.enclClass.sym = syms.errSymbol;
   393         return tree.accept(identAttributer, localEnv);
   394     }
   395     // where
   396         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   397         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   398             @Override
   399             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   400                 Symbol site = visit(node.getExpression(), env);
   401                 if (site.kind == ERR || site.kind == ABSENT_TYP)
   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 = env;
   485         }
   486     }
   488     class ResultInfo {
   489         final int pkind;
   490         final Type pt;
   491         final CheckContext checkContext;
   493         ResultInfo(int pkind, Type pt) {
   494             this(pkind, pt, chk.basicHandler);
   495         }
   497         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   498             this.pkind = pkind;
   499             this.pt = pt;
   500             this.checkContext = checkContext;
   501         }
   503         protected Type check(final DiagnosticPosition pos, final Type found) {
   504             return chk.checkType(pos, found, pt, checkContext);
   505         }
   507         protected ResultInfo dup(Type newPt) {
   508             return new ResultInfo(pkind, newPt, checkContext);
   509         }
   511         protected ResultInfo dup(CheckContext newContext) {
   512             return new ResultInfo(pkind, pt, newContext);
   513         }
   514     }
   516     class RecoveryInfo extends ResultInfo {
   518         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   519             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   520                 @Override
   521                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   522                     return deferredAttrContext;
   523                 }
   524                 @Override
   525                 public boolean compatible(Type found, Type req, Warner warn) {
   526                     return true;
   527                 }
   528                 @Override
   529                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   530                     chk.basicHandler.report(pos, details);
   531                 }
   532             });
   533         }
   534     }
   536     final ResultInfo statInfo;
   537     final ResultInfo varInfo;
   538     final ResultInfo unknownAnyPolyInfo;
   539     final ResultInfo unknownExprInfo;
   540     final ResultInfo unknownTypeInfo;
   541     final ResultInfo unknownTypeExprInfo;
   542     final ResultInfo recoveryInfo;
   544     Type pt() {
   545         return resultInfo.pt;
   546     }
   548     int pkind() {
   549         return resultInfo.pkind;
   550     }
   552 /* ************************************************************************
   553  * Visitor methods
   554  *************************************************************************/
   556     /** Visitor argument: the current environment.
   557      */
   558     Env<AttrContext> env;
   560     /** Visitor argument: the currently expected attribution result.
   561      */
   562     ResultInfo resultInfo;
   564     /** Visitor result: the computed type.
   565      */
   566     Type result;
   568     /** Visitor method: attribute a tree, catching any completion failure
   569      *  exceptions. Return the tree's type.
   570      *
   571      *  @param tree    The tree to be visited.
   572      *  @param env     The environment visitor argument.
   573      *  @param resultInfo   The result info visitor argument.
   574      */
   575     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   576         Env<AttrContext> prevEnv = this.env;
   577         ResultInfo prevResult = this.resultInfo;
   578         try {
   579             this.env = env;
   580             this.resultInfo = resultInfo;
   581             tree.accept(this);
   582             if (tree == breakTree &&
   583                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   584                 throw new BreakAttr(copyEnv(env));
   585             }
   586             return result;
   587         } catch (CompletionFailure ex) {
   588             tree.type = syms.errType;
   589             return chk.completionError(tree.pos(), ex);
   590         } finally {
   591             this.env = prevEnv;
   592             this.resultInfo = prevResult;
   593         }
   594     }
   596     Env<AttrContext> copyEnv(Env<AttrContext> env) {
   597         Env<AttrContext> newEnv =
   598                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   599         if (newEnv.outer != null) {
   600             newEnv.outer = copyEnv(newEnv.outer);
   601         }
   602         return newEnv;
   603     }
   605     Scope copyScope(Scope sc) {
   606         Scope newScope = new Scope(sc.owner);
   607         List<Symbol> elemsList = List.nil();
   608         while (sc != null) {
   609             for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   610                 elemsList = elemsList.prepend(e.sym);
   611             }
   612             sc = sc.next;
   613         }
   614         for (Symbol s : elemsList) {
   615             newScope.enter(s);
   616         }
   617         return newScope;
   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                                       JCVariableDecl variable,
   752                                       Type type) {
   754         DiagnosticPosition prevLintPos
   755                 = deferredLintHandler.setPos(variable.pos());
   757         try {
   758             // Use null as symbol to not attach the type annotation to any symbol.
   759             // The initializer will later also be visited and then we'll attach
   760             // to the symbol.
   761             // This prevents having multiple type annotations, just because of
   762             // lazy constant value evaluation.
   763             memberEnter.typeAnnotate(variable.init, env, null, variable.pos());
   764             annotate.flush();
   765             Type itype = attribExpr(variable.init, env, type);
   766             if (itype.constValue() != null) {
   767                 return coerce(itype, type).constValue();
   768             } else {
   769                 return null;
   770             }
   771         } finally {
   772             deferredLintHandler.setPos(prevLintPos);
   773         }
   774     }
   776     /** Attribute type reference in an `extends' or `implements' clause.
   777      *  Supertypes of anonymous inner classes are usually already attributed.
   778      *
   779      *  @param tree              The tree making up the type reference.
   780      *  @param env               The environment current at the reference.
   781      *  @param classExpected     true if only a class is expected here.
   782      *  @param interfaceExpected true if only an interface is expected here.
   783      */
   784     Type attribBase(JCTree tree,
   785                     Env<AttrContext> env,
   786                     boolean classExpected,
   787                     boolean interfaceExpected,
   788                     boolean checkExtensible) {
   789         Type t = tree.type != null ?
   790             tree.type :
   791             attribType(tree, env);
   792         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   793     }
   794     Type checkBase(Type t,
   795                    JCTree tree,
   796                    Env<AttrContext> env,
   797                    boolean classExpected,
   798                    boolean interfaceExpected,
   799                    boolean checkExtensible) {
   800         if (t.isErroneous())
   801             return t;
   802         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   803             // check that type variable is already visible
   804             if (t.getUpperBound() == null) {
   805                 log.error(tree.pos(), "illegal.forward.ref");
   806                 return types.createErrorType(t);
   807             }
   808         } else {
   809             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   810         }
   811         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   812             log.error(tree.pos(), "intf.expected.here");
   813             // return errType is necessary since otherwise there might
   814             // be undetected cycles which cause attribution to loop
   815             return types.createErrorType(t);
   816         } else if (checkExtensible &&
   817                    classExpected &&
   818                    (t.tsym.flags() & INTERFACE) != 0) {
   819                 log.error(tree.pos(), "no.intf.expected.here");
   820             return types.createErrorType(t);
   821         }
   822         if (checkExtensible &&
   823             ((t.tsym.flags() & FINAL) != 0)) {
   824             log.error(tree.pos(),
   825                       "cant.inherit.from.final", t.tsym);
   826         }
   827         chk.checkNonCyclic(tree.pos(), t);
   828         return t;
   829     }
   831     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   832         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   833         id.type = env.info.scope.owner.type;
   834         id.sym = env.info.scope.owner;
   835         return id.type;
   836     }
   838     public void visitClassDef(JCClassDecl tree) {
   839         // Local classes have not been entered yet, so we need to do it now:
   840         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   841             enter.classEnter(tree, env);
   843         ClassSymbol c = tree.sym;
   844         if (c == null) {
   845             // exit in case something drastic went wrong during enter.
   846             result = null;
   847         } else {
   848             // make sure class has been completed:
   849             c.complete();
   851             // If this class appears as an anonymous class
   852             // in a superclass constructor call where
   853             // no explicit outer instance is given,
   854             // disable implicit outer instance from being passed.
   855             // (This would be an illegal access to "this before super").
   856             if (env.info.isSelfCall &&
   857                 env.tree.hasTag(NEWCLASS) &&
   858                 ((JCNewClass) env.tree).encl == null)
   859             {
   860                 c.flags_field |= NOOUTERTHIS;
   861             }
   862             attribClass(tree.pos(), c);
   863             result = tree.type = c.type;
   864         }
   865     }
   867     public void visitMethodDef(JCMethodDecl tree) {
   868         MethodSymbol m = tree.sym;
   869         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   871         Lint lint = env.info.lint.augment(m);
   872         Lint prevLint = chk.setLint(lint);
   873         MethodSymbol prevMethod = chk.setMethod(m);
   874         try {
   875             deferredLintHandler.flush(tree.pos());
   876             chk.checkDeprecatedAnnotation(tree.pos(), m);
   879             // Create a new environment with local scope
   880             // for attributing the method.
   881             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   882             localEnv.info.lint = lint;
   884             attribStats(tree.typarams, localEnv);
   886             // If we override any other methods, check that we do so properly.
   887             // JLS ???
   888             if (m.isStatic()) {
   889                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   890             } else {
   891                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   892             }
   893             chk.checkOverride(tree, m);
   895             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   896                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   897             }
   899             // Enter all type parameters into the local method scope.
   900             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   901                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   903             ClassSymbol owner = env.enclClass.sym;
   904             if ((owner.flags() & ANNOTATION) != 0 &&
   905                 tree.params.nonEmpty())
   906                 log.error(tree.params.head.pos(),
   907                           "intf.annotation.members.cant.have.params");
   909             // Attribute all value parameters.
   910             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   911                 attribStat(l.head, localEnv);
   912             }
   914             chk.checkVarargsMethodDecl(localEnv, tree);
   916             // Check that type parameters are well-formed.
   917             chk.validate(tree.typarams, localEnv);
   919             // Check that result type is well-formed.
   920             chk.validate(tree.restype, localEnv);
   922             // Check that receiver type is well-formed.
   923             if (tree.recvparam != null) {
   924                 // Use a new environment to check the receiver parameter.
   925                 // Otherwise I get "might not have been initialized" errors.
   926                 // Is there a better way?
   927                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   928                 attribType(tree.recvparam, newEnv);
   929                 chk.validate(tree.recvparam, newEnv);
   930             }
   932             // annotation method checks
   933             if ((owner.flags() & ANNOTATION) != 0) {
   934                 // annotation method cannot have throws clause
   935                 if (tree.thrown.nonEmpty()) {
   936                     log.error(tree.thrown.head.pos(),
   937                             "throws.not.allowed.in.intf.annotation");
   938                 }
   939                 // annotation method cannot declare type-parameters
   940                 if (tree.typarams.nonEmpty()) {
   941                     log.error(tree.typarams.head.pos(),
   942                             "intf.annotation.members.cant.have.type.params");
   943                 }
   944                 // validate annotation method's return type (could be an annotation type)
   945                 chk.validateAnnotationType(tree.restype);
   946                 // ensure that annotation method does not clash with members of Object/Annotation
   947                 chk.validateAnnotationMethod(tree.pos(), m);
   949                 if (tree.defaultValue != null) {
   950                     // if default value is an annotation, check it is a well-formed
   951                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   952                     chk.validateAnnotationTree(tree.defaultValue);
   953                 }
   954             }
   956             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   957                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   959             if (tree.body == null) {
   960                 // Empty bodies are only allowed for
   961                 // abstract, native, or interface methods, or for methods
   962                 // in a retrofit signature class.
   963                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   964                     !relax)
   965                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   966                 if (tree.defaultValue != null) {
   967                     if ((owner.flags() & ANNOTATION) == 0)
   968                         log.error(tree.pos(),
   969                                   "default.allowed.in.intf.annotation.member");
   970                 }
   971             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   972                 if ((owner.flags() & INTERFACE) != 0) {
   973                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   974                 } else {
   975                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   976                 }
   977             } else if ((tree.mods.flags & NATIVE) != 0) {
   978                 log.error(tree.pos(), "native.meth.cant.have.body");
   979             } else {
   980                 // Add an implicit super() call unless an explicit call to
   981                 // super(...) or this(...) is given
   982                 // or we are compiling class java.lang.Object.
   983                 if (tree.name == names.init && owner.type != syms.objectType) {
   984                     JCBlock body = tree.body;
   985                     if (body.stats.isEmpty() ||
   986                         !TreeInfo.isSelfCall(body.stats.head)) {
   987                         body.stats = body.stats.
   988                             prepend(memberEnter.SuperCall(make.at(body.pos),
   989                                                           List.<Type>nil(),
   990                                                           List.<JCVariableDecl>nil(),
   991                                                           false));
   992                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   993                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   994                                TreeInfo.isSuperCall(body.stats.head)) {
   995                         // enum constructors are not allowed to call super
   996                         // directly, so make sure there aren't any super calls
   997                         // in enum constructors, except in the compiler
   998                         // generated one.
   999                         log.error(tree.body.stats.head.pos(),
  1000                                   "call.to.super.not.allowed.in.enum.ctor",
  1001                                   env.enclClass.sym);
  1005                 // Attribute all type annotations in the body
  1006                 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
  1007                 annotate.flush();
  1009                 // Attribute method body.
  1010                 attribStat(tree.body, localEnv);
  1013             localEnv.info.scope.leave();
  1014             result = tree.type = m.type;
  1015             chk.validateAnnotations(tree.mods.annotations, m);
  1017         finally {
  1018             chk.setLint(prevLint);
  1019             chk.setMethod(prevMethod);
  1023     public void visitVarDef(JCVariableDecl tree) {
  1024         // Local variables have not been entered yet, so we need to do it now:
  1025         if (env.info.scope.owner.kind == MTH) {
  1026             if (tree.sym != null) {
  1027                 // parameters have already been entered
  1028                 env.info.scope.enter(tree.sym);
  1029             } else {
  1030                 memberEnter.memberEnter(tree, env);
  1031                 annotate.flush();
  1033         } else {
  1034             if (tree.init != null) {
  1035                 // Field initializer expression need to be entered.
  1036                 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
  1037                 annotate.flush();
  1041         VarSymbol v = tree.sym;
  1042         Lint lint = env.info.lint.augment(v);
  1043         Lint prevLint = chk.setLint(lint);
  1045         // Check that the variable's declared type is well-formed.
  1046         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1047                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1048                 (tree.sym.flags() & PARAMETER) != 0;
  1049         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1051         try {
  1052             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1053             deferredLintHandler.flush(tree.pos());
  1054             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1056             if (tree.init != null) {
  1057                 if ((v.flags_field & FINAL) == 0 ||
  1058                     !memberEnter.needsLazyConstValue(tree.init)) {
  1059                     // Not a compile-time constant
  1060                     // Attribute initializer in a new environment
  1061                     // with the declared variable as owner.
  1062                     // Check that initializer conforms to variable's declared type.
  1063                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1064                     initEnv.info.lint = lint;
  1065                     // In order to catch self-references, we set the variable's
  1066                     // declaration position to maximal possible value, effectively
  1067                     // marking the variable as undefined.
  1068                     initEnv.info.enclVar = v;
  1069                     attribExpr(tree.init, initEnv, v.type);
  1072             result = tree.type = v.type;
  1073             chk.validateAnnotations(tree.mods.annotations, v);
  1075         finally {
  1076             chk.setLint(prevLint);
  1080     public void visitSkip(JCSkip tree) {
  1081         result = null;
  1084     public void visitBlock(JCBlock tree) {
  1085         if (env.info.scope.owner.kind == TYP) {
  1086             // Block is a static or instance initializer;
  1087             // let the owner of the environment be a freshly
  1088             // created BLOCK-method.
  1089             Env<AttrContext> localEnv =
  1090                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1091             localEnv.info.scope.owner =
  1092                 new MethodSymbol(tree.flags | BLOCK |
  1093                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1094                     env.info.scope.owner);
  1095             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1097             // Attribute all type annotations in the block
  1098             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1099             annotate.flush();
  1102                 // Store init and clinit type annotations with the ClassSymbol
  1103                 // to allow output in Gen.normalizeDefs.
  1104                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1105                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1106                 if ((tree.flags & STATIC) != 0) {
  1107                     cs.appendClassInitTypeAttributes(tas);
  1108                 } else {
  1109                     cs.appendInitTypeAttributes(tas);
  1113             attribStats(tree.stats, localEnv);
  1114         } else {
  1115             // Create a new local environment with a local scope.
  1116             Env<AttrContext> localEnv =
  1117                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1118             try {
  1119                 attribStats(tree.stats, localEnv);
  1120             } finally {
  1121                 localEnv.info.scope.leave();
  1124         result = null;
  1127     public void visitDoLoop(JCDoWhileLoop tree) {
  1128         attribStat(tree.body, env.dup(tree));
  1129         attribExpr(tree.cond, env, syms.booleanType);
  1130         result = null;
  1133     public void visitWhileLoop(JCWhileLoop tree) {
  1134         attribExpr(tree.cond, env, syms.booleanType);
  1135         attribStat(tree.body, env.dup(tree));
  1136         result = null;
  1139     public void visitForLoop(JCForLoop tree) {
  1140         Env<AttrContext> loopEnv =
  1141             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1142         try {
  1143             attribStats(tree.init, loopEnv);
  1144             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1145             loopEnv.tree = tree; // before, we were not in loop!
  1146             attribStats(tree.step, loopEnv);
  1147             attribStat(tree.body, loopEnv);
  1148             result = null;
  1150         finally {
  1151             loopEnv.info.scope.leave();
  1155     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1156         Env<AttrContext> loopEnv =
  1157             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1158         try {
  1159             //the Formal Parameter of a for-each loop is not in the scope when
  1160             //attributing the for-each expression; we mimick this by attributing
  1161             //the for-each expression first (against original scope).
  1162             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1163             attribStat(tree.var, loopEnv);
  1164             chk.checkNonVoid(tree.pos(), exprType);
  1165             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1166             if (elemtype == null) {
  1167                 // or perhaps expr implements Iterable<T>?
  1168                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1169                 if (base == null) {
  1170                     log.error(tree.expr.pos(),
  1171                             "foreach.not.applicable.to.type",
  1172                             exprType,
  1173                             diags.fragment("type.req.array.or.iterable"));
  1174                     elemtype = types.createErrorType(exprType);
  1175                 } else {
  1176                     List<Type> iterableParams = base.allparams();
  1177                     elemtype = iterableParams.isEmpty()
  1178                         ? syms.objectType
  1179                         : types.upperBound(iterableParams.head);
  1182             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1183             loopEnv.tree = tree; // before, we were not in loop!
  1184             attribStat(tree.body, loopEnv);
  1185             result = null;
  1187         finally {
  1188             loopEnv.info.scope.leave();
  1192     public void visitLabelled(JCLabeledStatement tree) {
  1193         // Check that label is not used in an enclosing statement
  1194         Env<AttrContext> env1 = env;
  1195         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1196             if (env1.tree.hasTag(LABELLED) &&
  1197                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1198                 log.error(tree.pos(), "label.already.in.use",
  1199                           tree.label);
  1200                 break;
  1202             env1 = env1.next;
  1205         attribStat(tree.body, env.dup(tree));
  1206         result = null;
  1209     public void visitSwitch(JCSwitch tree) {
  1210         Type seltype = attribExpr(tree.selector, env);
  1212         Env<AttrContext> switchEnv =
  1213             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1215         try {
  1217             boolean enumSwitch =
  1218                 allowEnums &&
  1219                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1220             boolean stringSwitch = false;
  1221             if (types.isSameType(seltype, syms.stringType)) {
  1222                 if (allowStringsInSwitch) {
  1223                     stringSwitch = true;
  1224                 } else {
  1225                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1228             if (!enumSwitch && !stringSwitch)
  1229                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1231             // Attribute all cases and
  1232             // check that there are no duplicate case labels or default clauses.
  1233             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1234             boolean hasDefault = false;      // Is there a default label?
  1235             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1236                 JCCase c = l.head;
  1237                 Env<AttrContext> caseEnv =
  1238                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1239                 try {
  1240                     if (c.pat != null) {
  1241                         if (enumSwitch) {
  1242                             Symbol sym = enumConstant(c.pat, seltype);
  1243                             if (sym == null) {
  1244                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1245                             } else if (!labels.add(sym)) {
  1246                                 log.error(c.pos(), "duplicate.case.label");
  1248                         } else {
  1249                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1250                             if (!pattype.hasTag(ERROR)) {
  1251                                 if (pattype.constValue() == null) {
  1252                                     log.error(c.pat.pos(),
  1253                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1254                                 } else if (labels.contains(pattype.constValue())) {
  1255                                     log.error(c.pos(), "duplicate.case.label");
  1256                                 } else {
  1257                                     labels.add(pattype.constValue());
  1261                     } else if (hasDefault) {
  1262                         log.error(c.pos(), "duplicate.default.label");
  1263                     } else {
  1264                         hasDefault = true;
  1266                     attribStats(c.stats, caseEnv);
  1267                 } finally {
  1268                     caseEnv.info.scope.leave();
  1269                     addVars(c.stats, switchEnv.info.scope);
  1273             result = null;
  1275         finally {
  1276             switchEnv.info.scope.leave();
  1279     // where
  1280         /** Add any variables defined in stats to the switch scope. */
  1281         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1282             for (;stats.nonEmpty(); stats = stats.tail) {
  1283                 JCTree stat = stats.head;
  1284                 if (stat.hasTag(VARDEF))
  1285                     switchScope.enter(((JCVariableDecl) stat).sym);
  1288     // where
  1289     /** Return the selected enumeration constant symbol, or null. */
  1290     private Symbol enumConstant(JCTree tree, Type enumType) {
  1291         if (!tree.hasTag(IDENT)) {
  1292             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1293             return syms.errSymbol;
  1295         JCIdent ident = (JCIdent)tree;
  1296         Name name = ident.name;
  1297         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1298              e.scope != null; e = e.next()) {
  1299             if (e.sym.kind == VAR) {
  1300                 Symbol s = ident.sym = e.sym;
  1301                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1302                 ident.type = s.type;
  1303                 return ((s.flags_field & Flags.ENUM) == 0)
  1304                     ? null : s;
  1307         return null;
  1310     public void visitSynchronized(JCSynchronized tree) {
  1311         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1312         attribStat(tree.body, env);
  1313         result = null;
  1316     public void visitTry(JCTry tree) {
  1317         // Create a new local environment with a local
  1318         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1319         try {
  1320             boolean isTryWithResource = tree.resources.nonEmpty();
  1321             // Create a nested environment for attributing the try block if needed
  1322             Env<AttrContext> tryEnv = isTryWithResource ?
  1323                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1324                 localEnv;
  1325             try {
  1326                 // Attribute resource declarations
  1327                 for (JCTree resource : tree.resources) {
  1328                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1329                         @Override
  1330                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1331                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1333                     };
  1334                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1335                     if (resource.hasTag(VARDEF)) {
  1336                         attribStat(resource, tryEnv);
  1337                         twrResult.check(resource, resource.type);
  1339                         //check that resource type cannot throw InterruptedException
  1340                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1342                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1343                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1344                     } else {
  1345                         attribTree(resource, tryEnv, twrResult);
  1348                 // Attribute body
  1349                 attribStat(tree.body, tryEnv);
  1350             } finally {
  1351                 if (isTryWithResource)
  1352                     tryEnv.info.scope.leave();
  1355             // Attribute catch clauses
  1356             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1357                 JCCatch c = l.head;
  1358                 Env<AttrContext> catchEnv =
  1359                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1360                 try {
  1361                     Type ctype = attribStat(c.param, catchEnv);
  1362                     if (TreeInfo.isMultiCatch(c)) {
  1363                         //multi-catch parameter is implicitly marked as final
  1364                         c.param.sym.flags_field |= FINAL | UNION;
  1366                     if (c.param.sym.kind == Kinds.VAR) {
  1367                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1369                     chk.checkType(c.param.vartype.pos(),
  1370                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1371                                   syms.throwableType);
  1372                     attribStat(c.body, catchEnv);
  1373                 } finally {
  1374                     catchEnv.info.scope.leave();
  1378             // Attribute finalizer
  1379             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1380             result = null;
  1382         finally {
  1383             localEnv.info.scope.leave();
  1387     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1388         if (!resource.isErroneous() &&
  1389             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1390             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1391             Symbol close = syms.noSymbol;
  1392             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1393             try {
  1394                 close = rs.resolveQualifiedMethod(pos,
  1395                         env,
  1396                         resource,
  1397                         names.close,
  1398                         List.<Type>nil(),
  1399                         List.<Type>nil());
  1401             finally {
  1402                 log.popDiagnosticHandler(discardHandler);
  1404             if (close.kind == MTH &&
  1405                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1406                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1407                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1408                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1413     public void visitConditional(JCConditional tree) {
  1414         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1416         tree.polyKind = (!allowPoly ||
  1417                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1418                 isBooleanOrNumeric(env, tree)) ?
  1419                 PolyKind.STANDALONE : PolyKind.POLY;
  1421         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1422             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1423             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1424             result = tree.type = types.createErrorType(resultInfo.pt);
  1425             return;
  1428         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1429                 unknownExprInfo :
  1430                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1431                     //this will use enclosing check context to check compatibility of
  1432                     //subexpression against target type; if we are in a method check context,
  1433                     //depending on whether boxing is allowed, we could have incompatibilities
  1434                     @Override
  1435                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1436                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1438                 });
  1440         Type truetype = attribTree(tree.truepart, env, condInfo);
  1441         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1443         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1444         if (condtype.constValue() != null &&
  1445                 truetype.constValue() != null &&
  1446                 falsetype.constValue() != null &&
  1447                 !owntype.hasTag(NONE)) {
  1448             //constant folding
  1449             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1451         result = check(tree, owntype, VAL, resultInfo);
  1453     //where
  1454         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1455             switch (tree.getTag()) {
  1456                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1457                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1458                               ((JCLiteral)tree).typetag == BOT;
  1459                 case LAMBDA: case REFERENCE: return false;
  1460                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1461                 case CONDEXPR:
  1462                     JCConditional condTree = (JCConditional)tree;
  1463                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1464                             isBooleanOrNumeric(env, condTree.falsepart);
  1465                 case APPLY:
  1466                     JCMethodInvocation speculativeMethodTree =
  1467                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1468                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1469                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1470                 case NEWCLASS:
  1471                     JCExpression className =
  1472                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1473                     JCExpression speculativeNewClassTree =
  1474                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1475                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1476                 default:
  1477                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1478                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1479                     return speculativeType.isPrimitive();
  1482         //where
  1483             TreeTranslator removeClassParams = new TreeTranslator() {
  1484                 @Override
  1485                 public void visitTypeApply(JCTypeApply tree) {
  1486                     result = translate(tree.clazz);
  1488             };
  1490         /** Compute the type of a conditional expression, after
  1491          *  checking that it exists.  See JLS 15.25. Does not take into
  1492          *  account the special case where condition and both arms
  1493          *  are constants.
  1495          *  @param pos      The source position to be used for error
  1496          *                  diagnostics.
  1497          *  @param thentype The type of the expression's then-part.
  1498          *  @param elsetype The type of the expression's else-part.
  1499          */
  1500         private Type condType(DiagnosticPosition pos,
  1501                                Type thentype, Type elsetype) {
  1502             // If same type, that is the result
  1503             if (types.isSameType(thentype, elsetype))
  1504                 return thentype.baseType();
  1506             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1507                 ? thentype : types.unboxedType(thentype);
  1508             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1509                 ? elsetype : types.unboxedType(elsetype);
  1511             // Otherwise, if both arms can be converted to a numeric
  1512             // type, return the least numeric type that fits both arms
  1513             // (i.e. return larger of the two, or return int if one
  1514             // arm is short, the other is char).
  1515             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1516                 // If one arm has an integer subrange type (i.e., byte,
  1517                 // short, or char), and the other is an integer constant
  1518                 // that fits into the subrange, return the subrange type.
  1519                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1520                     elseUnboxed.hasTag(INT) &&
  1521                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1522                     return thenUnboxed.baseType();
  1524                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1525                     thenUnboxed.hasTag(INT) &&
  1526                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1527                     return elseUnboxed.baseType();
  1530                 for (TypeTag tag : primitiveTags) {
  1531                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1532                     if (types.isSubtype(thenUnboxed, candidate) &&
  1533                         types.isSubtype(elseUnboxed, candidate)) {
  1534                         return candidate;
  1539             // Those were all the cases that could result in a primitive
  1540             if (allowBoxing) {
  1541                 if (thentype.isPrimitive())
  1542                     thentype = types.boxedClass(thentype).type;
  1543                 if (elsetype.isPrimitive())
  1544                     elsetype = types.boxedClass(elsetype).type;
  1547             if (types.isSubtype(thentype, elsetype))
  1548                 return elsetype.baseType();
  1549             if (types.isSubtype(elsetype, thentype))
  1550                 return thentype.baseType();
  1552             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1553                 log.error(pos, "neither.conditional.subtype",
  1554                           thentype, elsetype);
  1555                 return thentype.baseType();
  1558             // both are known to be reference types.  The result is
  1559             // lub(thentype,elsetype). This cannot fail, as it will
  1560             // always be possible to infer "Object" if nothing better.
  1561             return types.lub(thentype.baseType(), elsetype.baseType());
  1564     final static TypeTag[] primitiveTags = new TypeTag[]{
  1565         BYTE,
  1566         CHAR,
  1567         SHORT,
  1568         INT,
  1569         LONG,
  1570         FLOAT,
  1571         DOUBLE,
  1572         BOOLEAN,
  1573     };
  1575     public void visitIf(JCIf tree) {
  1576         attribExpr(tree.cond, env, syms.booleanType);
  1577         attribStat(tree.thenpart, env);
  1578         if (tree.elsepart != null)
  1579             attribStat(tree.elsepart, env);
  1580         chk.checkEmptyIf(tree);
  1581         result = null;
  1584     public void visitExec(JCExpressionStatement tree) {
  1585         //a fresh environment is required for 292 inference to work properly ---
  1586         //see Infer.instantiatePolymorphicSignatureInstance()
  1587         Env<AttrContext> localEnv = env.dup(tree);
  1588         attribExpr(tree.expr, localEnv);
  1589         result = null;
  1592     public void visitBreak(JCBreak tree) {
  1593         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1594         result = null;
  1597     public void visitContinue(JCContinue tree) {
  1598         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1599         result = null;
  1601     //where
  1602         /** Return the target of a break or continue statement, if it exists,
  1603          *  report an error if not.
  1604          *  Note: The target of a labelled break or continue is the
  1605          *  (non-labelled) statement tree referred to by the label,
  1606          *  not the tree representing the labelled statement itself.
  1608          *  @param pos     The position to be used for error diagnostics
  1609          *  @param tag     The tag of the jump statement. This is either
  1610          *                 Tree.BREAK or Tree.CONTINUE.
  1611          *  @param label   The label of the jump statement, or null if no
  1612          *                 label is given.
  1613          *  @param env     The environment current at the jump statement.
  1614          */
  1615         private JCTree findJumpTarget(DiagnosticPosition pos,
  1616                                     JCTree.Tag tag,
  1617                                     Name label,
  1618                                     Env<AttrContext> env) {
  1619             // Search environments outwards from the point of jump.
  1620             Env<AttrContext> env1 = env;
  1621             LOOP:
  1622             while (env1 != null) {
  1623                 switch (env1.tree.getTag()) {
  1624                     case LABELLED:
  1625                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1626                         if (label == labelled.label) {
  1627                             // If jump is a continue, check that target is a loop.
  1628                             if (tag == CONTINUE) {
  1629                                 if (!labelled.body.hasTag(DOLOOP) &&
  1630                                         !labelled.body.hasTag(WHILELOOP) &&
  1631                                         !labelled.body.hasTag(FORLOOP) &&
  1632                                         !labelled.body.hasTag(FOREACHLOOP))
  1633                                     log.error(pos, "not.loop.label", label);
  1634                                 // Found labelled statement target, now go inwards
  1635                                 // to next non-labelled tree.
  1636                                 return TreeInfo.referencedStatement(labelled);
  1637                             } else {
  1638                                 return labelled;
  1641                         break;
  1642                     case DOLOOP:
  1643                     case WHILELOOP:
  1644                     case FORLOOP:
  1645                     case FOREACHLOOP:
  1646                         if (label == null) return env1.tree;
  1647                         break;
  1648                     case SWITCH:
  1649                         if (label == null && tag == BREAK) return env1.tree;
  1650                         break;
  1651                     case LAMBDA:
  1652                     case METHODDEF:
  1653                     case CLASSDEF:
  1654                         break LOOP;
  1655                     default:
  1657                 env1 = env1.next;
  1659             if (label != null)
  1660                 log.error(pos, "undef.label", label);
  1661             else if (tag == CONTINUE)
  1662                 log.error(pos, "cont.outside.loop");
  1663             else
  1664                 log.error(pos, "break.outside.switch.loop");
  1665             return null;
  1668     public void visitReturn(JCReturn tree) {
  1669         // Check that there is an enclosing method which is
  1670         // nested within than the enclosing class.
  1671         if (env.info.returnResult == null) {
  1672             log.error(tree.pos(), "ret.outside.meth");
  1673         } else {
  1674             // Attribute return expression, if it exists, and check that
  1675             // it conforms to result type of enclosing method.
  1676             if (tree.expr != null) {
  1677                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1678                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1679                               diags.fragment("unexpected.ret.val"));
  1681                 attribTree(tree.expr, env, env.info.returnResult);
  1682             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1683                     !env.info.returnResult.pt.hasTag(NONE)) {
  1684                 env.info.returnResult.checkContext.report(tree.pos(),
  1685                               diags.fragment("missing.ret.val"));
  1688         result = null;
  1691     public void visitThrow(JCThrow tree) {
  1692         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1693         if (allowPoly) {
  1694             chk.checkType(tree, owntype, syms.throwableType);
  1696         result = null;
  1699     public void visitAssert(JCAssert tree) {
  1700         attribExpr(tree.cond, env, syms.booleanType);
  1701         if (tree.detail != null) {
  1702             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1704         result = null;
  1707      /** Visitor method for method invocations.
  1708      *  NOTE: The method part of an application will have in its type field
  1709      *        the return type of the method, not the method's type itself!
  1710      */
  1711     public void visitApply(JCMethodInvocation tree) {
  1712         // The local environment of a method application is
  1713         // a new environment nested in the current one.
  1714         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1716         // The types of the actual method arguments.
  1717         List<Type> argtypes;
  1719         // The types of the actual method type arguments.
  1720         List<Type> typeargtypes = null;
  1722         Name methName = TreeInfo.name(tree.meth);
  1724         boolean isConstructorCall =
  1725             methName == names._this || methName == names._super;
  1727         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1728         if (isConstructorCall) {
  1729             // We are seeing a ...this(...) or ...super(...) call.
  1730             // Check that this is the first statement in a constructor.
  1731             if (checkFirstConstructorStat(tree, env)) {
  1733                 // Record the fact
  1734                 // that this is a constructor call (using isSelfCall).
  1735                 localEnv.info.isSelfCall = true;
  1737                 // Attribute arguments, yielding list of argument types.
  1738                 attribArgs(tree.args, localEnv, argtypesBuf);
  1739                 argtypes = argtypesBuf.toList();
  1740                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1742                 // Variable `site' points to the class in which the called
  1743                 // constructor is defined.
  1744                 Type site = env.enclClass.sym.type;
  1745                 if (methName == names._super) {
  1746                     if (site == syms.objectType) {
  1747                         log.error(tree.meth.pos(), "no.superclass", site);
  1748                         site = types.createErrorType(syms.objectType);
  1749                     } else {
  1750                         site = types.supertype(site);
  1754                 if (site.hasTag(CLASS)) {
  1755                     Type encl = site.getEnclosingType();
  1756                     while (encl != null && encl.hasTag(TYPEVAR))
  1757                         encl = encl.getUpperBound();
  1758                     if (encl.hasTag(CLASS)) {
  1759                         // we are calling a nested class
  1761                         if (tree.meth.hasTag(SELECT)) {
  1762                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1764                             // We are seeing a prefixed call, of the form
  1765                             //     <expr>.super(...).
  1766                             // Check that the prefix expression conforms
  1767                             // to the outer instance type of the class.
  1768                             chk.checkRefType(qualifier.pos(),
  1769                                              attribExpr(qualifier, localEnv,
  1770                                                         encl));
  1771                         } else if (methName == names._super) {
  1772                             // qualifier omitted; check for existence
  1773                             // of an appropriate implicit qualifier.
  1774                             rs.resolveImplicitThis(tree.meth.pos(),
  1775                                                    localEnv, site, true);
  1777                     } else if (tree.meth.hasTag(SELECT)) {
  1778                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1779                                   site.tsym);
  1782                     // if we're calling a java.lang.Enum constructor,
  1783                     // prefix the implicit String and int parameters
  1784                     if (site.tsym == syms.enumSym && allowEnums)
  1785                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1787                     // Resolve the called constructor under the assumption
  1788                     // that we are referring to a superclass instance of the
  1789                     // current instance (JLS ???).
  1790                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1791                     localEnv.info.selectSuper = true;
  1792                     localEnv.info.pendingResolutionPhase = null;
  1793                     Symbol sym = rs.resolveConstructor(
  1794                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1795                     localEnv.info.selectSuper = selectSuperPrev;
  1797                     // Set method symbol to resolved constructor...
  1798                     TreeInfo.setSymbol(tree.meth, sym);
  1800                     // ...and check that it is legal in the current context.
  1801                     // (this will also set the tree's type)
  1802                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1803                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1805                 // Otherwise, `site' is an error type and we do nothing
  1807             result = tree.type = syms.voidType;
  1808         } else {
  1809             // Otherwise, we are seeing a regular method call.
  1810             // Attribute the arguments, yielding list of argument types, ...
  1811             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1812             argtypes = argtypesBuf.toList();
  1813             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1815             // ... and attribute the method using as a prototype a methodtype
  1816             // whose formal argument types is exactly the list of actual
  1817             // arguments (this will also set the method symbol).
  1818             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1819             localEnv.info.pendingResolutionPhase = null;
  1820             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1822             // Compute the result type.
  1823             Type restype = mtype.getReturnType();
  1824             if (restype.hasTag(WILDCARD))
  1825                 throw new AssertionError(mtype);
  1827             Type qualifier = (tree.meth.hasTag(SELECT))
  1828                     ? ((JCFieldAccess) tree.meth).selected.type
  1829                     : env.enclClass.sym.type;
  1830             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1832             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1834             // Check that value of resulting type is admissible in the
  1835             // current context.  Also, capture the return type
  1836             result = check(tree, capture(restype), VAL, resultInfo);
  1838         chk.validate(tree.typeargs, localEnv);
  1840     //where
  1841         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1842             if (allowCovariantReturns &&
  1843                     methodName == names.clone &&
  1844                 types.isArray(qualifierType)) {
  1845                 // as a special case, array.clone() has a result that is
  1846                 // the same as static type of the array being cloned
  1847                 return qualifierType;
  1848             } else if (allowGenerics &&
  1849                     methodName == names.getClass &&
  1850                     argtypes.isEmpty()) {
  1851                 // as a special case, x.getClass() has type Class<? extends |X|>
  1852                 return new ClassType(restype.getEnclosingType(),
  1853                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1854                                                                BoundKind.EXTENDS,
  1855                                                                syms.boundClass)),
  1856                               restype.tsym);
  1857             } else {
  1858                 return restype;
  1862         /** Check that given application node appears as first statement
  1863          *  in a constructor call.
  1864          *  @param tree   The application node
  1865          *  @param env    The environment current at the application.
  1866          */
  1867         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1868             JCMethodDecl enclMethod = env.enclMethod;
  1869             if (enclMethod != null && enclMethod.name == names.init) {
  1870                 JCBlock body = enclMethod.body;
  1871                 if (body.stats.head.hasTag(EXEC) &&
  1872                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1873                     return true;
  1875             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1876                       TreeInfo.name(tree.meth));
  1877             return false;
  1880         /** Obtain a method type with given argument types.
  1881          */
  1882         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1883             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1884             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1887     public void visitNewClass(final JCNewClass tree) {
  1888         Type owntype = types.createErrorType(tree.type);
  1890         // The local environment of a class creation is
  1891         // a new environment nested in the current one.
  1892         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1894         // The anonymous inner class definition of the new expression,
  1895         // if one is defined by it.
  1896         JCClassDecl cdef = tree.def;
  1898         // If enclosing class is given, attribute it, and
  1899         // complete class name to be fully qualified
  1900         JCExpression clazz = tree.clazz; // Class field following new
  1901         JCExpression clazzid;            // Identifier in class field
  1902         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1903         annoclazzid = null;
  1905         if (clazz.hasTag(TYPEAPPLY)) {
  1906             clazzid = ((JCTypeApply) clazz).clazz;
  1907             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1908                 annoclazzid = (JCAnnotatedType) clazzid;
  1909                 clazzid = annoclazzid.underlyingType;
  1911         } else {
  1912             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1913                 annoclazzid = (JCAnnotatedType) clazz;
  1914                 clazzid = annoclazzid.underlyingType;
  1915             } else {
  1916                 clazzid = clazz;
  1920         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1922         if (tree.encl != null) {
  1923             // We are seeing a qualified new, of the form
  1924             //    <expr>.new C <...> (...) ...
  1925             // In this case, we let clazz stand for the name of the
  1926             // allocated class C prefixed with the type of the qualifier
  1927             // expression, so that we can
  1928             // resolve it with standard techniques later. I.e., if
  1929             // <expr> has type T, then <expr>.new C <...> (...)
  1930             // yields a clazz T.C.
  1931             Type encltype = chk.checkRefType(tree.encl.pos(),
  1932                                              attribExpr(tree.encl, env));
  1933             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1934             // from expr to the combined type, or not? Yes, do this.
  1935             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1936                                                  ((JCIdent) clazzid).name);
  1938             EndPosTable endPosTable = this.env.toplevel.endPositions;
  1939             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  1940             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1941                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1942                 List<JCAnnotation> annos = annoType.annotations;
  1944                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1945                     clazzid1 = make.at(tree.pos).
  1946                         TypeApply(clazzid1,
  1947                                   ((JCTypeApply) clazz).arguments);
  1950                 clazzid1 = make.at(tree.pos).
  1951                     AnnotatedType(annos, clazzid1);
  1952             } else if (clazz.hasTag(TYPEAPPLY)) {
  1953                 clazzid1 = make.at(tree.pos).
  1954                     TypeApply(clazzid1,
  1955                               ((JCTypeApply) clazz).arguments);
  1958             clazz = clazzid1;
  1961         // Attribute clazz expression and store
  1962         // symbol + type back into the attributed tree.
  1963         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1964             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1965             attribType(clazz, env);
  1967         clazztype = chk.checkDiamond(tree, clazztype);
  1968         chk.validate(clazz, localEnv);
  1969         if (tree.encl != null) {
  1970             // We have to work in this case to store
  1971             // symbol + type back into the attributed tree.
  1972             tree.clazz.type = clazztype;
  1973             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1974             clazzid.type = ((JCIdent) clazzid).sym.type;
  1975             if (annoclazzid != null) {
  1976                 annoclazzid.type = clazzid.type;
  1978             if (!clazztype.isErroneous()) {
  1979                 if (cdef != null && clazztype.tsym.isInterface()) {
  1980                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1981                 } else if (clazztype.tsym.isStatic()) {
  1982                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1985         } else if (!clazztype.tsym.isInterface() &&
  1986                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1987             // Check for the existence of an apropos outer instance
  1988             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1991         // Attribute constructor arguments.
  1992         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1993         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  1994         List<Type> argtypes = argtypesBuf.toList();
  1995         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1997         // If we have made no mistakes in the class type...
  1998         if (clazztype.hasTag(CLASS)) {
  1999             // Enums may not be instantiated except implicitly
  2000             if (allowEnums &&
  2001                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  2002                 (!env.tree.hasTag(VARDEF) ||
  2003                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  2004                  ((JCVariableDecl) env.tree).init != tree))
  2005                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2006             // Check that class is not abstract
  2007             if (cdef == null &&
  2008                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2009                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2010                           clazztype.tsym);
  2011             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2012                 // Check that no constructor arguments are given to
  2013                 // anonymous classes implementing an interface
  2014                 if (!argtypes.isEmpty())
  2015                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2017                 if (!typeargtypes.isEmpty())
  2018                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2020                 // Error recovery: pretend no arguments were supplied.
  2021                 argtypes = List.nil();
  2022                 typeargtypes = List.nil();
  2023             } else if (TreeInfo.isDiamond(tree)) {
  2024                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2025                             clazztype.tsym.type.getTypeArguments(),
  2026                             clazztype.tsym);
  2028                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2029                 diamondEnv.info.selectSuper = cdef != null;
  2030                 diamondEnv.info.pendingResolutionPhase = null;
  2032                 //if the type of the instance creation expression is a class type
  2033                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2034                 //of the resolved constructor will be a partially instantiated type
  2035                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2036                             diamondEnv,
  2037                             site,
  2038                             argtypes,
  2039                             typeargtypes);
  2040                 tree.constructor = constructor.baseSymbol();
  2042                 final TypeSymbol csym = clazztype.tsym;
  2043                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2044                     @Override
  2045                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2046                         enclosingContext.report(tree.clazz,
  2047                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2049                 });
  2050                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2051                 constructorType = checkId(tree, site,
  2052                         constructor,
  2053                         diamondEnv,
  2054                         diamondResult);
  2056                 tree.clazz.type = types.createErrorType(clazztype);
  2057                 if (!constructorType.isErroneous()) {
  2058                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2059                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2061                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2064             // Resolve the called constructor under the assumption
  2065             // that we are referring to a superclass instance of the
  2066             // current instance (JLS ???).
  2067             else {
  2068                 //the following code alters some of the fields in the current
  2069                 //AttrContext - hence, the current context must be dup'ed in
  2070                 //order to avoid downstream failures
  2071                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2072                 rsEnv.info.selectSuper = cdef != null;
  2073                 rsEnv.info.pendingResolutionPhase = null;
  2074                 tree.constructor = rs.resolveConstructor(
  2075                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2076                 if (cdef == null) { //do not check twice!
  2077                     tree.constructorType = checkId(tree,
  2078                             clazztype,
  2079                             tree.constructor,
  2080                             rsEnv,
  2081                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2082                     if (rsEnv.info.lastResolveVarargs())
  2083                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2085                 if (cdef == null &&
  2086                         !clazztype.isErroneous() &&
  2087                         clazztype.getTypeArguments().nonEmpty() &&
  2088                         findDiamonds) {
  2089                     findDiamond(localEnv, tree, clazztype);
  2093             if (cdef != null) {
  2094                 // We are seeing an anonymous class instance creation.
  2095                 // In this case, the class instance creation
  2096                 // expression
  2097                 //
  2098                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2099                 //
  2100                 // is represented internally as
  2101                 //
  2102                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2103                 //
  2104                 // This expression is then *transformed* as follows:
  2105                 //
  2106                 // (1) add a STATIC flag to the class definition
  2107                 //     if the current environment is static
  2108                 // (2) add an extends or implements clause
  2109                 // (3) add a constructor.
  2110                 //
  2111                 // For instance, if C is a class, and ET is the type of E,
  2112                 // the expression
  2113                 //
  2114                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2115                 //
  2116                 // is translated to (where X is a fresh name and typarams is the
  2117                 // parameter list of the super constructor):
  2118                 //
  2119                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2120                 //     X extends C<typargs2> {
  2121                 //       <typarams> X(ET e, args) {
  2122                 //         e.<typeargs1>super(args)
  2123                 //       }
  2124                 //       ...
  2125                 //     }
  2126                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2128                 if (clazztype.tsym.isInterface()) {
  2129                     cdef.implementing = List.of(clazz);
  2130                 } else {
  2131                     cdef.extending = clazz;
  2134                 attribStat(cdef, localEnv);
  2136                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2138                 // If an outer instance is given,
  2139                 // prefix it to the constructor arguments
  2140                 // and delete it from the new expression
  2141                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2142                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2143                     argtypes = argtypes.prepend(tree.encl.type);
  2144                     tree.encl = null;
  2147                 // Reassign clazztype and recompute constructor.
  2148                 clazztype = cdef.sym.type;
  2149                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2150                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2151                 Assert.check(sym.kind < AMBIGUOUS);
  2152                 tree.constructor = sym;
  2153                 tree.constructorType = checkId(tree,
  2154                     clazztype,
  2155                     tree.constructor,
  2156                     localEnv,
  2157                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2158             } else {
  2159                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  2160                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  2161                             tree.clazz.type.tsym);
  2165             if (tree.constructor != null && tree.constructor.kind == MTH)
  2166                 owntype = clazztype;
  2168         result = check(tree, owntype, VAL, resultInfo);
  2169         chk.validate(tree.typeargs, localEnv);
  2171     //where
  2172         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2173             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2174             List<JCExpression> prevTypeargs = ta.arguments;
  2175             try {
  2176                 //create a 'fake' diamond AST node by removing type-argument trees
  2177                 ta.arguments = List.nil();
  2178                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2179                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2180                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2181                 Type polyPt = allowPoly ?
  2182                         syms.objectType :
  2183                         clazztype;
  2184                 if (!inferred.isErroneous() &&
  2185                     (allowPoly && pt() == Infer.anyPoly ?
  2186                         types.isSameType(inferred, clazztype) :
  2187                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
  2188                     String key = types.isSameType(clazztype, inferred) ?
  2189                         "diamond.redundant.args" :
  2190                         "diamond.redundant.args.1";
  2191                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2193             } finally {
  2194                 ta.arguments = prevTypeargs;
  2198             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2199                 if (allowLambda &&
  2200                         identifyLambdaCandidate &&
  2201                         clazztype.hasTag(CLASS) &&
  2202                         !pt().hasTag(NONE) &&
  2203                         types.isFunctionalInterface(clazztype.tsym)) {
  2204                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2205                     int count = 0;
  2206                     boolean found = false;
  2207                     for (Symbol sym : csym.members().getElements()) {
  2208                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2209                                 sym.isConstructor()) continue;
  2210                         count++;
  2211                         if (sym.kind != MTH ||
  2212                                 !sym.name.equals(descriptor.name)) continue;
  2213                         Type mtype = types.memberType(clazztype, sym);
  2214                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2215                             found = true;
  2218                     if (found && count == 1) {
  2219                         log.note(tree.def, "potential.lambda.found");
  2224     private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  2225             Symbol sym) {
  2226         // Ensure that no declaration annotations are present.
  2227         // Note that a tree type might be an AnnotatedType with
  2228         // empty annotations, if only declaration annotations were given.
  2229         // This method will raise an error for such a type.
  2230         for (JCAnnotation ai : annotations) {
  2231             if (TypeAnnotations.annotationType(syms, names, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  2232                 log.error(ai.pos(), "annotation.type.not.applicable");
  2238     /** Make an attributed null check tree.
  2239      */
  2240     public JCExpression makeNullCheck(JCExpression arg) {
  2241         // optimization: X.this is never null; skip null check
  2242         Name name = TreeInfo.name(arg);
  2243         if (name == names._this || name == names._super) return arg;
  2245         JCTree.Tag optag = NULLCHK;
  2246         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2247         tree.operator = syms.nullcheck;
  2248         tree.type = arg.type;
  2249         return tree;
  2252     public void visitNewArray(JCNewArray tree) {
  2253         Type owntype = types.createErrorType(tree.type);
  2254         Env<AttrContext> localEnv = env.dup(tree);
  2255         Type elemtype;
  2256         if (tree.elemtype != null) {
  2257             elemtype = attribType(tree.elemtype, localEnv);
  2258             chk.validate(tree.elemtype, localEnv);
  2259             owntype = elemtype;
  2260             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2261                 attribExpr(l.head, localEnv, syms.intType);
  2262                 owntype = new ArrayType(owntype, syms.arrayClass);
  2264             if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  2265                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  2266                         tree.elemtype.type.tsym);
  2268         } else {
  2269             // we are seeing an untyped aggregate { ... }
  2270             // this is allowed only if the prototype is an array
  2271             if (pt().hasTag(ARRAY)) {
  2272                 elemtype = types.elemtype(pt());
  2273             } else {
  2274                 if (!pt().hasTag(ERROR)) {
  2275                     log.error(tree.pos(), "illegal.initializer.for.type",
  2276                               pt());
  2278                 elemtype = types.createErrorType(pt());
  2281         if (tree.elems != null) {
  2282             attribExprs(tree.elems, localEnv, elemtype);
  2283             owntype = new ArrayType(elemtype, syms.arrayClass);
  2285         if (!types.isReifiable(elemtype))
  2286             log.error(tree.pos(), "generic.array.creation");
  2287         result = check(tree, owntype, VAL, resultInfo);
  2290     /*
  2291      * A lambda expression can only be attributed when a target-type is available.
  2292      * In addition, if the target-type is that of a functional interface whose
  2293      * descriptor contains inference variables in argument position the lambda expression
  2294      * is 'stuck' (see DeferredAttr).
  2295      */
  2296     @Override
  2297     public void visitLambda(final JCLambda that) {
  2298         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2299             if (pt().hasTag(NONE)) {
  2300                 //lambda only allowed in assignment or method invocation/cast context
  2301                 log.error(that.pos(), "unexpected.lambda");
  2303             result = that.type = types.createErrorType(pt());
  2304             return;
  2306         //create an environment for attribution of the lambda expression
  2307         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2308         boolean needsRecovery =
  2309                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2310         try {
  2311             Type currentTarget = pt();
  2312             List<Type> explicitParamTypes = null;
  2313             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2314                 //attribute lambda parameters
  2315                 attribStats(that.params, localEnv);
  2316                 explicitParamTypes = TreeInfo.types(that.params);
  2319             Type lambdaType;
  2320             if (pt() != Type.recoveryType) {
  2321                 /* We need to adjust the target. If the target is an
  2322                  * intersection type, for example: SAM & I1 & I2 ...
  2323                  * the target will be updated to SAM
  2324                  */
  2325                 currentTarget = targetChecker.visit(currentTarget, that);
  2326                 if (explicitParamTypes != null) {
  2327                     currentTarget = infer.instantiateFunctionalInterface(that,
  2328                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2330                 lambdaType = types.findDescriptorType(currentTarget);
  2331             } else {
  2332                 currentTarget = Type.recoveryType;
  2333                 lambdaType = fallbackDescriptorType(that);
  2336             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2338             if (lambdaType.hasTag(FORALL)) {
  2339                 //lambda expression target desc cannot be a generic method
  2340                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2341                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2342                 result = that.type = types.createErrorType(pt());
  2343                 return;
  2346             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2347                 //add param type info in the AST
  2348                 List<Type> actuals = lambdaType.getParameterTypes();
  2349                 List<JCVariableDecl> params = that.params;
  2351                 boolean arityMismatch = false;
  2353                 while (params.nonEmpty()) {
  2354                     if (actuals.isEmpty()) {
  2355                         //not enough actuals to perform lambda parameter inference
  2356                         arityMismatch = true;
  2358                     //reset previously set info
  2359                     Type argType = arityMismatch ?
  2360                             syms.errType :
  2361                             actuals.head;
  2362                     params.head.vartype = make.at(params.head).Type(argType);
  2363                     params.head.sym = null;
  2364                     actuals = actuals.isEmpty() ?
  2365                             actuals :
  2366                             actuals.tail;
  2367                     params = params.tail;
  2370                 //attribute lambda parameters
  2371                 attribStats(that.params, localEnv);
  2373                 if (arityMismatch) {
  2374                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2375                         result = that.type = types.createErrorType(currentTarget);
  2376                         return;
  2380             //from this point on, no recovery is needed; if we are in assignment context
  2381             //we will be able to attribute the whole lambda body, regardless of errors;
  2382             //if we are in a 'check' method context, and the lambda is not compatible
  2383             //with the target-type, it will be recovered anyway in Attr.checkId
  2384             needsRecovery = false;
  2386             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2387                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2388                     new FunctionalReturnContext(resultInfo.checkContext);
  2390             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2391                 recoveryInfo :
  2392                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2393             localEnv.info.returnResult = bodyResultInfo;
  2395             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2396                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2397             } else {
  2398                 JCBlock body = (JCBlock)that.body;
  2399                 attribStats(body.stats, localEnv);
  2402             result = check(that, currentTarget, VAL, resultInfo);
  2404             boolean isSpeculativeRound =
  2405                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2407             preFlow(that);
  2408             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2410             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2412             if (!isSpeculativeRound) {
  2413                 //add thrown types as bounds to the thrown types free variables if needed:
  2414                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2415                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2416                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asFree(lambdaType.getThrownTypes());
  2418                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2421                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2423             result = check(that, currentTarget, VAL, resultInfo);
  2424         } catch (Types.FunctionDescriptorLookupError ex) {
  2425             JCDiagnostic cause = ex.getDiagnostic();
  2426             resultInfo.checkContext.report(that, cause);
  2427             result = that.type = types.createErrorType(pt());
  2428             return;
  2429         } finally {
  2430             localEnv.info.scope.leave();
  2431             if (needsRecovery) {
  2432                 attribTree(that, env, recoveryInfo);
  2436     //where
  2437         void preFlow(JCLambda tree) {
  2438             new PostAttrAnalyzer() {
  2439                 @Override
  2440                 public void scan(JCTree tree) {
  2441                     if (tree == null ||
  2442                             (tree.type != null &&
  2443                             tree.type == Type.stuckType)) {
  2444                         //don't touch stuck expressions!
  2445                         return;
  2447                     super.scan(tree);
  2449             }.scan(tree);
  2452         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2454             @Override
  2455             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2456                 return t.isCompound() ?
  2457                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2460             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2461                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2462                 Type target = null;
  2463                 for (Type bound : ict.getExplicitComponents()) {
  2464                     TypeSymbol boundSym = bound.tsym;
  2465                     if (types.isFunctionalInterface(boundSym) &&
  2466                             types.findDescriptorSymbol(boundSym) == desc) {
  2467                         target = bound;
  2468                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2469                         //bound must be an interface
  2470                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2473                 return target != null ?
  2474                         target :
  2475                         ict.getExplicitComponents().head; //error recovery
  2478             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2479                 ListBuffer<Type> targs = new ListBuffer<>();
  2480                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2481                 for (Type i : ict.interfaces_field) {
  2482                     if (i.isParameterized()) {
  2483                         targs.appendList(i.tsym.type.allparams());
  2485                     supertypes.append(i.tsym.type);
  2487                 IntersectionClassType notionalIntf =
  2488                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2489                 notionalIntf.allparams_field = targs.toList();
  2490                 notionalIntf.tsym.flags_field |= INTERFACE;
  2491                 return notionalIntf.tsym;
  2494             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2495                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2496                         diags.fragment(key, args)));
  2498         };
  2500         private Type fallbackDescriptorType(JCExpression tree) {
  2501             switch (tree.getTag()) {
  2502                 case LAMBDA:
  2503                     JCLambda lambda = (JCLambda)tree;
  2504                     List<Type> argtypes = List.nil();
  2505                     for (JCVariableDecl param : lambda.params) {
  2506                         argtypes = param.vartype != null ?
  2507                                 argtypes.append(param.vartype.type) :
  2508                                 argtypes.append(syms.errType);
  2510                     return new MethodType(argtypes, Type.recoveryType,
  2511                             List.of(syms.throwableType), syms.methodClass);
  2512                 case REFERENCE:
  2513                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2514                             List.of(syms.throwableType), syms.methodClass);
  2515                 default:
  2516                     Assert.error("Cannot get here!");
  2518             return null;
  2521         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2522                 final InferenceContext inferenceContext, final Type... ts) {
  2523             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2526         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2527                 final InferenceContext inferenceContext, final List<Type> ts) {
  2528             if (inferenceContext.free(ts)) {
  2529                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2530                     @Override
  2531                     public void typesInferred(InferenceContext inferenceContext) {
  2532                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2534                 });
  2535             } else {
  2536                 for (Type t : ts) {
  2537                     rs.checkAccessibleType(env, t);
  2542         /**
  2543          * Lambda/method reference have a special check context that ensures
  2544          * that i.e. a lambda return type is compatible with the expected
  2545          * type according to both the inherited context and the assignment
  2546          * context.
  2547          */
  2548         class FunctionalReturnContext extends Check.NestedCheckContext {
  2550             FunctionalReturnContext(CheckContext enclosingContext) {
  2551                 super(enclosingContext);
  2554             @Override
  2555             public boolean compatible(Type found, Type req, Warner warn) {
  2556                 //return type must be compatible in both current context and assignment context
  2557                 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
  2560             @Override
  2561             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2562                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2566         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2568             JCExpression expr;
  2570             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2571                 super(enclosingContext);
  2572                 this.expr = expr;
  2575             @Override
  2576             public boolean compatible(Type found, Type req, Warner warn) {
  2577                 //a void return is compatible with an expression statement lambda
  2578                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2579                         super.compatible(found, req, warn);
  2583         /**
  2584         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2585         * are compatible with the expected functional interface descriptor. This means that:
  2586         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2587         * types must be compatible with the return type of the expected descriptor.
  2588         */
  2589         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2590             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2592             //return values have already been checked - but if lambda has no return
  2593             //values, we must ensure that void/value compatibility is correct;
  2594             //this amounts at checking that, if a lambda body can complete normally,
  2595             //the descriptor's return type must be void
  2596             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2597                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2598                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2599                         diags.fragment("missing.ret.val", returnType)));
  2602             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
  2603             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2604                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2608         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2609             Env<AttrContext> lambdaEnv;
  2610             Symbol owner = env.info.scope.owner;
  2611             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2612                 //field initializer
  2613                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2614                 lambdaEnv.info.scope.owner =
  2615                     new MethodSymbol((owner.flags() & STATIC) | BLOCK, names.empty, null,
  2616                                      env.info.scope.owner);
  2617             } else {
  2618                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2620             return lambdaEnv;
  2623     @Override
  2624     public void visitReference(final JCMemberReference that) {
  2625         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2626             if (pt().hasTag(NONE)) {
  2627                 //method reference only allowed in assignment or method invocation/cast context
  2628                 log.error(that.pos(), "unexpected.mref");
  2630             result = that.type = types.createErrorType(pt());
  2631             return;
  2633         final Env<AttrContext> localEnv = env.dup(that);
  2634         try {
  2635             //attribute member reference qualifier - if this is a constructor
  2636             //reference, the expected kind must be a type
  2637             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2639             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2640                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2641                 if (!exprType.isErroneous() &&
  2642                     exprType.isRaw() &&
  2643                     that.typeargs != null) {
  2644                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2645                         diags.fragment("mref.infer.and.explicit.params"));
  2646                     exprType = types.createErrorType(exprType);
  2650             if (exprType.isErroneous()) {
  2651                 //if the qualifier expression contains problems,
  2652                 //give up attribution of method reference
  2653                 result = that.type = exprType;
  2654                 return;
  2657             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2658                 //if the qualifier is a type, validate it; raw warning check is
  2659                 //omitted as we don't know at this stage as to whether this is a
  2660                 //raw selector (because of inference)
  2661                 chk.validate(that.expr, env, false);
  2664             //attrib type-arguments
  2665             List<Type> typeargtypes = List.nil();
  2666             if (that.typeargs != null) {
  2667                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2670             Type target;
  2671             Type desc;
  2672             if (pt() != Type.recoveryType) {
  2673                 target = targetChecker.visit(pt(), that);
  2674                 desc = types.findDescriptorType(target);
  2675             } else {
  2676                 target = Type.recoveryType;
  2677                 desc = fallbackDescriptorType(that);
  2680             setFunctionalInfo(localEnv, that, pt(), desc, target, resultInfo.checkContext);
  2681             List<Type> argtypes = desc.getParameterTypes();
  2682             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2684             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2685                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2688             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2689             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2690             try {
  2691                 refResult = rs.resolveMemberReference(that.pos(), localEnv, that, that.expr.type,
  2692                         that.name, argtypes, typeargtypes, true, referenceCheck,
  2693                         resultInfo.checkContext.inferenceContext());
  2694             } finally {
  2695                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2698             Symbol refSym = refResult.fst;
  2699             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2701             if (refSym.kind != MTH) {
  2702                 boolean targetError;
  2703                 switch (refSym.kind) {
  2704                     case ABSENT_MTH:
  2705                         targetError = false;
  2706                         break;
  2707                     case WRONG_MTH:
  2708                     case WRONG_MTHS:
  2709                     case AMBIGUOUS:
  2710                     case HIDDEN:
  2711                     case STATICERR:
  2712                     case MISSING_ENCL:
  2713                         targetError = true;
  2714                         break;
  2715                     default:
  2716                         Assert.error("unexpected result kind " + refSym.kind);
  2717                         targetError = false;
  2720                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2721                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2723                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2724                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2726                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2727                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2729                 if (targetError && target == Type.recoveryType) {
  2730                     //a target error doesn't make sense during recovery stage
  2731                     //as we don't know what actual parameter types are
  2732                     result = that.type = target;
  2733                     return;
  2734                 } else {
  2735                     if (targetError) {
  2736                         resultInfo.checkContext.report(that, diag);
  2737                     } else {
  2738                         log.report(diag);
  2740                     result = that.type = types.createErrorType(target);
  2741                     return;
  2745             that.sym = refSym.baseSymbol();
  2746             that.kind = lookupHelper.referenceKind(that.sym);
  2747             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2749             if (desc.getReturnType() == Type.recoveryType) {
  2750                 // stop here
  2751                 result = that.type = target;
  2752                 return;
  2755             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2757                 if (that.getMode() == ReferenceMode.INVOKE &&
  2758                         TreeInfo.isStaticSelector(that.expr, names) &&
  2759                         that.kind.isUnbound() &&
  2760                         !desc.getParameterTypes().head.isParameterized()) {
  2761                     chk.checkRaw(that.expr, localEnv);
  2764                 if (!that.kind.isUnbound() &&
  2765                         that.getMode() == ReferenceMode.INVOKE &&
  2766                         TreeInfo.isStaticSelector(that.expr, names) &&
  2767                         !that.sym.isStatic()) {
  2768                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2769                             diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym));
  2770                     result = that.type = types.createErrorType(target);
  2771                     return;
  2774                 if (that.kind.isUnbound() &&
  2775                         that.getMode() == ReferenceMode.INVOKE &&
  2776                         TreeInfo.isStaticSelector(that.expr, names) &&
  2777                         that.sym.isStatic()) {
  2778                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2779                             diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym));
  2780                     result = that.type = types.createErrorType(target);
  2781                     return;
  2784                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2785                         exprType.getTypeArguments().nonEmpty()) {
  2786                     //static ref with class type-args
  2787                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2788                             diags.fragment("static.mref.with.targs"));
  2789                     result = that.type = types.createErrorType(target);
  2790                     return;
  2793                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2794                         !that.kind.isUnbound()) {
  2795                     //no static bound mrefs
  2796                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2797                             diags.fragment("static.bound.mref"));
  2798                     result = that.type = types.createErrorType(target);
  2799                     return;
  2802                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2803                     // Check that super-qualified symbols are not abstract (JLS)
  2804                     rs.checkNonAbstract(that.pos(), that.sym);
  2808             ResultInfo checkInfo =
  2809                     resultInfo.dup(newMethodTemplate(
  2810                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2811                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes));
  2813             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2815             if (that.kind.isUnbound() &&
  2816                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2817                 //re-generate inference constraints for unbound receiver
  2818                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asFree(argtypes.head), exprType)) {
  2819                     //cannot happen as this has already been checked - we just need
  2820                     //to regenerate the inference constraints, as that has been lost
  2821                     //as a result of the call to inferenceContext.save()
  2822                     Assert.error("Can't get here");
  2826             if (!refType.isErroneous()) {
  2827                 refType = types.createMethodTypeWithReturn(refType,
  2828                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2831             //go ahead with standard method reference compatibility check - note that param check
  2832             //is a no-op (as this has been taken care during method applicability)
  2833             boolean isSpeculativeRound =
  2834                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2835             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2836             if (!isSpeculativeRound) {
  2837                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2839             result = check(that, target, VAL, resultInfo);
  2840         } catch (Types.FunctionDescriptorLookupError ex) {
  2841             JCDiagnostic cause = ex.getDiagnostic();
  2842             resultInfo.checkContext.report(that, cause);
  2843             result = that.type = types.createErrorType(pt());
  2844             return;
  2847     //where
  2848         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2849             //if this is a constructor reference, the expected kind must be a type
  2850             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2854     @SuppressWarnings("fallthrough")
  2855     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2856         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2858         Type resType;
  2859         switch (tree.getMode()) {
  2860             case NEW:
  2861                 if (!tree.expr.type.isRaw()) {
  2862                     resType = tree.expr.type;
  2863                     break;
  2865             default:
  2866                 resType = refType.getReturnType();
  2869         Type incompatibleReturnType = resType;
  2871         if (returnType.hasTag(VOID)) {
  2872             incompatibleReturnType = null;
  2875         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2876             if (resType.isErroneous() ||
  2877                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2878                 incompatibleReturnType = null;
  2882         if (incompatibleReturnType != null) {
  2883             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2884                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2887         if (!speculativeAttr) {
  2888             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2889             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2890                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2895     /**
  2896      * Set functional type info on the underlying AST. Note: as the target descriptor
  2897      * might contain inference variables, we might need to register an hook in the
  2898      * current inference context.
  2899      */
  2900     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  2901             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  2902         if (checkContext.inferenceContext().free(descriptorType)) {
  2903             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2904                 public void typesInferred(InferenceContext inferenceContext) {
  2905                     setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  2906                             inferenceContext.asInstType(primaryTarget), checkContext);
  2908             });
  2909         } else {
  2910             ListBuffer<Type> targets = new ListBuffer<>();
  2911             if (pt.hasTag(CLASS)) {
  2912                 if (pt.isCompound()) {
  2913                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  2914                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2915                         if (t != primaryTarget) {
  2916                             targets.append(types.removeWildcards(t));
  2919                 } else {
  2920                     targets.append(types.removeWildcards(primaryTarget));
  2923             fExpr.targets = targets.toList();
  2924             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2925                     pt != Type.recoveryType) {
  2926                 //check that functional interface class is well-formed
  2927                 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
  2928                         names.empty, List.of(fExpr.targets.head), ABSTRACT);
  2929                 if (csym != null) {
  2930                     chk.checkImplementations(env.tree, csym, csym);
  2936     public void visitParens(JCParens tree) {
  2937         Type owntype = attribTree(tree.expr, env, resultInfo);
  2938         result = check(tree, owntype, pkind(), resultInfo);
  2939         Symbol sym = TreeInfo.symbol(tree);
  2940         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2941             log.error(tree.pos(), "illegal.start.of.type");
  2944     public void visitAssign(JCAssign tree) {
  2945         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2946         Type capturedType = capture(owntype);
  2947         attribExpr(tree.rhs, env, owntype);
  2948         result = check(tree, capturedType, VAL, resultInfo);
  2951     public void visitAssignop(JCAssignOp tree) {
  2952         // Attribute arguments.
  2953         Type owntype = attribTree(tree.lhs, env, varInfo);
  2954         Type operand = attribExpr(tree.rhs, env);
  2955         // Find operator.
  2956         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2957             tree.pos(), tree.getTag().noAssignOp(), env,
  2958             owntype, operand);
  2960         if (operator.kind == MTH &&
  2961                 !owntype.isErroneous() &&
  2962                 !operand.isErroneous()) {
  2963             chk.checkOperator(tree.pos(),
  2964                               (OperatorSymbol)operator,
  2965                               tree.getTag().noAssignOp(),
  2966                               owntype,
  2967                               operand);
  2968             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2969             chk.checkCastable(tree.rhs.pos(),
  2970                               operator.type.getReturnType(),
  2971                               owntype);
  2973         result = check(tree, owntype, VAL, resultInfo);
  2976     public void visitUnary(JCUnary tree) {
  2977         // Attribute arguments.
  2978         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2979             ? attribTree(tree.arg, env, varInfo)
  2980             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2982         // Find operator.
  2983         Symbol operator = tree.operator =
  2984             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2986         Type owntype = types.createErrorType(tree.type);
  2987         if (operator.kind == MTH &&
  2988                 !argtype.isErroneous()) {
  2989             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2990                 ? tree.arg.type
  2991                 : operator.type.getReturnType();
  2992             int opc = ((OperatorSymbol)operator).opcode;
  2994             // If the argument is constant, fold it.
  2995             if (argtype.constValue() != null) {
  2996                 Type ctype = cfolder.fold1(opc, argtype);
  2997                 if (ctype != null) {
  2998                     owntype = cfolder.coerce(ctype, owntype);
  3000                     // Remove constant types from arguments to
  3001                     // conserve space. The parser will fold concatenations
  3002                     // of string literals; the code here also
  3003                     // gets rid of intermediate results when some of the
  3004                     // operands are constant identifiers.
  3005                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  3006                         tree.arg.type = syms.stringType;
  3011         result = check(tree, owntype, VAL, resultInfo);
  3014     public void visitBinary(JCBinary tree) {
  3015         // Attribute arguments.
  3016         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3017         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3019         // Find operator.
  3020         Symbol operator = tree.operator =
  3021             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3023         Type owntype = types.createErrorType(tree.type);
  3024         if (operator.kind == MTH &&
  3025                 !left.isErroneous() &&
  3026                 !right.isErroneous()) {
  3027             owntype = operator.type.getReturnType();
  3028             // This will figure out when unboxing can happen and
  3029             // choose the right comparison operator.
  3030             int opc = chk.checkOperator(tree.lhs.pos(),
  3031                                         (OperatorSymbol)operator,
  3032                                         tree.getTag(),
  3033                                         left,
  3034                                         right);
  3036             // If both arguments are constants, fold them.
  3037             if (left.constValue() != null && right.constValue() != null) {
  3038                 Type ctype = cfolder.fold2(opc, left, right);
  3039                 if (ctype != null) {
  3040                     owntype = cfolder.coerce(ctype, owntype);
  3042                     // Remove constant types from arguments to
  3043                     // conserve space. The parser will fold concatenations
  3044                     // of string literals; the code here also
  3045                     // gets rid of intermediate results when some of the
  3046                     // operands are constant identifiers.
  3047                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  3048                         tree.lhs.type = syms.stringType;
  3050                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  3051                         tree.rhs.type = syms.stringType;
  3056             // Check that argument types of a reference ==, != are
  3057             // castable to each other, (JLS 15.21).  Note: unboxing
  3058             // comparisons will not have an acmp* opc at this point.
  3059             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3060                 if (!types.isEqualityComparable(left, right,
  3061                                                 new Warner(tree.pos()))) {
  3062                     log.error(tree.pos(), "incomparable.types", left, right);
  3066             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3068         result = check(tree, owntype, VAL, resultInfo);
  3071     public void visitTypeCast(final JCTypeCast tree) {
  3072         Type clazztype = attribType(tree.clazz, env);
  3073         chk.validate(tree.clazz, env, false);
  3074         //a fresh environment is required for 292 inference to work properly ---
  3075         //see Infer.instantiatePolymorphicSignatureInstance()
  3076         Env<AttrContext> localEnv = env.dup(tree);
  3077         //should we propagate the target type?
  3078         final ResultInfo castInfo;
  3079         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3080         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3081         if (isPoly) {
  3082             //expression is a poly - we need to propagate target type info
  3083             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3084                 @Override
  3085                 public boolean compatible(Type found, Type req, Warner warn) {
  3086                     return types.isCastable(found, req, warn);
  3088             });
  3089         } else {
  3090             //standalone cast - target-type info is not propagated
  3091             castInfo = unknownExprInfo;
  3093         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3094         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3095         if (exprtype.constValue() != null)
  3096             owntype = cfolder.coerce(exprtype, owntype);
  3097         result = check(tree, capture(owntype), VAL, resultInfo);
  3098         if (!isPoly)
  3099             chk.checkRedundantCast(localEnv, tree);
  3102     public void visitTypeTest(JCInstanceOf tree) {
  3103         Type exprtype = chk.checkNullOrRefType(
  3104             tree.expr.pos(), attribExpr(tree.expr, env));
  3105         Type clazztype = attribType(tree.clazz, env);
  3106         if (!clazztype.hasTag(TYPEVAR)) {
  3107             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3109         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3110             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3111             clazztype = types.createErrorType(clazztype);
  3113         chk.validate(tree.clazz, env, false);
  3114         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3115         result = check(tree, syms.booleanType, VAL, resultInfo);
  3118     public void visitIndexed(JCArrayAccess tree) {
  3119         Type owntype = types.createErrorType(tree.type);
  3120         Type atype = attribExpr(tree.indexed, env);
  3121         attribExpr(tree.index, env, syms.intType);
  3122         if (types.isArray(atype))
  3123             owntype = types.elemtype(atype);
  3124         else if (!atype.hasTag(ERROR))
  3125             log.error(tree.pos(), "array.req.but.found", atype);
  3126         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3127         result = check(tree, owntype, VAR, resultInfo);
  3130     public void visitIdent(JCIdent tree) {
  3131         Symbol sym;
  3133         // Find symbol
  3134         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3135             // If we are looking for a method, the prototype `pt' will be a
  3136             // method type with the type of the call's arguments as parameters.
  3137             env.info.pendingResolutionPhase = null;
  3138             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3139         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3140             sym = tree.sym;
  3141         } else {
  3142             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3144         tree.sym = sym;
  3146         // (1) Also find the environment current for the class where
  3147         //     sym is defined (`symEnv').
  3148         // Only for pre-tiger versions (1.4 and earlier):
  3149         // (2) Also determine whether we access symbol out of an anonymous
  3150         //     class in a this or super call.  This is illegal for instance
  3151         //     members since such classes don't carry a this$n link.
  3152         //     (`noOuterThisPath').
  3153         Env<AttrContext> symEnv = env;
  3154         boolean noOuterThisPath = false;
  3155         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3156             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3157             sym.owner.kind == TYP &&
  3158             tree.name != names._this && tree.name != names._super) {
  3160             // Find environment in which identifier is defined.
  3161             while (symEnv.outer != null &&
  3162                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3163                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3164                     noOuterThisPath = !allowAnonOuterThis;
  3165                 symEnv = symEnv.outer;
  3169         // If symbol is a variable, ...
  3170         if (sym.kind == VAR) {
  3171             VarSymbol v = (VarSymbol)sym;
  3173             // ..., evaluate its initializer, if it has one, and check for
  3174             // illegal forward reference.
  3175             checkInit(tree, env, v, false);
  3177             // If we are expecting a variable (as opposed to a value), check
  3178             // that the variable is assignable in the current environment.
  3179             if (pkind() == VAR)
  3180                 checkAssignable(tree.pos(), v, null, env);
  3183         // In a constructor body,
  3184         // if symbol is a field or instance method, check that it is
  3185         // not accessed before the supertype constructor is called.
  3186         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3187             (sym.kind & (VAR | MTH)) != 0 &&
  3188             sym.owner.kind == TYP &&
  3189             (sym.flags() & STATIC) == 0) {
  3190             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3192         Env<AttrContext> env1 = env;
  3193         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3194             // If the found symbol is inaccessible, then it is
  3195             // accessed through an enclosing instance.  Locate this
  3196             // enclosing instance:
  3197             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3198                 env1 = env1.outer;
  3200         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3203     public void visitSelect(JCFieldAccess tree) {
  3204         // Determine the expected kind of the qualifier expression.
  3205         int skind = 0;
  3206         if (tree.name == names._this || tree.name == names._super ||
  3207             tree.name == names._class)
  3209             skind = TYP;
  3210         } else {
  3211             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3212             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3213             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3216         // Attribute the qualifier expression, and determine its symbol (if any).
  3217         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3218         if ((pkind() & (PCK | TYP)) == 0)
  3219             site = capture(site); // Capture field access
  3221         // don't allow T.class T[].class, etc
  3222         if (skind == TYP) {
  3223             Type elt = site;
  3224             while (elt.hasTag(ARRAY))
  3225                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3226             if (elt.hasTag(TYPEVAR)) {
  3227                 log.error(tree.pos(), "type.var.cant.be.deref");
  3228                 result = types.createErrorType(tree.type);
  3229                 return;
  3233         // If qualifier symbol is a type or `super', assert `selectSuper'
  3234         // for the selection. This is relevant for determining whether
  3235         // protected symbols are accessible.
  3236         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3237         boolean selectSuperPrev = env.info.selectSuper;
  3238         env.info.selectSuper =
  3239             sitesym != null &&
  3240             sitesym.name == names._super;
  3242         // Determine the symbol represented by the selection.
  3243         env.info.pendingResolutionPhase = null;
  3244         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3245         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3246             site = capture(site);
  3247             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3249         boolean varArgs = env.info.lastResolveVarargs();
  3250         tree.sym = sym;
  3252         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3253             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3254             site = capture(site);
  3257         // If that symbol is a variable, ...
  3258         if (sym.kind == VAR) {
  3259             VarSymbol v = (VarSymbol)sym;
  3261             // ..., evaluate its initializer, if it has one, and check for
  3262             // illegal forward reference.
  3263             checkInit(tree, env, v, true);
  3265             // If we are expecting a variable (as opposed to a value), check
  3266             // that the variable is assignable in the current environment.
  3267             if (pkind() == VAR)
  3268                 checkAssignable(tree.pos(), v, tree.selected, env);
  3271         if (sitesym != null &&
  3272                 sitesym.kind == VAR &&
  3273                 ((VarSymbol)sitesym).isResourceVariable() &&
  3274                 sym.kind == MTH &&
  3275                 sym.name.equals(names.close) &&
  3276                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3277                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3278             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3281         // Disallow selecting a type from an expression
  3282         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3283             tree.type = check(tree.selected, pt(),
  3284                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3287         if (isType(sitesym)) {
  3288             if (sym.name == names._this) {
  3289                 // If `C' is the currently compiled class, check that
  3290                 // C.this' does not appear in a call to a super(...)
  3291                 if (env.info.isSelfCall &&
  3292                     site.tsym == env.enclClass.sym) {
  3293                     chk.earlyRefError(tree.pos(), sym);
  3295             } else {
  3296                 // Check if type-qualified fields or methods are static (JLS)
  3297                 if ((sym.flags() & STATIC) == 0 &&
  3298                     !env.next.tree.hasTag(REFERENCE) &&
  3299                     sym.name != names._super &&
  3300                     (sym.kind == VAR || sym.kind == MTH)) {
  3301                     rs.accessBase(rs.new StaticError(sym),
  3302                               tree.pos(), site, sym.name, true);
  3305         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3306             // If the qualified item is not a type and the selected item is static, report
  3307             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3308             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3311         // If we are selecting an instance member via a `super', ...
  3312         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3314             // Check that super-qualified symbols are not abstract (JLS)
  3315             rs.checkNonAbstract(tree.pos(), sym);
  3317             if (site.isRaw()) {
  3318                 // Determine argument types for site.
  3319                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3320                 if (site1 != null) site = site1;
  3324         env.info.selectSuper = selectSuperPrev;
  3325         result = checkId(tree, site, sym, env, resultInfo);
  3327     //where
  3328         /** Determine symbol referenced by a Select expression,
  3330          *  @param tree   The select tree.
  3331          *  @param site   The type of the selected expression,
  3332          *  @param env    The current environment.
  3333          *  @param resultInfo The current result.
  3334          */
  3335         private Symbol selectSym(JCFieldAccess tree,
  3336                                  Symbol location,
  3337                                  Type site,
  3338                                  Env<AttrContext> env,
  3339                                  ResultInfo resultInfo) {
  3340             DiagnosticPosition pos = tree.pos();
  3341             Name name = tree.name;
  3342             switch (site.getTag()) {
  3343             case PACKAGE:
  3344                 return rs.accessBase(
  3345                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3346                     pos, location, site, name, true);
  3347             case ARRAY:
  3348             case CLASS:
  3349                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3350                     return rs.resolveQualifiedMethod(
  3351                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3352                 } else if (name == names._this || name == names._super) {
  3353                     return rs.resolveSelf(pos, env, site.tsym, name);
  3354                 } else if (name == names._class) {
  3355                     // In this case, we have already made sure in
  3356                     // visitSelect that qualifier expression is a type.
  3357                     Type t = syms.classType;
  3358                     List<Type> typeargs = allowGenerics
  3359                         ? List.of(types.erasure(site))
  3360                         : List.<Type>nil();
  3361                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3362                     return new VarSymbol(
  3363                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3364                 } else {
  3365                     // We are seeing a plain identifier as selector.
  3366                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3367                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3368                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3369                     return sym;
  3371             case WILDCARD:
  3372                 throw new AssertionError(tree);
  3373             case TYPEVAR:
  3374                 // Normally, site.getUpperBound() shouldn't be null.
  3375                 // It should only happen during memberEnter/attribBase
  3376                 // when determining the super type which *must* beac
  3377                 // done before attributing the type variables.  In
  3378                 // other words, we are seeing this illegal program:
  3379                 // class B<T> extends A<T.foo> {}
  3380                 Symbol sym = (site.getUpperBound() != null)
  3381                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3382                     : null;
  3383                 if (sym == null) {
  3384                     log.error(pos, "type.var.cant.be.deref");
  3385                     return syms.errSymbol;
  3386                 } else {
  3387                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3388                         rs.new AccessError(env, site, sym) :
  3389                                 sym;
  3390                     rs.accessBase(sym2, pos, location, site, name, true);
  3391                     return sym;
  3393             case ERROR:
  3394                 // preserve identifier names through errors
  3395                 return types.createErrorType(name, site.tsym, site).tsym;
  3396             default:
  3397                 // The qualifier expression is of a primitive type -- only
  3398                 // .class is allowed for these.
  3399                 if (name == names._class) {
  3400                     // In this case, we have already made sure in Select that
  3401                     // qualifier expression is a type.
  3402                     Type t = syms.classType;
  3403                     Type arg = types.boxedClass(site).type;
  3404                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3405                     return new VarSymbol(
  3406                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3407                 } else {
  3408                     log.error(pos, "cant.deref", site);
  3409                     return syms.errSymbol;
  3414         /** Determine type of identifier or select expression and check that
  3415          *  (1) the referenced symbol is not deprecated
  3416          *  (2) the symbol's type is safe (@see checkSafe)
  3417          *  (3) if symbol is a variable, check that its type and kind are
  3418          *      compatible with the prototype and protokind.
  3419          *  (4) if symbol is an instance field of a raw type,
  3420          *      which is being assigned to, issue an unchecked warning if its
  3421          *      type changes under erasure.
  3422          *  (5) if symbol is an instance method of a raw type, issue an
  3423          *      unchecked warning if its argument types change under erasure.
  3424          *  If checks succeed:
  3425          *    If symbol is a constant, return its constant type
  3426          *    else if symbol is a method, return its result type
  3427          *    otherwise return its type.
  3428          *  Otherwise return errType.
  3430          *  @param tree       The syntax tree representing the identifier
  3431          *  @param site       If this is a select, the type of the selected
  3432          *                    expression, otherwise the type of the current class.
  3433          *  @param sym        The symbol representing the identifier.
  3434          *  @param env        The current environment.
  3435          *  @param resultInfo    The expected result
  3436          */
  3437         Type checkId(JCTree tree,
  3438                      Type site,
  3439                      Symbol sym,
  3440                      Env<AttrContext> env,
  3441                      ResultInfo resultInfo) {
  3442             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3443                     checkMethodId(tree, site, sym, env, resultInfo) :
  3444                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3447         Type checkMethodId(JCTree tree,
  3448                      Type site,
  3449                      Symbol sym,
  3450                      Env<AttrContext> env,
  3451                      ResultInfo resultInfo) {
  3452             boolean isPolymorhicSignature =
  3453                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3454             return isPolymorhicSignature ?
  3455                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3456                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3459         Type checkSigPolyMethodId(JCTree tree,
  3460                      Type site,
  3461                      Symbol sym,
  3462                      Env<AttrContext> env,
  3463                      ResultInfo resultInfo) {
  3464             //recover original symbol for signature polymorphic methods
  3465             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3466             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3467             return sym.type;
  3470         Type checkMethodIdInternal(JCTree tree,
  3471                      Type site,
  3472                      Symbol sym,
  3473                      Env<AttrContext> env,
  3474                      ResultInfo resultInfo) {
  3475             if ((resultInfo.pkind & POLY) != 0) {
  3476                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3477                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3478                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3479                 return owntype;
  3480             } else {
  3481                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3485         Type checkIdInternal(JCTree tree,
  3486                      Type site,
  3487                      Symbol sym,
  3488                      Type pt,
  3489                      Env<AttrContext> env,
  3490                      ResultInfo resultInfo) {
  3491             if (pt.isErroneous()) {
  3492                 return types.createErrorType(site);
  3494             Type owntype; // The computed type of this identifier occurrence.
  3495             switch (sym.kind) {
  3496             case TYP:
  3497                 // For types, the computed type equals the symbol's type,
  3498                 // except for two situations:
  3499                 owntype = sym.type;
  3500                 if (owntype.hasTag(CLASS)) {
  3501                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3502                     Type ownOuter = owntype.getEnclosingType();
  3504                     // (a) If the symbol's type is parameterized, erase it
  3505                     // because no type parameters were given.
  3506                     // We recover generic outer type later in visitTypeApply.
  3507                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3508                         owntype = types.erasure(owntype);
  3511                     // (b) If the symbol's type is an inner class, then
  3512                     // we have to interpret its outer type as a superclass
  3513                     // of the site type. Example:
  3514                     //
  3515                     // class Tree<A> { class Visitor { ... } }
  3516                     // class PointTree extends Tree<Point> { ... }
  3517                     // ...PointTree.Visitor...
  3518                     //
  3519                     // Then the type of the last expression above is
  3520                     // Tree<Point>.Visitor.
  3521                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3522                         Type normOuter = site;
  3523                         if (normOuter.hasTag(CLASS)) {
  3524                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3525                             if (site.isAnnotated()) {
  3526                                 // Propagate any type annotations.
  3527                                 // TODO: should asEnclosingSuper do this?
  3528                                 // Note that the type annotations in site will be updated
  3529                                 // by annotateType. Therefore, modify site instead
  3530                                 // of creating a new AnnotatedType.
  3531                                 ((AnnotatedType)site).underlyingType = normOuter;
  3532                                 normOuter = site;
  3535                         if (normOuter == null) // perhaps from an import
  3536                             normOuter = types.erasure(ownOuter);
  3537                         if (normOuter != ownOuter)
  3538                             owntype = new ClassType(
  3539                                 normOuter, List.<Type>nil(), owntype.tsym);
  3542                 break;
  3543             case VAR:
  3544                 VarSymbol v = (VarSymbol)sym;
  3545                 // Test (4): if symbol is an instance field of a raw type,
  3546                 // which is being assigned to, issue an unchecked warning if
  3547                 // its type changes under erasure.
  3548                 if (allowGenerics &&
  3549                     resultInfo.pkind == VAR &&
  3550                     v.owner.kind == TYP &&
  3551                     (v.flags() & STATIC) == 0 &&
  3552                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3553                     Type s = types.asOuterSuper(site, v.owner);
  3554                     if (s != null &&
  3555                         s.isRaw() &&
  3556                         !types.isSameType(v.type, v.erasure(types))) {
  3557                         chk.warnUnchecked(tree.pos(),
  3558                                           "unchecked.assign.to.var",
  3559                                           v, s);
  3562                 // The computed type of a variable is the type of the
  3563                 // variable symbol, taken as a member of the site type.
  3564                 owntype = (sym.owner.kind == TYP &&
  3565                            sym.name != names._this && sym.name != names._super)
  3566                     ? types.memberType(site, sym)
  3567                     : sym.type;
  3569                 // If the variable is a constant, record constant value in
  3570                 // computed type.
  3571                 if (v.getConstValue() != null && isStaticReference(tree))
  3572                     owntype = owntype.constType(v.getConstValue());
  3574                 if (resultInfo.pkind == VAL) {
  3575                     owntype = capture(owntype); // capture "names as expressions"
  3577                 break;
  3578             case MTH: {
  3579                 owntype = checkMethod(site, sym,
  3580                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3581                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3582                         resultInfo.pt.getTypeArguments());
  3583                 break;
  3585             case PCK: case ERR:
  3586                 owntype = sym.type;
  3587                 break;
  3588             default:
  3589                 throw new AssertionError("unexpected kind: " + sym.kind +
  3590                                          " in tree " + tree);
  3593             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3594             // (for constructors, the error was given when the constructor was
  3595             // resolved)
  3597             if (sym.name != names.init) {
  3598                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3599                 chk.checkSunAPI(tree.pos(), sym);
  3600                 chk.checkProfile(tree.pos(), sym);
  3603             // Test (3): if symbol is a variable, check that its type and
  3604             // kind are compatible with the prototype and protokind.
  3605             return check(tree, owntype, sym.kind, resultInfo);
  3608         /** Check that variable is initialized and evaluate the variable's
  3609          *  initializer, if not yet done. Also check that variable is not
  3610          *  referenced before it is defined.
  3611          *  @param tree    The tree making up the variable reference.
  3612          *  @param env     The current environment.
  3613          *  @param v       The variable's symbol.
  3614          */
  3615         private void checkInit(JCTree tree,
  3616                                Env<AttrContext> env,
  3617                                VarSymbol v,
  3618                                boolean onlyWarning) {
  3619 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3620 //                             tree.pos + " " + v.pos + " " +
  3621 //                             Resolve.isStatic(env));//DEBUG
  3623             // A forward reference is diagnosed if the declaration position
  3624             // of the variable is greater than the current tree position
  3625             // and the tree and variable definition occur in the same class
  3626             // definition.  Note that writes don't count as references.
  3627             // This check applies only to class and instance
  3628             // variables.  Local variables follow different scope rules,
  3629             // and are subject to definite assignment checking.
  3630             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3631                 v.owner.kind == TYP &&
  3632                 canOwnInitializer(owner(env)) &&
  3633                 v.owner == env.info.scope.owner.enclClass() &&
  3634                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3635                 (!env.tree.hasTag(ASSIGN) ||
  3636                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3637                 String suffix = (env.info.enclVar == v) ?
  3638                                 "self.ref" : "forward.ref";
  3639                 if (!onlyWarning || isStaticEnumField(v)) {
  3640                     log.error(tree.pos(), "illegal." + suffix);
  3641                 } else if (useBeforeDeclarationWarning) {
  3642                     log.warning(tree.pos(), suffix, v);
  3646             v.getConstValue(); // ensure initializer is evaluated
  3648             checkEnumInitializer(tree, env, v);
  3651         /**
  3652          * Check for illegal references to static members of enum.  In
  3653          * an enum type, constructors and initializers may not
  3654          * reference its static members unless they are constant.
  3656          * @param tree    The tree making up the variable reference.
  3657          * @param env     The current environment.
  3658          * @param v       The variable's symbol.
  3659          * @jls  section 8.9 Enums
  3660          */
  3661         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3662             // JLS:
  3663             //
  3664             // "It is a compile-time error to reference a static field
  3665             // of an enum type that is not a compile-time constant
  3666             // (15.28) from constructors, instance initializer blocks,
  3667             // or instance variable initializer expressions of that
  3668             // type. It is a compile-time error for the constructors,
  3669             // instance initializer blocks, or instance variable
  3670             // initializer expressions of an enum constant e to refer
  3671             // to itself or to an enum constant of the same type that
  3672             // is declared to the right of e."
  3673             if (isStaticEnumField(v)) {
  3674                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3676                 if (enclClass == null || enclClass.owner == null)
  3677                     return;
  3679                 // See if the enclosing class is the enum (or a
  3680                 // subclass thereof) declaring v.  If not, this
  3681                 // reference is OK.
  3682                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3683                     return;
  3685                 // If the reference isn't from an initializer, then
  3686                 // the reference is OK.
  3687                 if (!Resolve.isInitializer(env))
  3688                     return;
  3690                 log.error(tree.pos(), "illegal.enum.static.ref");
  3694         /** Is the given symbol a static, non-constant field of an Enum?
  3695          *  Note: enum literals should not be regarded as such
  3696          */
  3697         private boolean isStaticEnumField(VarSymbol v) {
  3698             return Flags.isEnum(v.owner) &&
  3699                    Flags.isStatic(v) &&
  3700                    !Flags.isConstant(v) &&
  3701                    v.name != names._class;
  3704         /** Can the given symbol be the owner of code which forms part
  3705          *  if class initialization? This is the case if the symbol is
  3706          *  a type or field, or if the symbol is the synthetic method.
  3707          *  owning a block.
  3708          */
  3709         private boolean canOwnInitializer(Symbol sym) {
  3710             return
  3711                 (sym.kind & (VAR | TYP)) != 0 ||
  3712                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3715     Warner noteWarner = new Warner();
  3717     /**
  3718      * Check that method arguments conform to its instantiation.
  3719      **/
  3720     public Type checkMethod(Type site,
  3721                             final Symbol sym,
  3722                             ResultInfo resultInfo,
  3723                             Env<AttrContext> env,
  3724                             final List<JCExpression> argtrees,
  3725                             List<Type> argtypes,
  3726                             List<Type> typeargtypes) {
  3727         // Test (5): if symbol is an instance method of a raw type, issue
  3728         // an unchecked warning if its argument types change under erasure.
  3729         if (allowGenerics &&
  3730             (sym.flags() & STATIC) == 0 &&
  3731             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3732             Type s = types.asOuterSuper(site, sym.owner);
  3733             if (s != null && s.isRaw() &&
  3734                 !types.isSameTypes(sym.type.getParameterTypes(),
  3735                                    sym.erasure(types).getParameterTypes())) {
  3736                 chk.warnUnchecked(env.tree.pos(),
  3737                                   "unchecked.call.mbr.of.raw.type",
  3738                                   sym, s);
  3742         if (env.info.defaultSuperCallSite != null) {
  3743             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3744                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3745                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3746                 List<MethodSymbol> icand_sup =
  3747                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3748                 if (icand_sup.nonEmpty() &&
  3749                         icand_sup.head != sym &&
  3750                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3751                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3752                         diags.fragment("overridden.default", sym, sup));
  3753                     break;
  3756             env.info.defaultSuperCallSite = null;
  3759         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3760             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3761             if (app.meth.hasTag(SELECT) &&
  3762                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3763                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3767         // Compute the identifier's instantiated type.
  3768         // For methods, we need to compute the instance type by
  3769         // Resolve.instantiate from the symbol's type as well as
  3770         // any type arguments and value arguments.
  3771         noteWarner.clear();
  3772         try {
  3773             Type owntype = rs.checkMethod(
  3774                     env,
  3775                     site,
  3776                     sym,
  3777                     resultInfo,
  3778                     argtypes,
  3779                     typeargtypes,
  3780                     noteWarner);
  3782             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3783                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3785             argtypes = Type.map(argtypes, checkDeferredMap);
  3787             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3788                 chk.warnUnchecked(env.tree.pos(),
  3789                         "unchecked.meth.invocation.applied",
  3790                         kindName(sym),
  3791                         sym.name,
  3792                         rs.methodArguments(sym.type.getParameterTypes()),
  3793                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3794                         kindName(sym.location()),
  3795                         sym.location());
  3796                owntype = new MethodType(owntype.getParameterTypes(),
  3797                        types.erasure(owntype.getReturnType()),
  3798                        types.erasure(owntype.getThrownTypes()),
  3799                        syms.methodClass);
  3802             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3803                     resultInfo.checkContext.inferenceContext());
  3804         } catch (Infer.InferenceException ex) {
  3805             //invalid target type - propagate exception outwards or report error
  3806             //depending on the current check context
  3807             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3808             return types.createErrorType(site);
  3809         } catch (Resolve.InapplicableMethodException ex) {
  3810             final JCDiagnostic diag = ex.getDiagnostic();
  3811             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  3812                 @Override
  3813                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3814                     return new Pair<Symbol, JCDiagnostic>(sym, diag);
  3816             };
  3817             List<Type> argtypes2 = Type.map(argtypes,
  3818                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3819             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3820                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  3821             log.report(errDiag);
  3822             return types.createErrorType(site);
  3826     public void visitLiteral(JCLiteral tree) {
  3827         result = check(
  3828             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3830     //where
  3831     /** Return the type of a literal with given type tag.
  3832      */
  3833     Type litType(TypeTag tag) {
  3834         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3837     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3838         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3841     public void visitTypeArray(JCArrayTypeTree tree) {
  3842         Type etype = attribType(tree.elemtype, env);
  3843         Type type = new ArrayType(etype, syms.arrayClass);
  3844         result = check(tree, type, TYP, resultInfo);
  3847     /** Visitor method for parameterized types.
  3848      *  Bound checking is left until later, since types are attributed
  3849      *  before supertype structure is completely known
  3850      */
  3851     public void visitTypeApply(JCTypeApply tree) {
  3852         Type owntype = types.createErrorType(tree.type);
  3854         // Attribute functor part of application and make sure it's a class.
  3855         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3857         // Attribute type parameters
  3858         List<Type> actuals = attribTypes(tree.arguments, env);
  3860         if (clazztype.hasTag(CLASS)) {
  3861             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3862             if (actuals.isEmpty()) //diamond
  3863                 actuals = formals;
  3865             if (actuals.length() == formals.length()) {
  3866                 List<Type> a = actuals;
  3867                 List<Type> f = formals;
  3868                 while (a.nonEmpty()) {
  3869                     a.head = a.head.withTypeVar(f.head);
  3870                     a = a.tail;
  3871                     f = f.tail;
  3873                 // Compute the proper generic outer
  3874                 Type clazzOuter = clazztype.getEnclosingType();
  3875                 if (clazzOuter.hasTag(CLASS)) {
  3876                     Type site;
  3877                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3878                     if (clazz.hasTag(IDENT)) {
  3879                         site = env.enclClass.sym.type;
  3880                     } else if (clazz.hasTag(SELECT)) {
  3881                         site = ((JCFieldAccess) clazz).selected.type;
  3882                     } else throw new AssertionError(""+tree);
  3883                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3884                         if (site.hasTag(CLASS))
  3885                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3886                         if (site == null)
  3887                             site = types.erasure(clazzOuter);
  3888                         clazzOuter = site;
  3891                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3892                 if (clazztype.isAnnotated()) {
  3893                     // Use the same AnnotatedType, because it will have
  3894                     // its annotations set later.
  3895                     ((AnnotatedType)clazztype).underlyingType = owntype;
  3896                     owntype = clazztype;
  3898             } else {
  3899                 if (formals.length() != 0) {
  3900                     log.error(tree.pos(), "wrong.number.type.args",
  3901                               Integer.toString(formals.length()));
  3902                 } else {
  3903                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3905                 owntype = types.createErrorType(tree.type);
  3908         result = check(tree, owntype, TYP, resultInfo);
  3911     public void visitTypeUnion(JCTypeUnion tree) {
  3912         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  3913         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3914         for (JCExpression typeTree : tree.alternatives) {
  3915             Type ctype = attribType(typeTree, env);
  3916             ctype = chk.checkType(typeTree.pos(),
  3917                           chk.checkClassType(typeTree.pos(), ctype),
  3918                           syms.throwableType);
  3919             if (!ctype.isErroneous()) {
  3920                 //check that alternatives of a union type are pairwise
  3921                 //unrelated w.r.t. subtyping
  3922                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3923                     for (Type t : multicatchTypes) {
  3924                         boolean sub = types.isSubtype(ctype, t);
  3925                         boolean sup = types.isSubtype(t, ctype);
  3926                         if (sub || sup) {
  3927                             //assume 'a' <: 'b'
  3928                             Type a = sub ? ctype : t;
  3929                             Type b = sub ? t : ctype;
  3930                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3934                 multicatchTypes.append(ctype);
  3935                 if (all_multicatchTypes != null)
  3936                     all_multicatchTypes.append(ctype);
  3937             } else {
  3938                 if (all_multicatchTypes == null) {
  3939                     all_multicatchTypes = new ListBuffer<>();
  3940                     all_multicatchTypes.appendList(multicatchTypes);
  3942                 all_multicatchTypes.append(ctype);
  3945         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3946         if (t.hasTag(CLASS)) {
  3947             List<Type> alternatives =
  3948                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3949             t = new UnionClassType((ClassType) t, alternatives);
  3951         tree.type = result = t;
  3954     public void visitTypeIntersection(JCTypeIntersection tree) {
  3955         attribTypes(tree.bounds, env);
  3956         tree.type = result = checkIntersection(tree, tree.bounds);
  3959     public void visitTypeParameter(JCTypeParameter tree) {
  3960         TypeVar typeVar = (TypeVar) tree.type;
  3962         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3963             AnnotatedType antype = new AnnotatedType(typeVar);
  3964             annotateType(antype, tree.annotations);
  3965             tree.type = antype;
  3968         if (!typeVar.bound.isErroneous()) {
  3969             //fixup type-parameter bound computed in 'attribTypeVariables'
  3970             typeVar.bound = checkIntersection(tree, tree.bounds);
  3974     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3975         Set<Type> boundSet = new HashSet<Type>();
  3976         if (bounds.nonEmpty()) {
  3977             // accept class or interface or typevar as first bound.
  3978             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3979             boundSet.add(types.erasure(bounds.head.type));
  3980             if (bounds.head.type.isErroneous()) {
  3981                 return bounds.head.type;
  3983             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3984                 // if first bound was a typevar, do not accept further bounds.
  3985                 if (bounds.tail.nonEmpty()) {
  3986                     log.error(bounds.tail.head.pos(),
  3987                               "type.var.may.not.be.followed.by.other.bounds");
  3988                     return bounds.head.type;
  3990             } else {
  3991                 // if first bound was a class or interface, accept only interfaces
  3992                 // as further bounds.
  3993                 for (JCExpression bound : bounds.tail) {
  3994                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  3995                     if (bound.type.isErroneous()) {
  3996                         bounds = List.of(bound);
  3998                     else if (bound.type.hasTag(CLASS)) {
  3999                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4005         if (bounds.length() == 0) {
  4006             return syms.objectType;
  4007         } else if (bounds.length() == 1) {
  4008             return bounds.head.type;
  4009         } else {
  4010             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4011             if (tree.hasTag(TYPEINTERSECTION)) {
  4012                 ((IntersectionClassType)owntype).intersectionKind =
  4013                         IntersectionClassType.IntersectionKind.EXPLICIT;
  4015             // ... the variable's bound is a class type flagged COMPOUND
  4016             // (see comment for TypeVar.bound).
  4017             // In this case, generate a class tree that represents the
  4018             // bound class, ...
  4019             JCExpression extending;
  4020             List<JCExpression> implementing;
  4021             if (!bounds.head.type.isInterface()) {
  4022                 extending = bounds.head;
  4023                 implementing = bounds.tail;
  4024             } else {
  4025                 extending = null;
  4026                 implementing = bounds;
  4028             JCClassDecl cd = make.at(tree).ClassDef(
  4029                 make.Modifiers(PUBLIC | ABSTRACT),
  4030                 names.empty, List.<JCTypeParameter>nil(),
  4031                 extending, implementing, List.<JCTree>nil());
  4033             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4034             Assert.check((c.flags() & COMPOUND) != 0);
  4035             cd.sym = c;
  4036             c.sourcefile = env.toplevel.sourcefile;
  4038             // ... and attribute the bound class
  4039             c.flags_field |= UNATTRIBUTED;
  4040             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4041             enter.typeEnvs.put(c, cenv);
  4042             attribClass(c);
  4043             return owntype;
  4047     public void visitWildcard(JCWildcard tree) {
  4048         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4049         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4050             ? syms.objectType
  4051             : attribType(tree.inner, env);
  4052         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4053                                               tree.kind.kind,
  4054                                               syms.boundClass),
  4055                        TYP, resultInfo);
  4058     public void visitAnnotation(JCAnnotation tree) {
  4059         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  4060         result = tree.type = syms.errType;
  4063     public void visitAnnotatedType(JCAnnotatedType tree) {
  4064         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4065         this.attribAnnotationTypes(tree.annotations, env);
  4066         AnnotatedType antype = new AnnotatedType(underlyingType);
  4067         annotateType(antype, tree.annotations);
  4068         result = tree.type = antype;
  4071     /**
  4072      * Apply the annotations to the particular type.
  4073      */
  4074     public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
  4075         if (annotations.isEmpty())
  4076             return;
  4077         annotate.typeAnnotation(new Annotate.Annotator() {
  4078             @Override
  4079             public String toString() {
  4080                 return "annotate " + annotations + " onto " + type;
  4082             @Override
  4083             public void enterAnnotation() {
  4084                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4085                 type.typeAnnotations = compounds;
  4087         });
  4090     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4091         if (annotations.isEmpty())
  4092             return List.nil();
  4094         ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  4095         for (JCAnnotation anno : annotations) {
  4096             if (anno.attribute != null) {
  4097                 // TODO: this null-check is only needed for an obscure
  4098                 // ordering issue, where annotate.flush is called when
  4099                 // the attribute is not set yet. For an example failure
  4100                 // try the referenceinfos/NestedTypes.java test.
  4101                 // Any better solutions?
  4102                 buf.append((Attribute.TypeCompound) anno.attribute);
  4105         return buf.toList();
  4108     public void visitErroneous(JCErroneous tree) {
  4109         if (tree.errs != null)
  4110             for (JCTree err : tree.errs)
  4111                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4112         result = tree.type = syms.errType;
  4115     /** Default visitor method for all other trees.
  4116      */
  4117     public void visitTree(JCTree tree) {
  4118         throw new AssertionError();
  4121     /**
  4122      * Attribute an env for either a top level tree or class declaration.
  4123      */
  4124     public void attrib(Env<AttrContext> env) {
  4125         if (env.tree.hasTag(TOPLEVEL))
  4126             attribTopLevel(env);
  4127         else
  4128             attribClass(env.tree.pos(), env.enclClass.sym);
  4131     /**
  4132      * Attribute a top level tree. These trees are encountered when the
  4133      * package declaration has annotations.
  4134      */
  4135     public void attribTopLevel(Env<AttrContext> env) {
  4136         JCCompilationUnit toplevel = env.toplevel;
  4137         try {
  4138             annotate.flush();
  4139             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  4140         } catch (CompletionFailure ex) {
  4141             chk.completionError(toplevel.pos(), ex);
  4145     /** Main method: attribute class definition associated with given class symbol.
  4146      *  reporting completion failures at the given position.
  4147      *  @param pos The source position at which completion errors are to be
  4148      *             reported.
  4149      *  @param c   The class symbol whose definition will be attributed.
  4150      */
  4151     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4152         try {
  4153             annotate.flush();
  4154             attribClass(c);
  4155         } catch (CompletionFailure ex) {
  4156             chk.completionError(pos, ex);
  4160     /** Attribute class definition associated with given class symbol.
  4161      *  @param c   The class symbol whose definition will be attributed.
  4162      */
  4163     void attribClass(ClassSymbol c) throws CompletionFailure {
  4164         if (c.type.hasTag(ERROR)) return;
  4166         // Check for cycles in the inheritance graph, which can arise from
  4167         // ill-formed class files.
  4168         chk.checkNonCyclic(null, c.type);
  4170         Type st = types.supertype(c.type);
  4171         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4172             // First, attribute superclass.
  4173             if (st.hasTag(CLASS))
  4174                 attribClass((ClassSymbol)st.tsym);
  4176             // Next attribute owner, if it is a class.
  4177             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4178                 attribClass((ClassSymbol)c.owner);
  4181         // The previous operations might have attributed the current class
  4182         // if there was a cycle. So we test first whether the class is still
  4183         // UNATTRIBUTED.
  4184         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4185             c.flags_field &= ~UNATTRIBUTED;
  4187             // Get environment current at the point of class definition.
  4188             Env<AttrContext> env = enter.typeEnvs.get(c);
  4190             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4191             // because the annotations were not available at the time the env was created. Therefore,
  4192             // we look up the environment chain for the first enclosing environment for which the
  4193             // lint value is set. Typically, this is the parent env, but might be further if there
  4194             // are any envs created as a result of TypeParameter nodes.
  4195             Env<AttrContext> lintEnv = env;
  4196             while (lintEnv.info.lint == null)
  4197                 lintEnv = lintEnv.next;
  4199             // Having found the enclosing lint value, we can initialize the lint value for this class
  4200             env.info.lint = lintEnv.info.lint.augment(c);
  4202             Lint prevLint = chk.setLint(env.info.lint);
  4203             JavaFileObject prev = log.useSource(c.sourcefile);
  4204             ResultInfo prevReturnRes = env.info.returnResult;
  4206             try {
  4207                 deferredLintHandler.flush(env.tree);
  4208                 env.info.returnResult = null;
  4209                 // java.lang.Enum may not be subclassed by a non-enum
  4210                 if (st.tsym == syms.enumSym &&
  4211                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4212                     log.error(env.tree.pos(), "enum.no.subclassing");
  4214                 // Enums may not be extended by source-level classes
  4215                 if (st.tsym != null &&
  4216                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4217                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4218                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4220                 attribClassBody(env, c);
  4222                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4223                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4224             } finally {
  4225                 env.info.returnResult = prevReturnRes;
  4226                 log.useSource(prev);
  4227                 chk.setLint(prevLint);
  4233     public void visitImport(JCImport tree) {
  4234         // nothing to do
  4237     /** Finish the attribution of a class. */
  4238     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4239         JCClassDecl tree = (JCClassDecl)env.tree;
  4240         Assert.check(c == tree.sym);
  4242         // Validate annotations
  4243         chk.validateAnnotations(tree.mods.annotations, c);
  4245         // Validate type parameters, supertype and interfaces.
  4246         attribStats(tree.typarams, env);
  4247         if (!c.isAnonymous()) {
  4248             //already checked if anonymous
  4249             chk.validate(tree.typarams, env);
  4250             chk.validate(tree.extending, env);
  4251             chk.validate(tree.implementing, env);
  4254         // If this is a non-abstract class, check that it has no abstract
  4255         // methods or unimplemented methods of an implemented interface.
  4256         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4257             if (!relax)
  4258                 chk.checkAllDefined(tree.pos(), c);
  4261         if ((c.flags() & ANNOTATION) != 0) {
  4262             if (tree.implementing.nonEmpty())
  4263                 log.error(tree.implementing.head.pos(),
  4264                           "cant.extend.intf.annotation");
  4265             if (tree.typarams.nonEmpty())
  4266                 log.error(tree.typarams.head.pos(),
  4267                           "intf.annotation.cant.have.type.params");
  4269             // If this annotation has a @Repeatable, validate
  4270             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4271             if (repeatable != null) {
  4272                 // get diagnostic position for error reporting
  4273                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4274                 Assert.checkNonNull(cbPos);
  4276                 chk.validateRepeatable(c, repeatable, cbPos);
  4278         } else {
  4279             // Check that all extended classes and interfaces
  4280             // are compatible (i.e. no two define methods with same arguments
  4281             // yet different return types).  (JLS 8.4.6.3)
  4282             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4283             if (allowDefaultMethods) {
  4284                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4288         // Check that class does not import the same parameterized interface
  4289         // with two different argument lists.
  4290         chk.checkClassBounds(tree.pos(), c.type);
  4292         tree.type = c.type;
  4294         for (List<JCTypeParameter> l = tree.typarams;
  4295              l.nonEmpty(); l = l.tail) {
  4296              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4299         // Check that a generic class doesn't extend Throwable
  4300         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4301             log.error(tree.extending.pos(), "generic.throwable");
  4303         // Check that all methods which implement some
  4304         // method conform to the method they implement.
  4305         chk.checkImplementations(tree);
  4307         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4308         checkAutoCloseable(tree.pos(), env, c.type);
  4310         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4311             // Attribute declaration
  4312             attribStat(l.head, env);
  4313             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4314             // Make an exception for static constants.
  4315             if (c.owner.kind != PCK &&
  4316                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4317                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4318                 Symbol sym = null;
  4319                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4320                 if (sym == null ||
  4321                     sym.kind != VAR ||
  4322                     ((VarSymbol) sym).getConstValue() == null)
  4323                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4327         // Check for cycles among non-initial constructors.
  4328         chk.checkCyclicConstructors(tree);
  4330         // Check for cycles among annotation elements.
  4331         chk.checkNonCyclicElements(tree);
  4333         // Check for proper use of serialVersionUID
  4334         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4335             isSerializable(c) &&
  4336             (c.flags() & Flags.ENUM) == 0 &&
  4337             checkForSerial(c)) {
  4338             checkSerialVersionUID(tree, c);
  4340         if (allowTypeAnnos) {
  4341             // Correctly organize the postions of the type annotations
  4342             TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
  4344             // Check type annotations applicability rules
  4345             validateTypeAnnotations(tree);
  4348         // where
  4349         boolean checkForSerial(ClassSymbol c) {
  4350             if ((c.flags() & ABSTRACT) == 0) {
  4351                 return true;
  4352             } else {
  4353                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4357         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4358             @Override
  4359             public boolean accepts(Symbol s) {
  4360                 return s.kind == Kinds.MTH &&
  4361                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4363         };
  4365         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4366         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4367             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4368                 if (types.isSameType(al.head.annotationType.type, t))
  4369                     return al.head.pos();
  4372             return null;
  4375         /** check if a class is a subtype of Serializable, if that is available. */
  4376         private boolean isSerializable(ClassSymbol c) {
  4377             try {
  4378                 syms.serializableType.complete();
  4380             catch (CompletionFailure e) {
  4381                 return false;
  4383             return types.isSubtype(c.type, syms.serializableType);
  4386         /** Check that an appropriate serialVersionUID member is defined. */
  4387         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4389             // check for presence of serialVersionUID
  4390             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4391             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4392             if (e.scope == null) {
  4393                 log.warning(LintCategory.SERIAL,
  4394                         tree.pos(), "missing.SVUID", c);
  4395                 return;
  4398             // check that it is static final
  4399             VarSymbol svuid = (VarSymbol)e.sym;
  4400             if ((svuid.flags() & (STATIC | FINAL)) !=
  4401                 (STATIC | FINAL))
  4402                 log.warning(LintCategory.SERIAL,
  4403                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4405             // check that it is long
  4406             else if (!svuid.type.hasTag(LONG))
  4407                 log.warning(LintCategory.SERIAL,
  4408                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4410             // check constant
  4411             else if (svuid.getConstValue() == null)
  4412                 log.warning(LintCategory.SERIAL,
  4413                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4416     private Type capture(Type type) {
  4417         return types.capture(type);
  4420     private void validateTypeAnnotations(JCTree tree) {
  4421         tree.accept(typeAnnotationsValidator);
  4423     //where
  4424     private final JCTree.Visitor typeAnnotationsValidator = new TreeScanner() {
  4426         private boolean checkAllAnnotations = false;
  4428         public void visitAnnotation(JCAnnotation tree) {
  4429             if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
  4430                 chk.validateTypeAnnotation(tree, false);
  4432             super.visitAnnotation(tree);
  4434         public void visitTypeParameter(JCTypeParameter tree) {
  4435             chk.validateTypeAnnotations(tree.annotations, true);
  4436             scan(tree.bounds);
  4437             // Don't call super.
  4438             // This is needed because above we call validateTypeAnnotation with
  4439             // false, which would forbid annotations on type parameters.
  4440             // super.visitTypeParameter(tree);
  4442         public void visitMethodDef(JCMethodDecl tree) {
  4443             if (tree.recvparam != null &&
  4444                     tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
  4445                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4446                         tree.recvparam.vartype.type.tsym);
  4448             if (tree.restype != null && tree.restype.type != null) {
  4449                 validateAnnotatedType(tree.restype, tree.restype.type);
  4451             super.visitMethodDef(tree);
  4453         public void visitVarDef(final JCVariableDecl tree) {
  4454             if (tree.sym != null && tree.sym.type != null)
  4455                 validateAnnotatedType(tree, tree.sym.type);
  4456             super.visitVarDef(tree);
  4458         public void visitTypeCast(JCTypeCast tree) {
  4459             if (tree.clazz != null && tree.clazz.type != null)
  4460                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4461             super.visitTypeCast(tree);
  4463         public void visitTypeTest(JCInstanceOf tree) {
  4464             if (tree.clazz != null && tree.clazz.type != null)
  4465                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4466             super.visitTypeTest(tree);
  4468         public void visitNewClass(JCNewClass tree) {
  4469             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4470                 boolean prevCheck = this.checkAllAnnotations;
  4471                 try {
  4472                     this.checkAllAnnotations = true;
  4473                     scan(((JCAnnotatedType)tree.clazz).annotations);
  4474                 } finally {
  4475                     this.checkAllAnnotations = prevCheck;
  4478             super.visitNewClass(tree);
  4480         public void visitNewArray(JCNewArray tree) {
  4481             if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4482                 boolean prevCheck = this.checkAllAnnotations;
  4483                 try {
  4484                     this.checkAllAnnotations = true;
  4485                     scan(((JCAnnotatedType)tree.elemtype).annotations);
  4486                 } finally {
  4487                     this.checkAllAnnotations = prevCheck;
  4490             super.visitNewArray(tree);
  4493         /* I would want to model this after
  4494          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4495          * and override visitSelect and visitTypeApply.
  4496          * However, we only set the annotated type in the top-level type
  4497          * of the symbol.
  4498          * Therefore, we need to override each individual location where a type
  4499          * can occur.
  4500          */
  4501         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4502             if (type.getEnclosingType() != null &&
  4503                     type != type.getEnclosingType()) {
  4504                 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
  4506             for (Type targ : type.getTypeArguments()) {
  4507                 validateAnnotatedType(errtree, targ);
  4510         private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
  4511             validateAnnotatedType(errtree, type);
  4512             if (type.tsym != null &&
  4513                     type.tsym.isStatic() &&
  4514                     type.getAnnotationMirrors().nonEmpty()) {
  4515                     // Enclosing static classes cannot have type annotations.
  4516                 log.error(errtree.pos(), "cant.annotate.static.class");
  4519     };
  4521     // <editor-fold desc="post-attribution visitor">
  4523     /**
  4524      * Handle missing types/symbols in an AST. This routine is useful when
  4525      * the compiler has encountered some errors (which might have ended up
  4526      * terminating attribution abruptly); if the compiler is used in fail-over
  4527      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4528      * prevents NPE to be progagated during subsequent compilation steps.
  4529      */
  4530     public void postAttr(JCTree tree) {
  4531         new PostAttrAnalyzer().scan(tree);
  4534     class PostAttrAnalyzer extends TreeScanner {
  4536         private void initTypeIfNeeded(JCTree that) {
  4537             if (that.type == null) {
  4538                 that.type = syms.unknownType;
  4542         @Override
  4543         public void scan(JCTree tree) {
  4544             if (tree == null) return;
  4545             if (tree instanceof JCExpression) {
  4546                 initTypeIfNeeded(tree);
  4548             super.scan(tree);
  4551         @Override
  4552         public void visitIdent(JCIdent that) {
  4553             if (that.sym == null) {
  4554                 that.sym = syms.unknownSymbol;
  4558         @Override
  4559         public void visitSelect(JCFieldAccess that) {
  4560             if (that.sym == null) {
  4561                 that.sym = syms.unknownSymbol;
  4563             super.visitSelect(that);
  4566         @Override
  4567         public void visitClassDef(JCClassDecl that) {
  4568             initTypeIfNeeded(that);
  4569             if (that.sym == null) {
  4570                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4572             super.visitClassDef(that);
  4575         @Override
  4576         public void visitMethodDef(JCMethodDecl that) {
  4577             initTypeIfNeeded(that);
  4578             if (that.sym == null) {
  4579                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4581             super.visitMethodDef(that);
  4584         @Override
  4585         public void visitVarDef(JCVariableDecl that) {
  4586             initTypeIfNeeded(that);
  4587             if (that.sym == null) {
  4588                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4589                 that.sym.adr = 0;
  4591             super.visitVarDef(that);
  4594         @Override
  4595         public void visitNewClass(JCNewClass that) {
  4596             if (that.constructor == null) {
  4597                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  4599             if (that.constructorType == null) {
  4600                 that.constructorType = syms.unknownType;
  4602             super.visitNewClass(that);
  4605         @Override
  4606         public void visitAssignop(JCAssignOp that) {
  4607             if (that.operator == null)
  4608                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4609             super.visitAssignop(that);
  4612         @Override
  4613         public void visitBinary(JCBinary that) {
  4614             if (that.operator == null)
  4615                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4616             super.visitBinary(that);
  4619         @Override
  4620         public void visitUnary(JCUnary that) {
  4621             if (that.operator == null)
  4622                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4623             super.visitUnary(that);
  4626         @Override
  4627         public void visitLambda(JCLambda that) {
  4628             super.visitLambda(that);
  4629             if (that.targets == null) {
  4630                 that.targets = List.nil();
  4634         @Override
  4635         public void visitReference(JCMemberReference that) {
  4636             super.visitReference(that);
  4637             if (that.sym == null) {
  4638                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  4640             if (that.targets == null) {
  4641                 that.targets = List.nil();
  4645     // </editor-fold>

mercurial