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

Tue, 27 May 2014 17:30:48 -0600

author
dlsmith
date
Tue, 27 May 2014 17:30:48 -0600
changeset 2400
0e026d3f2786
parent 2399
f4254623c54e
child 2412
bf8edbcae43a
permissions
-rw-r--r--

8042338: Refactor Types.upperBound to treat wildcards and variables separately
Reviewed-by: vromero

     1 /*
     2  * Copyright (c) 1999, 2014, 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.tools.JavaFileObject;
    33 import com.sun.source.tree.IdentifierTree;
    34 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    35 import com.sun.source.tree.MemberSelectTree;
    36 import com.sun.source.tree.TreeVisitor;
    37 import com.sun.source.util.SimpleTreeVisitor;
    38 import com.sun.tools.javac.code.*;
    39 import com.sun.tools.javac.code.Lint.LintCategory;
    40 import com.sun.tools.javac.code.Symbol.*;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.comp.Check.CheckContext;
    43 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    44 import com.sun.tools.javac.comp.Infer.InferenceContext;
    45 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    46 import com.sun.tools.javac.jvm.*;
    47 import com.sun.tools.javac.tree.*;
    48 import com.sun.tools.javac.tree.JCTree.*;
    49 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    50 import com.sun.tools.javac.util.*;
    51 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    52 import com.sun.tools.javac.util.List;
    53 import static com.sun.tools.javac.code.Flags.*;
    54 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    55 import static com.sun.tools.javac.code.Flags.BLOCK;
    56 import static com.sun.tools.javac.code.Kinds.*;
    57 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    58 import static com.sun.tools.javac.code.TypeTag.*;
    59 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    60 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    62 /** This is the main context-dependent analysis phase in GJC. It
    63  *  encompasses name resolution, type checking and constant folding as
    64  *  subtasks. Some subtasks involve auxiliary classes.
    65  *  @see Check
    66  *  @see Resolve
    67  *  @see ConstFold
    68  *  @see Infer
    69  *
    70  *  <p><b>This is NOT part of any supported API.
    71  *  If you write code that depends on this, you do so at your own risk.
    72  *  This code and its internal interfaces are subject to change or
    73  *  deletion without notice.</b>
    74  */
    75 public class Attr extends JCTree.Visitor {
    76     protected static final Context.Key<Attr> attrKey =
    77         new Context.Key<Attr>();
    79     final Names names;
    80     final Log log;
    81     final Symtab syms;
    82     final Resolve rs;
    83     final Infer infer;
    84     final DeferredAttr deferredAttr;
    85     final Check chk;
    86     final Flow flow;
    87     final MemberEnter memberEnter;
    88     final TreeMaker make;
    89     final ConstFold cfolder;
    90     final Enter enter;
    91     final Target target;
    92     final Types types;
    93     final JCDiagnostic.Factory diags;
    94     final Annotate annotate;
    95     final TypeAnnotations typeAnnotations;
    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         typeAnnotations = TypeAnnotations.instance(context);
   125         deferredLintHandler = DeferredLintHandler.instance(context);
   127         Options options = Options.instance(context);
   129         Source source = Source.instance(context);
   130         allowGenerics = source.allowGenerics();
   131         allowVarargs = source.allowVarargs();
   132         allowEnums = source.allowEnums();
   133         allowBoxing = source.allowBoxing();
   134         allowCovariantReturns = source.allowCovariantReturns();
   135         allowAnonOuterThis = source.allowAnonOuterThis();
   136         allowStringsInSwitch = source.allowStringsInSwitch();
   137         allowPoly = source.allowPoly();
   138         allowTypeAnnos = source.allowTypeAnnotations();
   139         allowLambda = source.allowLambda();
   140         allowDefaultMethods = source.allowDefaultMethods();
   141         sourceName = source.name;
   142         relax = (options.isSet("-retrofit") ||
   143                  options.isSet("-relax"));
   144         findDiamonds = options.get("findDiamond") != null &&
   145                  source.allowDiamond();
   146         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   147         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   149         statInfo = new ResultInfo(NIL, Type.noType);
   150         varInfo = new ResultInfo(VAR, Type.noType);
   151         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   152         unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly);
   153         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   154         unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
   155         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   156     }
   158     /** Switch: relax some constraints for retrofit mode.
   159      */
   160     boolean relax;
   162     /** Switch: support target-typing inference
   163      */
   164     boolean allowPoly;
   166     /** Switch: support type annotations.
   167      */
   168     boolean allowTypeAnnos;
   170     /** Switch: support generics?
   171      */
   172     boolean allowGenerics;
   174     /** Switch: allow variable-arity methods.
   175      */
   176     boolean allowVarargs;
   178     /** Switch: support enums?
   179      */
   180     boolean allowEnums;
   182     /** Switch: support boxing and unboxing?
   183      */
   184     boolean allowBoxing;
   186     /** Switch: support covariant result types?
   187      */
   188     boolean allowCovariantReturns;
   190     /** Switch: support lambda expressions ?
   191      */
   192     boolean allowLambda;
   194     /** Switch: support default methods ?
   195      */
   196     boolean allowDefaultMethods;
   198     /** Switch: allow references to surrounding object from anonymous
   199      * objects during constructor call?
   200      */
   201     boolean allowAnonOuterThis;
   203     /** Switch: generates a warning if diamond can be safely applied
   204      *  to a given new expression
   205      */
   206     boolean findDiamonds;
   208     /**
   209      * Internally enables/disables diamond finder feature
   210      */
   211     static final boolean allowDiamondFinder = true;
   213     /**
   214      * Switch: warn about use of variable before declaration?
   215      * RFE: 6425594
   216      */
   217     boolean useBeforeDeclarationWarning;
   219     /**
   220      * Switch: generate warnings whenever an anonymous inner class that is convertible
   221      * to a lambda expression is found
   222      */
   223     boolean identifyLambdaCandidate;
   225     /**
   226      * Switch: allow strings in switch?
   227      */
   228     boolean allowStringsInSwitch;
   230     /**
   231      * Switch: name of source level; used for error reporting.
   232      */
   233     String sourceName;
   235     /** Check kind and type of given tree against protokind and prototype.
   236      *  If check succeeds, store type in tree and return it.
   237      *  If check fails, store errType in tree and return it.
   238      *  No checks are performed if the prototype is a method type.
   239      *  It is not necessary in this case since we know that kind and type
   240      *  are correct.
   241      *
   242      *  @param tree     The tree whose kind and type is checked
   243      *  @param ownkind  The computed kind of the tree
   244      *  @param resultInfo  The expected result of the tree
   245      */
   246     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   247         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   248         Type owntype = found;
   249         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   250             if (allowPoly && inferenceContext.free(found)) {
   251                 if ((ownkind & ~resultInfo.pkind) == 0) {
   252                     owntype = resultInfo.check(tree, inferenceContext.asUndetVar(owntype));
   253                 } else {
   254                     log.error(tree.pos(), "unexpected.type",
   255                             kindNames(resultInfo.pkind),
   256                             kindName(ownkind));
   257                     owntype = types.createErrorType(owntype);
   258                 }
   259                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   260                     @Override
   261                     public void typesInferred(InferenceContext inferenceContext) {
   262                         ResultInfo pendingResult =
   263                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   264                         check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   265                     }
   266                 });
   267                 return tree.type = resultInfo.pt;
   268             } else {
   269                 if ((ownkind & ~resultInfo.pkind) == 0) {
   270                     owntype = resultInfo.check(tree, owntype);
   271                 } else {
   272                     log.error(tree.pos(), "unexpected.type",
   273                             kindNames(resultInfo.pkind),
   274                             kindName(ownkind));
   275                     owntype = types.createErrorType(owntype);
   276                 }
   277             }
   278         }
   279         tree.type = owntype;
   280         return owntype;
   281     }
   283     /** Is given blank final variable assignable, i.e. in a scope where it
   284      *  may be assigned to even though it is final?
   285      *  @param v      The blank final variable.
   286      *  @param env    The current environment.
   287      */
   288     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   289         Symbol owner = owner(env);
   290            // owner refers to the innermost variable, method or
   291            // initializer block declaration at this point.
   292         return
   293             v.owner == owner
   294             ||
   295             ((owner.name == names.init ||    // i.e. we are in a constructor
   296               owner.kind == VAR ||           // i.e. we are in a variable initializer
   297               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   298              &&
   299              v.owner == owner.owner
   300              &&
   301              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   302     }
   304     /**
   305      * Return the innermost enclosing owner symbol in a given attribution context
   306      */
   307     Symbol owner(Env<AttrContext> env) {
   308         while (true) {
   309             switch (env.tree.getTag()) {
   310                 case VARDEF:
   311                     //a field can be owner
   312                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   313                     if (vsym.owner.kind == TYP) {
   314                         return vsym;
   315                     }
   316                     break;
   317                 case METHODDEF:
   318                     //method def is always an owner
   319                     return ((JCMethodDecl)env.tree).sym;
   320                 case CLASSDEF:
   321                     //class def is always an owner
   322                     return ((JCClassDecl)env.tree).sym;
   323                 case BLOCK:
   324                     //static/instance init blocks are owner
   325                     Symbol blockSym = env.info.scope.owner;
   326                     if ((blockSym.flags() & BLOCK) != 0) {
   327                         return blockSym;
   328                     }
   329                     break;
   330                 case TOPLEVEL:
   331                     //toplevel is always an owner (for pkge decls)
   332                     return env.info.scope.owner;
   333             }
   334             Assert.checkNonNull(env.next);
   335             env = env.next;
   336         }
   337     }
   339     /** Check that variable can be assigned to.
   340      *  @param pos    The current source code position.
   341      *  @param v      The assigned varaible
   342      *  @param base   If the variable is referred to in a Select, the part
   343      *                to the left of the `.', null otherwise.
   344      *  @param env    The current environment.
   345      */
   346     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   347         if ((v.flags() & FINAL) != 0 &&
   348             ((v.flags() & HASINIT) != 0
   349              ||
   350              !((base == null ||
   351                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   352                isAssignableAsBlankFinal(v, env)))) {
   353             if (v.isResourceVariable()) { //TWR resource
   354                 log.error(pos, "try.resource.may.not.be.assigned", v);
   355             } else {
   356                 log.error(pos, "cant.assign.val.to.final.var", v);
   357             }
   358         }
   359     }
   361     /** Does tree represent a static reference to an identifier?
   362      *  It is assumed that tree is either a SELECT or an IDENT.
   363      *  We have to weed out selects from non-type names here.
   364      *  @param tree    The candidate tree.
   365      */
   366     boolean isStaticReference(JCTree tree) {
   367         if (tree.hasTag(SELECT)) {
   368             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   369             if (lsym == null || lsym.kind != TYP) {
   370                 return false;
   371             }
   372         }
   373         return true;
   374     }
   376     /** Is this symbol a type?
   377      */
   378     static boolean isType(Symbol sym) {
   379         return sym != null && sym.kind == TYP;
   380     }
   382     /** The current `this' symbol.
   383      *  @param env    The current environment.
   384      */
   385     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   386         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   387     }
   389     /** Attribute a parsed identifier.
   390      * @param tree Parsed identifier name
   391      * @param topLevel The toplevel to use
   392      */
   393     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   394         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   395         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   396                                            syms.errSymbol.name,
   397                                            null, null, null, null);
   398         localEnv.enclClass.sym = syms.errSymbol;
   399         return tree.accept(identAttributer, localEnv);
   400     }
   401     // where
   402         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   403         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   404             @Override
   405             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   406                 Symbol site = visit(node.getExpression(), env);
   407                 if (site.kind == ERR || site.kind == ABSENT_TYP)
   408                     return site;
   409                 Name name = (Name)node.getIdentifier();
   410                 if (site.kind == PCK) {
   411                     env.toplevel.packge = (PackageSymbol)site;
   412                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   413                 } else {
   414                     env.enclClass.sym = (ClassSymbol)site;
   415                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   416                 }
   417             }
   419             @Override
   420             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   421                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   422             }
   423         }
   425     public Type coerce(Type etype, Type ttype) {
   426         return cfolder.coerce(etype, ttype);
   427     }
   429     public Type attribType(JCTree node, TypeSymbol sym) {
   430         Env<AttrContext> env = enter.typeEnvs.get(sym);
   431         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   432         return attribTree(node, localEnv, unknownTypeInfo);
   433     }
   435     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   436         // Attribute qualifying package or class.
   437         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   438         return attribTree(s.selected,
   439                        env,
   440                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   441                        Type.noType));
   442     }
   444     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   445         breakTree = tree;
   446         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   447         try {
   448             attribExpr(expr, env);
   449         } catch (BreakAttr b) {
   450             return b.env;
   451         } catch (AssertionError ae) {
   452             if (ae.getCause() instanceof BreakAttr) {
   453                 return ((BreakAttr)(ae.getCause())).env;
   454             } else {
   455                 throw ae;
   456             }
   457         } finally {
   458             breakTree = null;
   459             log.useSource(prev);
   460         }
   461         return env;
   462     }
   464     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   465         breakTree = tree;
   466         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   467         try {
   468             attribStat(stmt, env);
   469         } catch (BreakAttr b) {
   470             return b.env;
   471         } catch (AssertionError ae) {
   472             if (ae.getCause() instanceof BreakAttr) {
   473                 return ((BreakAttr)(ae.getCause())).env;
   474             } else {
   475                 throw ae;
   476             }
   477         } finally {
   478             breakTree = null;
   479             log.useSource(prev);
   480         }
   481         return env;
   482     }
   484     private JCTree breakTree = null;
   486     private static class BreakAttr extends RuntimeException {
   487         static final long serialVersionUID = -6924771130405446405L;
   488         private Env<AttrContext> env;
   489         private BreakAttr(Env<AttrContext> env) {
   490             this.env = env;
   491         }
   492     }
   494     class ResultInfo {
   495         final int pkind;
   496         final Type pt;
   497         final CheckContext checkContext;
   499         ResultInfo(int pkind, Type pt) {
   500             this(pkind, pt, chk.basicHandler);
   501         }
   503         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   504             this.pkind = pkind;
   505             this.pt = pt;
   506             this.checkContext = checkContext;
   507         }
   509         protected Type check(final DiagnosticPosition pos, final Type found) {
   510             return chk.checkType(pos, found, pt, checkContext);
   511         }
   513         protected ResultInfo dup(Type newPt) {
   514             return new ResultInfo(pkind, newPt, checkContext);
   515         }
   517         protected ResultInfo dup(CheckContext newContext) {
   518             return new ResultInfo(pkind, pt, newContext);
   519         }
   521         protected ResultInfo dup(Type newPt, CheckContext newContext) {
   522             return new ResultInfo(pkind, newPt, newContext);
   523         }
   525         @Override
   526         public String toString() {
   527             if (pt != null) {
   528                 return pt.toString();
   529             } else {
   530                 return "";
   531             }
   532         }
   533     }
   535     class RecoveryInfo extends ResultInfo {
   537         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   538             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   539                 @Override
   540                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   541                     return deferredAttrContext;
   542                 }
   543                 @Override
   544                 public boolean compatible(Type found, Type req, Warner warn) {
   545                     return true;
   546                 }
   547                 @Override
   548                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   549                     chk.basicHandler.report(pos, details);
   550                 }
   551             });
   552         }
   553     }
   555     final ResultInfo statInfo;
   556     final ResultInfo varInfo;
   557     final ResultInfo unknownAnyPolyInfo;
   558     final ResultInfo unknownExprInfo;
   559     final ResultInfo unknownTypeInfo;
   560     final ResultInfo unknownTypeExprInfo;
   561     final ResultInfo recoveryInfo;
   563     Type pt() {
   564         return resultInfo.pt;
   565     }
   567     int pkind() {
   568         return resultInfo.pkind;
   569     }
   571 /* ************************************************************************
   572  * Visitor methods
   573  *************************************************************************/
   575     /** Visitor argument: the current environment.
   576      */
   577     Env<AttrContext> env;
   579     /** Visitor argument: the currently expected attribution result.
   580      */
   581     ResultInfo resultInfo;
   583     /** Visitor result: the computed type.
   584      */
   585     Type result;
   587     /** Visitor method: attribute a tree, catching any completion failure
   588      *  exceptions. Return the tree's type.
   589      *
   590      *  @param tree    The tree to be visited.
   591      *  @param env     The environment visitor argument.
   592      *  @param resultInfo   The result info visitor argument.
   593      */
   594     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   595         Env<AttrContext> prevEnv = this.env;
   596         ResultInfo prevResult = this.resultInfo;
   597         try {
   598             this.env = env;
   599             this.resultInfo = resultInfo;
   600             tree.accept(this);
   601             if (tree == breakTree &&
   602                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   603                 throw new BreakAttr(copyEnv(env));
   604             }
   605             return result;
   606         } catch (CompletionFailure ex) {
   607             tree.type = syms.errType;
   608             return chk.completionError(tree.pos(), ex);
   609         } finally {
   610             this.env = prevEnv;
   611             this.resultInfo = prevResult;
   612         }
   613     }
   615     Env<AttrContext> copyEnv(Env<AttrContext> env) {
   616         Env<AttrContext> newEnv =
   617                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   618         if (newEnv.outer != null) {
   619             newEnv.outer = copyEnv(newEnv.outer);
   620         }
   621         return newEnv;
   622     }
   624     Scope copyScope(Scope sc) {
   625         Scope newScope = new Scope(sc.owner);
   626         List<Symbol> elemsList = List.nil();
   627         while (sc != null) {
   628             for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   629                 elemsList = elemsList.prepend(e.sym);
   630             }
   631             sc = sc.next;
   632         }
   633         for (Symbol s : elemsList) {
   634             newScope.enter(s);
   635         }
   636         return newScope;
   637     }
   639     /** Derived visitor method: attribute an expression tree.
   640      */
   641     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   642         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   643     }
   645     /** Derived visitor method: attribute an expression tree with
   646      *  no constraints on the computed type.
   647      */
   648     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   649         return attribTree(tree, env, unknownExprInfo);
   650     }
   652     /** Derived visitor method: attribute a type tree.
   653      */
   654     public Type attribType(JCTree tree, Env<AttrContext> env) {
   655         Type result = attribType(tree, env, Type.noType);
   656         return result;
   657     }
   659     /** Derived visitor method: attribute a type tree.
   660      */
   661     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   662         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   663         return result;
   664     }
   666     /** Derived visitor method: attribute a statement or definition tree.
   667      */
   668     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   669         return attribTree(tree, env, statInfo);
   670     }
   672     /** Attribute a list of expressions, returning a list of types.
   673      */
   674     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   675         ListBuffer<Type> ts = new ListBuffer<Type>();
   676         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   677             ts.append(attribExpr(l.head, env, pt));
   678         return ts.toList();
   679     }
   681     /** Attribute a list of statements, returning nothing.
   682      */
   683     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   684         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   685             attribStat(l.head, env);
   686     }
   688     /** Attribute the arguments in a method call, returning the method kind.
   689      */
   690     int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   691         int kind = VAL;
   692         for (JCExpression arg : trees) {
   693             Type argtype;
   694             if (allowPoly && deferredAttr.isDeferred(env, arg)) {
   695                 argtype = deferredAttr.new DeferredType(arg, env);
   696                 kind |= POLY;
   697             } else {
   698                 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
   699             }
   700             argtypes.append(argtype);
   701         }
   702         return kind;
   703     }
   705     /** Attribute a type argument list, returning a list of types.
   706      *  Caller is responsible for calling checkRefTypes.
   707      */
   708     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   709         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   710         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   711             argtypes.append(attribType(l.head, env));
   712         return argtypes.toList();
   713     }
   715     /** Attribute a type argument list, returning a list of types.
   716      *  Check that all the types are references.
   717      */
   718     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   719         List<Type> types = attribAnyTypes(trees, env);
   720         return chk.checkRefTypes(trees, types);
   721     }
   723     /**
   724      * Attribute type variables (of generic classes or methods).
   725      * Compound types are attributed later in attribBounds.
   726      * @param typarams the type variables to enter
   727      * @param env      the current environment
   728      */
   729     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   730         for (JCTypeParameter tvar : typarams) {
   731             TypeVar a = (TypeVar)tvar.type;
   732             a.tsym.flags_field |= UNATTRIBUTED;
   733             a.bound = Type.noType;
   734             if (!tvar.bounds.isEmpty()) {
   735                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   736                 for (JCExpression bound : tvar.bounds.tail)
   737                     bounds = bounds.prepend(attribType(bound, env));
   738                 types.setBounds(a, bounds.reverse());
   739             } else {
   740                 // if no bounds are given, assume a single bound of
   741                 // java.lang.Object.
   742                 types.setBounds(a, List.of(syms.objectType));
   743             }
   744             a.tsym.flags_field &= ~UNATTRIBUTED;
   745         }
   746         for (JCTypeParameter tvar : typarams) {
   747             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   748         }
   749     }
   751     /**
   752      * Attribute the type references in a list of annotations.
   753      */
   754     void attribAnnotationTypes(List<JCAnnotation> annotations,
   755                                Env<AttrContext> env) {
   756         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   757             JCAnnotation a = al.head;
   758             attribType(a.annotationType, env);
   759         }
   760     }
   762     /**
   763      * Attribute a "lazy constant value".
   764      *  @param env         The env for the const value
   765      *  @param initializer The initializer for the const value
   766      *  @param type        The expected type, or null
   767      *  @see VarSymbol#setLazyConstValue
   768      */
   769     public Object attribLazyConstantValue(Env<AttrContext> env,
   770                                       JCVariableDecl variable,
   771                                       Type type) {
   773         DiagnosticPosition prevLintPos
   774                 = deferredLintHandler.setPos(variable.pos());
   776         try {
   777             // Use null as symbol to not attach the type annotation to any symbol.
   778             // The initializer will later also be visited and then we'll attach
   779             // to the symbol.
   780             // This prevents having multiple type annotations, just because of
   781             // lazy constant value evaluation.
   782             memberEnter.typeAnnotate(variable.init, env, null, variable.pos());
   783             annotate.flush();
   784             Type itype = attribExpr(variable.init, env, type);
   785             if (itype.constValue() != null) {
   786                 return coerce(itype, type).constValue();
   787             } else {
   788                 return null;
   789             }
   790         } finally {
   791             deferredLintHandler.setPos(prevLintPos);
   792         }
   793     }
   795     /** Attribute type reference in an `extends' or `implements' clause.
   796      *  Supertypes of anonymous inner classes are usually already attributed.
   797      *
   798      *  @param tree              The tree making up the type reference.
   799      *  @param env               The environment current at the reference.
   800      *  @param classExpected     true if only a class is expected here.
   801      *  @param interfaceExpected true if only an interface is expected here.
   802      */
   803     Type attribBase(JCTree tree,
   804                     Env<AttrContext> env,
   805                     boolean classExpected,
   806                     boolean interfaceExpected,
   807                     boolean checkExtensible) {
   808         Type t = tree.type != null ?
   809             tree.type :
   810             attribType(tree, env);
   811         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   812     }
   813     Type checkBase(Type t,
   814                    JCTree tree,
   815                    Env<AttrContext> env,
   816                    boolean classExpected,
   817                    boolean interfaceExpected,
   818                    boolean checkExtensible) {
   819         if (t.tsym.isAnonymous()) {
   820             log.error(tree.pos(), "cant.inherit.from.anon");
   821             return types.createErrorType(t);
   822         }
   823         if (t.isErroneous())
   824             return t;
   825         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   826             // check that type variable is already visible
   827             if (t.getUpperBound() == null) {
   828                 log.error(tree.pos(), "illegal.forward.ref");
   829                 return types.createErrorType(t);
   830             }
   831         } else {
   832             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   833         }
   834         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   835             log.error(tree.pos(), "intf.expected.here");
   836             // return errType is necessary since otherwise there might
   837             // be undetected cycles which cause attribution to loop
   838             return types.createErrorType(t);
   839         } else if (checkExtensible &&
   840                    classExpected &&
   841                    (t.tsym.flags() & INTERFACE) != 0) {
   842             log.error(tree.pos(), "no.intf.expected.here");
   843             return types.createErrorType(t);
   844         }
   845         if (checkExtensible &&
   846             ((t.tsym.flags() & FINAL) != 0)) {
   847             log.error(tree.pos(),
   848                       "cant.inherit.from.final", t.tsym);
   849         }
   850         chk.checkNonCyclic(tree.pos(), t);
   851         return t;
   852     }
   854     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   855         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   856         id.type = env.info.scope.owner.type;
   857         id.sym = env.info.scope.owner;
   858         return id.type;
   859     }
   861     public void visitClassDef(JCClassDecl tree) {
   862         // Local classes have not been entered yet, so we need to do it now:
   863         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   864             enter.classEnter(tree, env);
   866         ClassSymbol c = tree.sym;
   867         if (c == null) {
   868             // exit in case something drastic went wrong during enter.
   869             result = null;
   870         } else {
   871             // make sure class has been completed:
   872             c.complete();
   874             // If this class appears as an anonymous class
   875             // in a superclass constructor call where
   876             // no explicit outer instance is given,
   877             // disable implicit outer instance from being passed.
   878             // (This would be an illegal access to "this before super").
   879             if (env.info.isSelfCall &&
   880                 env.tree.hasTag(NEWCLASS) &&
   881                 ((JCNewClass) env.tree).encl == null)
   882             {
   883                 c.flags_field |= NOOUTERTHIS;
   884             }
   885             attribClass(tree.pos(), c);
   886             result = tree.type = c.type;
   887         }
   888     }
   890     public void visitMethodDef(JCMethodDecl tree) {
   891         MethodSymbol m = tree.sym;
   892         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   894         Lint lint = env.info.lint.augment(m);
   895         Lint prevLint = chk.setLint(lint);
   896         MethodSymbol prevMethod = chk.setMethod(m);
   897         try {
   898             deferredLintHandler.flush(tree.pos());
   899             chk.checkDeprecatedAnnotation(tree.pos(), m);
   902             // Create a new environment with local scope
   903             // for attributing the method.
   904             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   905             localEnv.info.lint = lint;
   907             attribStats(tree.typarams, localEnv);
   909             // If we override any other methods, check that we do so properly.
   910             // JLS ???
   911             if (m.isStatic()) {
   912                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   913             } else {
   914                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   915             }
   916             chk.checkOverride(tree, m);
   918             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   919                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   920             }
   922             // Enter all type parameters into the local method scope.
   923             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   924                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   926             ClassSymbol owner = env.enclClass.sym;
   927             if ((owner.flags() & ANNOTATION) != 0 &&
   928                 tree.params.nonEmpty())
   929                 log.error(tree.params.head.pos(),
   930                           "intf.annotation.members.cant.have.params");
   932             // Attribute all value parameters.
   933             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   934                 attribStat(l.head, localEnv);
   935             }
   937             chk.checkVarargsMethodDecl(localEnv, tree);
   939             // Check that type parameters are well-formed.
   940             chk.validate(tree.typarams, localEnv);
   942             // Check that result type is well-formed.
   943             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
   944                 chk.validate(tree.restype, localEnv);
   946             // Check that receiver type is well-formed.
   947             if (tree.recvparam != null) {
   948                 // Use a new environment to check the receiver parameter.
   949                 // Otherwise I get "might not have been initialized" errors.
   950                 // Is there a better way?
   951                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   952                 attribType(tree.recvparam, newEnv);
   953                 chk.validate(tree.recvparam, newEnv);
   954             }
   956             // annotation method checks
   957             if ((owner.flags() & ANNOTATION) != 0) {
   958                 // annotation method cannot have throws clause
   959                 if (tree.thrown.nonEmpty()) {
   960                     log.error(tree.thrown.head.pos(),
   961                             "throws.not.allowed.in.intf.annotation");
   962                 }
   963                 // annotation method cannot declare type-parameters
   964                 if (tree.typarams.nonEmpty()) {
   965                     log.error(tree.typarams.head.pos(),
   966                             "intf.annotation.members.cant.have.type.params");
   967                 }
   968                 // validate annotation method's return type (could be an annotation type)
   969                 chk.validateAnnotationType(tree.restype);
   970                 // ensure that annotation method does not clash with members of Object/Annotation
   971                 chk.validateAnnotationMethod(tree.pos(), m);
   972             }
   974             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   975                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   977             if (tree.body == null) {
   978                 // Empty bodies are only allowed for
   979                 // abstract, native, or interface methods, or for methods
   980                 // in a retrofit signature class.
   981                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   982                     !relax)
   983                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   984                 if (tree.defaultValue != null) {
   985                     if ((owner.flags() & ANNOTATION) == 0)
   986                         log.error(tree.pos(),
   987                                   "default.allowed.in.intf.annotation.member");
   988                 }
   989             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   990                 if ((owner.flags() & INTERFACE) != 0) {
   991                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   992                 } else {
   993                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   994                 }
   995             } else if ((tree.mods.flags & NATIVE) != 0) {
   996                 log.error(tree.pos(), "native.meth.cant.have.body");
   997             } else {
   998                 // Add an implicit super() call unless an explicit call to
   999                 // super(...) or this(...) is given
  1000                 // or we are compiling class java.lang.Object.
  1001                 if (tree.name == names.init && owner.type != syms.objectType) {
  1002                     JCBlock body = tree.body;
  1003                     if (body.stats.isEmpty() ||
  1004                         !TreeInfo.isSelfCall(body.stats.head)) {
  1005                         body.stats = body.stats.
  1006                             prepend(memberEnter.SuperCall(make.at(body.pos),
  1007                                                           List.<Type>nil(),
  1008                                                           List.<JCVariableDecl>nil(),
  1009                                                           false));
  1010                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1011                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1012                                TreeInfo.isSuperCall(body.stats.head)) {
  1013                         // enum constructors are not allowed to call super
  1014                         // directly, so make sure there aren't any super calls
  1015                         // in enum constructors, except in the compiler
  1016                         // generated one.
  1017                         log.error(tree.body.stats.head.pos(),
  1018                                   "call.to.super.not.allowed.in.enum.ctor",
  1019                                   env.enclClass.sym);
  1023                 // Attribute all type annotations in the body
  1024                 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
  1025                 annotate.flush();
  1027                 // Attribute method body.
  1028                 attribStat(tree.body, localEnv);
  1031             localEnv.info.scope.leave();
  1032             result = tree.type = m.type;
  1034         finally {
  1035             chk.setLint(prevLint);
  1036             chk.setMethod(prevMethod);
  1040     public void visitVarDef(JCVariableDecl tree) {
  1041         // Local variables have not been entered yet, so we need to do it now:
  1042         if (env.info.scope.owner.kind == MTH) {
  1043             if (tree.sym != null) {
  1044                 // parameters have already been entered
  1045                 env.info.scope.enter(tree.sym);
  1046             } else {
  1047                 memberEnter.memberEnter(tree, env);
  1048                 annotate.flush();
  1050         } else {
  1051             if (tree.init != null) {
  1052                 // Field initializer expression need to be entered.
  1053                 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
  1054                 annotate.flush();
  1058         VarSymbol v = tree.sym;
  1059         Lint lint = env.info.lint.augment(v);
  1060         Lint prevLint = chk.setLint(lint);
  1062         // Check that the variable's declared type is well-formed.
  1063         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1064                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1065                 (tree.sym.flags() & PARAMETER) != 0;
  1066         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1068         try {
  1069             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1070             deferredLintHandler.flush(tree.pos());
  1071             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1073             if (tree.init != null) {
  1074                 if ((v.flags_field & FINAL) == 0 ||
  1075                     !memberEnter.needsLazyConstValue(tree.init)) {
  1076                     // Not a compile-time constant
  1077                     // Attribute initializer in a new environment
  1078                     // with the declared variable as owner.
  1079                     // Check that initializer conforms to variable's declared type.
  1080                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1081                     initEnv.info.lint = lint;
  1082                     // In order to catch self-references, we set the variable's
  1083                     // declaration position to maximal possible value, effectively
  1084                     // marking the variable as undefined.
  1085                     initEnv.info.enclVar = v;
  1086                     attribExpr(tree.init, initEnv, v.type);
  1089             result = tree.type = v.type;
  1091         finally {
  1092             chk.setLint(prevLint);
  1096     public void visitSkip(JCSkip tree) {
  1097         result = null;
  1100     public void visitBlock(JCBlock tree) {
  1101         if (env.info.scope.owner.kind == TYP) {
  1102             // Block is a static or instance initializer;
  1103             // let the owner of the environment be a freshly
  1104             // created BLOCK-method.
  1105             Env<AttrContext> localEnv =
  1106                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1107             localEnv.info.scope.owner =
  1108                 new MethodSymbol(tree.flags | BLOCK |
  1109                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1110                     env.info.scope.owner);
  1111             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1113             // Attribute all type annotations in the block
  1114             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1115             annotate.flush();
  1118                 // Store init and clinit type annotations with the ClassSymbol
  1119                 // to allow output in Gen.normalizeDefs.
  1120                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1121                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1122                 if ((tree.flags & STATIC) != 0) {
  1123                     cs.appendClassInitTypeAttributes(tas);
  1124                 } else {
  1125                     cs.appendInitTypeAttributes(tas);
  1129             attribStats(tree.stats, localEnv);
  1130         } else {
  1131             // Create a new local environment with a local scope.
  1132             Env<AttrContext> localEnv =
  1133                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1134             try {
  1135                 attribStats(tree.stats, localEnv);
  1136             } finally {
  1137                 localEnv.info.scope.leave();
  1140         result = null;
  1143     public void visitDoLoop(JCDoWhileLoop tree) {
  1144         attribStat(tree.body, env.dup(tree));
  1145         attribExpr(tree.cond, env, syms.booleanType);
  1146         result = null;
  1149     public void visitWhileLoop(JCWhileLoop tree) {
  1150         attribExpr(tree.cond, env, syms.booleanType);
  1151         attribStat(tree.body, env.dup(tree));
  1152         result = null;
  1155     public void visitForLoop(JCForLoop tree) {
  1156         Env<AttrContext> loopEnv =
  1157             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1158         try {
  1159             attribStats(tree.init, loopEnv);
  1160             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1161             loopEnv.tree = tree; // before, we were not in loop!
  1162             attribStats(tree.step, loopEnv);
  1163             attribStat(tree.body, loopEnv);
  1164             result = null;
  1166         finally {
  1167             loopEnv.info.scope.leave();
  1171     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1172         Env<AttrContext> loopEnv =
  1173             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1174         try {
  1175             //the Formal Parameter of a for-each loop is not in the scope when
  1176             //attributing the for-each expression; we mimick this by attributing
  1177             //the for-each expression first (against original scope).
  1178             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
  1179             attribStat(tree.var, loopEnv);
  1180             chk.checkNonVoid(tree.pos(), exprType);
  1181             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1182             if (elemtype == null) {
  1183                 // or perhaps expr implements Iterable<T>?
  1184                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1185                 if (base == null) {
  1186                     log.error(tree.expr.pos(),
  1187                             "foreach.not.applicable.to.type",
  1188                             exprType,
  1189                             diags.fragment("type.req.array.or.iterable"));
  1190                     elemtype = types.createErrorType(exprType);
  1191                 } else {
  1192                     List<Type> iterableParams = base.allparams();
  1193                     elemtype = iterableParams.isEmpty()
  1194                         ? syms.objectType
  1195                         : types.wildUpperBound(iterableParams.head);
  1198             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1199             loopEnv.tree = tree; // before, we were not in loop!
  1200             attribStat(tree.body, loopEnv);
  1201             result = null;
  1203         finally {
  1204             loopEnv.info.scope.leave();
  1208     public void visitLabelled(JCLabeledStatement tree) {
  1209         // Check that label is not used in an enclosing statement
  1210         Env<AttrContext> env1 = env;
  1211         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1212             if (env1.tree.hasTag(LABELLED) &&
  1213                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1214                 log.error(tree.pos(), "label.already.in.use",
  1215                           tree.label);
  1216                 break;
  1218             env1 = env1.next;
  1221         attribStat(tree.body, env.dup(tree));
  1222         result = null;
  1225     public void visitSwitch(JCSwitch tree) {
  1226         Type seltype = attribExpr(tree.selector, env);
  1228         Env<AttrContext> switchEnv =
  1229             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1231         try {
  1233             boolean enumSwitch =
  1234                 allowEnums &&
  1235                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1236             boolean stringSwitch = false;
  1237             if (types.isSameType(seltype, syms.stringType)) {
  1238                 if (allowStringsInSwitch) {
  1239                     stringSwitch = true;
  1240                 } else {
  1241                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1244             if (!enumSwitch && !stringSwitch)
  1245                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1247             // Attribute all cases and
  1248             // check that there are no duplicate case labels or default clauses.
  1249             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1250             boolean hasDefault = false;      // Is there a default label?
  1251             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1252                 JCCase c = l.head;
  1253                 Env<AttrContext> caseEnv =
  1254                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1255                 try {
  1256                     if (c.pat != null) {
  1257                         if (enumSwitch) {
  1258                             Symbol sym = enumConstant(c.pat, seltype);
  1259                             if (sym == null) {
  1260                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1261                             } else if (!labels.add(sym)) {
  1262                                 log.error(c.pos(), "duplicate.case.label");
  1264                         } else {
  1265                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1266                             if (!pattype.hasTag(ERROR)) {
  1267                                 if (pattype.constValue() == null) {
  1268                                     log.error(c.pat.pos(),
  1269                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1270                                 } else if (labels.contains(pattype.constValue())) {
  1271                                     log.error(c.pos(), "duplicate.case.label");
  1272                                 } else {
  1273                                     labels.add(pattype.constValue());
  1277                     } else if (hasDefault) {
  1278                         log.error(c.pos(), "duplicate.default.label");
  1279                     } else {
  1280                         hasDefault = true;
  1282                     attribStats(c.stats, caseEnv);
  1283                 } finally {
  1284                     caseEnv.info.scope.leave();
  1285                     addVars(c.stats, switchEnv.info.scope);
  1289             result = null;
  1291         finally {
  1292             switchEnv.info.scope.leave();
  1295     // where
  1296         /** Add any variables defined in stats to the switch scope. */
  1297         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1298             for (;stats.nonEmpty(); stats = stats.tail) {
  1299                 JCTree stat = stats.head;
  1300                 if (stat.hasTag(VARDEF))
  1301                     switchScope.enter(((JCVariableDecl) stat).sym);
  1304     // where
  1305     /** Return the selected enumeration constant symbol, or null. */
  1306     private Symbol enumConstant(JCTree tree, Type enumType) {
  1307         if (!tree.hasTag(IDENT)) {
  1308             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1309             return syms.errSymbol;
  1311         JCIdent ident = (JCIdent)tree;
  1312         Name name = ident.name;
  1313         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1314              e.scope != null; e = e.next()) {
  1315             if (e.sym.kind == VAR) {
  1316                 Symbol s = ident.sym = e.sym;
  1317                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1318                 ident.type = s.type;
  1319                 return ((s.flags_field & Flags.ENUM) == 0)
  1320                     ? null : s;
  1323         return null;
  1326     public void visitSynchronized(JCSynchronized tree) {
  1327         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1328         attribStat(tree.body, env);
  1329         result = null;
  1332     public void visitTry(JCTry tree) {
  1333         // Create a new local environment with a local
  1334         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1335         try {
  1336             boolean isTryWithResource = tree.resources.nonEmpty();
  1337             // Create a nested environment for attributing the try block if needed
  1338             Env<AttrContext> tryEnv = isTryWithResource ?
  1339                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1340                 localEnv;
  1341             try {
  1342                 // Attribute resource declarations
  1343                 for (JCTree resource : tree.resources) {
  1344                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1345                         @Override
  1346                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1347                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1349                     };
  1350                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1351                     if (resource.hasTag(VARDEF)) {
  1352                         attribStat(resource, tryEnv);
  1353                         twrResult.check(resource, resource.type);
  1355                         //check that resource type cannot throw InterruptedException
  1356                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1358                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1359                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1360                     } else {
  1361                         attribTree(resource, tryEnv, twrResult);
  1364                 // Attribute body
  1365                 attribStat(tree.body, tryEnv);
  1366             } finally {
  1367                 if (isTryWithResource)
  1368                     tryEnv.info.scope.leave();
  1371             // Attribute catch clauses
  1372             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1373                 JCCatch c = l.head;
  1374                 Env<AttrContext> catchEnv =
  1375                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1376                 try {
  1377                     Type ctype = attribStat(c.param, catchEnv);
  1378                     if (TreeInfo.isMultiCatch(c)) {
  1379                         //multi-catch parameter is implicitly marked as final
  1380                         c.param.sym.flags_field |= FINAL | UNION;
  1382                     if (c.param.sym.kind == Kinds.VAR) {
  1383                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1385                     chk.checkType(c.param.vartype.pos(),
  1386                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1387                                   syms.throwableType);
  1388                     attribStat(c.body, catchEnv);
  1389                 } finally {
  1390                     catchEnv.info.scope.leave();
  1394             // Attribute finalizer
  1395             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1396             result = null;
  1398         finally {
  1399             localEnv.info.scope.leave();
  1403     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1404         if (!resource.isErroneous() &&
  1405             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1406             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1407             Symbol close = syms.noSymbol;
  1408             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1409             try {
  1410                 close = rs.resolveQualifiedMethod(pos,
  1411                         env,
  1412                         resource,
  1413                         names.close,
  1414                         List.<Type>nil(),
  1415                         List.<Type>nil());
  1417             finally {
  1418                 log.popDiagnosticHandler(discardHandler);
  1420             if (close.kind == MTH &&
  1421                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1422                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1423                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1424                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1429     public void visitConditional(JCConditional tree) {
  1430         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1432         tree.polyKind = (!allowPoly ||
  1433                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1434                 isBooleanOrNumeric(env, tree)) ?
  1435                 PolyKind.STANDALONE : PolyKind.POLY;
  1437         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1438             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1439             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1440             result = tree.type = types.createErrorType(resultInfo.pt);
  1441             return;
  1444         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1445                 unknownExprInfo :
  1446                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1447                     //this will use enclosing check context to check compatibility of
  1448                     //subexpression against target type; if we are in a method check context,
  1449                     //depending on whether boxing is allowed, we could have incompatibilities
  1450                     @Override
  1451                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1452                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1454                 });
  1456         Type truetype = attribTree(tree.truepart, env, condInfo);
  1457         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1459         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1460         if (condtype.constValue() != null &&
  1461                 truetype.constValue() != null &&
  1462                 falsetype.constValue() != null &&
  1463                 !owntype.hasTag(NONE)) {
  1464             //constant folding
  1465             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1467         result = check(tree, owntype, VAL, resultInfo);
  1469     //where
  1470         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1471             switch (tree.getTag()) {
  1472                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1473                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1474                               ((JCLiteral)tree).typetag == BOT;
  1475                 case LAMBDA: case REFERENCE: return false;
  1476                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1477                 case CONDEXPR:
  1478                     JCConditional condTree = (JCConditional)tree;
  1479                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1480                             isBooleanOrNumeric(env, condTree.falsepart);
  1481                 case APPLY:
  1482                     JCMethodInvocation speculativeMethodTree =
  1483                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1484                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1485                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1486                 case NEWCLASS:
  1487                     JCExpression className =
  1488                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1489                     JCExpression speculativeNewClassTree =
  1490                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1491                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1492                 default:
  1493                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1494                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1495                     return speculativeType.isPrimitive();
  1498         //where
  1499             TreeTranslator removeClassParams = new TreeTranslator() {
  1500                 @Override
  1501                 public void visitTypeApply(JCTypeApply tree) {
  1502                     result = translate(tree.clazz);
  1504             };
  1506         /** Compute the type of a conditional expression, after
  1507          *  checking that it exists.  See JLS 15.25. Does not take into
  1508          *  account the special case where condition and both arms
  1509          *  are constants.
  1511          *  @param pos      The source position to be used for error
  1512          *                  diagnostics.
  1513          *  @param thentype The type of the expression's then-part.
  1514          *  @param elsetype The type of the expression's else-part.
  1515          */
  1516         private Type condType(DiagnosticPosition pos,
  1517                                Type thentype, Type elsetype) {
  1518             // If same type, that is the result
  1519             if (types.isSameType(thentype, elsetype))
  1520                 return thentype.baseType();
  1522             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1523                 ? thentype : types.unboxedType(thentype);
  1524             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1525                 ? elsetype : types.unboxedType(elsetype);
  1527             // Otherwise, if both arms can be converted to a numeric
  1528             // type, return the least numeric type that fits both arms
  1529             // (i.e. return larger of the two, or return int if one
  1530             // arm is short, the other is char).
  1531             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1532                 // If one arm has an integer subrange type (i.e., byte,
  1533                 // short, or char), and the other is an integer constant
  1534                 // that fits into the subrange, return the subrange type.
  1535                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1536                     elseUnboxed.hasTag(INT) &&
  1537                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1538                     return thenUnboxed.baseType();
  1540                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1541                     thenUnboxed.hasTag(INT) &&
  1542                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1543                     return elseUnboxed.baseType();
  1546                 for (TypeTag tag : primitiveTags) {
  1547                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1548                     if (types.isSubtype(thenUnboxed, candidate) &&
  1549                         types.isSubtype(elseUnboxed, candidate)) {
  1550                         return candidate;
  1555             // Those were all the cases that could result in a primitive
  1556             if (allowBoxing) {
  1557                 if (thentype.isPrimitive())
  1558                     thentype = types.boxedClass(thentype).type;
  1559                 if (elsetype.isPrimitive())
  1560                     elsetype = types.boxedClass(elsetype).type;
  1563             if (types.isSubtype(thentype, elsetype))
  1564                 return elsetype.baseType();
  1565             if (types.isSubtype(elsetype, thentype))
  1566                 return thentype.baseType();
  1568             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1569                 log.error(pos, "neither.conditional.subtype",
  1570                           thentype, elsetype);
  1571                 return thentype.baseType();
  1574             // both are known to be reference types.  The result is
  1575             // lub(thentype,elsetype). This cannot fail, as it will
  1576             // always be possible to infer "Object" if nothing better.
  1577             return types.lub(thentype.baseType(), elsetype.baseType());
  1580     final static TypeTag[] primitiveTags = new TypeTag[]{
  1581         BYTE,
  1582         CHAR,
  1583         SHORT,
  1584         INT,
  1585         LONG,
  1586         FLOAT,
  1587         DOUBLE,
  1588         BOOLEAN,
  1589     };
  1591     public void visitIf(JCIf tree) {
  1592         attribExpr(tree.cond, env, syms.booleanType);
  1593         attribStat(tree.thenpart, env);
  1594         if (tree.elsepart != null)
  1595             attribStat(tree.elsepart, env);
  1596         chk.checkEmptyIf(tree);
  1597         result = null;
  1600     public void visitExec(JCExpressionStatement tree) {
  1601         //a fresh environment is required for 292 inference to work properly ---
  1602         //see Infer.instantiatePolymorphicSignatureInstance()
  1603         Env<AttrContext> localEnv = env.dup(tree);
  1604         attribExpr(tree.expr, localEnv);
  1605         result = null;
  1608     public void visitBreak(JCBreak tree) {
  1609         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1610         result = null;
  1613     public void visitContinue(JCContinue tree) {
  1614         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1615         result = null;
  1617     //where
  1618         /** Return the target of a break or continue statement, if it exists,
  1619          *  report an error if not.
  1620          *  Note: The target of a labelled break or continue is the
  1621          *  (non-labelled) statement tree referred to by the label,
  1622          *  not the tree representing the labelled statement itself.
  1624          *  @param pos     The position to be used for error diagnostics
  1625          *  @param tag     The tag of the jump statement. This is either
  1626          *                 Tree.BREAK or Tree.CONTINUE.
  1627          *  @param label   The label of the jump statement, or null if no
  1628          *                 label is given.
  1629          *  @param env     The environment current at the jump statement.
  1630          */
  1631         private JCTree findJumpTarget(DiagnosticPosition pos,
  1632                                     JCTree.Tag tag,
  1633                                     Name label,
  1634                                     Env<AttrContext> env) {
  1635             // Search environments outwards from the point of jump.
  1636             Env<AttrContext> env1 = env;
  1637             LOOP:
  1638             while (env1 != null) {
  1639                 switch (env1.tree.getTag()) {
  1640                     case LABELLED:
  1641                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1642                         if (label == labelled.label) {
  1643                             // If jump is a continue, check that target is a loop.
  1644                             if (tag == CONTINUE) {
  1645                                 if (!labelled.body.hasTag(DOLOOP) &&
  1646                                         !labelled.body.hasTag(WHILELOOP) &&
  1647                                         !labelled.body.hasTag(FORLOOP) &&
  1648                                         !labelled.body.hasTag(FOREACHLOOP))
  1649                                     log.error(pos, "not.loop.label", label);
  1650                                 // Found labelled statement target, now go inwards
  1651                                 // to next non-labelled tree.
  1652                                 return TreeInfo.referencedStatement(labelled);
  1653                             } else {
  1654                                 return labelled;
  1657                         break;
  1658                     case DOLOOP:
  1659                     case WHILELOOP:
  1660                     case FORLOOP:
  1661                     case FOREACHLOOP:
  1662                         if (label == null) return env1.tree;
  1663                         break;
  1664                     case SWITCH:
  1665                         if (label == null && tag == BREAK) return env1.tree;
  1666                         break;
  1667                     case LAMBDA:
  1668                     case METHODDEF:
  1669                     case CLASSDEF:
  1670                         break LOOP;
  1671                     default:
  1673                 env1 = env1.next;
  1675             if (label != null)
  1676                 log.error(pos, "undef.label", label);
  1677             else if (tag == CONTINUE)
  1678                 log.error(pos, "cont.outside.loop");
  1679             else
  1680                 log.error(pos, "break.outside.switch.loop");
  1681             return null;
  1684     public void visitReturn(JCReturn tree) {
  1685         // Check that there is an enclosing method which is
  1686         // nested within than the enclosing class.
  1687         if (env.info.returnResult == null) {
  1688             log.error(tree.pos(), "ret.outside.meth");
  1689         } else {
  1690             // Attribute return expression, if it exists, and check that
  1691             // it conforms to result type of enclosing method.
  1692             if (tree.expr != null) {
  1693                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1694                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1695                               diags.fragment("unexpected.ret.val"));
  1697                 attribTree(tree.expr, env, env.info.returnResult);
  1698             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1699                     !env.info.returnResult.pt.hasTag(NONE)) {
  1700                 env.info.returnResult.checkContext.report(tree.pos(),
  1701                               diags.fragment("missing.ret.val"));
  1704         result = null;
  1707     public void visitThrow(JCThrow tree) {
  1708         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1709         if (allowPoly) {
  1710             chk.checkType(tree, owntype, syms.throwableType);
  1712         result = null;
  1715     public void visitAssert(JCAssert tree) {
  1716         attribExpr(tree.cond, env, syms.booleanType);
  1717         if (tree.detail != null) {
  1718             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1720         result = null;
  1723      /** Visitor method for method invocations.
  1724      *  NOTE: The method part of an application will have in its type field
  1725      *        the return type of the method, not the method's type itself!
  1726      */
  1727     public void visitApply(JCMethodInvocation tree) {
  1728         // The local environment of a method application is
  1729         // a new environment nested in the current one.
  1730         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1732         // The types of the actual method arguments.
  1733         List<Type> argtypes;
  1735         // The types of the actual method type arguments.
  1736         List<Type> typeargtypes = null;
  1738         Name methName = TreeInfo.name(tree.meth);
  1740         boolean isConstructorCall =
  1741             methName == names._this || methName == names._super;
  1743         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1744         if (isConstructorCall) {
  1745             // We are seeing a ...this(...) or ...super(...) call.
  1746             // Check that this is the first statement in a constructor.
  1747             if (checkFirstConstructorStat(tree, env)) {
  1749                 // Record the fact
  1750                 // that this is a constructor call (using isSelfCall).
  1751                 localEnv.info.isSelfCall = true;
  1753                 // Attribute arguments, yielding list of argument types.
  1754                 attribArgs(tree.args, localEnv, argtypesBuf);
  1755                 argtypes = argtypesBuf.toList();
  1756                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1758                 // Variable `site' points to the class in which the called
  1759                 // constructor is defined.
  1760                 Type site = env.enclClass.sym.type;
  1761                 if (methName == names._super) {
  1762                     if (site == syms.objectType) {
  1763                         log.error(tree.meth.pos(), "no.superclass", site);
  1764                         site = types.createErrorType(syms.objectType);
  1765                     } else {
  1766                         site = types.supertype(site);
  1770                 if (site.hasTag(CLASS)) {
  1771                     Type encl = site.getEnclosingType();
  1772                     while (encl != null && encl.hasTag(TYPEVAR))
  1773                         encl = encl.getUpperBound();
  1774                     if (encl.hasTag(CLASS)) {
  1775                         // we are calling a nested class
  1777                         if (tree.meth.hasTag(SELECT)) {
  1778                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1780                             // We are seeing a prefixed call, of the form
  1781                             //     <expr>.super(...).
  1782                             // Check that the prefix expression conforms
  1783                             // to the outer instance type of the class.
  1784                             chk.checkRefType(qualifier.pos(),
  1785                                              attribExpr(qualifier, localEnv,
  1786                                                         encl));
  1787                         } else if (methName == names._super) {
  1788                             // qualifier omitted; check for existence
  1789                             // of an appropriate implicit qualifier.
  1790                             rs.resolveImplicitThis(tree.meth.pos(),
  1791                                                    localEnv, site, true);
  1793                     } else if (tree.meth.hasTag(SELECT)) {
  1794                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1795                                   site.tsym);
  1798                     // if we're calling a java.lang.Enum constructor,
  1799                     // prefix the implicit String and int parameters
  1800                     if (site.tsym == syms.enumSym && allowEnums)
  1801                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1803                     // Resolve the called constructor under the assumption
  1804                     // that we are referring to a superclass instance of the
  1805                     // current instance (JLS ???).
  1806                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1807                     localEnv.info.selectSuper = true;
  1808                     localEnv.info.pendingResolutionPhase = null;
  1809                     Symbol sym = rs.resolveConstructor(
  1810                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1811                     localEnv.info.selectSuper = selectSuperPrev;
  1813                     // Set method symbol to resolved constructor...
  1814                     TreeInfo.setSymbol(tree.meth, sym);
  1816                     // ...and check that it is legal in the current context.
  1817                     // (this will also set the tree's type)
  1818                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1819                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1821                 // Otherwise, `site' is an error type and we do nothing
  1823             result = tree.type = syms.voidType;
  1824         } else {
  1825             // Otherwise, we are seeing a regular method call.
  1826             // Attribute the arguments, yielding list of argument types, ...
  1827             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1828             argtypes = argtypesBuf.toList();
  1829             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1831             // ... and attribute the method using as a prototype a methodtype
  1832             // whose formal argument types is exactly the list of actual
  1833             // arguments (this will also set the method symbol).
  1834             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1835             localEnv.info.pendingResolutionPhase = null;
  1836             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1838             // Compute the result type.
  1839             Type restype = mtype.getReturnType();
  1840             if (restype.hasTag(WILDCARD))
  1841                 throw new AssertionError(mtype);
  1843             Type qualifier = (tree.meth.hasTag(SELECT))
  1844                     ? ((JCFieldAccess) tree.meth).selected.type
  1845                     : env.enclClass.sym.type;
  1846             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1848             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1850             // Check that value of resulting type is admissible in the
  1851             // current context.  Also, capture the return type
  1852             result = check(tree, capture(restype), VAL, resultInfo);
  1854         chk.validate(tree.typeargs, localEnv);
  1856     //where
  1857         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1858             if (allowCovariantReturns &&
  1859                     methodName == names.clone &&
  1860                 types.isArray(qualifierType)) {
  1861                 // as a special case, array.clone() has a result that is
  1862                 // the same as static type of the array being cloned
  1863                 return qualifierType;
  1864             } else if (allowGenerics &&
  1865                     methodName == names.getClass &&
  1866                     argtypes.isEmpty()) {
  1867                 // as a special case, x.getClass() has type Class<? extends |X|>
  1868                 return new ClassType(restype.getEnclosingType(),
  1869                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1870                                                                BoundKind.EXTENDS,
  1871                                                                syms.boundClass)),
  1872                               restype.tsym);
  1873             } else {
  1874                 return restype;
  1878         /** Check that given application node appears as first statement
  1879          *  in a constructor call.
  1880          *  @param tree   The application node
  1881          *  @param env    The environment current at the application.
  1882          */
  1883         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1884             JCMethodDecl enclMethod = env.enclMethod;
  1885             if (enclMethod != null && enclMethod.name == names.init) {
  1886                 JCBlock body = enclMethod.body;
  1887                 if (body.stats.head.hasTag(EXEC) &&
  1888                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1889                     return true;
  1891             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1892                       TreeInfo.name(tree.meth));
  1893             return false;
  1896         /** Obtain a method type with given argument types.
  1897          */
  1898         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1899             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1900             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1903     public void visitNewClass(final JCNewClass tree) {
  1904         Type owntype = types.createErrorType(tree.type);
  1906         // The local environment of a class creation is
  1907         // a new environment nested in the current one.
  1908         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1910         // The anonymous inner class definition of the new expression,
  1911         // if one is defined by it.
  1912         JCClassDecl cdef = tree.def;
  1914         // If enclosing class is given, attribute it, and
  1915         // complete class name to be fully qualified
  1916         JCExpression clazz = tree.clazz; // Class field following new
  1917         JCExpression clazzid;            // Identifier in class field
  1918         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1919         annoclazzid = null;
  1921         if (clazz.hasTag(TYPEAPPLY)) {
  1922             clazzid = ((JCTypeApply) clazz).clazz;
  1923             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1924                 annoclazzid = (JCAnnotatedType) clazzid;
  1925                 clazzid = annoclazzid.underlyingType;
  1927         } else {
  1928             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1929                 annoclazzid = (JCAnnotatedType) clazz;
  1930                 clazzid = annoclazzid.underlyingType;
  1931             } else {
  1932                 clazzid = clazz;
  1936         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1938         if (tree.encl != null) {
  1939             // We are seeing a qualified new, of the form
  1940             //    <expr>.new C <...> (...) ...
  1941             // In this case, we let clazz stand for the name of the
  1942             // allocated class C prefixed with the type of the qualifier
  1943             // expression, so that we can
  1944             // resolve it with standard techniques later. I.e., if
  1945             // <expr> has type T, then <expr>.new C <...> (...)
  1946             // yields a clazz T.C.
  1947             Type encltype = chk.checkRefType(tree.encl.pos(),
  1948                                              attribExpr(tree.encl, env));
  1949             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1950             // from expr to the combined type, or not? Yes, do this.
  1951             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1952                                                  ((JCIdent) clazzid).name);
  1954             EndPosTable endPosTable = this.env.toplevel.endPositions;
  1955             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  1956             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1957                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1958                 List<JCAnnotation> annos = annoType.annotations;
  1960                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1961                     clazzid1 = make.at(tree.pos).
  1962                         TypeApply(clazzid1,
  1963                                   ((JCTypeApply) clazz).arguments);
  1966                 clazzid1 = make.at(tree.pos).
  1967                     AnnotatedType(annos, clazzid1);
  1968             } else if (clazz.hasTag(TYPEAPPLY)) {
  1969                 clazzid1 = make.at(tree.pos).
  1970                     TypeApply(clazzid1,
  1971                               ((JCTypeApply) clazz).arguments);
  1974             clazz = clazzid1;
  1977         // Attribute clazz expression and store
  1978         // symbol + type back into the attributed tree.
  1979         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1980             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1981             attribType(clazz, env);
  1983         clazztype = chk.checkDiamond(tree, clazztype);
  1984         chk.validate(clazz, localEnv);
  1985         if (tree.encl != null) {
  1986             // We have to work in this case to store
  1987             // symbol + type back into the attributed tree.
  1988             tree.clazz.type = clazztype;
  1989             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1990             clazzid.type = ((JCIdent) clazzid).sym.type;
  1991             if (annoclazzid != null) {
  1992                 annoclazzid.type = clazzid.type;
  1994             if (!clazztype.isErroneous()) {
  1995                 if (cdef != null && clazztype.tsym.isInterface()) {
  1996                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1997                 } else if (clazztype.tsym.isStatic()) {
  1998                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  2001         } else if (!clazztype.tsym.isInterface() &&
  2002                    clazztype.getEnclosingType().hasTag(CLASS)) {
  2003             // Check for the existence of an apropos outer instance
  2004             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  2007         // Attribute constructor arguments.
  2008         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  2009         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  2010         List<Type> argtypes = argtypesBuf.toList();
  2011         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  2013         // If we have made no mistakes in the class type...
  2014         if (clazztype.hasTag(CLASS)) {
  2015             // Enums may not be instantiated except implicitly
  2016             if (allowEnums &&
  2017                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  2018                 (!env.tree.hasTag(VARDEF) ||
  2019                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  2020                  ((JCVariableDecl) env.tree).init != tree))
  2021                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2022             // Check that class is not abstract
  2023             if (cdef == null &&
  2024                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2025                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2026                           clazztype.tsym);
  2027             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2028                 // Check that no constructor arguments are given to
  2029                 // anonymous classes implementing an interface
  2030                 if (!argtypes.isEmpty())
  2031                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2033                 if (!typeargtypes.isEmpty())
  2034                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2036                 // Error recovery: pretend no arguments were supplied.
  2037                 argtypes = List.nil();
  2038                 typeargtypes = List.nil();
  2039             } else if (TreeInfo.isDiamond(tree)) {
  2040                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2041                             clazztype.tsym.type.getTypeArguments(),
  2042                             clazztype.tsym);
  2044                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2045                 diamondEnv.info.selectSuper = cdef != null;
  2046                 diamondEnv.info.pendingResolutionPhase = null;
  2048                 //if the type of the instance creation expression is a class type
  2049                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2050                 //of the resolved constructor will be a partially instantiated type
  2051                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2052                             diamondEnv,
  2053                             site,
  2054                             argtypes,
  2055                             typeargtypes);
  2056                 tree.constructor = constructor.baseSymbol();
  2058                 final TypeSymbol csym = clazztype.tsym;
  2059                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2060                     @Override
  2061                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2062                         enclosingContext.report(tree.clazz,
  2063                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2065                 });
  2066                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2067                 constructorType = checkId(tree, site,
  2068                         constructor,
  2069                         diamondEnv,
  2070                         diamondResult);
  2072                 tree.clazz.type = types.createErrorType(clazztype);
  2073                 if (!constructorType.isErroneous()) {
  2074                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2075                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2077                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2080             // Resolve the called constructor under the assumption
  2081             // that we are referring to a superclass instance of the
  2082             // current instance (JLS ???).
  2083             else {
  2084                 //the following code alters some of the fields in the current
  2085                 //AttrContext - hence, the current context must be dup'ed in
  2086                 //order to avoid downstream failures
  2087                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2088                 rsEnv.info.selectSuper = cdef != null;
  2089                 rsEnv.info.pendingResolutionPhase = null;
  2090                 tree.constructor = rs.resolveConstructor(
  2091                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2092                 if (cdef == null) { //do not check twice!
  2093                     tree.constructorType = checkId(tree,
  2094                             clazztype,
  2095                             tree.constructor,
  2096                             rsEnv,
  2097                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2098                     if (rsEnv.info.lastResolveVarargs())
  2099                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2101                 if (cdef == null &&
  2102                         !clazztype.isErroneous() &&
  2103                         clazztype.getTypeArguments().nonEmpty() &&
  2104                         findDiamonds) {
  2105                     findDiamond(localEnv, tree, clazztype);
  2109             if (cdef != null) {
  2110                 // We are seeing an anonymous class instance creation.
  2111                 // In this case, the class instance creation
  2112                 // expression
  2113                 //
  2114                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2115                 //
  2116                 // is represented internally as
  2117                 //
  2118                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2119                 //
  2120                 // This expression is then *transformed* as follows:
  2121                 //
  2122                 // (1) add a STATIC flag to the class definition
  2123                 //     if the current environment is static
  2124                 // (2) add an extends or implements clause
  2125                 // (3) add a constructor.
  2126                 //
  2127                 // For instance, if C is a class, and ET is the type of E,
  2128                 // the expression
  2129                 //
  2130                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2131                 //
  2132                 // is translated to (where X is a fresh name and typarams is the
  2133                 // parameter list of the super constructor):
  2134                 //
  2135                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2136                 //     X extends C<typargs2> {
  2137                 //       <typarams> X(ET e, args) {
  2138                 //         e.<typeargs1>super(args)
  2139                 //       }
  2140                 //       ...
  2141                 //     }
  2142                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2144                 if (clazztype.tsym.isInterface()) {
  2145                     cdef.implementing = List.of(clazz);
  2146                 } else {
  2147                     cdef.extending = clazz;
  2150                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2151                     isSerializable(clazztype)) {
  2152                     localEnv.info.isSerializable = true;
  2155                 attribStat(cdef, localEnv);
  2157                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2159                 // If an outer instance is given,
  2160                 // prefix it to the constructor arguments
  2161                 // and delete it from the new expression
  2162                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2163                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2164                     argtypes = argtypes.prepend(tree.encl.type);
  2165                     tree.encl = null;
  2168                 // Reassign clazztype and recompute constructor.
  2169                 clazztype = cdef.sym.type;
  2170                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2171                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2172                 Assert.check(sym.kind < AMBIGUOUS);
  2173                 tree.constructor = sym;
  2174                 tree.constructorType = checkId(tree,
  2175                     clazztype,
  2176                     tree.constructor,
  2177                     localEnv,
  2178                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2181             if (tree.constructor != null && tree.constructor.kind == MTH)
  2182                 owntype = clazztype;
  2184         result = check(tree, owntype, VAL, resultInfo);
  2185         chk.validate(tree.typeargs, localEnv);
  2187     //where
  2188         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2189             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2190             List<JCExpression> prevTypeargs = ta.arguments;
  2191             try {
  2192                 //create a 'fake' diamond AST node by removing type-argument trees
  2193                 ta.arguments = List.nil();
  2194                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2195                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2196                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2197                 Type polyPt = allowPoly ?
  2198                         syms.objectType :
  2199                         clazztype;
  2200                 if (!inferred.isErroneous() &&
  2201                     (allowPoly && pt() == Infer.anyPoly ?
  2202                         types.isSameType(inferred, clazztype) :
  2203                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
  2204                     String key = types.isSameType(clazztype, inferred) ?
  2205                         "diamond.redundant.args" :
  2206                         "diamond.redundant.args.1";
  2207                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2209             } finally {
  2210                 ta.arguments = prevTypeargs;
  2214             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2215                 if (allowLambda &&
  2216                         identifyLambdaCandidate &&
  2217                         clazztype.hasTag(CLASS) &&
  2218                         !pt().hasTag(NONE) &&
  2219                         types.isFunctionalInterface(clazztype.tsym)) {
  2220                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2221                     int count = 0;
  2222                     boolean found = false;
  2223                     for (Symbol sym : csym.members().getElements()) {
  2224                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2225                                 sym.isConstructor()) continue;
  2226                         count++;
  2227                         if (sym.kind != MTH ||
  2228                                 !sym.name.equals(descriptor.name)) continue;
  2229                         Type mtype = types.memberType(clazztype, sym);
  2230                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2231                             found = true;
  2234                     if (found && count == 1) {
  2235                         log.note(tree.def, "potential.lambda.found");
  2240     /** Make an attributed null check tree.
  2241      */
  2242     public JCExpression makeNullCheck(JCExpression arg) {
  2243         // optimization: X.this is never null; skip null check
  2244         Name name = TreeInfo.name(arg);
  2245         if (name == names._this || name == names._super) return arg;
  2247         JCTree.Tag optag = NULLCHK;
  2248         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2249         tree.operator = syms.nullcheck;
  2250         tree.type = arg.type;
  2251         return tree;
  2254     public void visitNewArray(JCNewArray tree) {
  2255         Type owntype = types.createErrorType(tree.type);
  2256         Env<AttrContext> localEnv = env.dup(tree);
  2257         Type elemtype;
  2258         if (tree.elemtype != null) {
  2259             elemtype = attribType(tree.elemtype, localEnv);
  2260             chk.validate(tree.elemtype, localEnv);
  2261             owntype = elemtype;
  2262             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2263                 attribExpr(l.head, localEnv, syms.intType);
  2264                 owntype = new ArrayType(owntype, syms.arrayClass);
  2266         } else {
  2267             // we are seeing an untyped aggregate { ... }
  2268             // this is allowed only if the prototype is an array
  2269             if (pt().hasTag(ARRAY)) {
  2270                 elemtype = types.elemtype(pt());
  2271             } else {
  2272                 if (!pt().hasTag(ERROR)) {
  2273                     log.error(tree.pos(), "illegal.initializer.for.type",
  2274                               pt());
  2276                 elemtype = types.createErrorType(pt());
  2279         if (tree.elems != null) {
  2280             attribExprs(tree.elems, localEnv, elemtype);
  2281             owntype = new ArrayType(elemtype, syms.arrayClass);
  2283         if (!types.isReifiable(elemtype))
  2284             log.error(tree.pos(), "generic.array.creation");
  2285         result = check(tree, owntype, VAL, resultInfo);
  2288     /*
  2289      * A lambda expression can only be attributed when a target-type is available.
  2290      * In addition, if the target-type is that of a functional interface whose
  2291      * descriptor contains inference variables in argument position the lambda expression
  2292      * is 'stuck' (see DeferredAttr).
  2293      */
  2294     @Override
  2295     public void visitLambda(final JCLambda that) {
  2296         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2297             if (pt().hasTag(NONE)) {
  2298                 //lambda only allowed in assignment or method invocation/cast context
  2299                 log.error(that.pos(), "unexpected.lambda");
  2301             result = that.type = types.createErrorType(pt());
  2302             return;
  2304         //create an environment for attribution of the lambda expression
  2305         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2306         boolean needsRecovery =
  2307                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2308         try {
  2309             Type currentTarget = pt();
  2310             if (needsRecovery && isSerializable(currentTarget)) {
  2311                 localEnv.info.isSerializable = true;
  2313             List<Type> explicitParamTypes = null;
  2314             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2315                 //attribute lambda parameters
  2316                 attribStats(that.params, localEnv);
  2317                 explicitParamTypes = TreeInfo.types(that.params);
  2320             Type lambdaType;
  2321             if (pt() != Type.recoveryType) {
  2322                 /* We need to adjust the target. If the target is an
  2323                  * intersection type, for example: SAM & I1 & I2 ...
  2324                  * the target will be updated to SAM
  2325                  */
  2326                 currentTarget = targetChecker.visit(currentTarget, that);
  2327                 if (explicitParamTypes != null) {
  2328                     currentTarget = infer.instantiateFunctionalInterface(that,
  2329                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2331                 lambdaType = types.findDescriptorType(currentTarget);
  2332             } else {
  2333                 currentTarget = Type.recoveryType;
  2334                 lambdaType = fallbackDescriptorType(that);
  2337             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2339             if (lambdaType.hasTag(FORALL)) {
  2340                 //lambda expression target desc cannot be a generic method
  2341                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2342                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2343                 result = that.type = types.createErrorType(pt());
  2344                 return;
  2347             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2348                 //add param type info in the AST
  2349                 List<Type> actuals = lambdaType.getParameterTypes();
  2350                 List<JCVariableDecl> params = that.params;
  2352                 boolean arityMismatch = false;
  2354                 while (params.nonEmpty()) {
  2355                     if (actuals.isEmpty()) {
  2356                         //not enough actuals to perform lambda parameter inference
  2357                         arityMismatch = true;
  2359                     //reset previously set info
  2360                     Type argType = arityMismatch ?
  2361                             syms.errType :
  2362                             actuals.head;
  2363                     params.head.vartype = make.at(params.head).Type(argType);
  2364                     params.head.sym = null;
  2365                     actuals = actuals.isEmpty() ?
  2366                             actuals :
  2367                             actuals.tail;
  2368                     params = params.tail;
  2371                 //attribute lambda parameters
  2372                 attribStats(that.params, localEnv);
  2374                 if (arityMismatch) {
  2375                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2376                         result = that.type = types.createErrorType(currentTarget);
  2377                         return;
  2381             //from this point on, no recovery is needed; if we are in assignment context
  2382             //we will be able to attribute the whole lambda body, regardless of errors;
  2383             //if we are in a 'check' method context, and the lambda is not compatible
  2384             //with the target-type, it will be recovered anyway in Attr.checkId
  2385             needsRecovery = false;
  2387             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2388                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2389                     new FunctionalReturnContext(resultInfo.checkContext);
  2391             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2392                 recoveryInfo :
  2393                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2394             localEnv.info.returnResult = bodyResultInfo;
  2396             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2397                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2398             } else {
  2399                 JCBlock body = (JCBlock)that.body;
  2400                 attribStats(body.stats, localEnv);
  2403             result = check(that, currentTarget, VAL, resultInfo);
  2405             boolean isSpeculativeRound =
  2406                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2408             preFlow(that);
  2409             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2411             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2413             if (!isSpeculativeRound) {
  2414                 //add thrown types as bounds to the thrown types free variables if needed:
  2415                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2416                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2417                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
  2419                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2422                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2424             result = check(that, currentTarget, VAL, resultInfo);
  2425         } catch (Types.FunctionDescriptorLookupError ex) {
  2426             JCDiagnostic cause = ex.getDiagnostic();
  2427             resultInfo.checkContext.report(that, cause);
  2428             result = that.type = types.createErrorType(pt());
  2429             return;
  2430         } finally {
  2431             localEnv.info.scope.leave();
  2432             if (needsRecovery) {
  2433                 attribTree(that, env, recoveryInfo);
  2437     //where
  2438         void preFlow(JCLambda tree) {
  2439             new PostAttrAnalyzer() {
  2440                 @Override
  2441                 public void scan(JCTree tree) {
  2442                     if (tree == null ||
  2443                             (tree.type != null &&
  2444                             tree.type == Type.stuckType)) {
  2445                         //don't touch stuck expressions!
  2446                         return;
  2448                     super.scan(tree);
  2450             }.scan(tree);
  2453         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2455             @Override
  2456             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2457                 return t.isCompound() ?
  2458                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2461             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2462                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2463                 Type target = null;
  2464                 for (Type bound : ict.getExplicitComponents()) {
  2465                     TypeSymbol boundSym = bound.tsym;
  2466                     if (types.isFunctionalInterface(boundSym) &&
  2467                             types.findDescriptorSymbol(boundSym) == desc) {
  2468                         target = bound;
  2469                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2470                         //bound must be an interface
  2471                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2474                 return target != null ?
  2475                         target :
  2476                         ict.getExplicitComponents().head; //error recovery
  2479             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2480                 ListBuffer<Type> targs = new ListBuffer<>();
  2481                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2482                 for (Type i : ict.interfaces_field) {
  2483                     if (i.isParameterized()) {
  2484                         targs.appendList(i.tsym.type.allparams());
  2486                     supertypes.append(i.tsym.type);
  2488                 IntersectionClassType notionalIntf =
  2489                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2490                 notionalIntf.allparams_field = targs.toList();
  2491                 notionalIntf.tsym.flags_field |= INTERFACE;
  2492                 return notionalIntf.tsym;
  2495             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2496                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2497                         diags.fragment(key, args)));
  2499         };
  2501         private Type fallbackDescriptorType(JCExpression tree) {
  2502             switch (tree.getTag()) {
  2503                 case LAMBDA:
  2504                     JCLambda lambda = (JCLambda)tree;
  2505                     List<Type> argtypes = List.nil();
  2506                     for (JCVariableDecl param : lambda.params) {
  2507                         argtypes = param.vartype != null ?
  2508                                 argtypes.append(param.vartype.type) :
  2509                                 argtypes.append(syms.errType);
  2511                     return new MethodType(argtypes, Type.recoveryType,
  2512                             List.of(syms.throwableType), syms.methodClass);
  2513                 case REFERENCE:
  2514                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2515                             List.of(syms.throwableType), syms.methodClass);
  2516                 default:
  2517                     Assert.error("Cannot get here!");
  2519             return null;
  2522         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2523                 final InferenceContext inferenceContext, final Type... ts) {
  2524             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2527         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2528                 final InferenceContext inferenceContext, final List<Type> ts) {
  2529             if (inferenceContext.free(ts)) {
  2530                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2531                     @Override
  2532                     public void typesInferred(InferenceContext inferenceContext) {
  2533                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2535                 });
  2536             } else {
  2537                 for (Type t : ts) {
  2538                     rs.checkAccessibleType(env, t);
  2543         /**
  2544          * Lambda/method reference have a special check context that ensures
  2545          * that i.e. a lambda return type is compatible with the expected
  2546          * type according to both the inherited context and the assignment
  2547          * context.
  2548          */
  2549         class FunctionalReturnContext extends Check.NestedCheckContext {
  2551             FunctionalReturnContext(CheckContext enclosingContext) {
  2552                 super(enclosingContext);
  2555             @Override
  2556             public boolean compatible(Type found, Type req, Warner warn) {
  2557                 //return type must be compatible in both current context and assignment context
  2558                 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
  2561             @Override
  2562             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2563                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2567         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2569             JCExpression expr;
  2571             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2572                 super(enclosingContext);
  2573                 this.expr = expr;
  2576             @Override
  2577             public boolean compatible(Type found, Type req, Warner warn) {
  2578                 //a void return is compatible with an expression statement lambda
  2579                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2580                         super.compatible(found, req, warn);
  2584         /**
  2585         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2586         * are compatible with the expected functional interface descriptor. This means that:
  2587         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2588         * types must be compatible with the return type of the expected descriptor.
  2589         */
  2590         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2591             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2593             //return values have already been checked - but if lambda has no return
  2594             //values, we must ensure that void/value compatibility is correct;
  2595             //this amounts at checking that, if a lambda body can complete normally,
  2596             //the descriptor's return type must be void
  2597             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2598                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2599                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2600                         diags.fragment("missing.ret.val", returnType)));
  2603             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
  2604             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2605                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2609         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
  2610          * static field and that lambda has type annotations, these annotations will
  2611          * also be stored at these fake clinit methods.
  2613          * LambdaToMethod also use fake clinit methods so they can be reused.
  2614          * Also as LTM is a phase subsequent to attribution, the methods from
  2615          * clinits can be safely removed by LTM to save memory.
  2616          */
  2617         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
  2619         public MethodSymbol removeClinit(ClassSymbol sym) {
  2620             return clinits.remove(sym);
  2623         /* This method returns an environment to be used to attribute a lambda
  2624          * expression.
  2626          * The owner of this environment is a method symbol. If the current owner
  2627          * is not a method, for example if the lambda is used to initialize
  2628          * a field, then if the field is:
  2630          * - an instance field, we use the first constructor.
  2631          * - a static field, we create a fake clinit method.
  2632          */
  2633         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2634             Env<AttrContext> lambdaEnv;
  2635             Symbol owner = env.info.scope.owner;
  2636             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2637                 //field initializer
  2638                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2639                 ClassSymbol enclClass = owner.enclClass();
  2640                 /* if the field isn't static, then we can get the first constructor
  2641                  * and use it as the owner of the environment. This is what
  2642                  * LTM code is doing to look for type annotations so we are fine.
  2643                  */
  2644                 if ((owner.flags() & STATIC) == 0) {
  2645                     for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
  2646                         lambdaEnv.info.scope.owner = s;
  2647                         break;
  2649                 } else {
  2650                     /* if the field is static then we need to create a fake clinit
  2651                      * method, this method can later be reused by LTM.
  2652                      */
  2653                     MethodSymbol clinit = clinits.get(enclClass);
  2654                     if (clinit == null) {
  2655                         Type clinitType = new MethodType(List.<Type>nil(),
  2656                                 syms.voidType, List.<Type>nil(), syms.methodClass);
  2657                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
  2658                                 names.clinit, clinitType, enclClass);
  2659                         clinit.params = List.<VarSymbol>nil();
  2660                         clinits.put(enclClass, clinit);
  2662                     lambdaEnv.info.scope.owner = clinit;
  2664             } else {
  2665                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2667             return lambdaEnv;
  2670     @Override
  2671     public void visitReference(final JCMemberReference that) {
  2672         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2673             if (pt().hasTag(NONE)) {
  2674                 //method reference only allowed in assignment or method invocation/cast context
  2675                 log.error(that.pos(), "unexpected.mref");
  2677             result = that.type = types.createErrorType(pt());
  2678             return;
  2680         final Env<AttrContext> localEnv = env.dup(that);
  2681         try {
  2682             //attribute member reference qualifier - if this is a constructor
  2683             //reference, the expected kind must be a type
  2684             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2686             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2687                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2688                 if (!exprType.isErroneous() &&
  2689                     exprType.isRaw() &&
  2690                     that.typeargs != null) {
  2691                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2692                         diags.fragment("mref.infer.and.explicit.params"));
  2693                     exprType = types.createErrorType(exprType);
  2697             if (exprType.isErroneous()) {
  2698                 //if the qualifier expression contains problems,
  2699                 //give up attribution of method reference
  2700                 result = that.type = exprType;
  2701                 return;
  2704             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2705                 //if the qualifier is a type, validate it; raw warning check is
  2706                 //omitted as we don't know at this stage as to whether this is a
  2707                 //raw selector (because of inference)
  2708                 chk.validate(that.expr, env, false);
  2711             //attrib type-arguments
  2712             List<Type> typeargtypes = List.nil();
  2713             if (that.typeargs != null) {
  2714                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2717             Type desc;
  2718             Type currentTarget = pt();
  2719             boolean isTargetSerializable =
  2720                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2721                     isSerializable(currentTarget);
  2722             if (currentTarget != Type.recoveryType) {
  2723                 currentTarget = targetChecker.visit(currentTarget, that);
  2724                 desc = types.findDescriptorType(currentTarget);
  2725             } else {
  2726                 currentTarget = Type.recoveryType;
  2727                 desc = fallbackDescriptorType(that);
  2730             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
  2731             List<Type> argtypes = desc.getParameterTypes();
  2732             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2734             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2735                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2738             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2739             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2740             try {
  2741                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
  2742                         that.name, argtypes, typeargtypes, referenceCheck,
  2743                         resultInfo.checkContext.inferenceContext(),
  2744                         resultInfo.checkContext.deferredAttrContext().mode);
  2745             } finally {
  2746                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2749             Symbol refSym = refResult.fst;
  2750             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2752             if (refSym.kind != MTH) {
  2753                 boolean targetError;
  2754                 switch (refSym.kind) {
  2755                     case ABSENT_MTH:
  2756                         targetError = false;
  2757                         break;
  2758                     case WRONG_MTH:
  2759                     case WRONG_MTHS:
  2760                     case AMBIGUOUS:
  2761                     case HIDDEN:
  2762                     case STATICERR:
  2763                     case MISSING_ENCL:
  2764                     case WRONG_STATICNESS:
  2765                         targetError = true;
  2766                         break;
  2767                     default:
  2768                         Assert.error("unexpected result kind " + refSym.kind);
  2769                         targetError = false;
  2772                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2773                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2775                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2776                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2778                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2779                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2781                 if (targetError && currentTarget == Type.recoveryType) {
  2782                     //a target error doesn't make sense during recovery stage
  2783                     //as we don't know what actual parameter types are
  2784                     result = that.type = currentTarget;
  2785                     return;
  2786                 } else {
  2787                     if (targetError) {
  2788                         resultInfo.checkContext.report(that, diag);
  2789                     } else {
  2790                         log.report(diag);
  2792                     result = that.type = types.createErrorType(currentTarget);
  2793                     return;
  2797             that.sym = refSym.baseSymbol();
  2798             that.kind = lookupHelper.referenceKind(that.sym);
  2799             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2801             if (desc.getReturnType() == Type.recoveryType) {
  2802                 // stop here
  2803                 result = that.type = currentTarget;
  2804                 return;
  2807             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2809                 if (that.getMode() == ReferenceMode.INVOKE &&
  2810                         TreeInfo.isStaticSelector(that.expr, names) &&
  2811                         that.kind.isUnbound() &&
  2812                         !desc.getParameterTypes().head.isParameterized()) {
  2813                     chk.checkRaw(that.expr, localEnv);
  2816                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2817                         exprType.getTypeArguments().nonEmpty()) {
  2818                     //static ref with class type-args
  2819                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2820                             diags.fragment("static.mref.with.targs"));
  2821                     result = that.type = types.createErrorType(currentTarget);
  2822                     return;
  2825                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2826                         !that.kind.isUnbound()) {
  2827                     //no static bound mrefs
  2828                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2829                             diags.fragment("static.bound.mref"));
  2830                     result = that.type = types.createErrorType(currentTarget);
  2831                     return;
  2834                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2835                     // Check that super-qualified symbols are not abstract (JLS)
  2836                     rs.checkNonAbstract(that.pos(), that.sym);
  2839                 if (isTargetSerializable) {
  2840                     chk.checkElemAccessFromSerializableLambda(that);
  2844             ResultInfo checkInfo =
  2845                     resultInfo.dup(newMethodTemplate(
  2846                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2847                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
  2848                         new FunctionalReturnContext(resultInfo.checkContext));
  2850             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2852             if (that.kind.isUnbound() &&
  2853                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2854                 //re-generate inference constraints for unbound receiver
  2855                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
  2856                     //cannot happen as this has already been checked - we just need
  2857                     //to regenerate the inference constraints, as that has been lost
  2858                     //as a result of the call to inferenceContext.save()
  2859                     Assert.error("Can't get here");
  2863             if (!refType.isErroneous()) {
  2864                 refType = types.createMethodTypeWithReturn(refType,
  2865                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2868             //go ahead with standard method reference compatibility check - note that param check
  2869             //is a no-op (as this has been taken care during method applicability)
  2870             boolean isSpeculativeRound =
  2871                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2872             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2873             if (!isSpeculativeRound) {
  2874                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
  2876             result = check(that, currentTarget, VAL, resultInfo);
  2877         } catch (Types.FunctionDescriptorLookupError ex) {
  2878             JCDiagnostic cause = ex.getDiagnostic();
  2879             resultInfo.checkContext.report(that, cause);
  2880             result = that.type = types.createErrorType(pt());
  2881             return;
  2884     //where
  2885         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2886             //if this is a constructor reference, the expected kind must be a type
  2887             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2891     @SuppressWarnings("fallthrough")
  2892     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2893         Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2895         Type resType;
  2896         switch (tree.getMode()) {
  2897             case NEW:
  2898                 if (!tree.expr.type.isRaw()) {
  2899                     resType = tree.expr.type;
  2900                     break;
  2902             default:
  2903                 resType = refType.getReturnType();
  2906         Type incompatibleReturnType = resType;
  2908         if (returnType.hasTag(VOID)) {
  2909             incompatibleReturnType = null;
  2912         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2913             if (resType.isErroneous() ||
  2914                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2915                 incompatibleReturnType = null;
  2919         if (incompatibleReturnType != null) {
  2920             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2921                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2924         if (!speculativeAttr) {
  2925             List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
  2926             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2927                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2932     /**
  2933      * Set functional type info on the underlying AST. Note: as the target descriptor
  2934      * might contain inference variables, we might need to register an hook in the
  2935      * current inference context.
  2936      */
  2937     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  2938             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  2939         if (checkContext.inferenceContext().free(descriptorType)) {
  2940             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2941                 public void typesInferred(InferenceContext inferenceContext) {
  2942                     setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  2943                             inferenceContext.asInstType(primaryTarget), checkContext);
  2945             });
  2946         } else {
  2947             ListBuffer<Type> targets = new ListBuffer<>();
  2948             if (pt.hasTag(CLASS)) {
  2949                 if (pt.isCompound()) {
  2950                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  2951                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2952                         if (t != primaryTarget) {
  2953                             targets.append(types.removeWildcards(t));
  2956                 } else {
  2957                     targets.append(types.removeWildcards(primaryTarget));
  2960             fExpr.targets = targets.toList();
  2961             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2962                     pt != Type.recoveryType) {
  2963                 //check that functional interface class is well-formed
  2964                 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
  2965                         names.empty, List.of(fExpr.targets.head), ABSTRACT);
  2966                 if (csym != null) {
  2967                     chk.checkImplementations(env.tree, csym, csym);
  2973     public void visitParens(JCParens tree) {
  2974         Type owntype = attribTree(tree.expr, env, resultInfo);
  2975         result = check(tree, owntype, pkind(), resultInfo);
  2976         Symbol sym = TreeInfo.symbol(tree);
  2977         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2978             log.error(tree.pos(), "illegal.start.of.type");
  2981     public void visitAssign(JCAssign tree) {
  2982         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2983         Type capturedType = capture(owntype);
  2984         attribExpr(tree.rhs, env, owntype);
  2985         result = check(tree, capturedType, VAL, resultInfo);
  2988     public void visitAssignop(JCAssignOp tree) {
  2989         // Attribute arguments.
  2990         Type owntype = attribTree(tree.lhs, env, varInfo);
  2991         Type operand = attribExpr(tree.rhs, env);
  2992         // Find operator.
  2993         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2994             tree.pos(), tree.getTag().noAssignOp(), env,
  2995             owntype, operand);
  2997         if (operator.kind == MTH &&
  2998                 !owntype.isErroneous() &&
  2999                 !operand.isErroneous()) {
  3000             chk.checkOperator(tree.pos(),
  3001                               (OperatorSymbol)operator,
  3002                               tree.getTag().noAssignOp(),
  3003                               owntype,
  3004                               operand);
  3005             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  3006             chk.checkCastable(tree.rhs.pos(),
  3007                               operator.type.getReturnType(),
  3008                               owntype);
  3010         result = check(tree, owntype, VAL, resultInfo);
  3013     public void visitUnary(JCUnary tree) {
  3014         // Attribute arguments.
  3015         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  3016             ? attribTree(tree.arg, env, varInfo)
  3017             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  3019         // Find operator.
  3020         Symbol operator = tree.operator =
  3021             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  3023         Type owntype = types.createErrorType(tree.type);
  3024         if (operator.kind == MTH &&
  3025                 !argtype.isErroneous()) {
  3026             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3027                 ? tree.arg.type
  3028                 : operator.type.getReturnType();
  3029             int opc = ((OperatorSymbol)operator).opcode;
  3031             // If the argument is constant, fold it.
  3032             if (argtype.constValue() != null) {
  3033                 Type ctype = cfolder.fold1(opc, argtype);
  3034                 if (ctype != null) {
  3035                     owntype = cfolder.coerce(ctype, owntype);
  3039         result = check(tree, owntype, VAL, resultInfo);
  3042     public void visitBinary(JCBinary tree) {
  3043         // Attribute arguments.
  3044         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3045         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3047         // Find operator.
  3048         Symbol operator = tree.operator =
  3049             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3051         Type owntype = types.createErrorType(tree.type);
  3052         if (operator.kind == MTH &&
  3053                 !left.isErroneous() &&
  3054                 !right.isErroneous()) {
  3055             owntype = operator.type.getReturnType();
  3056             // This will figure out when unboxing can happen and
  3057             // choose the right comparison operator.
  3058             int opc = chk.checkOperator(tree.lhs.pos(),
  3059                                         (OperatorSymbol)operator,
  3060                                         tree.getTag(),
  3061                                         left,
  3062                                         right);
  3064             // If both arguments are constants, fold them.
  3065             if (left.constValue() != null && right.constValue() != null) {
  3066                 Type ctype = cfolder.fold2(opc, left, right);
  3067                 if (ctype != null) {
  3068                     owntype = cfolder.coerce(ctype, owntype);
  3072             // Check that argument types of a reference ==, != are
  3073             // castable to each other, (JLS 15.21).  Note: unboxing
  3074             // comparisons will not have an acmp* opc at this point.
  3075             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3076                 if (!types.isEqualityComparable(left, right,
  3077                                                 new Warner(tree.pos()))) {
  3078                     log.error(tree.pos(), "incomparable.types", left, right);
  3082             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3084         result = check(tree, owntype, VAL, resultInfo);
  3087     public void visitTypeCast(final JCTypeCast tree) {
  3088         Type clazztype = attribType(tree.clazz, env);
  3089         chk.validate(tree.clazz, env, false);
  3090         //a fresh environment is required for 292 inference to work properly ---
  3091         //see Infer.instantiatePolymorphicSignatureInstance()
  3092         Env<AttrContext> localEnv = env.dup(tree);
  3093         //should we propagate the target type?
  3094         final ResultInfo castInfo;
  3095         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3096         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3097         if (isPoly) {
  3098             //expression is a poly - we need to propagate target type info
  3099             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3100                 @Override
  3101                 public boolean compatible(Type found, Type req, Warner warn) {
  3102                     return types.isCastable(found, req, warn);
  3104             });
  3105         } else {
  3106             //standalone cast - target-type info is not propagated
  3107             castInfo = unknownExprInfo;
  3109         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3110         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3111         if (exprtype.constValue() != null)
  3112             owntype = cfolder.coerce(exprtype, owntype);
  3113         result = check(tree, capture(owntype), VAL, resultInfo);
  3114         if (!isPoly)
  3115             chk.checkRedundantCast(localEnv, tree);
  3118     public void visitTypeTest(JCInstanceOf tree) {
  3119         Type exprtype = chk.checkNullOrRefType(
  3120             tree.expr.pos(), attribExpr(tree.expr, env));
  3121         Type clazztype = attribType(tree.clazz, env);
  3122         if (!clazztype.hasTag(TYPEVAR)) {
  3123             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3125         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3126             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3127             clazztype = types.createErrorType(clazztype);
  3129         chk.validate(tree.clazz, env, false);
  3130         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3131         result = check(tree, syms.booleanType, VAL, resultInfo);
  3134     public void visitIndexed(JCArrayAccess tree) {
  3135         Type owntype = types.createErrorType(tree.type);
  3136         Type atype = attribExpr(tree.indexed, env);
  3137         attribExpr(tree.index, env, syms.intType);
  3138         if (types.isArray(atype))
  3139             owntype = types.elemtype(atype);
  3140         else if (!atype.hasTag(ERROR))
  3141             log.error(tree.pos(), "array.req.but.found", atype);
  3142         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3143         result = check(tree, owntype, VAR, resultInfo);
  3146     public void visitIdent(JCIdent tree) {
  3147         Symbol sym;
  3149         // Find symbol
  3150         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3151             // If we are looking for a method, the prototype `pt' will be a
  3152             // method type with the type of the call's arguments as parameters.
  3153             env.info.pendingResolutionPhase = null;
  3154             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3155         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3156             sym = tree.sym;
  3157         } else {
  3158             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3160         tree.sym = sym;
  3162         // (1) Also find the environment current for the class where
  3163         //     sym is defined (`symEnv').
  3164         // Only for pre-tiger versions (1.4 and earlier):
  3165         // (2) Also determine whether we access symbol out of an anonymous
  3166         //     class in a this or super call.  This is illegal for instance
  3167         //     members since such classes don't carry a this$n link.
  3168         //     (`noOuterThisPath').
  3169         Env<AttrContext> symEnv = env;
  3170         boolean noOuterThisPath = false;
  3171         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3172             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3173             sym.owner.kind == TYP &&
  3174             tree.name != names._this && tree.name != names._super) {
  3176             // Find environment in which identifier is defined.
  3177             while (symEnv.outer != null &&
  3178                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3179                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3180                     noOuterThisPath = !allowAnonOuterThis;
  3181                 symEnv = symEnv.outer;
  3185         // If symbol is a variable, ...
  3186         if (sym.kind == VAR) {
  3187             VarSymbol v = (VarSymbol)sym;
  3189             // ..., evaluate its initializer, if it has one, and check for
  3190             // illegal forward reference.
  3191             checkInit(tree, env, v, false);
  3193             // If we are expecting a variable (as opposed to a value), check
  3194             // that the variable is assignable in the current environment.
  3195             if (pkind() == VAR)
  3196                 checkAssignable(tree.pos(), v, null, env);
  3199         // In a constructor body,
  3200         // if symbol is a field or instance method, check that it is
  3201         // not accessed before the supertype constructor is called.
  3202         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3203             (sym.kind & (VAR | MTH)) != 0 &&
  3204             sym.owner.kind == TYP &&
  3205             (sym.flags() & STATIC) == 0) {
  3206             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3208         Env<AttrContext> env1 = env;
  3209         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3210             // If the found symbol is inaccessible, then it is
  3211             // accessed through an enclosing instance.  Locate this
  3212             // enclosing instance:
  3213             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3214                 env1 = env1.outer;
  3217         if (env.info.isSerializable) {
  3218             chk.checkElemAccessFromSerializableLambda(tree);
  3221         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3224     public void visitSelect(JCFieldAccess tree) {
  3225         // Determine the expected kind of the qualifier expression.
  3226         int skind = 0;
  3227         if (tree.name == names._this || tree.name == names._super ||
  3228             tree.name == names._class)
  3230             skind = TYP;
  3231         } else {
  3232             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3233             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3234             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3237         // Attribute the qualifier expression, and determine its symbol (if any).
  3238         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3239         if ((pkind() & (PCK | TYP)) == 0)
  3240             site = capture(site); // Capture field access
  3242         // don't allow T.class T[].class, etc
  3243         if (skind == TYP) {
  3244             Type elt = site;
  3245             while (elt.hasTag(ARRAY))
  3246                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3247             if (elt.hasTag(TYPEVAR)) {
  3248                 log.error(tree.pos(), "type.var.cant.be.deref");
  3249                 result = types.createErrorType(tree.type);
  3250                 return;
  3254         // If qualifier symbol is a type or `super', assert `selectSuper'
  3255         // for the selection. This is relevant for determining whether
  3256         // protected symbols are accessible.
  3257         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3258         boolean selectSuperPrev = env.info.selectSuper;
  3259         env.info.selectSuper =
  3260             sitesym != null &&
  3261             sitesym.name == names._super;
  3263         // Determine the symbol represented by the selection.
  3264         env.info.pendingResolutionPhase = null;
  3265         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3266         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3267             site = capture(site);
  3268             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3270         boolean varArgs = env.info.lastResolveVarargs();
  3271         tree.sym = sym;
  3273         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3274             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3275             site = capture(site);
  3278         // If that symbol is a variable, ...
  3279         if (sym.kind == VAR) {
  3280             VarSymbol v = (VarSymbol)sym;
  3282             // ..., evaluate its initializer, if it has one, and check for
  3283             // illegal forward reference.
  3284             checkInit(tree, env, v, true);
  3286             // If we are expecting a variable (as opposed to a value), check
  3287             // that the variable is assignable in the current environment.
  3288             if (pkind() == VAR)
  3289                 checkAssignable(tree.pos(), v, tree.selected, env);
  3292         if (sitesym != null &&
  3293                 sitesym.kind == VAR &&
  3294                 ((VarSymbol)sitesym).isResourceVariable() &&
  3295                 sym.kind == MTH &&
  3296                 sym.name.equals(names.close) &&
  3297                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3298                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3299             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3302         // Disallow selecting a type from an expression
  3303         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3304             tree.type = check(tree.selected, pt(),
  3305                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3308         if (isType(sitesym)) {
  3309             if (sym.name == names._this) {
  3310                 // If `C' is the currently compiled class, check that
  3311                 // C.this' does not appear in a call to a super(...)
  3312                 if (env.info.isSelfCall &&
  3313                     site.tsym == env.enclClass.sym) {
  3314                     chk.earlyRefError(tree.pos(), sym);
  3316             } else {
  3317                 // Check if type-qualified fields or methods are static (JLS)
  3318                 if ((sym.flags() & STATIC) == 0 &&
  3319                     !env.next.tree.hasTag(REFERENCE) &&
  3320                     sym.name != names._super &&
  3321                     (sym.kind == VAR || sym.kind == MTH)) {
  3322                     rs.accessBase(rs.new StaticError(sym),
  3323                               tree.pos(), site, sym.name, true);
  3326         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3327             // If the qualified item is not a type and the selected item is static, report
  3328             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3329             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3332         // If we are selecting an instance member via a `super', ...
  3333         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3335             // Check that super-qualified symbols are not abstract (JLS)
  3336             rs.checkNonAbstract(tree.pos(), sym);
  3338             if (site.isRaw()) {
  3339                 // Determine argument types for site.
  3340                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3341                 if (site1 != null) site = site1;
  3345         if (env.info.isSerializable) {
  3346             chk.checkElemAccessFromSerializableLambda(tree);
  3349         env.info.selectSuper = selectSuperPrev;
  3350         result = checkId(tree, site, sym, env, resultInfo);
  3352     //where
  3353         /** Determine symbol referenced by a Select expression,
  3355          *  @param tree   The select tree.
  3356          *  @param site   The type of the selected expression,
  3357          *  @param env    The current environment.
  3358          *  @param resultInfo The current result.
  3359          */
  3360         private Symbol selectSym(JCFieldAccess tree,
  3361                                  Symbol location,
  3362                                  Type site,
  3363                                  Env<AttrContext> env,
  3364                                  ResultInfo resultInfo) {
  3365             DiagnosticPosition pos = tree.pos();
  3366             Name name = tree.name;
  3367             switch (site.getTag()) {
  3368             case PACKAGE:
  3369                 return rs.accessBase(
  3370                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3371                     pos, location, site, name, true);
  3372             case ARRAY:
  3373             case CLASS:
  3374                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3375                     return rs.resolveQualifiedMethod(
  3376                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3377                 } else if (name == names._this || name == names._super) {
  3378                     return rs.resolveSelf(pos, env, site.tsym, name);
  3379                 } else if (name == names._class) {
  3380                     // In this case, we have already made sure in
  3381                     // visitSelect that qualifier expression is a type.
  3382                     Type t = syms.classType;
  3383                     List<Type> typeargs = allowGenerics
  3384                         ? List.of(types.erasure(site))
  3385                         : List.<Type>nil();
  3386                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3387                     return new VarSymbol(
  3388                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3389                 } else {
  3390                     // We are seeing a plain identifier as selector.
  3391                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3392                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3393                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3394                     return sym;
  3396             case WILDCARD:
  3397                 throw new AssertionError(tree);
  3398             case TYPEVAR:
  3399                 // Normally, site.getUpperBound() shouldn't be null.
  3400                 // It should only happen during memberEnter/attribBase
  3401                 // when determining the super type which *must* beac
  3402                 // done before attributing the type variables.  In
  3403                 // other words, we are seeing this illegal program:
  3404                 // class B<T> extends A<T.foo> {}
  3405                 Symbol sym = (site.getUpperBound() != null)
  3406                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3407                     : null;
  3408                 if (sym == null) {
  3409                     log.error(pos, "type.var.cant.be.deref");
  3410                     return syms.errSymbol;
  3411                 } else {
  3412                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3413                         rs.new AccessError(env, site, sym) :
  3414                                 sym;
  3415                     rs.accessBase(sym2, pos, location, site, name, true);
  3416                     return sym;
  3418             case ERROR:
  3419                 // preserve identifier names through errors
  3420                 return types.createErrorType(name, site.tsym, site).tsym;
  3421             default:
  3422                 // The qualifier expression is of a primitive type -- only
  3423                 // .class is allowed for these.
  3424                 if (name == names._class) {
  3425                     // In this case, we have already made sure in Select that
  3426                     // qualifier expression is a type.
  3427                     Type t = syms.classType;
  3428                     Type arg = types.boxedClass(site).type;
  3429                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3430                     return new VarSymbol(
  3431                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3432                 } else {
  3433                     log.error(pos, "cant.deref", site);
  3434                     return syms.errSymbol;
  3439         /** Determine type of identifier or select expression and check that
  3440          *  (1) the referenced symbol is not deprecated
  3441          *  (2) the symbol's type is safe (@see checkSafe)
  3442          *  (3) if symbol is a variable, check that its type and kind are
  3443          *      compatible with the prototype and protokind.
  3444          *  (4) if symbol is an instance field of a raw type,
  3445          *      which is being assigned to, issue an unchecked warning if its
  3446          *      type changes under erasure.
  3447          *  (5) if symbol is an instance method of a raw type, issue an
  3448          *      unchecked warning if its argument types change under erasure.
  3449          *  If checks succeed:
  3450          *    If symbol is a constant, return its constant type
  3451          *    else if symbol is a method, return its result type
  3452          *    otherwise return its type.
  3453          *  Otherwise return errType.
  3455          *  @param tree       The syntax tree representing the identifier
  3456          *  @param site       If this is a select, the type of the selected
  3457          *                    expression, otherwise the type of the current class.
  3458          *  @param sym        The symbol representing the identifier.
  3459          *  @param env        The current environment.
  3460          *  @param resultInfo    The expected result
  3461          */
  3462         Type checkId(JCTree tree,
  3463                      Type site,
  3464                      Symbol sym,
  3465                      Env<AttrContext> env,
  3466                      ResultInfo resultInfo) {
  3467             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3468                     checkMethodId(tree, site, sym, env, resultInfo) :
  3469                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3472         Type checkMethodId(JCTree tree,
  3473                      Type site,
  3474                      Symbol sym,
  3475                      Env<AttrContext> env,
  3476                      ResultInfo resultInfo) {
  3477             boolean isPolymorhicSignature =
  3478                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3479             return isPolymorhicSignature ?
  3480                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3481                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3484         Type checkSigPolyMethodId(JCTree tree,
  3485                      Type site,
  3486                      Symbol sym,
  3487                      Env<AttrContext> env,
  3488                      ResultInfo resultInfo) {
  3489             //recover original symbol for signature polymorphic methods
  3490             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3491             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3492             return sym.type;
  3495         Type checkMethodIdInternal(JCTree tree,
  3496                      Type site,
  3497                      Symbol sym,
  3498                      Env<AttrContext> env,
  3499                      ResultInfo resultInfo) {
  3500             if ((resultInfo.pkind & POLY) != 0) {
  3501                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3502                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3503                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3504                 return owntype;
  3505             } else {
  3506                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3510         Type checkIdInternal(JCTree tree,
  3511                      Type site,
  3512                      Symbol sym,
  3513                      Type pt,
  3514                      Env<AttrContext> env,
  3515                      ResultInfo resultInfo) {
  3516             if (pt.isErroneous()) {
  3517                 return types.createErrorType(site);
  3519             Type owntype; // The computed type of this identifier occurrence.
  3520             switch (sym.kind) {
  3521             case TYP:
  3522                 // For types, the computed type equals the symbol's type,
  3523                 // except for two situations:
  3524                 owntype = sym.type;
  3525                 if (owntype.hasTag(CLASS)) {
  3526                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3527                     Type ownOuter = owntype.getEnclosingType();
  3529                     // (a) If the symbol's type is parameterized, erase it
  3530                     // because no type parameters were given.
  3531                     // We recover generic outer type later in visitTypeApply.
  3532                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3533                         owntype = types.erasure(owntype);
  3536                     // (b) If the symbol's type is an inner class, then
  3537                     // we have to interpret its outer type as a superclass
  3538                     // of the site type. Example:
  3539                     //
  3540                     // class Tree<A> { class Visitor { ... } }
  3541                     // class PointTree extends Tree<Point> { ... }
  3542                     // ...PointTree.Visitor...
  3543                     //
  3544                     // Then the type of the last expression above is
  3545                     // Tree<Point>.Visitor.
  3546                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3547                         Type normOuter = site;
  3548                         if (normOuter.hasTag(CLASS)) {
  3549                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3551                         if (normOuter == null) // perhaps from an import
  3552                             normOuter = types.erasure(ownOuter);
  3553                         if (normOuter != ownOuter)
  3554                             owntype = new ClassType(
  3555                                 normOuter, List.<Type>nil(), owntype.tsym);
  3558                 break;
  3559             case VAR:
  3560                 VarSymbol v = (VarSymbol)sym;
  3561                 // Test (4): if symbol is an instance field of a raw type,
  3562                 // which is being assigned to, issue an unchecked warning if
  3563                 // its type changes under erasure.
  3564                 if (allowGenerics &&
  3565                     resultInfo.pkind == VAR &&
  3566                     v.owner.kind == TYP &&
  3567                     (v.flags() & STATIC) == 0 &&
  3568                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3569                     Type s = types.asOuterSuper(site, v.owner);
  3570                     if (s != null &&
  3571                         s.isRaw() &&
  3572                         !types.isSameType(v.type, v.erasure(types))) {
  3573                         chk.warnUnchecked(tree.pos(),
  3574                                           "unchecked.assign.to.var",
  3575                                           v, s);
  3578                 // The computed type of a variable is the type of the
  3579                 // variable symbol, taken as a member of the site type.
  3580                 owntype = (sym.owner.kind == TYP &&
  3581                            sym.name != names._this && sym.name != names._super)
  3582                     ? types.memberType(site, sym)
  3583                     : sym.type;
  3585                 // If the variable is a constant, record constant value in
  3586                 // computed type.
  3587                 if (v.getConstValue() != null && isStaticReference(tree))
  3588                     owntype = owntype.constType(v.getConstValue());
  3590                 if (resultInfo.pkind == VAL) {
  3591                     owntype = capture(owntype); // capture "names as expressions"
  3593                 break;
  3594             case MTH: {
  3595                 owntype = checkMethod(site, sym,
  3596                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3597                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3598                         resultInfo.pt.getTypeArguments());
  3599                 break;
  3601             case PCK: case ERR:
  3602                 owntype = sym.type;
  3603                 break;
  3604             default:
  3605                 throw new AssertionError("unexpected kind: " + sym.kind +
  3606                                          " in tree " + tree);
  3609             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3610             // (for constructors, the error was given when the constructor was
  3611             // resolved)
  3613             if (sym.name != names.init) {
  3614                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3615                 chk.checkSunAPI(tree.pos(), sym);
  3616                 chk.checkProfile(tree.pos(), sym);
  3619             // Test (3): if symbol is a variable, check that its type and
  3620             // kind are compatible with the prototype and protokind.
  3621             return check(tree, owntype, sym.kind, resultInfo);
  3624         /** Check that variable is initialized and evaluate the variable's
  3625          *  initializer, if not yet done. Also check that variable is not
  3626          *  referenced before it is defined.
  3627          *  @param tree    The tree making up the variable reference.
  3628          *  @param env     The current environment.
  3629          *  @param v       The variable's symbol.
  3630          */
  3631         private void checkInit(JCTree tree,
  3632                                Env<AttrContext> env,
  3633                                VarSymbol v,
  3634                                boolean onlyWarning) {
  3635 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3636 //                             tree.pos + " " + v.pos + " " +
  3637 //                             Resolve.isStatic(env));//DEBUG
  3639             // A forward reference is diagnosed if the declaration position
  3640             // of the variable is greater than the current tree position
  3641             // and the tree and variable definition occur in the same class
  3642             // definition.  Note that writes don't count as references.
  3643             // This check applies only to class and instance
  3644             // variables.  Local variables follow different scope rules,
  3645             // and are subject to definite assignment checking.
  3646             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3647                 v.owner.kind == TYP &&
  3648                 canOwnInitializer(owner(env)) &&
  3649                 v.owner == env.info.scope.owner.enclClass() &&
  3650                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3651                 (!env.tree.hasTag(ASSIGN) ||
  3652                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3653                 String suffix = (env.info.enclVar == v) ?
  3654                                 "self.ref" : "forward.ref";
  3655                 if (!onlyWarning || isStaticEnumField(v)) {
  3656                     log.error(tree.pos(), "illegal." + suffix);
  3657                 } else if (useBeforeDeclarationWarning) {
  3658                     log.warning(tree.pos(), suffix, v);
  3662             v.getConstValue(); // ensure initializer is evaluated
  3664             checkEnumInitializer(tree, env, v);
  3667         /**
  3668          * Check for illegal references to static members of enum.  In
  3669          * an enum type, constructors and initializers may not
  3670          * reference its static members unless they are constant.
  3672          * @param tree    The tree making up the variable reference.
  3673          * @param env     The current environment.
  3674          * @param v       The variable's symbol.
  3675          * @jls  section 8.9 Enums
  3676          */
  3677         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3678             // JLS:
  3679             //
  3680             // "It is a compile-time error to reference a static field
  3681             // of an enum type that is not a compile-time constant
  3682             // (15.28) from constructors, instance initializer blocks,
  3683             // or instance variable initializer expressions of that
  3684             // type. It is a compile-time error for the constructors,
  3685             // instance initializer blocks, or instance variable
  3686             // initializer expressions of an enum constant e to refer
  3687             // to itself or to an enum constant of the same type that
  3688             // is declared to the right of e."
  3689             if (isStaticEnumField(v)) {
  3690                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3692                 if (enclClass == null || enclClass.owner == null)
  3693                     return;
  3695                 // See if the enclosing class is the enum (or a
  3696                 // subclass thereof) declaring v.  If not, this
  3697                 // reference is OK.
  3698                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3699                     return;
  3701                 // If the reference isn't from an initializer, then
  3702                 // the reference is OK.
  3703                 if (!Resolve.isInitializer(env))
  3704                     return;
  3706                 log.error(tree.pos(), "illegal.enum.static.ref");
  3710         /** Is the given symbol a static, non-constant field of an Enum?
  3711          *  Note: enum literals should not be regarded as such
  3712          */
  3713         private boolean isStaticEnumField(VarSymbol v) {
  3714             return Flags.isEnum(v.owner) &&
  3715                    Flags.isStatic(v) &&
  3716                    !Flags.isConstant(v) &&
  3717                    v.name != names._class;
  3720         /** Can the given symbol be the owner of code which forms part
  3721          *  if class initialization? This is the case if the symbol is
  3722          *  a type or field, or if the symbol is the synthetic method.
  3723          *  owning a block.
  3724          */
  3725         private boolean canOwnInitializer(Symbol sym) {
  3726             return
  3727                 (sym.kind & (VAR | TYP)) != 0 ||
  3728                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3731     Warner noteWarner = new Warner();
  3733     /**
  3734      * Check that method arguments conform to its instantiation.
  3735      **/
  3736     public Type checkMethod(Type site,
  3737                             final Symbol sym,
  3738                             ResultInfo resultInfo,
  3739                             Env<AttrContext> env,
  3740                             final List<JCExpression> argtrees,
  3741                             List<Type> argtypes,
  3742                             List<Type> typeargtypes) {
  3743         // Test (5): if symbol is an instance method of a raw type, issue
  3744         // an unchecked warning if its argument types change under erasure.
  3745         if (allowGenerics &&
  3746             (sym.flags() & STATIC) == 0 &&
  3747             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3748             Type s = types.asOuterSuper(site, sym.owner);
  3749             if (s != null && s.isRaw() &&
  3750                 !types.isSameTypes(sym.type.getParameterTypes(),
  3751                                    sym.erasure(types).getParameterTypes())) {
  3752                 chk.warnUnchecked(env.tree.pos(),
  3753                                   "unchecked.call.mbr.of.raw.type",
  3754                                   sym, s);
  3758         if (env.info.defaultSuperCallSite != null) {
  3759             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3760                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3761                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3762                 List<MethodSymbol> icand_sup =
  3763                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3764                 if (icand_sup.nonEmpty() &&
  3765                         icand_sup.head != sym &&
  3766                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3767                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3768                         diags.fragment("overridden.default", sym, sup));
  3769                     break;
  3772             env.info.defaultSuperCallSite = null;
  3775         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3776             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3777             if (app.meth.hasTag(SELECT) &&
  3778                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3779                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3783         // Compute the identifier's instantiated type.
  3784         // For methods, we need to compute the instance type by
  3785         // Resolve.instantiate from the symbol's type as well as
  3786         // any type arguments and value arguments.
  3787         noteWarner.clear();
  3788         try {
  3789             Type owntype = rs.checkMethod(
  3790                     env,
  3791                     site,
  3792                     sym,
  3793                     resultInfo,
  3794                     argtypes,
  3795                     typeargtypes,
  3796                     noteWarner);
  3798             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3799                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3801             argtypes = Type.map(argtypes, checkDeferredMap);
  3803             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3804                 chk.warnUnchecked(env.tree.pos(),
  3805                         "unchecked.meth.invocation.applied",
  3806                         kindName(sym),
  3807                         sym.name,
  3808                         rs.methodArguments(sym.type.getParameterTypes()),
  3809                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3810                         kindName(sym.location()),
  3811                         sym.location());
  3812                owntype = new MethodType(owntype.getParameterTypes(),
  3813                        types.erasure(owntype.getReturnType()),
  3814                        types.erasure(owntype.getThrownTypes()),
  3815                        syms.methodClass);
  3818             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3819                     resultInfo.checkContext.inferenceContext());
  3820         } catch (Infer.InferenceException ex) {
  3821             //invalid target type - propagate exception outwards or report error
  3822             //depending on the current check context
  3823             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3824             return types.createErrorType(site);
  3825         } catch (Resolve.InapplicableMethodException ex) {
  3826             final JCDiagnostic diag = ex.getDiagnostic();
  3827             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  3828                 @Override
  3829                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3830                     return new Pair<Symbol, JCDiagnostic>(sym, diag);
  3832             };
  3833             List<Type> argtypes2 = Type.map(argtypes,
  3834                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3835             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3836                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  3837             log.report(errDiag);
  3838             return types.createErrorType(site);
  3842     public void visitLiteral(JCLiteral tree) {
  3843         result = check(
  3844             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3846     //where
  3847     /** Return the type of a literal with given type tag.
  3848      */
  3849     Type litType(TypeTag tag) {
  3850         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3853     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3854         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3857     public void visitTypeArray(JCArrayTypeTree tree) {
  3858         Type etype = attribType(tree.elemtype, env);
  3859         Type type = new ArrayType(etype, syms.arrayClass);
  3860         result = check(tree, type, TYP, resultInfo);
  3863     /** Visitor method for parameterized types.
  3864      *  Bound checking is left until later, since types are attributed
  3865      *  before supertype structure is completely known
  3866      */
  3867     public void visitTypeApply(JCTypeApply tree) {
  3868         Type owntype = types.createErrorType(tree.type);
  3870         // Attribute functor part of application and make sure it's a class.
  3871         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3873         // Attribute type parameters
  3874         List<Type> actuals = attribTypes(tree.arguments, env);
  3876         if (clazztype.hasTag(CLASS)) {
  3877             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3878             if (actuals.isEmpty()) //diamond
  3879                 actuals = formals;
  3881             if (actuals.length() == formals.length()) {
  3882                 List<Type> a = actuals;
  3883                 List<Type> f = formals;
  3884                 while (a.nonEmpty()) {
  3885                     a.head = a.head.withTypeVar(f.head);
  3886                     a = a.tail;
  3887                     f = f.tail;
  3889                 // Compute the proper generic outer
  3890                 Type clazzOuter = clazztype.getEnclosingType();
  3891                 if (clazzOuter.hasTag(CLASS)) {
  3892                     Type site;
  3893                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3894                     if (clazz.hasTag(IDENT)) {
  3895                         site = env.enclClass.sym.type;
  3896                     } else if (clazz.hasTag(SELECT)) {
  3897                         site = ((JCFieldAccess) clazz).selected.type;
  3898                     } else throw new AssertionError(""+tree);
  3899                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3900                         if (site.hasTag(CLASS))
  3901                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3902                         if (site == null)
  3903                             site = types.erasure(clazzOuter);
  3904                         clazzOuter = site;
  3907                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3908             } else {
  3909                 if (formals.length() != 0) {
  3910                     log.error(tree.pos(), "wrong.number.type.args",
  3911                               Integer.toString(formals.length()));
  3912                 } else {
  3913                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3915                 owntype = types.createErrorType(tree.type);
  3918         result = check(tree, owntype, TYP, resultInfo);
  3921     public void visitTypeUnion(JCTypeUnion tree) {
  3922         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  3923         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3924         for (JCExpression typeTree : tree.alternatives) {
  3925             Type ctype = attribType(typeTree, env);
  3926             ctype = chk.checkType(typeTree.pos(),
  3927                           chk.checkClassType(typeTree.pos(), ctype),
  3928                           syms.throwableType);
  3929             if (!ctype.isErroneous()) {
  3930                 //check that alternatives of a union type are pairwise
  3931                 //unrelated w.r.t. subtyping
  3932                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3933                     for (Type t : multicatchTypes) {
  3934                         boolean sub = types.isSubtype(ctype, t);
  3935                         boolean sup = types.isSubtype(t, ctype);
  3936                         if (sub || sup) {
  3937                             //assume 'a' <: 'b'
  3938                             Type a = sub ? ctype : t;
  3939                             Type b = sub ? t : ctype;
  3940                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3944                 multicatchTypes.append(ctype);
  3945                 if (all_multicatchTypes != null)
  3946                     all_multicatchTypes.append(ctype);
  3947             } else {
  3948                 if (all_multicatchTypes == null) {
  3949                     all_multicatchTypes = new ListBuffer<>();
  3950                     all_multicatchTypes.appendList(multicatchTypes);
  3952                 all_multicatchTypes.append(ctype);
  3955         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3956         if (t.hasTag(CLASS)) {
  3957             List<Type> alternatives =
  3958                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3959             t = new UnionClassType((ClassType) t, alternatives);
  3961         tree.type = result = t;
  3964     public void visitTypeIntersection(JCTypeIntersection tree) {
  3965         attribTypes(tree.bounds, env);
  3966         tree.type = result = checkIntersection(tree, tree.bounds);
  3969     public void visitTypeParameter(JCTypeParameter tree) {
  3970         TypeVar typeVar = (TypeVar) tree.type;
  3972         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3973             annotateType(tree, tree.annotations);
  3976         if (!typeVar.bound.isErroneous()) {
  3977             //fixup type-parameter bound computed in 'attribTypeVariables'
  3978             typeVar.bound = checkIntersection(tree, tree.bounds);
  3982     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3983         Set<Type> boundSet = new HashSet<Type>();
  3984         if (bounds.nonEmpty()) {
  3985             // accept class or interface or typevar as first bound.
  3986             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3987             boundSet.add(types.erasure(bounds.head.type));
  3988             if (bounds.head.type.isErroneous()) {
  3989                 return bounds.head.type;
  3991             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3992                 // if first bound was a typevar, do not accept further bounds.
  3993                 if (bounds.tail.nonEmpty()) {
  3994                     log.error(bounds.tail.head.pos(),
  3995                               "type.var.may.not.be.followed.by.other.bounds");
  3996                     return bounds.head.type;
  3998             } else {
  3999                 // if first bound was a class or interface, accept only interfaces
  4000                 // as further bounds.
  4001                 for (JCExpression bound : bounds.tail) {
  4002                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  4003                     if (bound.type.isErroneous()) {
  4004                         bounds = List.of(bound);
  4006                     else if (bound.type.hasTag(CLASS)) {
  4007                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4013         if (bounds.length() == 0) {
  4014             return syms.objectType;
  4015         } else if (bounds.length() == 1) {
  4016             return bounds.head.type;
  4017         } else {
  4018             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4019             // ... the variable's bound is a class type flagged COMPOUND
  4020             // (see comment for TypeVar.bound).
  4021             // In this case, generate a class tree that represents the
  4022             // bound class, ...
  4023             JCExpression extending;
  4024             List<JCExpression> implementing;
  4025             if (!bounds.head.type.isInterface()) {
  4026                 extending = bounds.head;
  4027                 implementing = bounds.tail;
  4028             } else {
  4029                 extending = null;
  4030                 implementing = bounds;
  4032             JCClassDecl cd = make.at(tree).ClassDef(
  4033                 make.Modifiers(PUBLIC | ABSTRACT),
  4034                 names.empty, List.<JCTypeParameter>nil(),
  4035                 extending, implementing, List.<JCTree>nil());
  4037             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4038             Assert.check((c.flags() & COMPOUND) != 0);
  4039             cd.sym = c;
  4040             c.sourcefile = env.toplevel.sourcefile;
  4042             // ... and attribute the bound class
  4043             c.flags_field |= UNATTRIBUTED;
  4044             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4045             enter.typeEnvs.put(c, cenv);
  4046             attribClass(c);
  4047             return owntype;
  4051     public void visitWildcard(JCWildcard tree) {
  4052         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4053         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4054             ? syms.objectType
  4055             : attribType(tree.inner, env);
  4056         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4057                                               tree.kind.kind,
  4058                                               syms.boundClass),
  4059                        TYP, resultInfo);
  4062     public void visitAnnotation(JCAnnotation tree) {
  4063         Assert.error("should be handled in Annotate");
  4066     public void visitAnnotatedType(JCAnnotatedType tree) {
  4067         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4068         this.attribAnnotationTypes(tree.annotations, env);
  4069         annotateType(tree, tree.annotations);
  4070         result = tree.type = underlyingType;
  4073     /**
  4074      * Apply the annotations to the particular type.
  4075      */
  4076     public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
  4077         annotate.typeAnnotation(new Annotate.Worker() {
  4078             @Override
  4079             public String toString() {
  4080                 return "annotate " + annotations + " onto " + tree;
  4082             @Override
  4083             public void run() {
  4084                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4085                 if (annotations.size() == compounds.size()) {
  4086                     // All annotations were successfully converted into compounds
  4087                     tree.type = tree.type.unannotatedType().annotatedType(compounds);
  4090         });
  4093     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4094         if (annotations.isEmpty()) {
  4095             return List.nil();
  4098         ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  4099         for (JCAnnotation anno : annotations) {
  4100             if (anno.attribute != null) {
  4101                 // TODO: this null-check is only needed for an obscure
  4102                 // ordering issue, where annotate.flush is called when
  4103                 // the attribute is not set yet. For an example failure
  4104                 // try the referenceinfos/NestedTypes.java test.
  4105                 // Any better solutions?
  4106                 buf.append((Attribute.TypeCompound) anno.attribute);
  4108             // Eventually we will want to throw an exception here, but
  4109             // we can't do that just yet, because it gets triggered
  4110             // when attempting to attach an annotation that isn't
  4111             // defined.
  4113         return buf.toList();
  4116     public void visitErroneous(JCErroneous tree) {
  4117         if (tree.errs != null)
  4118             for (JCTree err : tree.errs)
  4119                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4120         result = tree.type = syms.errType;
  4123     /** Default visitor method for all other trees.
  4124      */
  4125     public void visitTree(JCTree tree) {
  4126         throw new AssertionError();
  4129     /**
  4130      * Attribute an env for either a top level tree or class declaration.
  4131      */
  4132     public void attrib(Env<AttrContext> env) {
  4133         if (env.tree.hasTag(TOPLEVEL))
  4134             attribTopLevel(env);
  4135         else
  4136             attribClass(env.tree.pos(), env.enclClass.sym);
  4139     /**
  4140      * Attribute a top level tree. These trees are encountered when the
  4141      * package declaration has annotations.
  4142      */
  4143     public void attribTopLevel(Env<AttrContext> env) {
  4144         JCCompilationUnit toplevel = env.toplevel;
  4145         try {
  4146             annotate.flush();
  4147         } catch (CompletionFailure ex) {
  4148             chk.completionError(toplevel.pos(), ex);
  4152     /** Main method: attribute class definition associated with given class symbol.
  4153      *  reporting completion failures at the given position.
  4154      *  @param pos The source position at which completion errors are to be
  4155      *             reported.
  4156      *  @param c   The class symbol whose definition will be attributed.
  4157      */
  4158     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4159         try {
  4160             annotate.flush();
  4161             attribClass(c);
  4162         } catch (CompletionFailure ex) {
  4163             chk.completionError(pos, ex);
  4167     /** Attribute class definition associated with given class symbol.
  4168      *  @param c   The class symbol whose definition will be attributed.
  4169      */
  4170     void attribClass(ClassSymbol c) throws CompletionFailure {
  4171         if (c.type.hasTag(ERROR)) return;
  4173         // Check for cycles in the inheritance graph, which can arise from
  4174         // ill-formed class files.
  4175         chk.checkNonCyclic(null, c.type);
  4177         Type st = types.supertype(c.type);
  4178         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4179             // First, attribute superclass.
  4180             if (st.hasTag(CLASS))
  4181                 attribClass((ClassSymbol)st.tsym);
  4183             // Next attribute owner, if it is a class.
  4184             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4185                 attribClass((ClassSymbol)c.owner);
  4188         // The previous operations might have attributed the current class
  4189         // if there was a cycle. So we test first whether the class is still
  4190         // UNATTRIBUTED.
  4191         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4192             c.flags_field &= ~UNATTRIBUTED;
  4194             // Get environment current at the point of class definition.
  4195             Env<AttrContext> env = enter.typeEnvs.get(c);
  4197             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4198             // because the annotations were not available at the time the env was created. Therefore,
  4199             // we look up the environment chain for the first enclosing environment for which the
  4200             // lint value is set. Typically, this is the parent env, but might be further if there
  4201             // are any envs created as a result of TypeParameter nodes.
  4202             Env<AttrContext> lintEnv = env;
  4203             while (lintEnv.info.lint == null)
  4204                 lintEnv = lintEnv.next;
  4206             // Having found the enclosing lint value, we can initialize the lint value for this class
  4207             env.info.lint = lintEnv.info.lint.augment(c);
  4209             Lint prevLint = chk.setLint(env.info.lint);
  4210             JavaFileObject prev = log.useSource(c.sourcefile);
  4211             ResultInfo prevReturnRes = env.info.returnResult;
  4213             try {
  4214                 deferredLintHandler.flush(env.tree);
  4215                 env.info.returnResult = null;
  4216                 // java.lang.Enum may not be subclassed by a non-enum
  4217                 if (st.tsym == syms.enumSym &&
  4218                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4219                     log.error(env.tree.pos(), "enum.no.subclassing");
  4221                 // Enums may not be extended by source-level classes
  4222                 if (st.tsym != null &&
  4223                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4224                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4225                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4228                 if (isSerializable(c.type)) {
  4229                     env.info.isSerializable = true;
  4232                 attribClassBody(env, c);
  4234                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4235                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4236                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
  4237             } finally {
  4238                 env.info.returnResult = prevReturnRes;
  4239                 log.useSource(prev);
  4240                 chk.setLint(prevLint);
  4246     public void visitImport(JCImport tree) {
  4247         // nothing to do
  4250     /** Finish the attribution of a class. */
  4251     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4252         JCClassDecl tree = (JCClassDecl)env.tree;
  4253         Assert.check(c == tree.sym);
  4255         // Validate type parameters, supertype and interfaces.
  4256         attribStats(tree.typarams, env);
  4257         if (!c.isAnonymous()) {
  4258             //already checked if anonymous
  4259             chk.validate(tree.typarams, env);
  4260             chk.validate(tree.extending, env);
  4261             chk.validate(tree.implementing, env);
  4264         // If this is a non-abstract class, check that it has no abstract
  4265         // methods or unimplemented methods of an implemented interface.
  4266         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4267             if (!relax)
  4268                 chk.checkAllDefined(tree.pos(), c);
  4271         if ((c.flags() & ANNOTATION) != 0) {
  4272             if (tree.implementing.nonEmpty())
  4273                 log.error(tree.implementing.head.pos(),
  4274                           "cant.extend.intf.annotation");
  4275             if (tree.typarams.nonEmpty())
  4276                 log.error(tree.typarams.head.pos(),
  4277                           "intf.annotation.cant.have.type.params");
  4279             // If this annotation has a @Repeatable, validate
  4280             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4281             if (repeatable != null) {
  4282                 // get diagnostic position for error reporting
  4283                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4284                 Assert.checkNonNull(cbPos);
  4286                 chk.validateRepeatable(c, repeatable, cbPos);
  4288         } else {
  4289             // Check that all extended classes and interfaces
  4290             // are compatible (i.e. no two define methods with same arguments
  4291             // yet different return types).  (JLS 8.4.6.3)
  4292             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4293             if (allowDefaultMethods) {
  4294                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4298         // Check that class does not import the same parameterized interface
  4299         // with two different argument lists.
  4300         chk.checkClassBounds(tree.pos(), c.type);
  4302         tree.type = c.type;
  4304         for (List<JCTypeParameter> l = tree.typarams;
  4305              l.nonEmpty(); l = l.tail) {
  4306              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4309         // Check that a generic class doesn't extend Throwable
  4310         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4311             log.error(tree.extending.pos(), "generic.throwable");
  4313         // Check that all methods which implement some
  4314         // method conform to the method they implement.
  4315         chk.checkImplementations(tree);
  4317         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4318         checkAutoCloseable(tree.pos(), env, c.type);
  4320         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4321             // Attribute declaration
  4322             attribStat(l.head, env);
  4323             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4324             // Make an exception for static constants.
  4325             if (c.owner.kind != PCK &&
  4326                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4327                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4328                 Symbol sym = null;
  4329                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4330                 if (sym == null ||
  4331                     sym.kind != VAR ||
  4332                     ((VarSymbol) sym).getConstValue() == null)
  4333                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4337         // Check for cycles among non-initial constructors.
  4338         chk.checkCyclicConstructors(tree);
  4340         // Check for cycles among annotation elements.
  4341         chk.checkNonCyclicElements(tree);
  4343         // Check for proper use of serialVersionUID
  4344         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4345             isSerializable(c.type) &&
  4346             (c.flags() & Flags.ENUM) == 0 &&
  4347             checkForSerial(c)) {
  4348             checkSerialVersionUID(tree, c);
  4350         if (allowTypeAnnos) {
  4351             // Correctly organize the postions of the type annotations
  4352             typeAnnotations.organizeTypeAnnotationsBodies(tree);
  4354             // Check type annotations applicability rules
  4355             validateTypeAnnotations(tree, false);
  4358         // where
  4359         boolean checkForSerial(ClassSymbol c) {
  4360             if ((c.flags() & ABSTRACT) == 0) {
  4361                 return true;
  4362             } else {
  4363                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4367         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4368             @Override
  4369             public boolean accepts(Symbol s) {
  4370                 return s.kind == Kinds.MTH &&
  4371                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4373         };
  4375         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4376         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4377             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4378                 if (types.isSameType(al.head.annotationType.type, t))
  4379                     return al.head.pos();
  4382             return null;
  4385         /** check if a type is a subtype of Serializable, if that is available. */
  4386         boolean isSerializable(Type t) {
  4387             try {
  4388                 syms.serializableType.complete();
  4390             catch (CompletionFailure e) {
  4391                 return false;
  4393             return types.isSubtype(t, syms.serializableType);
  4396         /** Check that an appropriate serialVersionUID member is defined. */
  4397         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4399             // check for presence of serialVersionUID
  4400             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4401             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4402             if (e.scope == null) {
  4403                 log.warning(LintCategory.SERIAL,
  4404                         tree.pos(), "missing.SVUID", c);
  4405                 return;
  4408             // check that it is static final
  4409             VarSymbol svuid = (VarSymbol)e.sym;
  4410             if ((svuid.flags() & (STATIC | FINAL)) !=
  4411                 (STATIC | FINAL))
  4412                 log.warning(LintCategory.SERIAL,
  4413                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4415             // check that it is long
  4416             else if (!svuid.type.hasTag(LONG))
  4417                 log.warning(LintCategory.SERIAL,
  4418                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4420             // check constant
  4421             else if (svuid.getConstValue() == null)
  4422                 log.warning(LintCategory.SERIAL,
  4423                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4426     private Type capture(Type type) {
  4427         return types.capture(type);
  4430     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
  4431         tree.accept(new TypeAnnotationsValidator(sigOnly));
  4433     //where
  4434     private final class TypeAnnotationsValidator extends TreeScanner {
  4436         private final boolean sigOnly;
  4437         public TypeAnnotationsValidator(boolean sigOnly) {
  4438             this.sigOnly = sigOnly;
  4441         public void visitAnnotation(JCAnnotation tree) {
  4442             chk.validateTypeAnnotation(tree, false);
  4443             super.visitAnnotation(tree);
  4445         public void visitAnnotatedType(JCAnnotatedType tree) {
  4446             if (!tree.underlyingType.type.isErroneous()) {
  4447                 super.visitAnnotatedType(tree);
  4450         public void visitTypeParameter(JCTypeParameter tree) {
  4451             chk.validateTypeAnnotations(tree.annotations, true);
  4452             scan(tree.bounds);
  4453             // Don't call super.
  4454             // This is needed because above we call validateTypeAnnotation with
  4455             // false, which would forbid annotations on type parameters.
  4456             // super.visitTypeParameter(tree);
  4458         public void visitMethodDef(JCMethodDecl tree) {
  4459             if (tree.recvparam != null &&
  4460                     !tree.recvparam.vartype.type.isErroneous()) {
  4461                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4462                         tree.recvparam.vartype.type.tsym);
  4464             if (tree.restype != null && tree.restype.type != null) {
  4465                 validateAnnotatedType(tree.restype, tree.restype.type);
  4467             if (sigOnly) {
  4468                 scan(tree.mods);
  4469                 scan(tree.restype);
  4470                 scan(tree.typarams);
  4471                 scan(tree.recvparam);
  4472                 scan(tree.params);
  4473                 scan(tree.thrown);
  4474             } else {
  4475                 scan(tree.defaultValue);
  4476                 scan(tree.body);
  4479         public void visitVarDef(final JCVariableDecl tree) {
  4480             if (tree.sym != null && tree.sym.type != null)
  4481                 validateAnnotatedType(tree.vartype, tree.sym.type);
  4482             scan(tree.mods);
  4483             scan(tree.vartype);
  4484             if (!sigOnly) {
  4485                 scan(tree.init);
  4488         public void visitTypeCast(JCTypeCast tree) {
  4489             if (tree.clazz != null && tree.clazz.type != null)
  4490                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4491             super.visitTypeCast(tree);
  4493         public void visitTypeTest(JCInstanceOf tree) {
  4494             if (tree.clazz != null && tree.clazz.type != null)
  4495                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4496             super.visitTypeTest(tree);
  4498         public void visitNewClass(JCNewClass tree) {
  4499             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4500                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  4501                         tree.clazz.type.tsym);
  4503             if (tree.def != null) {
  4504                 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
  4506             if (tree.clazz.type != null) {
  4507                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4509             super.visitNewClass(tree);
  4511         public void visitNewArray(JCNewArray tree) {
  4512             if (tree.elemtype != null && tree.elemtype.type != null) {
  4513                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4514                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  4515                             tree.elemtype.type.tsym);
  4517                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
  4519             super.visitNewArray(tree);
  4521         public void visitClassDef(JCClassDecl tree) {
  4522             if (sigOnly) {
  4523                 scan(tree.mods);
  4524                 scan(tree.typarams);
  4525                 scan(tree.extending);
  4526                 scan(tree.implementing);
  4528             for (JCTree member : tree.defs) {
  4529                 if (member.hasTag(Tag.CLASSDEF)) {
  4530                     continue;
  4532                 scan(member);
  4535         public void visitBlock(JCBlock tree) {
  4536             if (!sigOnly) {
  4537                 scan(tree.stats);
  4541         /* I would want to model this after
  4542          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4543          * and override visitSelect and visitTypeApply.
  4544          * However, we only set the annotated type in the top-level type
  4545          * of the symbol.
  4546          * Therefore, we need to override each individual location where a type
  4547          * can occur.
  4548          */
  4549         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4550             // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
  4552             if (type.isPrimitiveOrVoid()) {
  4553                 return;
  4556             JCTree enclTr = errtree;
  4557             Type enclTy = type;
  4559             boolean repeat = true;
  4560             while (repeat) {
  4561                 if (enclTr.hasTag(TYPEAPPLY)) {
  4562                     List<Type> tyargs = enclTy.getTypeArguments();
  4563                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
  4564                     if (trargs.length() > 0) {
  4565                         // Nothing to do for diamonds
  4566                         if (tyargs.length() == trargs.length()) {
  4567                             for (int i = 0; i < tyargs.length(); ++i) {
  4568                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
  4571                         // If the lengths don't match, it's either a diamond
  4572                         // or some nested type that redundantly provides
  4573                         // type arguments in the tree.
  4576                     // Look at the clazz part of a generic type
  4577                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
  4580                 if (enclTr.hasTag(SELECT)) {
  4581                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
  4582                     if (enclTy != null &&
  4583                             !enclTy.hasTag(NONE)) {
  4584                         enclTy = enclTy.getEnclosingType();
  4586                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
  4587                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
  4588                     if (enclTy == null ||
  4589                             enclTy.hasTag(NONE)) {
  4590                         if (at.getAnnotations().size() == 1) {
  4591                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
  4592                         } else {
  4593                             ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
  4594                             for (JCAnnotation an : at.getAnnotations()) {
  4595                                 comps.add(an.attribute);
  4597                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
  4599                         repeat = false;
  4601                     enclTr = at.underlyingType;
  4602                     // enclTy doesn't need to be changed
  4603                 } else if (enclTr.hasTag(IDENT)) {
  4604                     repeat = false;
  4605                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
  4606                     JCWildcard wc = (JCWildcard) enclTr;
  4607                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
  4608                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
  4609                     } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
  4610                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
  4611                     } else {
  4612                         // Nothing to do for UNBOUND
  4614                     repeat = false;
  4615                 } else if (enclTr.hasTag(TYPEARRAY)) {
  4616                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
  4617                     validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
  4618                     repeat = false;
  4619                 } else if (enclTr.hasTag(TYPEUNION)) {
  4620                     JCTypeUnion ut = (JCTypeUnion) enclTr;
  4621                     for (JCTree t : ut.getTypeAlternatives()) {
  4622                         validateAnnotatedType(t, t.type);
  4624                     repeat = false;
  4625                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
  4626                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
  4627                     for (JCTree t : it.getBounds()) {
  4628                         validateAnnotatedType(t, t.type);
  4630                     repeat = false;
  4631                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
  4632                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  4633                     repeat = false;
  4634                 } else {
  4635                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
  4636                             " within: "+ errtree + " with kind: " + errtree.getKind());
  4641         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  4642                 Symbol sym) {
  4643             // Ensure that no declaration annotations are present.
  4644             // Note that a tree type might be an AnnotatedType with
  4645             // empty annotations, if only declaration annotations were given.
  4646             // This method will raise an error for such a type.
  4647             for (JCAnnotation ai : annotations) {
  4648                 if (!ai.type.isErroneous() &&
  4649                         typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  4650                     log.error(ai.pos(), "annotation.type.not.applicable");
  4654     };
  4656     // <editor-fold desc="post-attribution visitor">
  4658     /**
  4659      * Handle missing types/symbols in an AST. This routine is useful when
  4660      * the compiler has encountered some errors (which might have ended up
  4661      * terminating attribution abruptly); if the compiler is used in fail-over
  4662      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4663      * prevents NPE to be progagated during subsequent compilation steps.
  4664      */
  4665     public void postAttr(JCTree tree) {
  4666         new PostAttrAnalyzer().scan(tree);
  4669     class PostAttrAnalyzer extends TreeScanner {
  4671         private void initTypeIfNeeded(JCTree that) {
  4672             if (that.type == null) {
  4673                 if (that.hasTag(METHODDEF)) {
  4674                     that.type = dummyMethodType((JCMethodDecl)that);
  4675                 } else {
  4676                     that.type = syms.unknownType;
  4681         /* Construct a dummy method type. If we have a method declaration,
  4682          * and the declared return type is void, then use that return type
  4683          * instead of UNKNOWN to avoid spurious error messages in lambda
  4684          * bodies (see:JDK-8041704).
  4685          */
  4686         private Type dummyMethodType(JCMethodDecl md) {
  4687             Type restype = syms.unknownType;
  4688             if (md != null && md.restype.hasTag(TYPEIDENT)) {
  4689                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
  4690                 if (prim.typetag == VOID)
  4691                     restype = syms.voidType;
  4693             return new MethodType(List.<Type>nil(), restype,
  4694                                   List.<Type>nil(), syms.methodClass);
  4696         private Type dummyMethodType() {
  4697             return dummyMethodType(null);
  4700         @Override
  4701         public void scan(JCTree tree) {
  4702             if (tree == null) return;
  4703             if (tree instanceof JCExpression) {
  4704                 initTypeIfNeeded(tree);
  4706             super.scan(tree);
  4709         @Override
  4710         public void visitIdent(JCIdent that) {
  4711             if (that.sym == null) {
  4712                 that.sym = syms.unknownSymbol;
  4716         @Override
  4717         public void visitSelect(JCFieldAccess that) {
  4718             if (that.sym == null) {
  4719                 that.sym = syms.unknownSymbol;
  4721             super.visitSelect(that);
  4724         @Override
  4725         public void visitClassDef(JCClassDecl that) {
  4726             initTypeIfNeeded(that);
  4727             if (that.sym == null) {
  4728                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4730             super.visitClassDef(that);
  4733         @Override
  4734         public void visitMethodDef(JCMethodDecl that) {
  4735             initTypeIfNeeded(that);
  4736             if (that.sym == null) {
  4737                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4739             super.visitMethodDef(that);
  4742         @Override
  4743         public void visitVarDef(JCVariableDecl that) {
  4744             initTypeIfNeeded(that);
  4745             if (that.sym == null) {
  4746                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4747                 that.sym.adr = 0;
  4749             super.visitVarDef(that);
  4752         @Override
  4753         public void visitNewClass(JCNewClass that) {
  4754             if (that.constructor == null) {
  4755                 that.constructor = new MethodSymbol(0, names.init,
  4756                         dummyMethodType(), syms.noSymbol);
  4758             if (that.constructorType == null) {
  4759                 that.constructorType = syms.unknownType;
  4761             super.visitNewClass(that);
  4764         @Override
  4765         public void visitAssignop(JCAssignOp that) {
  4766             if (that.operator == null) {
  4767                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4768                         -1, syms.noSymbol);
  4770             super.visitAssignop(that);
  4773         @Override
  4774         public void visitBinary(JCBinary that) {
  4775             if (that.operator == null) {
  4776                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4777                         -1, syms.noSymbol);
  4779             super.visitBinary(that);
  4782         @Override
  4783         public void visitUnary(JCUnary that) {
  4784             if (that.operator == null) {
  4785                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4786                         -1, syms.noSymbol);
  4788             super.visitUnary(that);
  4791         @Override
  4792         public void visitLambda(JCLambda that) {
  4793             super.visitLambda(that);
  4794             if (that.targets == null) {
  4795                 that.targets = List.nil();
  4799         @Override
  4800         public void visitReference(JCMemberReference that) {
  4801             super.visitReference(that);
  4802             if (that.sym == null) {
  4803                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
  4804                         syms.noSymbol);
  4806             if (that.targets == null) {
  4807                 that.targets = List.nil();
  4811     // </editor-fold>

mercurial