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

Mon, 27 Jan 2014 21:15:39 +0000

author
vromero
date
Mon, 27 Jan 2014 21:15:39 +0000
changeset 2253
afb6642d0603
parent 2222
8832b6048e65
child 2359
ba7ee72d5d6b
permissions
-rw-r--r--

8030816: javac crashes when mixing lambdas and inner classes
Reviewed-by: jjg, jlahoda

     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.asFree(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         @Override
   522         public String toString() {
   523             if (pt != null) {
   524                 return pt.toString();
   525             } else {
   526                 return "";
   527             }
   528         }
   529     }
   531     class RecoveryInfo extends ResultInfo {
   533         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   534             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   535                 @Override
   536                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   537                     return deferredAttrContext;
   538                 }
   539                 @Override
   540                 public boolean compatible(Type found, Type req, Warner warn) {
   541                     return true;
   542                 }
   543                 @Override
   544                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   545                     chk.basicHandler.report(pos, details);
   546                 }
   547             });
   548         }
   549     }
   551     final ResultInfo statInfo;
   552     final ResultInfo varInfo;
   553     final ResultInfo unknownAnyPolyInfo;
   554     final ResultInfo unknownExprInfo;
   555     final ResultInfo unknownTypeInfo;
   556     final ResultInfo unknownTypeExprInfo;
   557     final ResultInfo recoveryInfo;
   559     Type pt() {
   560         return resultInfo.pt;
   561     }
   563     int pkind() {
   564         return resultInfo.pkind;
   565     }
   567 /* ************************************************************************
   568  * Visitor methods
   569  *************************************************************************/
   571     /** Visitor argument: the current environment.
   572      */
   573     Env<AttrContext> env;
   575     /** Visitor argument: the currently expected attribution result.
   576      */
   577     ResultInfo resultInfo;
   579     /** Visitor result: the computed type.
   580      */
   581     Type result;
   583     /** Visitor method: attribute a tree, catching any completion failure
   584      *  exceptions. Return the tree's type.
   585      *
   586      *  @param tree    The tree to be visited.
   587      *  @param env     The environment visitor argument.
   588      *  @param resultInfo   The result info visitor argument.
   589      */
   590     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   591         Env<AttrContext> prevEnv = this.env;
   592         ResultInfo prevResult = this.resultInfo;
   593         try {
   594             this.env = env;
   595             this.resultInfo = resultInfo;
   596             tree.accept(this);
   597             if (tree == breakTree &&
   598                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   599                 throw new BreakAttr(copyEnv(env));
   600             }
   601             return result;
   602         } catch (CompletionFailure ex) {
   603             tree.type = syms.errType;
   604             return chk.completionError(tree.pos(), ex);
   605         } finally {
   606             this.env = prevEnv;
   607             this.resultInfo = prevResult;
   608         }
   609     }
   611     Env<AttrContext> copyEnv(Env<AttrContext> env) {
   612         Env<AttrContext> newEnv =
   613                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   614         if (newEnv.outer != null) {
   615             newEnv.outer = copyEnv(newEnv.outer);
   616         }
   617         return newEnv;
   618     }
   620     Scope copyScope(Scope sc) {
   621         Scope newScope = new Scope(sc.owner);
   622         List<Symbol> elemsList = List.nil();
   623         while (sc != null) {
   624             for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   625                 elemsList = elemsList.prepend(e.sym);
   626             }
   627             sc = sc.next;
   628         }
   629         for (Symbol s : elemsList) {
   630             newScope.enter(s);
   631         }
   632         return newScope;
   633     }
   635     /** Derived visitor method: attribute an expression tree.
   636      */
   637     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   638         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   639     }
   641     /** Derived visitor method: attribute an expression tree with
   642      *  no constraints on the computed type.
   643      */
   644     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   645         return attribTree(tree, env, unknownExprInfo);
   646     }
   648     /** Derived visitor method: attribute a type tree.
   649      */
   650     public Type attribType(JCTree tree, Env<AttrContext> env) {
   651         Type result = attribType(tree, env, Type.noType);
   652         return result;
   653     }
   655     /** Derived visitor method: attribute a type tree.
   656      */
   657     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   658         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   659         return result;
   660     }
   662     /** Derived visitor method: attribute a statement or definition tree.
   663      */
   664     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   665         return attribTree(tree, env, statInfo);
   666     }
   668     /** Attribute a list of expressions, returning a list of types.
   669      */
   670     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   671         ListBuffer<Type> ts = new ListBuffer<Type>();
   672         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   673             ts.append(attribExpr(l.head, env, pt));
   674         return ts.toList();
   675     }
   677     /** Attribute a list of statements, returning nothing.
   678      */
   679     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   680         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   681             attribStat(l.head, env);
   682     }
   684     /** Attribute the arguments in a method call, returning the method kind.
   685      */
   686     int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   687         int kind = VAL;
   688         for (JCExpression arg : trees) {
   689             Type argtype;
   690             if (allowPoly && deferredAttr.isDeferred(env, arg)) {
   691                 argtype = deferredAttr.new DeferredType(arg, env);
   692                 kind |= POLY;
   693             } else {
   694                 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
   695             }
   696             argtypes.append(argtype);
   697         }
   698         return kind;
   699     }
   701     /** Attribute a type argument list, returning a list of types.
   702      *  Caller is responsible for calling checkRefTypes.
   703      */
   704     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   705         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   706         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   707             argtypes.append(attribType(l.head, env));
   708         return argtypes.toList();
   709     }
   711     /** Attribute a type argument list, returning a list of types.
   712      *  Check that all the types are references.
   713      */
   714     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   715         List<Type> types = attribAnyTypes(trees, env);
   716         return chk.checkRefTypes(trees, types);
   717     }
   719     /**
   720      * Attribute type variables (of generic classes or methods).
   721      * Compound types are attributed later in attribBounds.
   722      * @param typarams the type variables to enter
   723      * @param env      the current environment
   724      */
   725     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   726         for (JCTypeParameter tvar : typarams) {
   727             TypeVar a = (TypeVar)tvar.type;
   728             a.tsym.flags_field |= UNATTRIBUTED;
   729             a.bound = Type.noType;
   730             if (!tvar.bounds.isEmpty()) {
   731                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   732                 for (JCExpression bound : tvar.bounds.tail)
   733                     bounds = bounds.prepend(attribType(bound, env));
   734                 types.setBounds(a, bounds.reverse());
   735             } else {
   736                 // if no bounds are given, assume a single bound of
   737                 // java.lang.Object.
   738                 types.setBounds(a, List.of(syms.objectType));
   739             }
   740             a.tsym.flags_field &= ~UNATTRIBUTED;
   741         }
   742         for (JCTypeParameter tvar : typarams) {
   743             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   744         }
   745     }
   747     /**
   748      * Attribute the type references in a list of annotations.
   749      */
   750     void attribAnnotationTypes(List<JCAnnotation> annotations,
   751                                Env<AttrContext> env) {
   752         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   753             JCAnnotation a = al.head;
   754             attribType(a.annotationType, env);
   755         }
   756     }
   758     /**
   759      * Attribute a "lazy constant value".
   760      *  @param env         The env for the const value
   761      *  @param initializer The initializer for the const value
   762      *  @param type        The expected type, or null
   763      *  @see VarSymbol#setLazyConstValue
   764      */
   765     public Object attribLazyConstantValue(Env<AttrContext> env,
   766                                       JCVariableDecl variable,
   767                                       Type type) {
   769         DiagnosticPosition prevLintPos
   770                 = deferredLintHandler.setPos(variable.pos());
   772         try {
   773             // Use null as symbol to not attach the type annotation to any symbol.
   774             // The initializer will later also be visited and then we'll attach
   775             // to the symbol.
   776             // This prevents having multiple type annotations, just because of
   777             // lazy constant value evaluation.
   778             memberEnter.typeAnnotate(variable.init, env, null, variable.pos());
   779             annotate.flush();
   780             Type itype = attribExpr(variable.init, env, type);
   781             if (itype.constValue() != null) {
   782                 return coerce(itype, type).constValue();
   783             } else {
   784                 return null;
   785             }
   786         } finally {
   787             deferredLintHandler.setPos(prevLintPos);
   788         }
   789     }
   791     /** Attribute type reference in an `extends' or `implements' clause.
   792      *  Supertypes of anonymous inner classes are usually already attributed.
   793      *
   794      *  @param tree              The tree making up the type reference.
   795      *  @param env               The environment current at the reference.
   796      *  @param classExpected     true if only a class is expected here.
   797      *  @param interfaceExpected true if only an interface is expected here.
   798      */
   799     Type attribBase(JCTree tree,
   800                     Env<AttrContext> env,
   801                     boolean classExpected,
   802                     boolean interfaceExpected,
   803                     boolean checkExtensible) {
   804         Type t = tree.type != null ?
   805             tree.type :
   806             attribType(tree, env);
   807         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   808     }
   809     Type checkBase(Type t,
   810                    JCTree tree,
   811                    Env<AttrContext> env,
   812                    boolean classExpected,
   813                    boolean interfaceExpected,
   814                    boolean checkExtensible) {
   815         if (t.isErroneous())
   816             return t;
   817         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   818             // check that type variable is already visible
   819             if (t.getUpperBound() == null) {
   820                 log.error(tree.pos(), "illegal.forward.ref");
   821                 return types.createErrorType(t);
   822             }
   823         } else {
   824             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   825         }
   826         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   827             log.error(tree.pos(), "intf.expected.here");
   828             // return errType is necessary since otherwise there might
   829             // be undetected cycles which cause attribution to loop
   830             return types.createErrorType(t);
   831         } else if (checkExtensible &&
   832                    classExpected &&
   833                    (t.tsym.flags() & INTERFACE) != 0) {
   834             log.error(tree.pos(), "no.intf.expected.here");
   835             return types.createErrorType(t);
   836         }
   837         if (checkExtensible &&
   838             ((t.tsym.flags() & FINAL) != 0)) {
   839             log.error(tree.pos(),
   840                       "cant.inherit.from.final", t.tsym);
   841         }
   842         chk.checkNonCyclic(tree.pos(), t);
   843         return t;
   844     }
   846     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   847         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   848         id.type = env.info.scope.owner.type;
   849         id.sym = env.info.scope.owner;
   850         return id.type;
   851     }
   853     public void visitClassDef(JCClassDecl tree) {
   854         // Local classes have not been entered yet, so we need to do it now:
   855         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   856             enter.classEnter(tree, env);
   858         ClassSymbol c = tree.sym;
   859         if (c == null) {
   860             // exit in case something drastic went wrong during enter.
   861             result = null;
   862         } else {
   863             // make sure class has been completed:
   864             c.complete();
   866             // If this class appears as an anonymous class
   867             // in a superclass constructor call where
   868             // no explicit outer instance is given,
   869             // disable implicit outer instance from being passed.
   870             // (This would be an illegal access to "this before super").
   871             if (env.info.isSelfCall &&
   872                 env.tree.hasTag(NEWCLASS) &&
   873                 ((JCNewClass) env.tree).encl == null)
   874             {
   875                 c.flags_field |= NOOUTERTHIS;
   876             }
   877             attribClass(tree.pos(), c);
   878             result = tree.type = c.type;
   879         }
   880     }
   882     public void visitMethodDef(JCMethodDecl tree) {
   883         MethodSymbol m = tree.sym;
   884         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   886         Lint lint = env.info.lint.augment(m);
   887         Lint prevLint = chk.setLint(lint);
   888         MethodSymbol prevMethod = chk.setMethod(m);
   889         try {
   890             deferredLintHandler.flush(tree.pos());
   891             chk.checkDeprecatedAnnotation(tree.pos(), m);
   894             // Create a new environment with local scope
   895             // for attributing the method.
   896             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   897             localEnv.info.lint = lint;
   899             attribStats(tree.typarams, localEnv);
   901             // If we override any other methods, check that we do so properly.
   902             // JLS ???
   903             if (m.isStatic()) {
   904                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   905             } else {
   906                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   907             }
   908             chk.checkOverride(tree, m);
   910             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   911                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   912             }
   914             // Enter all type parameters into the local method scope.
   915             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   916                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   918             ClassSymbol owner = env.enclClass.sym;
   919             if ((owner.flags() & ANNOTATION) != 0 &&
   920                 tree.params.nonEmpty())
   921                 log.error(tree.params.head.pos(),
   922                           "intf.annotation.members.cant.have.params");
   924             // Attribute all value parameters.
   925             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   926                 attribStat(l.head, localEnv);
   927             }
   929             chk.checkVarargsMethodDecl(localEnv, tree);
   931             // Check that type parameters are well-formed.
   932             chk.validate(tree.typarams, localEnv);
   934             // Check that result type is well-formed.
   935             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
   936                 chk.validate(tree.restype, localEnv);
   938             // Check that receiver type is well-formed.
   939             if (tree.recvparam != null) {
   940                 // Use a new environment to check the receiver parameter.
   941                 // Otherwise I get "might not have been initialized" errors.
   942                 // Is there a better way?
   943                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   944                 attribType(tree.recvparam, newEnv);
   945                 chk.validate(tree.recvparam, newEnv);
   946             }
   948             // annotation method checks
   949             if ((owner.flags() & ANNOTATION) != 0) {
   950                 // annotation method cannot have throws clause
   951                 if (tree.thrown.nonEmpty()) {
   952                     log.error(tree.thrown.head.pos(),
   953                             "throws.not.allowed.in.intf.annotation");
   954                 }
   955                 // annotation method cannot declare type-parameters
   956                 if (tree.typarams.nonEmpty()) {
   957                     log.error(tree.typarams.head.pos(),
   958                             "intf.annotation.members.cant.have.type.params");
   959                 }
   960                 // validate annotation method's return type (could be an annotation type)
   961                 chk.validateAnnotationType(tree.restype);
   962                 // ensure that annotation method does not clash with members of Object/Annotation
   963                 chk.validateAnnotationMethod(tree.pos(), m);
   964             }
   966             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   967                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   969             if (tree.body == null) {
   970                 // Empty bodies are only allowed for
   971                 // abstract, native, or interface methods, or for methods
   972                 // in a retrofit signature class.
   973                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   974                     !relax)
   975                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   976                 if (tree.defaultValue != null) {
   977                     if ((owner.flags() & ANNOTATION) == 0)
   978                         log.error(tree.pos(),
   979                                   "default.allowed.in.intf.annotation.member");
   980                 }
   981             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   982                 if ((owner.flags() & INTERFACE) != 0) {
   983                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   984                 } else {
   985                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   986                 }
   987             } else if ((tree.mods.flags & NATIVE) != 0) {
   988                 log.error(tree.pos(), "native.meth.cant.have.body");
   989             } else {
   990                 // Add an implicit super() call unless an explicit call to
   991                 // super(...) or this(...) is given
   992                 // or we are compiling class java.lang.Object.
   993                 if (tree.name == names.init && owner.type != syms.objectType) {
   994                     JCBlock body = tree.body;
   995                     if (body.stats.isEmpty() ||
   996                         !TreeInfo.isSelfCall(body.stats.head)) {
   997                         body.stats = body.stats.
   998                             prepend(memberEnter.SuperCall(make.at(body.pos),
   999                                                           List.<Type>nil(),
  1000                                                           List.<JCVariableDecl>nil(),
  1001                                                           false));
  1002                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1003                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1004                                TreeInfo.isSuperCall(body.stats.head)) {
  1005                         // enum constructors are not allowed to call super
  1006                         // directly, so make sure there aren't any super calls
  1007                         // in enum constructors, except in the compiler
  1008                         // generated one.
  1009                         log.error(tree.body.stats.head.pos(),
  1010                                   "call.to.super.not.allowed.in.enum.ctor",
  1011                                   env.enclClass.sym);
  1015                 // Attribute all type annotations in the body
  1016                 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
  1017                 annotate.flush();
  1019                 // Attribute method body.
  1020                 attribStat(tree.body, localEnv);
  1023             localEnv.info.scope.leave();
  1024             result = tree.type = m.type;
  1026         finally {
  1027             chk.setLint(prevLint);
  1028             chk.setMethod(prevMethod);
  1032     public void visitVarDef(JCVariableDecl tree) {
  1033         // Local variables have not been entered yet, so we need to do it now:
  1034         if (env.info.scope.owner.kind == MTH) {
  1035             if (tree.sym != null) {
  1036                 // parameters have already been entered
  1037                 env.info.scope.enter(tree.sym);
  1038             } else {
  1039                 memberEnter.memberEnter(tree, env);
  1040                 annotate.flush();
  1042         } else {
  1043             if (tree.init != null) {
  1044                 // Field initializer expression need to be entered.
  1045                 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
  1046                 annotate.flush();
  1050         VarSymbol v = tree.sym;
  1051         Lint lint = env.info.lint.augment(v);
  1052         Lint prevLint = chk.setLint(lint);
  1054         // Check that the variable's declared type is well-formed.
  1055         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1056                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1057                 (tree.sym.flags() & PARAMETER) != 0;
  1058         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1060         try {
  1061             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1062             deferredLintHandler.flush(tree.pos());
  1063             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1065             if (tree.init != null) {
  1066                 if ((v.flags_field & FINAL) == 0 ||
  1067                     !memberEnter.needsLazyConstValue(tree.init)) {
  1068                     // Not a compile-time constant
  1069                     // Attribute initializer in a new environment
  1070                     // with the declared variable as owner.
  1071                     // Check that initializer conforms to variable's declared type.
  1072                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1073                     initEnv.info.lint = lint;
  1074                     // In order to catch self-references, we set the variable's
  1075                     // declaration position to maximal possible value, effectively
  1076                     // marking the variable as undefined.
  1077                     initEnv.info.enclVar = v;
  1078                     attribExpr(tree.init, initEnv, v.type);
  1081             result = tree.type = v.type;
  1083         finally {
  1084             chk.setLint(prevLint);
  1088     public void visitSkip(JCSkip tree) {
  1089         result = null;
  1092     public void visitBlock(JCBlock tree) {
  1093         if (env.info.scope.owner.kind == TYP) {
  1094             // Block is a static or instance initializer;
  1095             // let the owner of the environment be a freshly
  1096             // created BLOCK-method.
  1097             Env<AttrContext> localEnv =
  1098                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1099             localEnv.info.scope.owner =
  1100                 new MethodSymbol(tree.flags | BLOCK |
  1101                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1102                     env.info.scope.owner);
  1103             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1105             // Attribute all type annotations in the block
  1106             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1107             annotate.flush();
  1110                 // Store init and clinit type annotations with the ClassSymbol
  1111                 // to allow output in Gen.normalizeDefs.
  1112                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1113                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1114                 if ((tree.flags & STATIC) != 0) {
  1115                     cs.appendClassInitTypeAttributes(tas);
  1116                 } else {
  1117                     cs.appendInitTypeAttributes(tas);
  1121             attribStats(tree.stats, localEnv);
  1122         } else {
  1123             // Create a new local environment with a local scope.
  1124             Env<AttrContext> localEnv =
  1125                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1126             try {
  1127                 attribStats(tree.stats, localEnv);
  1128             } finally {
  1129                 localEnv.info.scope.leave();
  1132         result = null;
  1135     public void visitDoLoop(JCDoWhileLoop tree) {
  1136         attribStat(tree.body, env.dup(tree));
  1137         attribExpr(tree.cond, env, syms.booleanType);
  1138         result = null;
  1141     public void visitWhileLoop(JCWhileLoop tree) {
  1142         attribExpr(tree.cond, env, syms.booleanType);
  1143         attribStat(tree.body, env.dup(tree));
  1144         result = null;
  1147     public void visitForLoop(JCForLoop tree) {
  1148         Env<AttrContext> loopEnv =
  1149             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1150         try {
  1151             attribStats(tree.init, loopEnv);
  1152             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1153             loopEnv.tree = tree; // before, we were not in loop!
  1154             attribStats(tree.step, loopEnv);
  1155             attribStat(tree.body, loopEnv);
  1156             result = null;
  1158         finally {
  1159             loopEnv.info.scope.leave();
  1163     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1164         Env<AttrContext> loopEnv =
  1165             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1166         try {
  1167             //the Formal Parameter of a for-each loop is not in the scope when
  1168             //attributing the for-each expression; we mimick this by attributing
  1169             //the for-each expression first (against original scope).
  1170             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1171             attribStat(tree.var, loopEnv);
  1172             chk.checkNonVoid(tree.pos(), exprType);
  1173             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1174             if (elemtype == null) {
  1175                 // or perhaps expr implements Iterable<T>?
  1176                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1177                 if (base == null) {
  1178                     log.error(tree.expr.pos(),
  1179                             "foreach.not.applicable.to.type",
  1180                             exprType,
  1181                             diags.fragment("type.req.array.or.iterable"));
  1182                     elemtype = types.createErrorType(exprType);
  1183                 } else {
  1184                     List<Type> iterableParams = base.allparams();
  1185                     elemtype = iterableParams.isEmpty()
  1186                         ? syms.objectType
  1187                         : types.upperBound(iterableParams.head);
  1190             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1191             loopEnv.tree = tree; // before, we were not in loop!
  1192             attribStat(tree.body, loopEnv);
  1193             result = null;
  1195         finally {
  1196             loopEnv.info.scope.leave();
  1200     public void visitLabelled(JCLabeledStatement tree) {
  1201         // Check that label is not used in an enclosing statement
  1202         Env<AttrContext> env1 = env;
  1203         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1204             if (env1.tree.hasTag(LABELLED) &&
  1205                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1206                 log.error(tree.pos(), "label.already.in.use",
  1207                           tree.label);
  1208                 break;
  1210             env1 = env1.next;
  1213         attribStat(tree.body, env.dup(tree));
  1214         result = null;
  1217     public void visitSwitch(JCSwitch tree) {
  1218         Type seltype = attribExpr(tree.selector, env);
  1220         Env<AttrContext> switchEnv =
  1221             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1223         try {
  1225             boolean enumSwitch =
  1226                 allowEnums &&
  1227                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1228             boolean stringSwitch = false;
  1229             if (types.isSameType(seltype, syms.stringType)) {
  1230                 if (allowStringsInSwitch) {
  1231                     stringSwitch = true;
  1232                 } else {
  1233                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1236             if (!enumSwitch && !stringSwitch)
  1237                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1239             // Attribute all cases and
  1240             // check that there are no duplicate case labels or default clauses.
  1241             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1242             boolean hasDefault = false;      // Is there a default label?
  1243             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1244                 JCCase c = l.head;
  1245                 Env<AttrContext> caseEnv =
  1246                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1247                 try {
  1248                     if (c.pat != null) {
  1249                         if (enumSwitch) {
  1250                             Symbol sym = enumConstant(c.pat, seltype);
  1251                             if (sym == null) {
  1252                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1253                             } else if (!labels.add(sym)) {
  1254                                 log.error(c.pos(), "duplicate.case.label");
  1256                         } else {
  1257                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1258                             if (!pattype.hasTag(ERROR)) {
  1259                                 if (pattype.constValue() == null) {
  1260                                     log.error(c.pat.pos(),
  1261                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1262                                 } else if (labels.contains(pattype.constValue())) {
  1263                                     log.error(c.pos(), "duplicate.case.label");
  1264                                 } else {
  1265                                     labels.add(pattype.constValue());
  1269                     } else if (hasDefault) {
  1270                         log.error(c.pos(), "duplicate.default.label");
  1271                     } else {
  1272                         hasDefault = true;
  1274                     attribStats(c.stats, caseEnv);
  1275                 } finally {
  1276                     caseEnv.info.scope.leave();
  1277                     addVars(c.stats, switchEnv.info.scope);
  1281             result = null;
  1283         finally {
  1284             switchEnv.info.scope.leave();
  1287     // where
  1288         /** Add any variables defined in stats to the switch scope. */
  1289         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1290             for (;stats.nonEmpty(); stats = stats.tail) {
  1291                 JCTree stat = stats.head;
  1292                 if (stat.hasTag(VARDEF))
  1293                     switchScope.enter(((JCVariableDecl) stat).sym);
  1296     // where
  1297     /** Return the selected enumeration constant symbol, or null. */
  1298     private Symbol enumConstant(JCTree tree, Type enumType) {
  1299         if (!tree.hasTag(IDENT)) {
  1300             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1301             return syms.errSymbol;
  1303         JCIdent ident = (JCIdent)tree;
  1304         Name name = ident.name;
  1305         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1306              e.scope != null; e = e.next()) {
  1307             if (e.sym.kind == VAR) {
  1308                 Symbol s = ident.sym = e.sym;
  1309                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1310                 ident.type = s.type;
  1311                 return ((s.flags_field & Flags.ENUM) == 0)
  1312                     ? null : s;
  1315         return null;
  1318     public void visitSynchronized(JCSynchronized tree) {
  1319         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1320         attribStat(tree.body, env);
  1321         result = null;
  1324     public void visitTry(JCTry tree) {
  1325         // Create a new local environment with a local
  1326         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1327         try {
  1328             boolean isTryWithResource = tree.resources.nonEmpty();
  1329             // Create a nested environment for attributing the try block if needed
  1330             Env<AttrContext> tryEnv = isTryWithResource ?
  1331                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1332                 localEnv;
  1333             try {
  1334                 // Attribute resource declarations
  1335                 for (JCTree resource : tree.resources) {
  1336                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1337                         @Override
  1338                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1339                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1341                     };
  1342                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1343                     if (resource.hasTag(VARDEF)) {
  1344                         attribStat(resource, tryEnv);
  1345                         twrResult.check(resource, resource.type);
  1347                         //check that resource type cannot throw InterruptedException
  1348                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1350                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1351                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1352                     } else {
  1353                         attribTree(resource, tryEnv, twrResult);
  1356                 // Attribute body
  1357                 attribStat(tree.body, tryEnv);
  1358             } finally {
  1359                 if (isTryWithResource)
  1360                     tryEnv.info.scope.leave();
  1363             // Attribute catch clauses
  1364             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1365                 JCCatch c = l.head;
  1366                 Env<AttrContext> catchEnv =
  1367                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1368                 try {
  1369                     Type ctype = attribStat(c.param, catchEnv);
  1370                     if (TreeInfo.isMultiCatch(c)) {
  1371                         //multi-catch parameter is implicitly marked as final
  1372                         c.param.sym.flags_field |= FINAL | UNION;
  1374                     if (c.param.sym.kind == Kinds.VAR) {
  1375                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1377                     chk.checkType(c.param.vartype.pos(),
  1378                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1379                                   syms.throwableType);
  1380                     attribStat(c.body, catchEnv);
  1381                 } finally {
  1382                     catchEnv.info.scope.leave();
  1386             // Attribute finalizer
  1387             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1388             result = null;
  1390         finally {
  1391             localEnv.info.scope.leave();
  1395     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1396         if (!resource.isErroneous() &&
  1397             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1398             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1399             Symbol close = syms.noSymbol;
  1400             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1401             try {
  1402                 close = rs.resolveQualifiedMethod(pos,
  1403                         env,
  1404                         resource,
  1405                         names.close,
  1406                         List.<Type>nil(),
  1407                         List.<Type>nil());
  1409             finally {
  1410                 log.popDiagnosticHandler(discardHandler);
  1412             if (close.kind == MTH &&
  1413                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1414                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1415                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1416                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1421     public void visitConditional(JCConditional tree) {
  1422         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1424         tree.polyKind = (!allowPoly ||
  1425                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1426                 isBooleanOrNumeric(env, tree)) ?
  1427                 PolyKind.STANDALONE : PolyKind.POLY;
  1429         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1430             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1431             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1432             result = tree.type = types.createErrorType(resultInfo.pt);
  1433             return;
  1436         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1437                 unknownExprInfo :
  1438                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1439                     //this will use enclosing check context to check compatibility of
  1440                     //subexpression against target type; if we are in a method check context,
  1441                     //depending on whether boxing is allowed, we could have incompatibilities
  1442                     @Override
  1443                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1444                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1446                 });
  1448         Type truetype = attribTree(tree.truepart, env, condInfo);
  1449         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1451         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1452         if (condtype.constValue() != null &&
  1453                 truetype.constValue() != null &&
  1454                 falsetype.constValue() != null &&
  1455                 !owntype.hasTag(NONE)) {
  1456             //constant folding
  1457             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1459         result = check(tree, owntype, VAL, resultInfo);
  1461     //where
  1462         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1463             switch (tree.getTag()) {
  1464                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1465                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1466                               ((JCLiteral)tree).typetag == BOT;
  1467                 case LAMBDA: case REFERENCE: return false;
  1468                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1469                 case CONDEXPR:
  1470                     JCConditional condTree = (JCConditional)tree;
  1471                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1472                             isBooleanOrNumeric(env, condTree.falsepart);
  1473                 case APPLY:
  1474                     JCMethodInvocation speculativeMethodTree =
  1475                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1476                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1477                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1478                 case NEWCLASS:
  1479                     JCExpression className =
  1480                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1481                     JCExpression speculativeNewClassTree =
  1482                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1483                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1484                 default:
  1485                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1486                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1487                     return speculativeType.isPrimitive();
  1490         //where
  1491             TreeTranslator removeClassParams = new TreeTranslator() {
  1492                 @Override
  1493                 public void visitTypeApply(JCTypeApply tree) {
  1494                     result = translate(tree.clazz);
  1496             };
  1498         /** Compute the type of a conditional expression, after
  1499          *  checking that it exists.  See JLS 15.25. Does not take into
  1500          *  account the special case where condition and both arms
  1501          *  are constants.
  1503          *  @param pos      The source position to be used for error
  1504          *                  diagnostics.
  1505          *  @param thentype The type of the expression's then-part.
  1506          *  @param elsetype The type of the expression's else-part.
  1507          */
  1508         private Type condType(DiagnosticPosition pos,
  1509                                Type thentype, Type elsetype) {
  1510             // If same type, that is the result
  1511             if (types.isSameType(thentype, elsetype))
  1512                 return thentype.baseType();
  1514             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1515                 ? thentype : types.unboxedType(thentype);
  1516             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1517                 ? elsetype : types.unboxedType(elsetype);
  1519             // Otherwise, if both arms can be converted to a numeric
  1520             // type, return the least numeric type that fits both arms
  1521             // (i.e. return larger of the two, or return int if one
  1522             // arm is short, the other is char).
  1523             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1524                 // If one arm has an integer subrange type (i.e., byte,
  1525                 // short, or char), and the other is an integer constant
  1526                 // that fits into the subrange, return the subrange type.
  1527                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1528                     elseUnboxed.hasTag(INT) &&
  1529                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1530                     return thenUnboxed.baseType();
  1532                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1533                     thenUnboxed.hasTag(INT) &&
  1534                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1535                     return elseUnboxed.baseType();
  1538                 for (TypeTag tag : primitiveTags) {
  1539                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1540                     if (types.isSubtype(thenUnboxed, candidate) &&
  1541                         types.isSubtype(elseUnboxed, candidate)) {
  1542                         return candidate;
  1547             // Those were all the cases that could result in a primitive
  1548             if (allowBoxing) {
  1549                 if (thentype.isPrimitive())
  1550                     thentype = types.boxedClass(thentype).type;
  1551                 if (elsetype.isPrimitive())
  1552                     elsetype = types.boxedClass(elsetype).type;
  1555             if (types.isSubtype(thentype, elsetype))
  1556                 return elsetype.baseType();
  1557             if (types.isSubtype(elsetype, thentype))
  1558                 return thentype.baseType();
  1560             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1561                 log.error(pos, "neither.conditional.subtype",
  1562                           thentype, elsetype);
  1563                 return thentype.baseType();
  1566             // both are known to be reference types.  The result is
  1567             // lub(thentype,elsetype). This cannot fail, as it will
  1568             // always be possible to infer "Object" if nothing better.
  1569             return types.lub(thentype.baseType(), elsetype.baseType());
  1572     final static TypeTag[] primitiveTags = new TypeTag[]{
  1573         BYTE,
  1574         CHAR,
  1575         SHORT,
  1576         INT,
  1577         LONG,
  1578         FLOAT,
  1579         DOUBLE,
  1580         BOOLEAN,
  1581     };
  1583     public void visitIf(JCIf tree) {
  1584         attribExpr(tree.cond, env, syms.booleanType);
  1585         attribStat(tree.thenpart, env);
  1586         if (tree.elsepart != null)
  1587             attribStat(tree.elsepart, env);
  1588         chk.checkEmptyIf(tree);
  1589         result = null;
  1592     public void visitExec(JCExpressionStatement tree) {
  1593         //a fresh environment is required for 292 inference to work properly ---
  1594         //see Infer.instantiatePolymorphicSignatureInstance()
  1595         Env<AttrContext> localEnv = env.dup(tree);
  1596         attribExpr(tree.expr, localEnv);
  1597         result = null;
  1600     public void visitBreak(JCBreak tree) {
  1601         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1602         result = null;
  1605     public void visitContinue(JCContinue tree) {
  1606         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1607         result = null;
  1609     //where
  1610         /** Return the target of a break or continue statement, if it exists,
  1611          *  report an error if not.
  1612          *  Note: The target of a labelled break or continue is the
  1613          *  (non-labelled) statement tree referred to by the label,
  1614          *  not the tree representing the labelled statement itself.
  1616          *  @param pos     The position to be used for error diagnostics
  1617          *  @param tag     The tag of the jump statement. This is either
  1618          *                 Tree.BREAK or Tree.CONTINUE.
  1619          *  @param label   The label of the jump statement, or null if no
  1620          *                 label is given.
  1621          *  @param env     The environment current at the jump statement.
  1622          */
  1623         private JCTree findJumpTarget(DiagnosticPosition pos,
  1624                                     JCTree.Tag tag,
  1625                                     Name label,
  1626                                     Env<AttrContext> env) {
  1627             // Search environments outwards from the point of jump.
  1628             Env<AttrContext> env1 = env;
  1629             LOOP:
  1630             while (env1 != null) {
  1631                 switch (env1.tree.getTag()) {
  1632                     case LABELLED:
  1633                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1634                         if (label == labelled.label) {
  1635                             // If jump is a continue, check that target is a loop.
  1636                             if (tag == CONTINUE) {
  1637                                 if (!labelled.body.hasTag(DOLOOP) &&
  1638                                         !labelled.body.hasTag(WHILELOOP) &&
  1639                                         !labelled.body.hasTag(FORLOOP) &&
  1640                                         !labelled.body.hasTag(FOREACHLOOP))
  1641                                     log.error(pos, "not.loop.label", label);
  1642                                 // Found labelled statement target, now go inwards
  1643                                 // to next non-labelled tree.
  1644                                 return TreeInfo.referencedStatement(labelled);
  1645                             } else {
  1646                                 return labelled;
  1649                         break;
  1650                     case DOLOOP:
  1651                     case WHILELOOP:
  1652                     case FORLOOP:
  1653                     case FOREACHLOOP:
  1654                         if (label == null) return env1.tree;
  1655                         break;
  1656                     case SWITCH:
  1657                         if (label == null && tag == BREAK) return env1.tree;
  1658                         break;
  1659                     case LAMBDA:
  1660                     case METHODDEF:
  1661                     case CLASSDEF:
  1662                         break LOOP;
  1663                     default:
  1665                 env1 = env1.next;
  1667             if (label != null)
  1668                 log.error(pos, "undef.label", label);
  1669             else if (tag == CONTINUE)
  1670                 log.error(pos, "cont.outside.loop");
  1671             else
  1672                 log.error(pos, "break.outside.switch.loop");
  1673             return null;
  1676     public void visitReturn(JCReturn tree) {
  1677         // Check that there is an enclosing method which is
  1678         // nested within than the enclosing class.
  1679         if (env.info.returnResult == null) {
  1680             log.error(tree.pos(), "ret.outside.meth");
  1681         } else {
  1682             // Attribute return expression, if it exists, and check that
  1683             // it conforms to result type of enclosing method.
  1684             if (tree.expr != null) {
  1685                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1686                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1687                               diags.fragment("unexpected.ret.val"));
  1689                 attribTree(tree.expr, env, env.info.returnResult);
  1690             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1691                     !env.info.returnResult.pt.hasTag(NONE)) {
  1692                 env.info.returnResult.checkContext.report(tree.pos(),
  1693                               diags.fragment("missing.ret.val"));
  1696         result = null;
  1699     public void visitThrow(JCThrow tree) {
  1700         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1701         if (allowPoly) {
  1702             chk.checkType(tree, owntype, syms.throwableType);
  1704         result = null;
  1707     public void visitAssert(JCAssert tree) {
  1708         attribExpr(tree.cond, env, syms.booleanType);
  1709         if (tree.detail != null) {
  1710             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1712         result = null;
  1715      /** Visitor method for method invocations.
  1716      *  NOTE: The method part of an application will have in its type field
  1717      *        the return type of the method, not the method's type itself!
  1718      */
  1719     public void visitApply(JCMethodInvocation tree) {
  1720         // The local environment of a method application is
  1721         // a new environment nested in the current one.
  1722         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1724         // The types of the actual method arguments.
  1725         List<Type> argtypes;
  1727         // The types of the actual method type arguments.
  1728         List<Type> typeargtypes = null;
  1730         Name methName = TreeInfo.name(tree.meth);
  1732         boolean isConstructorCall =
  1733             methName == names._this || methName == names._super;
  1735         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1736         if (isConstructorCall) {
  1737             // We are seeing a ...this(...) or ...super(...) call.
  1738             // Check that this is the first statement in a constructor.
  1739             if (checkFirstConstructorStat(tree, env)) {
  1741                 // Record the fact
  1742                 // that this is a constructor call (using isSelfCall).
  1743                 localEnv.info.isSelfCall = true;
  1745                 // Attribute arguments, yielding list of argument types.
  1746                 attribArgs(tree.args, localEnv, argtypesBuf);
  1747                 argtypes = argtypesBuf.toList();
  1748                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1750                 // Variable `site' points to the class in which the called
  1751                 // constructor is defined.
  1752                 Type site = env.enclClass.sym.type;
  1753                 if (methName == names._super) {
  1754                     if (site == syms.objectType) {
  1755                         log.error(tree.meth.pos(), "no.superclass", site);
  1756                         site = types.createErrorType(syms.objectType);
  1757                     } else {
  1758                         site = types.supertype(site);
  1762                 if (site.hasTag(CLASS)) {
  1763                     Type encl = site.getEnclosingType();
  1764                     while (encl != null && encl.hasTag(TYPEVAR))
  1765                         encl = encl.getUpperBound();
  1766                     if (encl.hasTag(CLASS)) {
  1767                         // we are calling a nested class
  1769                         if (tree.meth.hasTag(SELECT)) {
  1770                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1772                             // We are seeing a prefixed call, of the form
  1773                             //     <expr>.super(...).
  1774                             // Check that the prefix expression conforms
  1775                             // to the outer instance type of the class.
  1776                             chk.checkRefType(qualifier.pos(),
  1777                                              attribExpr(qualifier, localEnv,
  1778                                                         encl));
  1779                         } else if (methName == names._super) {
  1780                             // qualifier omitted; check for existence
  1781                             // of an appropriate implicit qualifier.
  1782                             rs.resolveImplicitThis(tree.meth.pos(),
  1783                                                    localEnv, site, true);
  1785                     } else if (tree.meth.hasTag(SELECT)) {
  1786                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1787                                   site.tsym);
  1790                     // if we're calling a java.lang.Enum constructor,
  1791                     // prefix the implicit String and int parameters
  1792                     if (site.tsym == syms.enumSym && allowEnums)
  1793                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1795                     // Resolve the called constructor under the assumption
  1796                     // that we are referring to a superclass instance of the
  1797                     // current instance (JLS ???).
  1798                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1799                     localEnv.info.selectSuper = true;
  1800                     localEnv.info.pendingResolutionPhase = null;
  1801                     Symbol sym = rs.resolveConstructor(
  1802                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1803                     localEnv.info.selectSuper = selectSuperPrev;
  1805                     // Set method symbol to resolved constructor...
  1806                     TreeInfo.setSymbol(tree.meth, sym);
  1808                     // ...and check that it is legal in the current context.
  1809                     // (this will also set the tree's type)
  1810                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1811                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1813                 // Otherwise, `site' is an error type and we do nothing
  1815             result = tree.type = syms.voidType;
  1816         } else {
  1817             // Otherwise, we are seeing a regular method call.
  1818             // Attribute the arguments, yielding list of argument types, ...
  1819             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1820             argtypes = argtypesBuf.toList();
  1821             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1823             // ... and attribute the method using as a prototype a methodtype
  1824             // whose formal argument types is exactly the list of actual
  1825             // arguments (this will also set the method symbol).
  1826             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1827             localEnv.info.pendingResolutionPhase = null;
  1828             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1830             // Compute the result type.
  1831             Type restype = mtype.getReturnType();
  1832             if (restype.hasTag(WILDCARD))
  1833                 throw new AssertionError(mtype);
  1835             Type qualifier = (tree.meth.hasTag(SELECT))
  1836                     ? ((JCFieldAccess) tree.meth).selected.type
  1837                     : env.enclClass.sym.type;
  1838             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1840             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1842             // Check that value of resulting type is admissible in the
  1843             // current context.  Also, capture the return type
  1844             result = check(tree, capture(restype), VAL, resultInfo);
  1846         chk.validate(tree.typeargs, localEnv);
  1848     //where
  1849         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1850             if (allowCovariantReturns &&
  1851                     methodName == names.clone &&
  1852                 types.isArray(qualifierType)) {
  1853                 // as a special case, array.clone() has a result that is
  1854                 // the same as static type of the array being cloned
  1855                 return qualifierType;
  1856             } else if (allowGenerics &&
  1857                     methodName == names.getClass &&
  1858                     argtypes.isEmpty()) {
  1859                 // as a special case, x.getClass() has type Class<? extends |X|>
  1860                 return new ClassType(restype.getEnclosingType(),
  1861                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1862                                                                BoundKind.EXTENDS,
  1863                                                                syms.boundClass)),
  1864                               restype.tsym);
  1865             } else {
  1866                 return restype;
  1870         /** Check that given application node appears as first statement
  1871          *  in a constructor call.
  1872          *  @param tree   The application node
  1873          *  @param env    The environment current at the application.
  1874          */
  1875         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1876             JCMethodDecl enclMethod = env.enclMethod;
  1877             if (enclMethod != null && enclMethod.name == names.init) {
  1878                 JCBlock body = enclMethod.body;
  1879                 if (body.stats.head.hasTag(EXEC) &&
  1880                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1881                     return true;
  1883             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1884                       TreeInfo.name(tree.meth));
  1885             return false;
  1888         /** Obtain a method type with given argument types.
  1889          */
  1890         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1891             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1892             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1895     public void visitNewClass(final JCNewClass tree) {
  1896         Type owntype = types.createErrorType(tree.type);
  1898         // The local environment of a class creation is
  1899         // a new environment nested in the current one.
  1900         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1902         // The anonymous inner class definition of the new expression,
  1903         // if one is defined by it.
  1904         JCClassDecl cdef = tree.def;
  1906         // If enclosing class is given, attribute it, and
  1907         // complete class name to be fully qualified
  1908         JCExpression clazz = tree.clazz; // Class field following new
  1909         JCExpression clazzid;            // Identifier in class field
  1910         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1911         annoclazzid = null;
  1913         if (clazz.hasTag(TYPEAPPLY)) {
  1914             clazzid = ((JCTypeApply) clazz).clazz;
  1915             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1916                 annoclazzid = (JCAnnotatedType) clazzid;
  1917                 clazzid = annoclazzid.underlyingType;
  1919         } else {
  1920             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1921                 annoclazzid = (JCAnnotatedType) clazz;
  1922                 clazzid = annoclazzid.underlyingType;
  1923             } else {
  1924                 clazzid = clazz;
  1928         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1930         if (tree.encl != null) {
  1931             // We are seeing a qualified new, of the form
  1932             //    <expr>.new C <...> (...) ...
  1933             // In this case, we let clazz stand for the name of the
  1934             // allocated class C prefixed with the type of the qualifier
  1935             // expression, so that we can
  1936             // resolve it with standard techniques later. I.e., if
  1937             // <expr> has type T, then <expr>.new C <...> (...)
  1938             // yields a clazz T.C.
  1939             Type encltype = chk.checkRefType(tree.encl.pos(),
  1940                                              attribExpr(tree.encl, env));
  1941             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1942             // from expr to the combined type, or not? Yes, do this.
  1943             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1944                                                  ((JCIdent) clazzid).name);
  1946             EndPosTable endPosTable = this.env.toplevel.endPositions;
  1947             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  1948             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1949                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1950                 List<JCAnnotation> annos = annoType.annotations;
  1952                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1953                     clazzid1 = make.at(tree.pos).
  1954                         TypeApply(clazzid1,
  1955                                   ((JCTypeApply) clazz).arguments);
  1958                 clazzid1 = make.at(tree.pos).
  1959                     AnnotatedType(annos, clazzid1);
  1960             } else if (clazz.hasTag(TYPEAPPLY)) {
  1961                 clazzid1 = make.at(tree.pos).
  1962                     TypeApply(clazzid1,
  1963                               ((JCTypeApply) clazz).arguments);
  1966             clazz = clazzid1;
  1969         // Attribute clazz expression and store
  1970         // symbol + type back into the attributed tree.
  1971         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1972             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1973             attribType(clazz, env);
  1975         clazztype = chk.checkDiamond(tree, clazztype);
  1976         chk.validate(clazz, localEnv);
  1977         if (tree.encl != null) {
  1978             // We have to work in this case to store
  1979             // symbol + type back into the attributed tree.
  1980             tree.clazz.type = clazztype;
  1981             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1982             clazzid.type = ((JCIdent) clazzid).sym.type;
  1983             if (annoclazzid != null) {
  1984                 annoclazzid.type = clazzid.type;
  1986             if (!clazztype.isErroneous()) {
  1987                 if (cdef != null && clazztype.tsym.isInterface()) {
  1988                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1989                 } else if (clazztype.tsym.isStatic()) {
  1990                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1993         } else if (!clazztype.tsym.isInterface() &&
  1994                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1995             // Check for the existence of an apropos outer instance
  1996             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1999         // Attribute constructor arguments.
  2000         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  2001         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  2002         List<Type> argtypes = argtypesBuf.toList();
  2003         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  2005         // If we have made no mistakes in the class type...
  2006         if (clazztype.hasTag(CLASS)) {
  2007             // Enums may not be instantiated except implicitly
  2008             if (allowEnums &&
  2009                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  2010                 (!env.tree.hasTag(VARDEF) ||
  2011                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  2012                  ((JCVariableDecl) env.tree).init != tree))
  2013                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2014             // Check that class is not abstract
  2015             if (cdef == null &&
  2016                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2017                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2018                           clazztype.tsym);
  2019             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2020                 // Check that no constructor arguments are given to
  2021                 // anonymous classes implementing an interface
  2022                 if (!argtypes.isEmpty())
  2023                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2025                 if (!typeargtypes.isEmpty())
  2026                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2028                 // Error recovery: pretend no arguments were supplied.
  2029                 argtypes = List.nil();
  2030                 typeargtypes = List.nil();
  2031             } else if (TreeInfo.isDiamond(tree)) {
  2032                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2033                             clazztype.tsym.type.getTypeArguments(),
  2034                             clazztype.tsym);
  2036                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2037                 diamondEnv.info.selectSuper = cdef != null;
  2038                 diamondEnv.info.pendingResolutionPhase = null;
  2040                 //if the type of the instance creation expression is a class type
  2041                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2042                 //of the resolved constructor will be a partially instantiated type
  2043                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2044                             diamondEnv,
  2045                             site,
  2046                             argtypes,
  2047                             typeargtypes);
  2048                 tree.constructor = constructor.baseSymbol();
  2050                 final TypeSymbol csym = clazztype.tsym;
  2051                 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2052                     @Override
  2053                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2054                         enclosingContext.report(tree.clazz,
  2055                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2057                 });
  2058                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2059                 constructorType = checkId(tree, site,
  2060                         constructor,
  2061                         diamondEnv,
  2062                         diamondResult);
  2064                 tree.clazz.type = types.createErrorType(clazztype);
  2065                 if (!constructorType.isErroneous()) {
  2066                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2067                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2069                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2072             // Resolve the called constructor under the assumption
  2073             // that we are referring to a superclass instance of the
  2074             // current instance (JLS ???).
  2075             else {
  2076                 //the following code alters some of the fields in the current
  2077                 //AttrContext - hence, the current context must be dup'ed in
  2078                 //order to avoid downstream failures
  2079                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2080                 rsEnv.info.selectSuper = cdef != null;
  2081                 rsEnv.info.pendingResolutionPhase = null;
  2082                 tree.constructor = rs.resolveConstructor(
  2083                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2084                 if (cdef == null) { //do not check twice!
  2085                     tree.constructorType = checkId(tree,
  2086                             clazztype,
  2087                             tree.constructor,
  2088                             rsEnv,
  2089                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2090                     if (rsEnv.info.lastResolveVarargs())
  2091                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2093                 if (cdef == null &&
  2094                         !clazztype.isErroneous() &&
  2095                         clazztype.getTypeArguments().nonEmpty() &&
  2096                         findDiamonds) {
  2097                     findDiamond(localEnv, tree, clazztype);
  2101             if (cdef != null) {
  2102                 // We are seeing an anonymous class instance creation.
  2103                 // In this case, the class instance creation
  2104                 // expression
  2105                 //
  2106                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2107                 //
  2108                 // is represented internally as
  2109                 //
  2110                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2111                 //
  2112                 // This expression is then *transformed* as follows:
  2113                 //
  2114                 // (1) add a STATIC flag to the class definition
  2115                 //     if the current environment is static
  2116                 // (2) add an extends or implements clause
  2117                 // (3) add a constructor.
  2118                 //
  2119                 // For instance, if C is a class, and ET is the type of E,
  2120                 // the expression
  2121                 //
  2122                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2123                 //
  2124                 // is translated to (where X is a fresh name and typarams is the
  2125                 // parameter list of the super constructor):
  2126                 //
  2127                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2128                 //     X extends C<typargs2> {
  2129                 //       <typarams> X(ET e, args) {
  2130                 //         e.<typeargs1>super(args)
  2131                 //       }
  2132                 //       ...
  2133                 //     }
  2134                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2136                 if (clazztype.tsym.isInterface()) {
  2137                     cdef.implementing = List.of(clazz);
  2138                 } else {
  2139                     cdef.extending = clazz;
  2142                 attribStat(cdef, localEnv);
  2144                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2146                 // If an outer instance is given,
  2147                 // prefix it to the constructor arguments
  2148                 // and delete it from the new expression
  2149                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2150                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2151                     argtypes = argtypes.prepend(tree.encl.type);
  2152                     tree.encl = null;
  2155                 // Reassign clazztype and recompute constructor.
  2156                 clazztype = cdef.sym.type;
  2157                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2158                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2159                 Assert.check(sym.kind < AMBIGUOUS);
  2160                 tree.constructor = sym;
  2161                 tree.constructorType = checkId(tree,
  2162                     clazztype,
  2163                     tree.constructor,
  2164                     localEnv,
  2165                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2168             if (tree.constructor != null && tree.constructor.kind == MTH)
  2169                 owntype = clazztype;
  2171         result = check(tree, owntype, VAL, resultInfo);
  2172         chk.validate(tree.typeargs, localEnv);
  2174     //where
  2175         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2176             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2177             List<JCExpression> prevTypeargs = ta.arguments;
  2178             try {
  2179                 //create a 'fake' diamond AST node by removing type-argument trees
  2180                 ta.arguments = List.nil();
  2181                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2182                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2183                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2184                 Type polyPt = allowPoly ?
  2185                         syms.objectType :
  2186                         clazztype;
  2187                 if (!inferred.isErroneous() &&
  2188                     (allowPoly && pt() == Infer.anyPoly ?
  2189                         types.isSameType(inferred, clazztype) :
  2190                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
  2191                     String key = types.isSameType(clazztype, inferred) ?
  2192                         "diamond.redundant.args" :
  2193                         "diamond.redundant.args.1";
  2194                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2196             } finally {
  2197                 ta.arguments = prevTypeargs;
  2201             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2202                 if (allowLambda &&
  2203                         identifyLambdaCandidate &&
  2204                         clazztype.hasTag(CLASS) &&
  2205                         !pt().hasTag(NONE) &&
  2206                         types.isFunctionalInterface(clazztype.tsym)) {
  2207                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2208                     int count = 0;
  2209                     boolean found = false;
  2210                     for (Symbol sym : csym.members().getElements()) {
  2211                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2212                                 sym.isConstructor()) continue;
  2213                         count++;
  2214                         if (sym.kind != MTH ||
  2215                                 !sym.name.equals(descriptor.name)) continue;
  2216                         Type mtype = types.memberType(clazztype, sym);
  2217                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2218                             found = true;
  2221                     if (found && count == 1) {
  2222                         log.note(tree.def, "potential.lambda.found");
  2227     /** Make an attributed null check tree.
  2228      */
  2229     public JCExpression makeNullCheck(JCExpression arg) {
  2230         // optimization: X.this is never null; skip null check
  2231         Name name = TreeInfo.name(arg);
  2232         if (name == names._this || name == names._super) return arg;
  2234         JCTree.Tag optag = NULLCHK;
  2235         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2236         tree.operator = syms.nullcheck;
  2237         tree.type = arg.type;
  2238         return tree;
  2241     public void visitNewArray(JCNewArray tree) {
  2242         Type owntype = types.createErrorType(tree.type);
  2243         Env<AttrContext> localEnv = env.dup(tree);
  2244         Type elemtype;
  2245         if (tree.elemtype != null) {
  2246             elemtype = attribType(tree.elemtype, localEnv);
  2247             chk.validate(tree.elemtype, localEnv);
  2248             owntype = elemtype;
  2249             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2250                 attribExpr(l.head, localEnv, syms.intType);
  2251                 owntype = new ArrayType(owntype, syms.arrayClass);
  2253         } else {
  2254             // we are seeing an untyped aggregate { ... }
  2255             // this is allowed only if the prototype is an array
  2256             if (pt().hasTag(ARRAY)) {
  2257                 elemtype = types.elemtype(pt());
  2258             } else {
  2259                 if (!pt().hasTag(ERROR)) {
  2260                     log.error(tree.pos(), "illegal.initializer.for.type",
  2261                               pt());
  2263                 elemtype = types.createErrorType(pt());
  2266         if (tree.elems != null) {
  2267             attribExprs(tree.elems, localEnv, elemtype);
  2268             owntype = new ArrayType(elemtype, syms.arrayClass);
  2270         if (!types.isReifiable(elemtype))
  2271             log.error(tree.pos(), "generic.array.creation");
  2272         result = check(tree, owntype, VAL, resultInfo);
  2275     /*
  2276      * A lambda expression can only be attributed when a target-type is available.
  2277      * In addition, if the target-type is that of a functional interface whose
  2278      * descriptor contains inference variables in argument position the lambda expression
  2279      * is 'stuck' (see DeferredAttr).
  2280      */
  2281     @Override
  2282     public void visitLambda(final JCLambda that) {
  2283         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2284             if (pt().hasTag(NONE)) {
  2285                 //lambda only allowed in assignment or method invocation/cast context
  2286                 log.error(that.pos(), "unexpected.lambda");
  2288             result = that.type = types.createErrorType(pt());
  2289             return;
  2291         //create an environment for attribution of the lambda expression
  2292         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2293         boolean needsRecovery =
  2294                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2295         try {
  2296             Type currentTarget = pt();
  2297             List<Type> explicitParamTypes = null;
  2298             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2299                 //attribute lambda parameters
  2300                 attribStats(that.params, localEnv);
  2301                 explicitParamTypes = TreeInfo.types(that.params);
  2304             Type lambdaType;
  2305             if (pt() != Type.recoveryType) {
  2306                 /* We need to adjust the target. If the target is an
  2307                  * intersection type, for example: SAM & I1 & I2 ...
  2308                  * the target will be updated to SAM
  2309                  */
  2310                 currentTarget = targetChecker.visit(currentTarget, that);
  2311                 if (explicitParamTypes != null) {
  2312                     currentTarget = infer.instantiateFunctionalInterface(that,
  2313                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2315                 lambdaType = types.findDescriptorType(currentTarget);
  2316             } else {
  2317                 currentTarget = Type.recoveryType;
  2318                 lambdaType = fallbackDescriptorType(that);
  2321             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2323             if (lambdaType.hasTag(FORALL)) {
  2324                 //lambda expression target desc cannot be a generic method
  2325                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2326                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2327                 result = that.type = types.createErrorType(pt());
  2328                 return;
  2331             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2332                 //add param type info in the AST
  2333                 List<Type> actuals = lambdaType.getParameterTypes();
  2334                 List<JCVariableDecl> params = that.params;
  2336                 boolean arityMismatch = false;
  2338                 while (params.nonEmpty()) {
  2339                     if (actuals.isEmpty()) {
  2340                         //not enough actuals to perform lambda parameter inference
  2341                         arityMismatch = true;
  2343                     //reset previously set info
  2344                     Type argType = arityMismatch ?
  2345                             syms.errType :
  2346                             actuals.head;
  2347                     params.head.vartype = make.at(params.head).Type(argType);
  2348                     params.head.sym = null;
  2349                     actuals = actuals.isEmpty() ?
  2350                             actuals :
  2351                             actuals.tail;
  2352                     params = params.tail;
  2355                 //attribute lambda parameters
  2356                 attribStats(that.params, localEnv);
  2358                 if (arityMismatch) {
  2359                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2360                         result = that.type = types.createErrorType(currentTarget);
  2361                         return;
  2365             //from this point on, no recovery is needed; if we are in assignment context
  2366             //we will be able to attribute the whole lambda body, regardless of errors;
  2367             //if we are in a 'check' method context, and the lambda is not compatible
  2368             //with the target-type, it will be recovered anyway in Attr.checkId
  2369             needsRecovery = false;
  2371             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2372                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2373                     new FunctionalReturnContext(resultInfo.checkContext);
  2375             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2376                 recoveryInfo :
  2377                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2378             localEnv.info.returnResult = bodyResultInfo;
  2380             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2381                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2382             } else {
  2383                 JCBlock body = (JCBlock)that.body;
  2384                 attribStats(body.stats, localEnv);
  2387             result = check(that, currentTarget, VAL, resultInfo);
  2389             boolean isSpeculativeRound =
  2390                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2392             preFlow(that);
  2393             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2395             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2397             if (!isSpeculativeRound) {
  2398                 //add thrown types as bounds to the thrown types free variables if needed:
  2399                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2400                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2401                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asFree(lambdaType.getThrownTypes());
  2403                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2406                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2408             result = check(that, currentTarget, VAL, resultInfo);
  2409         } catch (Types.FunctionDescriptorLookupError ex) {
  2410             JCDiagnostic cause = ex.getDiagnostic();
  2411             resultInfo.checkContext.report(that, cause);
  2412             result = that.type = types.createErrorType(pt());
  2413             return;
  2414         } finally {
  2415             localEnv.info.scope.leave();
  2416             if (needsRecovery) {
  2417                 attribTree(that, env, recoveryInfo);
  2421     //where
  2422         void preFlow(JCLambda tree) {
  2423             new PostAttrAnalyzer() {
  2424                 @Override
  2425                 public void scan(JCTree tree) {
  2426                     if (tree == null ||
  2427                             (tree.type != null &&
  2428                             tree.type == Type.stuckType)) {
  2429                         //don't touch stuck expressions!
  2430                         return;
  2432                     super.scan(tree);
  2434             }.scan(tree);
  2437         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2439             @Override
  2440             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2441                 return t.isCompound() ?
  2442                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2445             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2446                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2447                 Type target = null;
  2448                 for (Type bound : ict.getExplicitComponents()) {
  2449                     TypeSymbol boundSym = bound.tsym;
  2450                     if (types.isFunctionalInterface(boundSym) &&
  2451                             types.findDescriptorSymbol(boundSym) == desc) {
  2452                         target = bound;
  2453                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2454                         //bound must be an interface
  2455                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2458                 return target != null ?
  2459                         target :
  2460                         ict.getExplicitComponents().head; //error recovery
  2463             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2464                 ListBuffer<Type> targs = new ListBuffer<>();
  2465                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2466                 for (Type i : ict.interfaces_field) {
  2467                     if (i.isParameterized()) {
  2468                         targs.appendList(i.tsym.type.allparams());
  2470                     supertypes.append(i.tsym.type);
  2472                 IntersectionClassType notionalIntf =
  2473                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2474                 notionalIntf.allparams_field = targs.toList();
  2475                 notionalIntf.tsym.flags_field |= INTERFACE;
  2476                 return notionalIntf.tsym;
  2479             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2480                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2481                         diags.fragment(key, args)));
  2483         };
  2485         private Type fallbackDescriptorType(JCExpression tree) {
  2486             switch (tree.getTag()) {
  2487                 case LAMBDA:
  2488                     JCLambda lambda = (JCLambda)tree;
  2489                     List<Type> argtypes = List.nil();
  2490                     for (JCVariableDecl param : lambda.params) {
  2491                         argtypes = param.vartype != null ?
  2492                                 argtypes.append(param.vartype.type) :
  2493                                 argtypes.append(syms.errType);
  2495                     return new MethodType(argtypes, Type.recoveryType,
  2496                             List.of(syms.throwableType), syms.methodClass);
  2497                 case REFERENCE:
  2498                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2499                             List.of(syms.throwableType), syms.methodClass);
  2500                 default:
  2501                     Assert.error("Cannot get here!");
  2503             return null;
  2506         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2507                 final InferenceContext inferenceContext, final Type... ts) {
  2508             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2511         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2512                 final InferenceContext inferenceContext, final List<Type> ts) {
  2513             if (inferenceContext.free(ts)) {
  2514                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2515                     @Override
  2516                     public void typesInferred(InferenceContext inferenceContext) {
  2517                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2519                 });
  2520             } else {
  2521                 for (Type t : ts) {
  2522                     rs.checkAccessibleType(env, t);
  2527         /**
  2528          * Lambda/method reference have a special check context that ensures
  2529          * that i.e. a lambda return type is compatible with the expected
  2530          * type according to both the inherited context and the assignment
  2531          * context.
  2532          */
  2533         class FunctionalReturnContext extends Check.NestedCheckContext {
  2535             FunctionalReturnContext(CheckContext enclosingContext) {
  2536                 super(enclosingContext);
  2539             @Override
  2540             public boolean compatible(Type found, Type req, Warner warn) {
  2541                 //return type must be compatible in both current context and assignment context
  2542                 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
  2545             @Override
  2546             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2547                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2551         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2553             JCExpression expr;
  2555             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2556                 super(enclosingContext);
  2557                 this.expr = expr;
  2560             @Override
  2561             public boolean compatible(Type found, Type req, Warner warn) {
  2562                 //a void return is compatible with an expression statement lambda
  2563                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2564                         super.compatible(found, req, warn);
  2568         /**
  2569         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2570         * are compatible with the expected functional interface descriptor. This means that:
  2571         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2572         * types must be compatible with the return type of the expected descriptor.
  2573         */
  2574         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2575             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2577             //return values have already been checked - but if lambda has no return
  2578             //values, we must ensure that void/value compatibility is correct;
  2579             //this amounts at checking that, if a lambda body can complete normally,
  2580             //the descriptor's return type must be void
  2581             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2582                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2583                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2584                         diags.fragment("missing.ret.val", returnType)));
  2587             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
  2588             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2589                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2593         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
  2594          * static field and that lambda has type annotations, these annotations will
  2595          * also be stored at these fake clinit methods.
  2597          * LambdaToMethod also use fake clinit methods so they can be reused.
  2598          * Also as LTM is a phase subsequent to attribution, the methods from
  2599          * clinits can be safely removed by LTM to save memory.
  2600          */
  2601         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
  2603         public MethodSymbol removeClinit(ClassSymbol sym) {
  2604             return clinits.remove(sym);
  2607         /* This method returns an environment to be used to attribute a lambda
  2608          * expression.
  2610          * The owner of this environment is a method symbol. If the current owner
  2611          * is not a method, for example if the lambda is used to initialize
  2612          * a field, then if the field is:
  2614          * - an instance field, we use the first constructor.
  2615          * - a static field, we create a fake clinit method.
  2616          */
  2617         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2618             Env<AttrContext> lambdaEnv;
  2619             Symbol owner = env.info.scope.owner;
  2620             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2621                 //field initializer
  2622                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2623                 ClassSymbol enclClass = owner.enclClass();
  2624                 /* if the field isn't static, then we can get the first constructor
  2625                  * and use it as the owner of the environment. This is what
  2626                  * LTM code is doing to look for type annotations so we are fine.
  2627                  */
  2628                 if ((owner.flags() & STATIC) == 0) {
  2629                     for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
  2630                         lambdaEnv.info.scope.owner = s;
  2631                         break;
  2633                 } else {
  2634                     /* if the field is static then we need to create a fake clinit
  2635                      * method, this method can later be reused by LTM.
  2636                      */
  2637                     MethodSymbol clinit = clinits.get(enclClass);
  2638                     if (clinit == null) {
  2639                         Type clinitType = new MethodType(List.<Type>nil(),
  2640                                 syms.voidType, List.<Type>nil(), syms.methodClass);
  2641                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
  2642                                 names.clinit, clinitType, enclClass);
  2643                         clinit.params = List.<VarSymbol>nil();
  2644                         clinits.put(enclClass, clinit);
  2646                     lambdaEnv.info.scope.owner = clinit;
  2648             } else {
  2649                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2651             return lambdaEnv;
  2654     @Override
  2655     public void visitReference(final JCMemberReference that) {
  2656         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2657             if (pt().hasTag(NONE)) {
  2658                 //method reference only allowed in assignment or method invocation/cast context
  2659                 log.error(that.pos(), "unexpected.mref");
  2661             result = that.type = types.createErrorType(pt());
  2662             return;
  2664         final Env<AttrContext> localEnv = env.dup(that);
  2665         try {
  2666             //attribute member reference qualifier - if this is a constructor
  2667             //reference, the expected kind must be a type
  2668             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2670             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2671                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2672                 if (!exprType.isErroneous() &&
  2673                     exprType.isRaw() &&
  2674                     that.typeargs != null) {
  2675                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2676                         diags.fragment("mref.infer.and.explicit.params"));
  2677                     exprType = types.createErrorType(exprType);
  2681             if (exprType.isErroneous()) {
  2682                 //if the qualifier expression contains problems,
  2683                 //give up attribution of method reference
  2684                 result = that.type = exprType;
  2685                 return;
  2688             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2689                 //if the qualifier is a type, validate it; raw warning check is
  2690                 //omitted as we don't know at this stage as to whether this is a
  2691                 //raw selector (because of inference)
  2692                 chk.validate(that.expr, env, false);
  2695             //attrib type-arguments
  2696             List<Type> typeargtypes = List.nil();
  2697             if (that.typeargs != null) {
  2698                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2701             Type target;
  2702             Type desc;
  2703             if (pt() != Type.recoveryType) {
  2704                 target = targetChecker.visit(pt(), that);
  2705                 desc = types.findDescriptorType(target);
  2706             } else {
  2707                 target = Type.recoveryType;
  2708                 desc = fallbackDescriptorType(that);
  2711             setFunctionalInfo(localEnv, that, pt(), desc, target, resultInfo.checkContext);
  2712             List<Type> argtypes = desc.getParameterTypes();
  2713             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2715             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2716                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2719             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2720             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2721             try {
  2722                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
  2723                         that.name, argtypes, typeargtypes, referenceCheck,
  2724                         resultInfo.checkContext.inferenceContext(),
  2725                         resultInfo.checkContext.deferredAttrContext().mode);
  2726             } finally {
  2727                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2730             Symbol refSym = refResult.fst;
  2731             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2733             if (refSym.kind != MTH) {
  2734                 boolean targetError;
  2735                 switch (refSym.kind) {
  2736                     case ABSENT_MTH:
  2737                         targetError = false;
  2738                         break;
  2739                     case WRONG_MTH:
  2740                     case WRONG_MTHS:
  2741                     case AMBIGUOUS:
  2742                     case HIDDEN:
  2743                     case STATICERR:
  2744                     case MISSING_ENCL:
  2745                     case WRONG_STATICNESS:
  2746                         targetError = true;
  2747                         break;
  2748                     default:
  2749                         Assert.error("unexpected result kind " + refSym.kind);
  2750                         targetError = false;
  2753                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2754                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2756                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2757                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2759                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2760                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2762                 if (targetError && target == Type.recoveryType) {
  2763                     //a target error doesn't make sense during recovery stage
  2764                     //as we don't know what actual parameter types are
  2765                     result = that.type = target;
  2766                     return;
  2767                 } else {
  2768                     if (targetError) {
  2769                         resultInfo.checkContext.report(that, diag);
  2770                     } else {
  2771                         log.report(diag);
  2773                     result = that.type = types.createErrorType(target);
  2774                     return;
  2778             that.sym = refSym.baseSymbol();
  2779             that.kind = lookupHelper.referenceKind(that.sym);
  2780             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2782             if (desc.getReturnType() == Type.recoveryType) {
  2783                 // stop here
  2784                 result = that.type = target;
  2785                 return;
  2788             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2790                 if (that.getMode() == ReferenceMode.INVOKE &&
  2791                         TreeInfo.isStaticSelector(that.expr, names) &&
  2792                         that.kind.isUnbound() &&
  2793                         !desc.getParameterTypes().head.isParameterized()) {
  2794                     chk.checkRaw(that.expr, localEnv);
  2797                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2798                         exprType.getTypeArguments().nonEmpty()) {
  2799                     //static ref with class type-args
  2800                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2801                             diags.fragment("static.mref.with.targs"));
  2802                     result = that.type = types.createErrorType(target);
  2803                     return;
  2806                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2807                         !that.kind.isUnbound()) {
  2808                     //no static bound mrefs
  2809                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2810                             diags.fragment("static.bound.mref"));
  2811                     result = that.type = types.createErrorType(target);
  2812                     return;
  2815                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2816                     // Check that super-qualified symbols are not abstract (JLS)
  2817                     rs.checkNonAbstract(that.pos(), that.sym);
  2821             ResultInfo checkInfo =
  2822                     resultInfo.dup(newMethodTemplate(
  2823                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2824                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes));
  2826             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2828             if (that.kind.isUnbound() &&
  2829                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2830                 //re-generate inference constraints for unbound receiver
  2831                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asFree(argtypes.head), exprType)) {
  2832                     //cannot happen as this has already been checked - we just need
  2833                     //to regenerate the inference constraints, as that has been lost
  2834                     //as a result of the call to inferenceContext.save()
  2835                     Assert.error("Can't get here");
  2839             if (!refType.isErroneous()) {
  2840                 refType = types.createMethodTypeWithReturn(refType,
  2841                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2844             //go ahead with standard method reference compatibility check - note that param check
  2845             //is a no-op (as this has been taken care during method applicability)
  2846             boolean isSpeculativeRound =
  2847                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2848             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2849             if (!isSpeculativeRound) {
  2850                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2852             result = check(that, target, VAL, resultInfo);
  2853         } catch (Types.FunctionDescriptorLookupError ex) {
  2854             JCDiagnostic cause = ex.getDiagnostic();
  2855             resultInfo.checkContext.report(that, cause);
  2856             result = that.type = types.createErrorType(pt());
  2857             return;
  2860     //where
  2861         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2862             //if this is a constructor reference, the expected kind must be a type
  2863             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2867     @SuppressWarnings("fallthrough")
  2868     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2869         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2871         Type resType;
  2872         switch (tree.getMode()) {
  2873             case NEW:
  2874                 if (!tree.expr.type.isRaw()) {
  2875                     resType = tree.expr.type;
  2876                     break;
  2878             default:
  2879                 resType = refType.getReturnType();
  2882         Type incompatibleReturnType = resType;
  2884         if (returnType.hasTag(VOID)) {
  2885             incompatibleReturnType = null;
  2888         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2889             if (resType.isErroneous() ||
  2890                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2891                 incompatibleReturnType = null;
  2895         if (incompatibleReturnType != null) {
  2896             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2897                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2900         if (!speculativeAttr) {
  2901             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2902             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2903                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2908     /**
  2909      * Set functional type info on the underlying AST. Note: as the target descriptor
  2910      * might contain inference variables, we might need to register an hook in the
  2911      * current inference context.
  2912      */
  2913     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  2914             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  2915         if (checkContext.inferenceContext().free(descriptorType)) {
  2916             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2917                 public void typesInferred(InferenceContext inferenceContext) {
  2918                     setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  2919                             inferenceContext.asInstType(primaryTarget), checkContext);
  2921             });
  2922         } else {
  2923             ListBuffer<Type> targets = new ListBuffer<>();
  2924             if (pt.hasTag(CLASS)) {
  2925                 if (pt.isCompound()) {
  2926                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  2927                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2928                         if (t != primaryTarget) {
  2929                             targets.append(types.removeWildcards(t));
  2932                 } else {
  2933                     targets.append(types.removeWildcards(primaryTarget));
  2936             fExpr.targets = targets.toList();
  2937             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2938                     pt != Type.recoveryType) {
  2939                 //check that functional interface class is well-formed
  2940                 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
  2941                         names.empty, List.of(fExpr.targets.head), ABSTRACT);
  2942                 if (csym != null) {
  2943                     chk.checkImplementations(env.tree, csym, csym);
  2949     public void visitParens(JCParens tree) {
  2950         Type owntype = attribTree(tree.expr, env, resultInfo);
  2951         result = check(tree, owntype, pkind(), resultInfo);
  2952         Symbol sym = TreeInfo.symbol(tree);
  2953         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2954             log.error(tree.pos(), "illegal.start.of.type");
  2957     public void visitAssign(JCAssign tree) {
  2958         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2959         Type capturedType = capture(owntype);
  2960         attribExpr(tree.rhs, env, owntype);
  2961         result = check(tree, capturedType, VAL, resultInfo);
  2964     public void visitAssignop(JCAssignOp tree) {
  2965         // Attribute arguments.
  2966         Type owntype = attribTree(tree.lhs, env, varInfo);
  2967         Type operand = attribExpr(tree.rhs, env);
  2968         // Find operator.
  2969         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2970             tree.pos(), tree.getTag().noAssignOp(), env,
  2971             owntype, operand);
  2973         if (operator.kind == MTH &&
  2974                 !owntype.isErroneous() &&
  2975                 !operand.isErroneous()) {
  2976             chk.checkOperator(tree.pos(),
  2977                               (OperatorSymbol)operator,
  2978                               tree.getTag().noAssignOp(),
  2979                               owntype,
  2980                               operand);
  2981             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2982             chk.checkCastable(tree.rhs.pos(),
  2983                               operator.type.getReturnType(),
  2984                               owntype);
  2986         result = check(tree, owntype, VAL, resultInfo);
  2989     public void visitUnary(JCUnary tree) {
  2990         // Attribute arguments.
  2991         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2992             ? attribTree(tree.arg, env, varInfo)
  2993             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2995         // Find operator.
  2996         Symbol operator = tree.operator =
  2997             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2999         Type owntype = types.createErrorType(tree.type);
  3000         if (operator.kind == MTH &&
  3001                 !argtype.isErroneous()) {
  3002             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3003                 ? tree.arg.type
  3004                 : operator.type.getReturnType();
  3005             int opc = ((OperatorSymbol)operator).opcode;
  3007             // If the argument is constant, fold it.
  3008             if (argtype.constValue() != null) {
  3009                 Type ctype = cfolder.fold1(opc, argtype);
  3010                 if (ctype != null) {
  3011                     owntype = cfolder.coerce(ctype, owntype);
  3013                     // Remove constant types from arguments to
  3014                     // conserve space. The parser will fold concatenations
  3015                     // of string literals; the code here also
  3016                     // gets rid of intermediate results when some of the
  3017                     // operands are constant identifiers.
  3018                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  3019                         tree.arg.type = syms.stringType;
  3024         result = check(tree, owntype, VAL, resultInfo);
  3027     public void visitBinary(JCBinary tree) {
  3028         // Attribute arguments.
  3029         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3030         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3032         // Find operator.
  3033         Symbol operator = tree.operator =
  3034             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3036         Type owntype = types.createErrorType(tree.type);
  3037         if (operator.kind == MTH &&
  3038                 !left.isErroneous() &&
  3039                 !right.isErroneous()) {
  3040             owntype = operator.type.getReturnType();
  3041             // This will figure out when unboxing can happen and
  3042             // choose the right comparison operator.
  3043             int opc = chk.checkOperator(tree.lhs.pos(),
  3044                                         (OperatorSymbol)operator,
  3045                                         tree.getTag(),
  3046                                         left,
  3047                                         right);
  3049             // If both arguments are constants, fold them.
  3050             if (left.constValue() != null && right.constValue() != null) {
  3051                 Type ctype = cfolder.fold2(opc, left, right);
  3052                 if (ctype != null) {
  3053                     owntype = cfolder.coerce(ctype, owntype);
  3055                     // Remove constant types from arguments to
  3056                     // conserve space. The parser will fold concatenations
  3057                     // of string literals; the code here also
  3058                     // gets rid of intermediate results when some of the
  3059                     // operands are constant identifiers.
  3060                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  3061                         tree.lhs.type = syms.stringType;
  3063                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  3064                         tree.rhs.type = syms.stringType;
  3069             // Check that argument types of a reference ==, != are
  3070             // castable to each other, (JLS 15.21).  Note: unboxing
  3071             // comparisons will not have an acmp* opc at this point.
  3072             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3073                 if (!types.isEqualityComparable(left, right,
  3074                                                 new Warner(tree.pos()))) {
  3075                     log.error(tree.pos(), "incomparable.types", left, right);
  3079             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3081         result = check(tree, owntype, VAL, resultInfo);
  3084     public void visitTypeCast(final JCTypeCast tree) {
  3085         Type clazztype = attribType(tree.clazz, env);
  3086         chk.validate(tree.clazz, env, false);
  3087         //a fresh environment is required for 292 inference to work properly ---
  3088         //see Infer.instantiatePolymorphicSignatureInstance()
  3089         Env<AttrContext> localEnv = env.dup(tree);
  3090         //should we propagate the target type?
  3091         final ResultInfo castInfo;
  3092         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3093         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3094         if (isPoly) {
  3095             //expression is a poly - we need to propagate target type info
  3096             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3097                 @Override
  3098                 public boolean compatible(Type found, Type req, Warner warn) {
  3099                     return types.isCastable(found, req, warn);
  3101             });
  3102         } else {
  3103             //standalone cast - target-type info is not propagated
  3104             castInfo = unknownExprInfo;
  3106         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3107         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3108         if (exprtype.constValue() != null)
  3109             owntype = cfolder.coerce(exprtype, owntype);
  3110         result = check(tree, capture(owntype), VAL, resultInfo);
  3111         if (!isPoly)
  3112             chk.checkRedundantCast(localEnv, tree);
  3115     public void visitTypeTest(JCInstanceOf tree) {
  3116         Type exprtype = chk.checkNullOrRefType(
  3117             tree.expr.pos(), attribExpr(tree.expr, env));
  3118         Type clazztype = attribType(tree.clazz, env);
  3119         if (!clazztype.hasTag(TYPEVAR)) {
  3120             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3122         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3123             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3124             clazztype = types.createErrorType(clazztype);
  3126         chk.validate(tree.clazz, env, false);
  3127         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3128         result = check(tree, syms.booleanType, VAL, resultInfo);
  3131     public void visitIndexed(JCArrayAccess tree) {
  3132         Type owntype = types.createErrorType(tree.type);
  3133         Type atype = attribExpr(tree.indexed, env);
  3134         attribExpr(tree.index, env, syms.intType);
  3135         if (types.isArray(atype))
  3136             owntype = types.elemtype(atype);
  3137         else if (!atype.hasTag(ERROR))
  3138             log.error(tree.pos(), "array.req.but.found", atype);
  3139         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3140         result = check(tree, owntype, VAR, resultInfo);
  3143     public void visitIdent(JCIdent tree) {
  3144         Symbol sym;
  3146         // Find symbol
  3147         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3148             // If we are looking for a method, the prototype `pt' will be a
  3149             // method type with the type of the call's arguments as parameters.
  3150             env.info.pendingResolutionPhase = null;
  3151             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3152         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3153             sym = tree.sym;
  3154         } else {
  3155             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3157         tree.sym = sym;
  3159         // (1) Also find the environment current for the class where
  3160         //     sym is defined (`symEnv').
  3161         // Only for pre-tiger versions (1.4 and earlier):
  3162         // (2) Also determine whether we access symbol out of an anonymous
  3163         //     class in a this or super call.  This is illegal for instance
  3164         //     members since such classes don't carry a this$n link.
  3165         //     (`noOuterThisPath').
  3166         Env<AttrContext> symEnv = env;
  3167         boolean noOuterThisPath = false;
  3168         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3169             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3170             sym.owner.kind == TYP &&
  3171             tree.name != names._this && tree.name != names._super) {
  3173             // Find environment in which identifier is defined.
  3174             while (symEnv.outer != null &&
  3175                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3176                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3177                     noOuterThisPath = !allowAnonOuterThis;
  3178                 symEnv = symEnv.outer;
  3182         // If symbol is a variable, ...
  3183         if (sym.kind == VAR) {
  3184             VarSymbol v = (VarSymbol)sym;
  3186             // ..., evaluate its initializer, if it has one, and check for
  3187             // illegal forward reference.
  3188             checkInit(tree, env, v, false);
  3190             // If we are expecting a variable (as opposed to a value), check
  3191             // that the variable is assignable in the current environment.
  3192             if (pkind() == VAR)
  3193                 checkAssignable(tree.pos(), v, null, env);
  3196         // In a constructor body,
  3197         // if symbol is a field or instance method, check that it is
  3198         // not accessed before the supertype constructor is called.
  3199         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3200             (sym.kind & (VAR | MTH)) != 0 &&
  3201             sym.owner.kind == TYP &&
  3202             (sym.flags() & STATIC) == 0) {
  3203             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3205         Env<AttrContext> env1 = env;
  3206         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3207             // If the found symbol is inaccessible, then it is
  3208             // accessed through an enclosing instance.  Locate this
  3209             // enclosing instance:
  3210             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3211                 env1 = env1.outer;
  3213         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3216     public void visitSelect(JCFieldAccess tree) {
  3217         // Determine the expected kind of the qualifier expression.
  3218         int skind = 0;
  3219         if (tree.name == names._this || tree.name == names._super ||
  3220             tree.name == names._class)
  3222             skind = TYP;
  3223         } else {
  3224             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3225             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3226             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3229         // Attribute the qualifier expression, and determine its symbol (if any).
  3230         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3231         if ((pkind() & (PCK | TYP)) == 0)
  3232             site = capture(site); // Capture field access
  3234         // don't allow T.class T[].class, etc
  3235         if (skind == TYP) {
  3236             Type elt = site;
  3237             while (elt.hasTag(ARRAY))
  3238                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3239             if (elt.hasTag(TYPEVAR)) {
  3240                 log.error(tree.pos(), "type.var.cant.be.deref");
  3241                 result = types.createErrorType(tree.type);
  3242                 return;
  3246         // If qualifier symbol is a type or `super', assert `selectSuper'
  3247         // for the selection. This is relevant for determining whether
  3248         // protected symbols are accessible.
  3249         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3250         boolean selectSuperPrev = env.info.selectSuper;
  3251         env.info.selectSuper =
  3252             sitesym != null &&
  3253             sitesym.name == names._super;
  3255         // Determine the symbol represented by the selection.
  3256         env.info.pendingResolutionPhase = null;
  3257         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3258         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3259             site = capture(site);
  3260             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3262         boolean varArgs = env.info.lastResolveVarargs();
  3263         tree.sym = sym;
  3265         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3266             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3267             site = capture(site);
  3270         // If that symbol is a variable, ...
  3271         if (sym.kind == VAR) {
  3272             VarSymbol v = (VarSymbol)sym;
  3274             // ..., evaluate its initializer, if it has one, and check for
  3275             // illegal forward reference.
  3276             checkInit(tree, env, v, true);
  3278             // If we are expecting a variable (as opposed to a value), check
  3279             // that the variable is assignable in the current environment.
  3280             if (pkind() == VAR)
  3281                 checkAssignable(tree.pos(), v, tree.selected, env);
  3284         if (sitesym != null &&
  3285                 sitesym.kind == VAR &&
  3286                 ((VarSymbol)sitesym).isResourceVariable() &&
  3287                 sym.kind == MTH &&
  3288                 sym.name.equals(names.close) &&
  3289                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3290                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3291             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3294         // Disallow selecting a type from an expression
  3295         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3296             tree.type = check(tree.selected, pt(),
  3297                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3300         if (isType(sitesym)) {
  3301             if (sym.name == names._this) {
  3302                 // If `C' is the currently compiled class, check that
  3303                 // C.this' does not appear in a call to a super(...)
  3304                 if (env.info.isSelfCall &&
  3305                     site.tsym == env.enclClass.sym) {
  3306                     chk.earlyRefError(tree.pos(), sym);
  3308             } else {
  3309                 // Check if type-qualified fields or methods are static (JLS)
  3310                 if ((sym.flags() & STATIC) == 0 &&
  3311                     !env.next.tree.hasTag(REFERENCE) &&
  3312                     sym.name != names._super &&
  3313                     (sym.kind == VAR || sym.kind == MTH)) {
  3314                     rs.accessBase(rs.new StaticError(sym),
  3315                               tree.pos(), site, sym.name, true);
  3318         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3319             // If the qualified item is not a type and the selected item is static, report
  3320             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3321             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3324         // If we are selecting an instance member via a `super', ...
  3325         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3327             // Check that super-qualified symbols are not abstract (JLS)
  3328             rs.checkNonAbstract(tree.pos(), sym);
  3330             if (site.isRaw()) {
  3331                 // Determine argument types for site.
  3332                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3333                 if (site1 != null) site = site1;
  3337         env.info.selectSuper = selectSuperPrev;
  3338         result = checkId(tree, site, sym, env, resultInfo);
  3340     //where
  3341         /** Determine symbol referenced by a Select expression,
  3343          *  @param tree   The select tree.
  3344          *  @param site   The type of the selected expression,
  3345          *  @param env    The current environment.
  3346          *  @param resultInfo The current result.
  3347          */
  3348         private Symbol selectSym(JCFieldAccess tree,
  3349                                  Symbol location,
  3350                                  Type site,
  3351                                  Env<AttrContext> env,
  3352                                  ResultInfo resultInfo) {
  3353             DiagnosticPosition pos = tree.pos();
  3354             Name name = tree.name;
  3355             switch (site.getTag()) {
  3356             case PACKAGE:
  3357                 return rs.accessBase(
  3358                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3359                     pos, location, site, name, true);
  3360             case ARRAY:
  3361             case CLASS:
  3362                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3363                     return rs.resolveQualifiedMethod(
  3364                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3365                 } else if (name == names._this || name == names._super) {
  3366                     return rs.resolveSelf(pos, env, site.tsym, name);
  3367                 } else if (name == names._class) {
  3368                     // In this case, we have already made sure in
  3369                     // visitSelect that qualifier expression is a type.
  3370                     Type t = syms.classType;
  3371                     List<Type> typeargs = allowGenerics
  3372                         ? List.of(types.erasure(site))
  3373                         : List.<Type>nil();
  3374                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3375                     return new VarSymbol(
  3376                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3377                 } else {
  3378                     // We are seeing a plain identifier as selector.
  3379                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3380                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3381                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3382                     return sym;
  3384             case WILDCARD:
  3385                 throw new AssertionError(tree);
  3386             case TYPEVAR:
  3387                 // Normally, site.getUpperBound() shouldn't be null.
  3388                 // It should only happen during memberEnter/attribBase
  3389                 // when determining the super type which *must* beac
  3390                 // done before attributing the type variables.  In
  3391                 // other words, we are seeing this illegal program:
  3392                 // class B<T> extends A<T.foo> {}
  3393                 Symbol sym = (site.getUpperBound() != null)
  3394                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3395                     : null;
  3396                 if (sym == null) {
  3397                     log.error(pos, "type.var.cant.be.deref");
  3398                     return syms.errSymbol;
  3399                 } else {
  3400                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3401                         rs.new AccessError(env, site, sym) :
  3402                                 sym;
  3403                     rs.accessBase(sym2, pos, location, site, name, true);
  3404                     return sym;
  3406             case ERROR:
  3407                 // preserve identifier names through errors
  3408                 return types.createErrorType(name, site.tsym, site).tsym;
  3409             default:
  3410                 // The qualifier expression is of a primitive type -- only
  3411                 // .class is allowed for these.
  3412                 if (name == names._class) {
  3413                     // In this case, we have already made sure in Select that
  3414                     // qualifier expression is a type.
  3415                     Type t = syms.classType;
  3416                     Type arg = types.boxedClass(site).type;
  3417                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3418                     return new VarSymbol(
  3419                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3420                 } else {
  3421                     log.error(pos, "cant.deref", site);
  3422                     return syms.errSymbol;
  3427         /** Determine type of identifier or select expression and check that
  3428          *  (1) the referenced symbol is not deprecated
  3429          *  (2) the symbol's type is safe (@see checkSafe)
  3430          *  (3) if symbol is a variable, check that its type and kind are
  3431          *      compatible with the prototype and protokind.
  3432          *  (4) if symbol is an instance field of a raw type,
  3433          *      which is being assigned to, issue an unchecked warning if its
  3434          *      type changes under erasure.
  3435          *  (5) if symbol is an instance method of a raw type, issue an
  3436          *      unchecked warning if its argument types change under erasure.
  3437          *  If checks succeed:
  3438          *    If symbol is a constant, return its constant type
  3439          *    else if symbol is a method, return its result type
  3440          *    otherwise return its type.
  3441          *  Otherwise return errType.
  3443          *  @param tree       The syntax tree representing the identifier
  3444          *  @param site       If this is a select, the type of the selected
  3445          *                    expression, otherwise the type of the current class.
  3446          *  @param sym        The symbol representing the identifier.
  3447          *  @param env        The current environment.
  3448          *  @param resultInfo    The expected result
  3449          */
  3450         Type checkId(JCTree tree,
  3451                      Type site,
  3452                      Symbol sym,
  3453                      Env<AttrContext> env,
  3454                      ResultInfo resultInfo) {
  3455             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3456                     checkMethodId(tree, site, sym, env, resultInfo) :
  3457                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3460         Type checkMethodId(JCTree tree,
  3461                      Type site,
  3462                      Symbol sym,
  3463                      Env<AttrContext> env,
  3464                      ResultInfo resultInfo) {
  3465             boolean isPolymorhicSignature =
  3466                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3467             return isPolymorhicSignature ?
  3468                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3469                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3472         Type checkSigPolyMethodId(JCTree tree,
  3473                      Type site,
  3474                      Symbol sym,
  3475                      Env<AttrContext> env,
  3476                      ResultInfo resultInfo) {
  3477             //recover original symbol for signature polymorphic methods
  3478             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3479             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3480             return sym.type;
  3483         Type checkMethodIdInternal(JCTree tree,
  3484                      Type site,
  3485                      Symbol sym,
  3486                      Env<AttrContext> env,
  3487                      ResultInfo resultInfo) {
  3488             if ((resultInfo.pkind & POLY) != 0) {
  3489                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3490                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3491                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3492                 return owntype;
  3493             } else {
  3494                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3498         Type checkIdInternal(JCTree tree,
  3499                      Type site,
  3500                      Symbol sym,
  3501                      Type pt,
  3502                      Env<AttrContext> env,
  3503                      ResultInfo resultInfo) {
  3504             if (pt.isErroneous()) {
  3505                 return types.createErrorType(site);
  3507             Type owntype; // The computed type of this identifier occurrence.
  3508             switch (sym.kind) {
  3509             case TYP:
  3510                 // For types, the computed type equals the symbol's type,
  3511                 // except for two situations:
  3512                 owntype = sym.type;
  3513                 if (owntype.hasTag(CLASS)) {
  3514                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3515                     Type ownOuter = owntype.getEnclosingType();
  3517                     // (a) If the symbol's type is parameterized, erase it
  3518                     // because no type parameters were given.
  3519                     // We recover generic outer type later in visitTypeApply.
  3520                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3521                         owntype = types.erasure(owntype);
  3524                     // (b) If the symbol's type is an inner class, then
  3525                     // we have to interpret its outer type as a superclass
  3526                     // of the site type. Example:
  3527                     //
  3528                     // class Tree<A> { class Visitor { ... } }
  3529                     // class PointTree extends Tree<Point> { ... }
  3530                     // ...PointTree.Visitor...
  3531                     //
  3532                     // Then the type of the last expression above is
  3533                     // Tree<Point>.Visitor.
  3534                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3535                         Type normOuter = site;
  3536                         if (normOuter.hasTag(CLASS)) {
  3537                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3539                         if (normOuter == null) // perhaps from an import
  3540                             normOuter = types.erasure(ownOuter);
  3541                         if (normOuter != ownOuter)
  3542                             owntype = new ClassType(
  3543                                 normOuter, List.<Type>nil(), owntype.tsym);
  3546                 break;
  3547             case VAR:
  3548                 VarSymbol v = (VarSymbol)sym;
  3549                 // Test (4): if symbol is an instance field of a raw type,
  3550                 // which is being assigned to, issue an unchecked warning if
  3551                 // its type changes under erasure.
  3552                 if (allowGenerics &&
  3553                     resultInfo.pkind == VAR &&
  3554                     v.owner.kind == TYP &&
  3555                     (v.flags() & STATIC) == 0 &&
  3556                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3557                     Type s = types.asOuterSuper(site, v.owner);
  3558                     if (s != null &&
  3559                         s.isRaw() &&
  3560                         !types.isSameType(v.type, v.erasure(types))) {
  3561                         chk.warnUnchecked(tree.pos(),
  3562                                           "unchecked.assign.to.var",
  3563                                           v, s);
  3566                 // The computed type of a variable is the type of the
  3567                 // variable symbol, taken as a member of the site type.
  3568                 owntype = (sym.owner.kind == TYP &&
  3569                            sym.name != names._this && sym.name != names._super)
  3570                     ? types.memberType(site, sym)
  3571                     : sym.type;
  3573                 // If the variable is a constant, record constant value in
  3574                 // computed type.
  3575                 if (v.getConstValue() != null && isStaticReference(tree))
  3576                     owntype = owntype.constType(v.getConstValue());
  3578                 if (resultInfo.pkind == VAL) {
  3579                     owntype = capture(owntype); // capture "names as expressions"
  3581                 break;
  3582             case MTH: {
  3583                 owntype = checkMethod(site, sym,
  3584                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3585                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3586                         resultInfo.pt.getTypeArguments());
  3587                 break;
  3589             case PCK: case ERR:
  3590                 owntype = sym.type;
  3591                 break;
  3592             default:
  3593                 throw new AssertionError("unexpected kind: " + sym.kind +
  3594                                          " in tree " + tree);
  3597             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3598             // (for constructors, the error was given when the constructor was
  3599             // resolved)
  3601             if (sym.name != names.init) {
  3602                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3603                 chk.checkSunAPI(tree.pos(), sym);
  3604                 chk.checkProfile(tree.pos(), sym);
  3607             // Test (3): if symbol is a variable, check that its type and
  3608             // kind are compatible with the prototype and protokind.
  3609             return check(tree, owntype, sym.kind, resultInfo);
  3612         /** Check that variable is initialized and evaluate the variable's
  3613          *  initializer, if not yet done. Also check that variable is not
  3614          *  referenced before it is defined.
  3615          *  @param tree    The tree making up the variable reference.
  3616          *  @param env     The current environment.
  3617          *  @param v       The variable's symbol.
  3618          */
  3619         private void checkInit(JCTree tree,
  3620                                Env<AttrContext> env,
  3621                                VarSymbol v,
  3622                                boolean onlyWarning) {
  3623 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3624 //                             tree.pos + " " + v.pos + " " +
  3625 //                             Resolve.isStatic(env));//DEBUG
  3627             // A forward reference is diagnosed if the declaration position
  3628             // of the variable is greater than the current tree position
  3629             // and the tree and variable definition occur in the same class
  3630             // definition.  Note that writes don't count as references.
  3631             // This check applies only to class and instance
  3632             // variables.  Local variables follow different scope rules,
  3633             // and are subject to definite assignment checking.
  3634             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3635                 v.owner.kind == TYP &&
  3636                 canOwnInitializer(owner(env)) &&
  3637                 v.owner == env.info.scope.owner.enclClass() &&
  3638                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3639                 (!env.tree.hasTag(ASSIGN) ||
  3640                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3641                 String suffix = (env.info.enclVar == v) ?
  3642                                 "self.ref" : "forward.ref";
  3643                 if (!onlyWarning || isStaticEnumField(v)) {
  3644                     log.error(tree.pos(), "illegal." + suffix);
  3645                 } else if (useBeforeDeclarationWarning) {
  3646                     log.warning(tree.pos(), suffix, v);
  3650             v.getConstValue(); // ensure initializer is evaluated
  3652             checkEnumInitializer(tree, env, v);
  3655         /**
  3656          * Check for illegal references to static members of enum.  In
  3657          * an enum type, constructors and initializers may not
  3658          * reference its static members unless they are constant.
  3660          * @param tree    The tree making up the variable reference.
  3661          * @param env     The current environment.
  3662          * @param v       The variable's symbol.
  3663          * @jls  section 8.9 Enums
  3664          */
  3665         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3666             // JLS:
  3667             //
  3668             // "It is a compile-time error to reference a static field
  3669             // of an enum type that is not a compile-time constant
  3670             // (15.28) from constructors, instance initializer blocks,
  3671             // or instance variable initializer expressions of that
  3672             // type. It is a compile-time error for the constructors,
  3673             // instance initializer blocks, or instance variable
  3674             // initializer expressions of an enum constant e to refer
  3675             // to itself or to an enum constant of the same type that
  3676             // is declared to the right of e."
  3677             if (isStaticEnumField(v)) {
  3678                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3680                 if (enclClass == null || enclClass.owner == null)
  3681                     return;
  3683                 // See if the enclosing class is the enum (or a
  3684                 // subclass thereof) declaring v.  If not, this
  3685                 // reference is OK.
  3686                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3687                     return;
  3689                 // If the reference isn't from an initializer, then
  3690                 // the reference is OK.
  3691                 if (!Resolve.isInitializer(env))
  3692                     return;
  3694                 log.error(tree.pos(), "illegal.enum.static.ref");
  3698         /** Is the given symbol a static, non-constant field of an Enum?
  3699          *  Note: enum literals should not be regarded as such
  3700          */
  3701         private boolean isStaticEnumField(VarSymbol v) {
  3702             return Flags.isEnum(v.owner) &&
  3703                    Flags.isStatic(v) &&
  3704                    !Flags.isConstant(v) &&
  3705                    v.name != names._class;
  3708         /** Can the given symbol be the owner of code which forms part
  3709          *  if class initialization? This is the case if the symbol is
  3710          *  a type or field, or if the symbol is the synthetic method.
  3711          *  owning a block.
  3712          */
  3713         private boolean canOwnInitializer(Symbol sym) {
  3714             return
  3715                 (sym.kind & (VAR | TYP)) != 0 ||
  3716                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3719     Warner noteWarner = new Warner();
  3721     /**
  3722      * Check that method arguments conform to its instantiation.
  3723      **/
  3724     public Type checkMethod(Type site,
  3725                             final Symbol sym,
  3726                             ResultInfo resultInfo,
  3727                             Env<AttrContext> env,
  3728                             final List<JCExpression> argtrees,
  3729                             List<Type> argtypes,
  3730                             List<Type> typeargtypes) {
  3731         // Test (5): if symbol is an instance method of a raw type, issue
  3732         // an unchecked warning if its argument types change under erasure.
  3733         if (allowGenerics &&
  3734             (sym.flags() & STATIC) == 0 &&
  3735             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3736             Type s = types.asOuterSuper(site, sym.owner);
  3737             if (s != null && s.isRaw() &&
  3738                 !types.isSameTypes(sym.type.getParameterTypes(),
  3739                                    sym.erasure(types).getParameterTypes())) {
  3740                 chk.warnUnchecked(env.tree.pos(),
  3741                                   "unchecked.call.mbr.of.raw.type",
  3742                                   sym, s);
  3746         if (env.info.defaultSuperCallSite != null) {
  3747             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3748                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3749                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3750                 List<MethodSymbol> icand_sup =
  3751                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3752                 if (icand_sup.nonEmpty() &&
  3753                         icand_sup.head != sym &&
  3754                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3755                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3756                         diags.fragment("overridden.default", sym, sup));
  3757                     break;
  3760             env.info.defaultSuperCallSite = null;
  3763         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3764             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3765             if (app.meth.hasTag(SELECT) &&
  3766                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3767                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3771         // Compute the identifier's instantiated type.
  3772         // For methods, we need to compute the instance type by
  3773         // Resolve.instantiate from the symbol's type as well as
  3774         // any type arguments and value arguments.
  3775         noteWarner.clear();
  3776         try {
  3777             Type owntype = rs.checkMethod(
  3778                     env,
  3779                     site,
  3780                     sym,
  3781                     resultInfo,
  3782                     argtypes,
  3783                     typeargtypes,
  3784                     noteWarner);
  3786             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3787                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3789             argtypes = Type.map(argtypes, checkDeferredMap);
  3791             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3792                 chk.warnUnchecked(env.tree.pos(),
  3793                         "unchecked.meth.invocation.applied",
  3794                         kindName(sym),
  3795                         sym.name,
  3796                         rs.methodArguments(sym.type.getParameterTypes()),
  3797                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3798                         kindName(sym.location()),
  3799                         sym.location());
  3800                owntype = new MethodType(owntype.getParameterTypes(),
  3801                        types.erasure(owntype.getReturnType()),
  3802                        types.erasure(owntype.getThrownTypes()),
  3803                        syms.methodClass);
  3806             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3807                     resultInfo.checkContext.inferenceContext());
  3808         } catch (Infer.InferenceException ex) {
  3809             //invalid target type - propagate exception outwards or report error
  3810             //depending on the current check context
  3811             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3812             return types.createErrorType(site);
  3813         } catch (Resolve.InapplicableMethodException ex) {
  3814             final JCDiagnostic diag = ex.getDiagnostic();
  3815             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  3816                 @Override
  3817                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3818                     return new Pair<Symbol, JCDiagnostic>(sym, diag);
  3820             };
  3821             List<Type> argtypes2 = Type.map(argtypes,
  3822                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3823             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3824                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  3825             log.report(errDiag);
  3826             return types.createErrorType(site);
  3830     public void visitLiteral(JCLiteral tree) {
  3831         result = check(
  3832             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3834     //where
  3835     /** Return the type of a literal with given type tag.
  3836      */
  3837     Type litType(TypeTag tag) {
  3838         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3841     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3842         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3845     public void visitTypeArray(JCArrayTypeTree tree) {
  3846         Type etype = attribType(tree.elemtype, env);
  3847         Type type = new ArrayType(etype, syms.arrayClass);
  3848         result = check(tree, type, TYP, resultInfo);
  3851     /** Visitor method for parameterized types.
  3852      *  Bound checking is left until later, since types are attributed
  3853      *  before supertype structure is completely known
  3854      */
  3855     public void visitTypeApply(JCTypeApply tree) {
  3856         Type owntype = types.createErrorType(tree.type);
  3858         // Attribute functor part of application and make sure it's a class.
  3859         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3861         // Attribute type parameters
  3862         List<Type> actuals = attribTypes(tree.arguments, env);
  3864         if (clazztype.hasTag(CLASS)) {
  3865             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3866             if (actuals.isEmpty()) //diamond
  3867                 actuals = formals;
  3869             if (actuals.length() == formals.length()) {
  3870                 List<Type> a = actuals;
  3871                 List<Type> f = formals;
  3872                 while (a.nonEmpty()) {
  3873                     a.head = a.head.withTypeVar(f.head);
  3874                     a = a.tail;
  3875                     f = f.tail;
  3877                 // Compute the proper generic outer
  3878                 Type clazzOuter = clazztype.getEnclosingType();
  3879                 if (clazzOuter.hasTag(CLASS)) {
  3880                     Type site;
  3881                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3882                     if (clazz.hasTag(IDENT)) {
  3883                         site = env.enclClass.sym.type;
  3884                     } else if (clazz.hasTag(SELECT)) {
  3885                         site = ((JCFieldAccess) clazz).selected.type;
  3886                     } else throw new AssertionError(""+tree);
  3887                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3888                         if (site.hasTag(CLASS))
  3889                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3890                         if (site == null)
  3891                             site = types.erasure(clazzOuter);
  3892                         clazzOuter = site;
  3895                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3896             } else {
  3897                 if (formals.length() != 0) {
  3898                     log.error(tree.pos(), "wrong.number.type.args",
  3899                               Integer.toString(formals.length()));
  3900                 } else {
  3901                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3903                 owntype = types.createErrorType(tree.type);
  3906         result = check(tree, owntype, TYP, resultInfo);
  3909     public void visitTypeUnion(JCTypeUnion tree) {
  3910         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  3911         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3912         for (JCExpression typeTree : tree.alternatives) {
  3913             Type ctype = attribType(typeTree, env);
  3914             ctype = chk.checkType(typeTree.pos(),
  3915                           chk.checkClassType(typeTree.pos(), ctype),
  3916                           syms.throwableType);
  3917             if (!ctype.isErroneous()) {
  3918                 //check that alternatives of a union type are pairwise
  3919                 //unrelated w.r.t. subtyping
  3920                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3921                     for (Type t : multicatchTypes) {
  3922                         boolean sub = types.isSubtype(ctype, t);
  3923                         boolean sup = types.isSubtype(t, ctype);
  3924                         if (sub || sup) {
  3925                             //assume 'a' <: 'b'
  3926                             Type a = sub ? ctype : t;
  3927                             Type b = sub ? t : ctype;
  3928                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3932                 multicatchTypes.append(ctype);
  3933                 if (all_multicatchTypes != null)
  3934                     all_multicatchTypes.append(ctype);
  3935             } else {
  3936                 if (all_multicatchTypes == null) {
  3937                     all_multicatchTypes = new ListBuffer<>();
  3938                     all_multicatchTypes.appendList(multicatchTypes);
  3940                 all_multicatchTypes.append(ctype);
  3943         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3944         if (t.hasTag(CLASS)) {
  3945             List<Type> alternatives =
  3946                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3947             t = new UnionClassType((ClassType) t, alternatives);
  3949         tree.type = result = t;
  3952     public void visitTypeIntersection(JCTypeIntersection tree) {
  3953         attribTypes(tree.bounds, env);
  3954         tree.type = result = checkIntersection(tree, tree.bounds);
  3957     public void visitTypeParameter(JCTypeParameter tree) {
  3958         TypeVar typeVar = (TypeVar) tree.type;
  3960         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3961             annotateType(tree, tree.annotations);
  3964         if (!typeVar.bound.isErroneous()) {
  3965             //fixup type-parameter bound computed in 'attribTypeVariables'
  3966             typeVar.bound = checkIntersection(tree, tree.bounds);
  3970     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3971         Set<Type> boundSet = new HashSet<Type>();
  3972         if (bounds.nonEmpty()) {
  3973             // accept class or interface or typevar as first bound.
  3974             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3975             boundSet.add(types.erasure(bounds.head.type));
  3976             if (bounds.head.type.isErroneous()) {
  3977                 return bounds.head.type;
  3979             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3980                 // if first bound was a typevar, do not accept further bounds.
  3981                 if (bounds.tail.nonEmpty()) {
  3982                     log.error(bounds.tail.head.pos(),
  3983                               "type.var.may.not.be.followed.by.other.bounds");
  3984                     return bounds.head.type;
  3986             } else {
  3987                 // if first bound was a class or interface, accept only interfaces
  3988                 // as further bounds.
  3989                 for (JCExpression bound : bounds.tail) {
  3990                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  3991                     if (bound.type.isErroneous()) {
  3992                         bounds = List.of(bound);
  3994                     else if (bound.type.hasTag(CLASS)) {
  3995                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4001         if (bounds.length() == 0) {
  4002             return syms.objectType;
  4003         } else if (bounds.length() == 1) {
  4004             return bounds.head.type;
  4005         } else {
  4006             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4007             // ... the variable's bound is a class type flagged COMPOUND
  4008             // (see comment for TypeVar.bound).
  4009             // In this case, generate a class tree that represents the
  4010             // bound class, ...
  4011             JCExpression extending;
  4012             List<JCExpression> implementing;
  4013             if (!bounds.head.type.isInterface()) {
  4014                 extending = bounds.head;
  4015                 implementing = bounds.tail;
  4016             } else {
  4017                 extending = null;
  4018                 implementing = bounds;
  4020             JCClassDecl cd = make.at(tree).ClassDef(
  4021                 make.Modifiers(PUBLIC | ABSTRACT),
  4022                 names.empty, List.<JCTypeParameter>nil(),
  4023                 extending, implementing, List.<JCTree>nil());
  4025             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4026             Assert.check((c.flags() & COMPOUND) != 0);
  4027             cd.sym = c;
  4028             c.sourcefile = env.toplevel.sourcefile;
  4030             // ... and attribute the bound class
  4031             c.flags_field |= UNATTRIBUTED;
  4032             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4033             enter.typeEnvs.put(c, cenv);
  4034             attribClass(c);
  4035             return owntype;
  4039     public void visitWildcard(JCWildcard tree) {
  4040         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4041         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4042             ? syms.objectType
  4043             : attribType(tree.inner, env);
  4044         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4045                                               tree.kind.kind,
  4046                                               syms.boundClass),
  4047                        TYP, resultInfo);
  4050     public void visitAnnotation(JCAnnotation tree) {
  4051         Assert.error("should be handled in Annotate");
  4054     public void visitAnnotatedType(JCAnnotatedType tree) {
  4055         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4056         this.attribAnnotationTypes(tree.annotations, env);
  4057         annotateType(tree, tree.annotations);
  4058         result = tree.type = underlyingType;
  4061     /**
  4062      * Apply the annotations to the particular type.
  4063      */
  4064     public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
  4065         annotate.typeAnnotation(new Annotate.Worker() {
  4066             @Override
  4067             public String toString() {
  4068                 return "annotate " + annotations + " onto " + tree;
  4070             @Override
  4071             public void run() {
  4072                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4073                 if (annotations.size() == compounds.size()) {
  4074                     // All annotations were successfully converted into compounds
  4075                     tree.type = tree.type.unannotatedType().annotatedType(compounds);
  4078         });
  4081     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4082         if (annotations.isEmpty()) {
  4083             return List.nil();
  4086         ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  4087         for (JCAnnotation anno : annotations) {
  4088             if (anno.attribute != null) {
  4089                 // TODO: this null-check is only needed for an obscure
  4090                 // ordering issue, where annotate.flush is called when
  4091                 // the attribute is not set yet. For an example failure
  4092                 // try the referenceinfos/NestedTypes.java test.
  4093                 // Any better solutions?
  4094                 buf.append((Attribute.TypeCompound) anno.attribute);
  4096             // Eventually we will want to throw an exception here, but
  4097             // we can't do that just yet, because it gets triggered
  4098             // when attempting to attach an annotation that isn't
  4099             // defined.
  4101         return buf.toList();
  4104     public void visitErroneous(JCErroneous tree) {
  4105         if (tree.errs != null)
  4106             for (JCTree err : tree.errs)
  4107                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4108         result = tree.type = syms.errType;
  4111     /** Default visitor method for all other trees.
  4112      */
  4113     public void visitTree(JCTree tree) {
  4114         throw new AssertionError();
  4117     /**
  4118      * Attribute an env for either a top level tree or class declaration.
  4119      */
  4120     public void attrib(Env<AttrContext> env) {
  4121         if (env.tree.hasTag(TOPLEVEL))
  4122             attribTopLevel(env);
  4123         else
  4124             attribClass(env.tree.pos(), env.enclClass.sym);
  4127     /**
  4128      * Attribute a top level tree. These trees are encountered when the
  4129      * package declaration has annotations.
  4130      */
  4131     public void attribTopLevel(Env<AttrContext> env) {
  4132         JCCompilationUnit toplevel = env.toplevel;
  4133         try {
  4134             annotate.flush();
  4135         } catch (CompletionFailure ex) {
  4136             chk.completionError(toplevel.pos(), ex);
  4140     /** Main method: attribute class definition associated with given class symbol.
  4141      *  reporting completion failures at the given position.
  4142      *  @param pos The source position at which completion errors are to be
  4143      *             reported.
  4144      *  @param c   The class symbol whose definition will be attributed.
  4145      */
  4146     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4147         try {
  4148             annotate.flush();
  4149             attribClass(c);
  4150         } catch (CompletionFailure ex) {
  4151             chk.completionError(pos, ex);
  4155     /** Attribute class definition associated with given class symbol.
  4156      *  @param c   The class symbol whose definition will be attributed.
  4157      */
  4158     void attribClass(ClassSymbol c) throws CompletionFailure {
  4159         if (c.type.hasTag(ERROR)) return;
  4161         // Check for cycles in the inheritance graph, which can arise from
  4162         // ill-formed class files.
  4163         chk.checkNonCyclic(null, c.type);
  4165         Type st = types.supertype(c.type);
  4166         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4167             // First, attribute superclass.
  4168             if (st.hasTag(CLASS))
  4169                 attribClass((ClassSymbol)st.tsym);
  4171             // Next attribute owner, if it is a class.
  4172             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4173                 attribClass((ClassSymbol)c.owner);
  4176         // The previous operations might have attributed the current class
  4177         // if there was a cycle. So we test first whether the class is still
  4178         // UNATTRIBUTED.
  4179         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4180             c.flags_field &= ~UNATTRIBUTED;
  4182             // Get environment current at the point of class definition.
  4183             Env<AttrContext> env = enter.typeEnvs.get(c);
  4185             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4186             // because the annotations were not available at the time the env was created. Therefore,
  4187             // we look up the environment chain for the first enclosing environment for which the
  4188             // lint value is set. Typically, this is the parent env, but might be further if there
  4189             // are any envs created as a result of TypeParameter nodes.
  4190             Env<AttrContext> lintEnv = env;
  4191             while (lintEnv.info.lint == null)
  4192                 lintEnv = lintEnv.next;
  4194             // Having found the enclosing lint value, we can initialize the lint value for this class
  4195             env.info.lint = lintEnv.info.lint.augment(c);
  4197             Lint prevLint = chk.setLint(env.info.lint);
  4198             JavaFileObject prev = log.useSource(c.sourcefile);
  4199             ResultInfo prevReturnRes = env.info.returnResult;
  4201             try {
  4202                 deferredLintHandler.flush(env.tree);
  4203                 env.info.returnResult = null;
  4204                 // java.lang.Enum may not be subclassed by a non-enum
  4205                 if (st.tsym == syms.enumSym &&
  4206                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4207                     log.error(env.tree.pos(), "enum.no.subclassing");
  4209                 // Enums may not be extended by source-level classes
  4210                 if (st.tsym != null &&
  4211                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4212                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4213                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4215                 attribClassBody(env, c);
  4217                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4218                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4219                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
  4220             } finally {
  4221                 env.info.returnResult = prevReturnRes;
  4222                 log.useSource(prev);
  4223                 chk.setLint(prevLint);
  4229     public void visitImport(JCImport tree) {
  4230         // nothing to do
  4233     /** Finish the attribution of a class. */
  4234     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4235         JCClassDecl tree = (JCClassDecl)env.tree;
  4236         Assert.check(c == tree.sym);
  4238         // Validate type parameters, supertype and interfaces.
  4239         attribStats(tree.typarams, env);
  4240         if (!c.isAnonymous()) {
  4241             //already checked if anonymous
  4242             chk.validate(tree.typarams, env);
  4243             chk.validate(tree.extending, env);
  4244             chk.validate(tree.implementing, env);
  4247         // If this is a non-abstract class, check that it has no abstract
  4248         // methods or unimplemented methods of an implemented interface.
  4249         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4250             if (!relax)
  4251                 chk.checkAllDefined(tree.pos(), c);
  4254         if ((c.flags() & ANNOTATION) != 0) {
  4255             if (tree.implementing.nonEmpty())
  4256                 log.error(tree.implementing.head.pos(),
  4257                           "cant.extend.intf.annotation");
  4258             if (tree.typarams.nonEmpty())
  4259                 log.error(tree.typarams.head.pos(),
  4260                           "intf.annotation.cant.have.type.params");
  4262             // If this annotation has a @Repeatable, validate
  4263             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4264             if (repeatable != null) {
  4265                 // get diagnostic position for error reporting
  4266                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4267                 Assert.checkNonNull(cbPos);
  4269                 chk.validateRepeatable(c, repeatable, cbPos);
  4271         } else {
  4272             // Check that all extended classes and interfaces
  4273             // are compatible (i.e. no two define methods with same arguments
  4274             // yet different return types).  (JLS 8.4.6.3)
  4275             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4276             if (allowDefaultMethods) {
  4277                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4281         // Check that class does not import the same parameterized interface
  4282         // with two different argument lists.
  4283         chk.checkClassBounds(tree.pos(), c.type);
  4285         tree.type = c.type;
  4287         for (List<JCTypeParameter> l = tree.typarams;
  4288              l.nonEmpty(); l = l.tail) {
  4289              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4292         // Check that a generic class doesn't extend Throwable
  4293         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4294             log.error(tree.extending.pos(), "generic.throwable");
  4296         // Check that all methods which implement some
  4297         // method conform to the method they implement.
  4298         chk.checkImplementations(tree);
  4300         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4301         checkAutoCloseable(tree.pos(), env, c.type);
  4303         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4304             // Attribute declaration
  4305             attribStat(l.head, env);
  4306             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4307             // Make an exception for static constants.
  4308             if (c.owner.kind != PCK &&
  4309                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4310                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4311                 Symbol sym = null;
  4312                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4313                 if (sym == null ||
  4314                     sym.kind != VAR ||
  4315                     ((VarSymbol) sym).getConstValue() == null)
  4316                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4320         // Check for cycles among non-initial constructors.
  4321         chk.checkCyclicConstructors(tree);
  4323         // Check for cycles among annotation elements.
  4324         chk.checkNonCyclicElements(tree);
  4326         // Check for proper use of serialVersionUID
  4327         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4328             isSerializable(c) &&
  4329             (c.flags() & Flags.ENUM) == 0 &&
  4330             checkForSerial(c)) {
  4331             checkSerialVersionUID(tree, c);
  4333         if (allowTypeAnnos) {
  4334             // Correctly organize the postions of the type annotations
  4335             typeAnnotations.organizeTypeAnnotationsBodies(tree);
  4337             // Check type annotations applicability rules
  4338             validateTypeAnnotations(tree, false);
  4341         // where
  4342         boolean checkForSerial(ClassSymbol c) {
  4343             if ((c.flags() & ABSTRACT) == 0) {
  4344                 return true;
  4345             } else {
  4346                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4350         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4351             @Override
  4352             public boolean accepts(Symbol s) {
  4353                 return s.kind == Kinds.MTH &&
  4354                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4356         };
  4358         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4359         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4360             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4361                 if (types.isSameType(al.head.annotationType.type, t))
  4362                     return al.head.pos();
  4365             return null;
  4368         /** check if a class is a subtype of Serializable, if that is available. */
  4369         private boolean isSerializable(ClassSymbol c) {
  4370             try {
  4371                 syms.serializableType.complete();
  4373             catch (CompletionFailure e) {
  4374                 return false;
  4376             return types.isSubtype(c.type, syms.serializableType);
  4379         /** Check that an appropriate serialVersionUID member is defined. */
  4380         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4382             // check for presence of serialVersionUID
  4383             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4384             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4385             if (e.scope == null) {
  4386                 log.warning(LintCategory.SERIAL,
  4387                         tree.pos(), "missing.SVUID", c);
  4388                 return;
  4391             // check that it is static final
  4392             VarSymbol svuid = (VarSymbol)e.sym;
  4393             if ((svuid.flags() & (STATIC | FINAL)) !=
  4394                 (STATIC | FINAL))
  4395                 log.warning(LintCategory.SERIAL,
  4396                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4398             // check that it is long
  4399             else if (!svuid.type.hasTag(LONG))
  4400                 log.warning(LintCategory.SERIAL,
  4401                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4403             // check constant
  4404             else if (svuid.getConstValue() == null)
  4405                 log.warning(LintCategory.SERIAL,
  4406                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4409     private Type capture(Type type) {
  4410         return types.capture(type);
  4413     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
  4414         tree.accept(new TypeAnnotationsValidator(sigOnly));
  4416     //where
  4417     private final class TypeAnnotationsValidator extends TreeScanner {
  4419         private final boolean sigOnly;
  4420         public TypeAnnotationsValidator(boolean sigOnly) {
  4421             this.sigOnly = sigOnly;
  4424         public void visitAnnotation(JCAnnotation tree) {
  4425             chk.validateTypeAnnotation(tree, false);
  4426             super.visitAnnotation(tree);
  4428         public void visitAnnotatedType(JCAnnotatedType tree) {
  4429             if (!tree.underlyingType.type.isErroneous()) {
  4430                 super.visitAnnotatedType(tree);
  4433         public void visitTypeParameter(JCTypeParameter tree) {
  4434             chk.validateTypeAnnotations(tree.annotations, true);
  4435             scan(tree.bounds);
  4436             // Don't call super.
  4437             // This is needed because above we call validateTypeAnnotation with
  4438             // false, which would forbid annotations on type parameters.
  4439             // super.visitTypeParameter(tree);
  4441         public void visitMethodDef(JCMethodDecl tree) {
  4442             if (tree.recvparam != null &&
  4443                     !tree.recvparam.vartype.type.isErroneous()) {
  4444                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4445                         tree.recvparam.vartype.type.tsym);
  4447             if (tree.restype != null && tree.restype.type != null) {
  4448                 validateAnnotatedType(tree.restype, tree.restype.type);
  4450             if (sigOnly) {
  4451                 scan(tree.mods);
  4452                 scan(tree.restype);
  4453                 scan(tree.typarams);
  4454                 scan(tree.recvparam);
  4455                 scan(tree.params);
  4456                 scan(tree.thrown);
  4457             } else {
  4458                 scan(tree.defaultValue);
  4459                 scan(tree.body);
  4462         public void visitVarDef(final JCVariableDecl tree) {
  4463             if (tree.sym != null && tree.sym.type != null)
  4464                 validateAnnotatedType(tree.vartype, tree.sym.type);
  4465             scan(tree.mods);
  4466             scan(tree.vartype);
  4467             if (!sigOnly) {
  4468                 scan(tree.init);
  4471         public void visitTypeCast(JCTypeCast tree) {
  4472             if (tree.clazz != null && tree.clazz.type != null)
  4473                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4474             super.visitTypeCast(tree);
  4476         public void visitTypeTest(JCInstanceOf tree) {
  4477             if (tree.clazz != null && tree.clazz.type != null)
  4478                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4479             super.visitTypeTest(tree);
  4481         public void visitNewClass(JCNewClass tree) {
  4482             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4483                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  4484                         tree.clazz.type.tsym);
  4486             if (tree.def != null) {
  4487                 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
  4489             if (tree.clazz.type != null) {
  4490                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4492             super.visitNewClass(tree);
  4494         public void visitNewArray(JCNewArray tree) {
  4495             if (tree.elemtype != null && tree.elemtype.type != null) {
  4496                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4497                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  4498                             tree.elemtype.type.tsym);
  4500                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
  4502             super.visitNewArray(tree);
  4504         public void visitClassDef(JCClassDecl tree) {
  4505             if (sigOnly) {
  4506                 scan(tree.mods);
  4507                 scan(tree.typarams);
  4508                 scan(tree.extending);
  4509                 scan(tree.implementing);
  4511             for (JCTree member : tree.defs) {
  4512                 if (member.hasTag(Tag.CLASSDEF)) {
  4513                     continue;
  4515                 scan(member);
  4518         public void visitBlock(JCBlock tree) {
  4519             if (!sigOnly) {
  4520                 scan(tree.stats);
  4524         /* I would want to model this after
  4525          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4526          * and override visitSelect and visitTypeApply.
  4527          * However, we only set the annotated type in the top-level type
  4528          * of the symbol.
  4529          * Therefore, we need to override each individual location where a type
  4530          * can occur.
  4531          */
  4532         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4533             // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
  4535             if (type.isPrimitiveOrVoid()) {
  4536                 return;
  4539             JCTree enclTr = errtree;
  4540             Type enclTy = type;
  4542             boolean repeat = true;
  4543             while (repeat) {
  4544                 if (enclTr.hasTag(TYPEAPPLY)) {
  4545                     List<Type> tyargs = enclTy.getTypeArguments();
  4546                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
  4547                     if (trargs.length() > 0) {
  4548                         // Nothing to do for diamonds
  4549                         if (tyargs.length() == trargs.length()) {
  4550                             for (int i = 0; i < tyargs.length(); ++i) {
  4551                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
  4554                         // If the lengths don't match, it's either a diamond
  4555                         // or some nested type that redundantly provides
  4556                         // type arguments in the tree.
  4559                     // Look at the clazz part of a generic type
  4560                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
  4563                 if (enclTr.hasTag(SELECT)) {
  4564                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
  4565                     if (enclTy != null &&
  4566                             !enclTy.hasTag(NONE)) {
  4567                         enclTy = enclTy.getEnclosingType();
  4569                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
  4570                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
  4571                     if (enclTy == null ||
  4572                             enclTy.hasTag(NONE)) {
  4573                         if (at.getAnnotations().size() == 1) {
  4574                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
  4575                         } else {
  4576                             ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
  4577                             for (JCAnnotation an : at.getAnnotations()) {
  4578                                 comps.add(an.attribute);
  4580                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
  4582                         repeat = false;
  4584                     enclTr = at.underlyingType;
  4585                     // enclTy doesn't need to be changed
  4586                 } else if (enclTr.hasTag(IDENT)) {
  4587                     repeat = false;
  4588                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
  4589                     JCWildcard wc = (JCWildcard) enclTr;
  4590                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
  4591                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
  4592                     } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
  4593                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
  4594                     } else {
  4595                         // Nothing to do for UNBOUND
  4597                     repeat = false;
  4598                 } else if (enclTr.hasTag(TYPEARRAY)) {
  4599                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
  4600                     validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
  4601                     repeat = false;
  4602                 } else if (enclTr.hasTag(TYPEUNION)) {
  4603                     JCTypeUnion ut = (JCTypeUnion) enclTr;
  4604                     for (JCTree t : ut.getTypeAlternatives()) {
  4605                         validateAnnotatedType(t, t.type);
  4607                     repeat = false;
  4608                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
  4609                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
  4610                     for (JCTree t : it.getBounds()) {
  4611                         validateAnnotatedType(t, t.type);
  4613                     repeat = false;
  4614                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
  4615                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  4616                     repeat = false;
  4617                 } else {
  4618                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
  4619                             " within: "+ errtree + " with kind: " + errtree.getKind());
  4624         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  4625                 Symbol sym) {
  4626             // Ensure that no declaration annotations are present.
  4627             // Note that a tree type might be an AnnotatedType with
  4628             // empty annotations, if only declaration annotations were given.
  4629             // This method will raise an error for such a type.
  4630             for (JCAnnotation ai : annotations) {
  4631                 if (!ai.type.isErroneous() &&
  4632                         typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  4633                     log.error(ai.pos(), "annotation.type.not.applicable");
  4637     };
  4639     // <editor-fold desc="post-attribution visitor">
  4641     /**
  4642      * Handle missing types/symbols in an AST. This routine is useful when
  4643      * the compiler has encountered some errors (which might have ended up
  4644      * terminating attribution abruptly); if the compiler is used in fail-over
  4645      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4646      * prevents NPE to be progagated during subsequent compilation steps.
  4647      */
  4648     public void postAttr(JCTree tree) {
  4649         new PostAttrAnalyzer().scan(tree);
  4652     class PostAttrAnalyzer extends TreeScanner {
  4654         private void initTypeIfNeeded(JCTree that) {
  4655             if (that.type == null) {
  4656                 if (that.hasTag(METHODDEF)) {
  4657                     that.type = dummyMethodType();
  4658                 } else {
  4659                     that.type = syms.unknownType;
  4664         private Type dummyMethodType() {
  4665             return new MethodType(List.<Type>nil(), syms.unknownType,
  4666                             List.<Type>nil(), syms.methodClass);
  4669         @Override
  4670         public void scan(JCTree tree) {
  4671             if (tree == null) return;
  4672             if (tree instanceof JCExpression) {
  4673                 initTypeIfNeeded(tree);
  4675             super.scan(tree);
  4678         @Override
  4679         public void visitIdent(JCIdent that) {
  4680             if (that.sym == null) {
  4681                 that.sym = syms.unknownSymbol;
  4685         @Override
  4686         public void visitSelect(JCFieldAccess that) {
  4687             if (that.sym == null) {
  4688                 that.sym = syms.unknownSymbol;
  4690             super.visitSelect(that);
  4693         @Override
  4694         public void visitClassDef(JCClassDecl that) {
  4695             initTypeIfNeeded(that);
  4696             if (that.sym == null) {
  4697                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4699             super.visitClassDef(that);
  4702         @Override
  4703         public void visitMethodDef(JCMethodDecl that) {
  4704             initTypeIfNeeded(that);
  4705             if (that.sym == null) {
  4706                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4708             super.visitMethodDef(that);
  4711         @Override
  4712         public void visitVarDef(JCVariableDecl that) {
  4713             initTypeIfNeeded(that);
  4714             if (that.sym == null) {
  4715                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4716                 that.sym.adr = 0;
  4718             super.visitVarDef(that);
  4721         @Override
  4722         public void visitNewClass(JCNewClass that) {
  4723             if (that.constructor == null) {
  4724                 that.constructor = new MethodSymbol(0, names.init,
  4725                         dummyMethodType(), syms.noSymbol);
  4727             if (that.constructorType == null) {
  4728                 that.constructorType = syms.unknownType;
  4730             super.visitNewClass(that);
  4733         @Override
  4734         public void visitAssignop(JCAssignOp that) {
  4735             if (that.operator == null) {
  4736                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4737                         -1, syms.noSymbol);
  4739             super.visitAssignop(that);
  4742         @Override
  4743         public void visitBinary(JCBinary that) {
  4744             if (that.operator == null) {
  4745                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4746                         -1, syms.noSymbol);
  4748             super.visitBinary(that);
  4751         @Override
  4752         public void visitUnary(JCUnary that) {
  4753             if (that.operator == null) {
  4754                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4755                         -1, syms.noSymbol);
  4757             super.visitUnary(that);
  4760         @Override
  4761         public void visitLambda(JCLambda that) {
  4762             super.visitLambda(that);
  4763             if (that.targets == null) {
  4764                 that.targets = List.nil();
  4768         @Override
  4769         public void visitReference(JCMemberReference that) {
  4770             super.visitReference(that);
  4771             if (that.sym == null) {
  4772                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
  4773                         syms.noSymbol);
  4775             if (that.targets == null) {
  4776                 that.targets = List.nil();
  4780     // </editor-fold>

mercurial