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

Mon, 22 Sep 2014 14:55:14 +0200

author
jlahoda
date
Mon, 22 Sep 2014 14:55:14 +0200
changeset 2617
a12a9932f649
parent 2615
4d2222373842
child 2702
9ca8d8713094
child 2717
11743872bfc9
permissions
-rw-r--r--

8057794: Compiler Error when obtaining .class property
Summary: Ensuring a non-null type and sym for illegal T.class to prevent downstream errors.
Reviewed-by: mcimadamore

     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;
    97     final TypeEnvs typeEnvs;
    99     public static Attr instance(Context context) {
   100         Attr instance = context.get(attrKey);
   101         if (instance == null)
   102             instance = new Attr(context);
   103         return instance;
   104     }
   106     protected Attr(Context context) {
   107         context.put(attrKey, this);
   109         names = Names.instance(context);
   110         log = Log.instance(context);
   111         syms = Symtab.instance(context);
   112         rs = Resolve.instance(context);
   113         chk = Check.instance(context);
   114         flow = Flow.instance(context);
   115         memberEnter = MemberEnter.instance(context);
   116         make = TreeMaker.instance(context);
   117         enter = Enter.instance(context);
   118         infer = Infer.instance(context);
   119         deferredAttr = DeferredAttr.instance(context);
   120         cfolder = ConstFold.instance(context);
   121         target = Target.instance(context);
   122         types = Types.instance(context);
   123         diags = JCDiagnostic.Factory.instance(context);
   124         annotate = Annotate.instance(context);
   125         typeAnnotations = TypeAnnotations.instance(context);
   126         deferredLintHandler = DeferredLintHandler.instance(context);
   127         typeEnvs = TypeEnvs.instance(context);
   129         Options options = Options.instance(context);
   131         Source source = Source.instance(context);
   132         allowGenerics = source.allowGenerics();
   133         allowVarargs = source.allowVarargs();
   134         allowEnums = source.allowEnums();
   135         allowBoxing = source.allowBoxing();
   136         allowCovariantReturns = source.allowCovariantReturns();
   137         allowAnonOuterThis = source.allowAnonOuterThis();
   138         allowStringsInSwitch = source.allowStringsInSwitch();
   139         allowPoly = source.allowPoly();
   140         allowTypeAnnos = source.allowTypeAnnotations();
   141         allowLambda = source.allowLambda();
   142         allowDefaultMethods = source.allowDefaultMethods();
   143         allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
   144         sourceName = source.name;
   145         relax = (options.isSet("-retrofit") ||
   146                  options.isSet("-relax"));
   147         findDiamonds = options.get("findDiamond") != null &&
   148                  source.allowDiamond();
   149         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   150         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   152         statInfo = new ResultInfo(NIL, Type.noType);
   153         varInfo = new ResultInfo(VAR, Type.noType);
   154         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   155         unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly);
   156         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   157         unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
   158         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   159     }
   161     /** Switch: relax some constraints for retrofit mode.
   162      */
   163     boolean relax;
   165     /** Switch: support target-typing inference
   166      */
   167     boolean allowPoly;
   169     /** Switch: support type annotations.
   170      */
   171     boolean allowTypeAnnos;
   173     /** Switch: support generics?
   174      */
   175     boolean allowGenerics;
   177     /** Switch: allow variable-arity methods.
   178      */
   179     boolean allowVarargs;
   181     /** Switch: support enums?
   182      */
   183     boolean allowEnums;
   185     /** Switch: support boxing and unboxing?
   186      */
   187     boolean allowBoxing;
   189     /** Switch: support covariant result types?
   190      */
   191     boolean allowCovariantReturns;
   193     /** Switch: support lambda expressions ?
   194      */
   195     boolean allowLambda;
   197     /** Switch: support default methods ?
   198      */
   199     boolean allowDefaultMethods;
   201     /** Switch: static interface methods enabled?
   202      */
   203     boolean allowStaticInterfaceMethods;
   205     /** Switch: allow references to surrounding object from anonymous
   206      * objects during constructor call?
   207      */
   208     boolean allowAnonOuterThis;
   210     /** Switch: generates a warning if diamond can be safely applied
   211      *  to a given new expression
   212      */
   213     boolean findDiamonds;
   215     /**
   216      * Internally enables/disables diamond finder feature
   217      */
   218     static final boolean allowDiamondFinder = true;
   220     /**
   221      * Switch: warn about use of variable before declaration?
   222      * RFE: 6425594
   223      */
   224     boolean useBeforeDeclarationWarning;
   226     /**
   227      * Switch: generate warnings whenever an anonymous inner class that is convertible
   228      * to a lambda expression is found
   229      */
   230     boolean identifyLambdaCandidate;
   232     /**
   233      * Switch: allow strings in switch?
   234      */
   235     boolean allowStringsInSwitch;
   237     /**
   238      * Switch: name of source level; used for error reporting.
   239      */
   240     String sourceName;
   242     /** Check kind and type of given tree against protokind and prototype.
   243      *  If check succeeds, store type in tree and return it.
   244      *  If check fails, store errType in tree and return it.
   245      *  No checks are performed if the prototype is a method type.
   246      *  It is not necessary in this case since we know that kind and type
   247      *  are correct.
   248      *
   249      *  @param tree     The tree whose kind and type is checked
   250      *  @param ownkind  The computed kind of the tree
   251      *  @param resultInfo  The expected result of the tree
   252      */
   253     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   254         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   255         Type owntype;
   256         if (!found.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   257             if ((ownkind & ~resultInfo.pkind) != 0) {
   258                 log.error(tree.pos(), "unexpected.type",
   259                         kindNames(resultInfo.pkind),
   260                         kindName(ownkind));
   261                 owntype = types.createErrorType(found);
   262             } else if (allowPoly && inferenceContext.free(found)) {
   263                 //delay the check if there are inference variables in the found type
   264                 //this means we are dealing with a partially inferred poly expression
   265                 owntype = resultInfo.pt;
   266                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   267                     @Override
   268                     public void typesInferred(InferenceContext inferenceContext) {
   269                         ResultInfo pendingResult =
   270                                 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   271                         check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   272                     }
   273                 });
   274             } else {
   275                 owntype = resultInfo.check(tree, found);
   276             }
   277         } else {
   278             owntype = found;
   279         }
   280         tree.type = owntype;
   281         return owntype;
   282     }
   284     /** Is given blank final variable assignable, i.e. in a scope where it
   285      *  may be assigned to even though it is final?
   286      *  @param v      The blank final variable.
   287      *  @param env    The current environment.
   288      */
   289     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   290         Symbol owner = env.info.scope.owner;
   291            // owner refers to the innermost variable, method or
   292            // initializer block declaration at this point.
   293         return
   294             v.owner == owner
   295             ||
   296             ((owner.name == names.init ||    // i.e. we are in a constructor
   297               owner.kind == VAR ||           // i.e. we are in a variable initializer
   298               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   299              &&
   300              v.owner == owner.owner
   301              &&
   302              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   303     }
   305     /** Check that variable can be assigned to.
   306      *  @param pos    The current source code position.
   307      *  @param v      The assigned varaible
   308      *  @param base   If the variable is referred to in a Select, the part
   309      *                to the left of the `.', null otherwise.
   310      *  @param env    The current environment.
   311      */
   312     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   313         if ((v.flags() & FINAL) != 0 &&
   314             ((v.flags() & HASINIT) != 0
   315              ||
   316              !((base == null ||
   317                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   318                isAssignableAsBlankFinal(v, env)))) {
   319             if (v.isResourceVariable()) { //TWR resource
   320                 log.error(pos, "try.resource.may.not.be.assigned", v);
   321             } else {
   322                 log.error(pos, "cant.assign.val.to.final.var", v);
   323             }
   324         }
   325     }
   327     /** Does tree represent a static reference to an identifier?
   328      *  It is assumed that tree is either a SELECT or an IDENT.
   329      *  We have to weed out selects from non-type names here.
   330      *  @param tree    The candidate tree.
   331      */
   332     boolean isStaticReference(JCTree tree) {
   333         if (tree.hasTag(SELECT)) {
   334             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   335             if (lsym == null || lsym.kind != TYP) {
   336                 return false;
   337             }
   338         }
   339         return true;
   340     }
   342     /** Is this symbol a type?
   343      */
   344     static boolean isType(Symbol sym) {
   345         return sym != null && sym.kind == TYP;
   346     }
   348     /** The current `this' symbol.
   349      *  @param env    The current environment.
   350      */
   351     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   352         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   353     }
   355     /** Attribute a parsed identifier.
   356      * @param tree Parsed identifier name
   357      * @param topLevel The toplevel to use
   358      */
   359     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   360         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   361         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   362                                            syms.errSymbol.name,
   363                                            null, null, null, null);
   364         localEnv.enclClass.sym = syms.errSymbol;
   365         return tree.accept(identAttributer, localEnv);
   366     }
   367     // where
   368         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   369         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   370             @Override
   371             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   372                 Symbol site = visit(node.getExpression(), env);
   373                 if (site.kind == ERR || site.kind == ABSENT_TYP)
   374                     return site;
   375                 Name name = (Name)node.getIdentifier();
   376                 if (site.kind == PCK) {
   377                     env.toplevel.packge = (PackageSymbol)site;
   378                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   379                 } else {
   380                     env.enclClass.sym = (ClassSymbol)site;
   381                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   382                 }
   383             }
   385             @Override
   386             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   387                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   388             }
   389         }
   391     public Type coerce(Type etype, Type ttype) {
   392         return cfolder.coerce(etype, ttype);
   393     }
   395     public Type attribType(JCTree node, TypeSymbol sym) {
   396         Env<AttrContext> env = typeEnvs.get(sym);
   397         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   398         return attribTree(node, localEnv, unknownTypeInfo);
   399     }
   401     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   402         // Attribute qualifying package or class.
   403         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   404         return attribTree(s.selected,
   405                        env,
   406                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   407                        Type.noType));
   408     }
   410     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   411         breakTree = tree;
   412         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   413         try {
   414             attribExpr(expr, env);
   415         } catch (BreakAttr b) {
   416             return b.env;
   417         } catch (AssertionError ae) {
   418             if (ae.getCause() instanceof BreakAttr) {
   419                 return ((BreakAttr)(ae.getCause())).env;
   420             } else {
   421                 throw ae;
   422             }
   423         } finally {
   424             breakTree = null;
   425             log.useSource(prev);
   426         }
   427         return env;
   428     }
   430     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   431         breakTree = tree;
   432         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   433         try {
   434             attribStat(stmt, env);
   435         } catch (BreakAttr b) {
   436             return b.env;
   437         } catch (AssertionError ae) {
   438             if (ae.getCause() instanceof BreakAttr) {
   439                 return ((BreakAttr)(ae.getCause())).env;
   440             } else {
   441                 throw ae;
   442             }
   443         } finally {
   444             breakTree = null;
   445             log.useSource(prev);
   446         }
   447         return env;
   448     }
   450     private JCTree breakTree = null;
   452     private static class BreakAttr extends RuntimeException {
   453         static final long serialVersionUID = -6924771130405446405L;
   454         private Env<AttrContext> env;
   455         private BreakAttr(Env<AttrContext> env) {
   456             this.env = env;
   457         }
   458     }
   460     class ResultInfo {
   461         final int pkind;
   462         final Type pt;
   463         final CheckContext checkContext;
   465         ResultInfo(int pkind, Type pt) {
   466             this(pkind, pt, chk.basicHandler);
   467         }
   469         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   470             this.pkind = pkind;
   471             this.pt = pt;
   472             this.checkContext = checkContext;
   473         }
   475         protected Type check(final DiagnosticPosition pos, final Type found) {
   476             return chk.checkType(pos, found, pt, checkContext);
   477         }
   479         protected ResultInfo dup(Type newPt) {
   480             return new ResultInfo(pkind, newPt, checkContext);
   481         }
   483         protected ResultInfo dup(CheckContext newContext) {
   484             return new ResultInfo(pkind, pt, newContext);
   485         }
   487         protected ResultInfo dup(Type newPt, CheckContext newContext) {
   488             return new ResultInfo(pkind, newPt, newContext);
   489         }
   491         @Override
   492         public String toString() {
   493             if (pt != null) {
   494                 return pt.toString();
   495             } else {
   496                 return "";
   497             }
   498         }
   499     }
   501     class RecoveryInfo extends ResultInfo {
   503         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   504             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   505                 @Override
   506                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   507                     return deferredAttrContext;
   508                 }
   509                 @Override
   510                 public boolean compatible(Type found, Type req, Warner warn) {
   511                     return true;
   512                 }
   513                 @Override
   514                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   515                     chk.basicHandler.report(pos, details);
   516                 }
   517             });
   518         }
   519     }
   521     final ResultInfo statInfo;
   522     final ResultInfo varInfo;
   523     final ResultInfo unknownAnyPolyInfo;
   524     final ResultInfo unknownExprInfo;
   525     final ResultInfo unknownTypeInfo;
   526     final ResultInfo unknownTypeExprInfo;
   527     final ResultInfo recoveryInfo;
   529     Type pt() {
   530         return resultInfo.pt;
   531     }
   533     int pkind() {
   534         return resultInfo.pkind;
   535     }
   537 /* ************************************************************************
   538  * Visitor methods
   539  *************************************************************************/
   541     /** Visitor argument: the current environment.
   542      */
   543     Env<AttrContext> env;
   545     /** Visitor argument: the currently expected attribution result.
   546      */
   547     ResultInfo resultInfo;
   549     /** Visitor result: the computed type.
   550      */
   551     Type result;
   553     /** Visitor method: attribute a tree, catching any completion failure
   554      *  exceptions. Return the tree's type.
   555      *
   556      *  @param tree    The tree to be visited.
   557      *  @param env     The environment visitor argument.
   558      *  @param resultInfo   The result info visitor argument.
   559      */
   560     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   561         Env<AttrContext> prevEnv = this.env;
   562         ResultInfo prevResult = this.resultInfo;
   563         try {
   564             this.env = env;
   565             this.resultInfo = resultInfo;
   566             tree.accept(this);
   567             if (tree == breakTree &&
   568                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   569                 throw new BreakAttr(copyEnv(env));
   570             }
   571             return result;
   572         } catch (CompletionFailure ex) {
   573             tree.type = syms.errType;
   574             return chk.completionError(tree.pos(), ex);
   575         } finally {
   576             this.env = prevEnv;
   577             this.resultInfo = prevResult;
   578         }
   579     }
   581     Env<AttrContext> copyEnv(Env<AttrContext> env) {
   582         Env<AttrContext> newEnv =
   583                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   584         if (newEnv.outer != null) {
   585             newEnv.outer = copyEnv(newEnv.outer);
   586         }
   587         return newEnv;
   588     }
   590     Scope copyScope(Scope sc) {
   591         Scope newScope = new Scope(sc.owner);
   592         List<Symbol> elemsList = List.nil();
   593         while (sc != null) {
   594             for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   595                 elemsList = elemsList.prepend(e.sym);
   596             }
   597             sc = sc.next;
   598         }
   599         for (Symbol s : elemsList) {
   600             newScope.enter(s);
   601         }
   602         return newScope;
   603     }
   605     /** Derived visitor method: attribute an expression tree.
   606      */
   607     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   608         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   609     }
   611     /** Derived visitor method: attribute an expression tree with
   612      *  no constraints on the computed type.
   613      */
   614     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   615         return attribTree(tree, env, unknownExprInfo);
   616     }
   618     /** Derived visitor method: attribute a type tree.
   619      */
   620     public Type attribType(JCTree tree, Env<AttrContext> env) {
   621         Type result = attribType(tree, env, Type.noType);
   622         return result;
   623     }
   625     /** Derived visitor method: attribute a type tree.
   626      */
   627     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   628         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   629         return result;
   630     }
   632     /** Derived visitor method: attribute a statement or definition tree.
   633      */
   634     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   635         return attribTree(tree, env, statInfo);
   636     }
   638     /** Attribute a list of expressions, returning a list of types.
   639      */
   640     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   641         ListBuffer<Type> ts = new ListBuffer<Type>();
   642         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   643             ts.append(attribExpr(l.head, env, pt));
   644         return ts.toList();
   645     }
   647     /** Attribute a list of statements, returning nothing.
   648      */
   649     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   650         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   651             attribStat(l.head, env);
   652     }
   654     /** Attribute the arguments in a method call, returning the method kind.
   655      */
   656     int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   657         int kind = VAL;
   658         for (JCExpression arg : trees) {
   659             Type argtype;
   660             if (allowPoly && deferredAttr.isDeferred(env, arg)) {
   661                 argtype = deferredAttr.new DeferredType(arg, env);
   662                 kind |= POLY;
   663             } else {
   664                 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
   665             }
   666             argtypes.append(argtype);
   667         }
   668         return kind;
   669     }
   671     /** Attribute a type argument list, returning a list of types.
   672      *  Caller is responsible for calling checkRefTypes.
   673      */
   674     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   675         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   676         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   677             argtypes.append(attribType(l.head, env));
   678         return argtypes.toList();
   679     }
   681     /** Attribute a type argument list, returning a list of types.
   682      *  Check that all the types are references.
   683      */
   684     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   685         List<Type> types = attribAnyTypes(trees, env);
   686         return chk.checkRefTypes(trees, types);
   687     }
   689     /**
   690      * Attribute type variables (of generic classes or methods).
   691      * Compound types are attributed later in attribBounds.
   692      * @param typarams the type variables to enter
   693      * @param env      the current environment
   694      */
   695     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   696         for (JCTypeParameter tvar : typarams) {
   697             TypeVar a = (TypeVar)tvar.type;
   698             a.tsym.flags_field |= UNATTRIBUTED;
   699             a.bound = Type.noType;
   700             if (!tvar.bounds.isEmpty()) {
   701                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   702                 for (JCExpression bound : tvar.bounds.tail)
   703                     bounds = bounds.prepend(attribType(bound, env));
   704                 types.setBounds(a, bounds.reverse());
   705             } else {
   706                 // if no bounds are given, assume a single bound of
   707                 // java.lang.Object.
   708                 types.setBounds(a, List.of(syms.objectType));
   709             }
   710             a.tsym.flags_field &= ~UNATTRIBUTED;
   711         }
   712         for (JCTypeParameter tvar : typarams) {
   713             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   714         }
   715     }
   717     /**
   718      * Attribute the type references in a list of annotations.
   719      */
   720     void attribAnnotationTypes(List<JCAnnotation> annotations,
   721                                Env<AttrContext> env) {
   722         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   723             JCAnnotation a = al.head;
   724             attribType(a.annotationType, env);
   725         }
   726     }
   728     /**
   729      * Attribute a "lazy constant value".
   730      *  @param env         The env for the const value
   731      *  @param initializer The initializer for the const value
   732      *  @param type        The expected type, or null
   733      *  @see VarSymbol#setLazyConstValue
   734      */
   735     public Object attribLazyConstantValue(Env<AttrContext> env,
   736                                       JCVariableDecl variable,
   737                                       Type type) {
   739         DiagnosticPosition prevLintPos
   740                 = deferredLintHandler.setPos(variable.pos());
   742         try {
   743             // Use null as symbol to not attach the type annotation to any symbol.
   744             // The initializer will later also be visited and then we'll attach
   745             // to the symbol.
   746             // This prevents having multiple type annotations, just because of
   747             // lazy constant value evaluation.
   748             memberEnter.typeAnnotate(variable.init, env, null, variable.pos());
   749             annotate.flush();
   750             Type itype = attribExpr(variable.init, env, type);
   751             if (itype.constValue() != null) {
   752                 return coerce(itype, type).constValue();
   753             } else {
   754                 return null;
   755             }
   756         } finally {
   757             deferredLintHandler.setPos(prevLintPos);
   758         }
   759     }
   761     /** Attribute type reference in an `extends' or `implements' clause.
   762      *  Supertypes of anonymous inner classes are usually already attributed.
   763      *
   764      *  @param tree              The tree making up the type reference.
   765      *  @param env               The environment current at the reference.
   766      *  @param classExpected     true if only a class is expected here.
   767      *  @param interfaceExpected true if only an interface is expected here.
   768      */
   769     Type attribBase(JCTree tree,
   770                     Env<AttrContext> env,
   771                     boolean classExpected,
   772                     boolean interfaceExpected,
   773                     boolean checkExtensible) {
   774         Type t = tree.type != null ?
   775             tree.type :
   776             attribType(tree, env);
   777         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   778     }
   779     Type checkBase(Type t,
   780                    JCTree tree,
   781                    Env<AttrContext> env,
   782                    boolean classExpected,
   783                    boolean interfaceExpected,
   784                    boolean checkExtensible) {
   785         if (t.tsym.isAnonymous()) {
   786             log.error(tree.pos(), "cant.inherit.from.anon");
   787             return types.createErrorType(t);
   788         }
   789         if (t.isErroneous())
   790             return t;
   791         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   792             // check that type variable is already visible
   793             if (t.getUpperBound() == null) {
   794                 log.error(tree.pos(), "illegal.forward.ref");
   795                 return types.createErrorType(t);
   796             }
   797         } else {
   798             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   799         }
   800         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   801             log.error(tree.pos(), "intf.expected.here");
   802             // return errType is necessary since otherwise there might
   803             // be undetected cycles which cause attribution to loop
   804             return types.createErrorType(t);
   805         } else if (checkExtensible &&
   806                    classExpected &&
   807                    (t.tsym.flags() & INTERFACE) != 0) {
   808             log.error(tree.pos(), "no.intf.expected.here");
   809             return types.createErrorType(t);
   810         }
   811         if (checkExtensible &&
   812             ((t.tsym.flags() & FINAL) != 0)) {
   813             log.error(tree.pos(),
   814                       "cant.inherit.from.final", t.tsym);
   815         }
   816         chk.checkNonCyclic(tree.pos(), t);
   817         return t;
   818     }
   820     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   821         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   822         id.type = env.info.scope.owner.type;
   823         id.sym = env.info.scope.owner;
   824         return id.type;
   825     }
   827     public void visitClassDef(JCClassDecl tree) {
   828         // Local classes have not been entered yet, so we need to do it now:
   829         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   830             enter.classEnter(tree, env);
   832         ClassSymbol c = tree.sym;
   833         if (c == null) {
   834             // exit in case something drastic went wrong during enter.
   835             result = null;
   836         } else {
   837             // make sure class has been completed:
   838             c.complete();
   840             // If this class appears as an anonymous class
   841             // in a superclass constructor call where
   842             // no explicit outer instance is given,
   843             // disable implicit outer instance from being passed.
   844             // (This would be an illegal access to "this before super").
   845             if (env.info.isSelfCall &&
   846                 env.tree.hasTag(NEWCLASS) &&
   847                 ((JCNewClass) env.tree).encl == null)
   848             {
   849                 c.flags_field |= NOOUTERTHIS;
   850             }
   851             attribClass(tree.pos(), c);
   852             result = tree.type = c.type;
   853         }
   854     }
   856     public void visitMethodDef(JCMethodDecl tree) {
   857         MethodSymbol m = tree.sym;
   858         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   860         Lint lint = env.info.lint.augment(m);
   861         Lint prevLint = chk.setLint(lint);
   862         MethodSymbol prevMethod = chk.setMethod(m);
   863         try {
   864             deferredLintHandler.flush(tree.pos());
   865             chk.checkDeprecatedAnnotation(tree.pos(), m);
   868             // Create a new environment with local scope
   869             // for attributing the method.
   870             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   871             localEnv.info.lint = lint;
   873             attribStats(tree.typarams, localEnv);
   875             // If we override any other methods, check that we do so properly.
   876             // JLS ???
   877             if (m.isStatic()) {
   878                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   879             } else {
   880                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   881             }
   882             chk.checkOverride(tree, m);
   884             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   885                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   886             }
   888             // Enter all type parameters into the local method scope.
   889             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   890                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   892             ClassSymbol owner = env.enclClass.sym;
   893             if ((owner.flags() & ANNOTATION) != 0 &&
   894                 tree.params.nonEmpty())
   895                 log.error(tree.params.head.pos(),
   896                           "intf.annotation.members.cant.have.params");
   898             // Attribute all value parameters.
   899             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   900                 attribStat(l.head, localEnv);
   901             }
   903             chk.checkVarargsMethodDecl(localEnv, tree);
   905             // Check that type parameters are well-formed.
   906             chk.validate(tree.typarams, localEnv);
   908             // Check that result type is well-formed.
   909             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
   910                 chk.validate(tree.restype, localEnv);
   912             // Check that receiver type is well-formed.
   913             if (tree.recvparam != null) {
   914                 // Use a new environment to check the receiver parameter.
   915                 // Otherwise I get "might not have been initialized" errors.
   916                 // Is there a better way?
   917                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   918                 attribType(tree.recvparam, newEnv);
   919                 chk.validate(tree.recvparam, newEnv);
   920             }
   922             // annotation method checks
   923             if ((owner.flags() & ANNOTATION) != 0) {
   924                 // annotation method cannot have throws clause
   925                 if (tree.thrown.nonEmpty()) {
   926                     log.error(tree.thrown.head.pos(),
   927                             "throws.not.allowed.in.intf.annotation");
   928                 }
   929                 // annotation method cannot declare type-parameters
   930                 if (tree.typarams.nonEmpty()) {
   931                     log.error(tree.typarams.head.pos(),
   932                             "intf.annotation.members.cant.have.type.params");
   933                 }
   934                 // validate annotation method's return type (could be an annotation type)
   935                 chk.validateAnnotationType(tree.restype);
   936                 // ensure that annotation method does not clash with members of Object/Annotation
   937                 chk.validateAnnotationMethod(tree.pos(), m);
   938             }
   940             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   941                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   943             if (tree.body == null) {
   944                 // Empty bodies are only allowed for
   945                 // abstract, native, or interface methods, or for methods
   946                 // in a retrofit signature class.
   947                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   948                     !relax)
   949                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   950                 if (tree.defaultValue != null) {
   951                     if ((owner.flags() & ANNOTATION) == 0)
   952                         log.error(tree.pos(),
   953                                   "default.allowed.in.intf.annotation.member");
   954                 }
   955             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   956                 if ((owner.flags() & INTERFACE) != 0) {
   957                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   958                 } else {
   959                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   960                 }
   961             } else if ((tree.mods.flags & NATIVE) != 0) {
   962                 log.error(tree.pos(), "native.meth.cant.have.body");
   963             } else {
   964                 // Add an implicit super() call unless an explicit call to
   965                 // super(...) or this(...) is given
   966                 // or we are compiling class java.lang.Object.
   967                 if (tree.name == names.init && owner.type != syms.objectType) {
   968                     JCBlock body = tree.body;
   969                     if (body.stats.isEmpty() ||
   970                         !TreeInfo.isSelfCall(body.stats.head)) {
   971                         body.stats = body.stats.
   972                             prepend(memberEnter.SuperCall(make.at(body.pos),
   973                                                           List.<Type>nil(),
   974                                                           List.<JCVariableDecl>nil(),
   975                                                           false));
   976                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   977                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   978                                TreeInfo.isSuperCall(body.stats.head)) {
   979                         // enum constructors are not allowed to call super
   980                         // directly, so make sure there aren't any super calls
   981                         // in enum constructors, except in the compiler
   982                         // generated one.
   983                         log.error(tree.body.stats.head.pos(),
   984                                   "call.to.super.not.allowed.in.enum.ctor",
   985                                   env.enclClass.sym);
   986                     }
   987                 }
   989                 // Attribute all type annotations in the body
   990                 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
   991                 annotate.flush();
   993                 // Attribute method body.
   994                 attribStat(tree.body, localEnv);
   995             }
   997             localEnv.info.scope.leave();
   998             result = tree.type = m.type;
   999         }
  1000         finally {
  1001             chk.setLint(prevLint);
  1002             chk.setMethod(prevMethod);
  1006     public void visitVarDef(JCVariableDecl tree) {
  1007         // Local variables have not been entered yet, so we need to do it now:
  1008         if (env.info.scope.owner.kind == MTH) {
  1009             if (tree.sym != null) {
  1010                 // parameters have already been entered
  1011                 env.info.scope.enter(tree.sym);
  1012             } else {
  1013                 try {
  1014                     annotate.enterStart();
  1015                     memberEnter.memberEnter(tree, env);
  1016                 } finally {
  1017                     annotate.enterDone();
  1020         } else {
  1021             if (tree.init != null) {
  1022                 // Field initializer expression need to be entered.
  1023                 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
  1024                 annotate.flush();
  1028         VarSymbol v = tree.sym;
  1029         Lint lint = env.info.lint.augment(v);
  1030         Lint prevLint = chk.setLint(lint);
  1032         // Check that the variable's declared type is well-formed.
  1033         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1034                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1035                 (tree.sym.flags() & PARAMETER) != 0;
  1036         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1038         try {
  1039             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1040             deferredLintHandler.flush(tree.pos());
  1041             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1043             if (tree.init != null) {
  1044                 if ((v.flags_field & FINAL) == 0 ||
  1045                     !memberEnter.needsLazyConstValue(tree.init)) {
  1046                     // Not a compile-time constant
  1047                     // Attribute initializer in a new environment
  1048                     // with the declared variable as owner.
  1049                     // Check that initializer conforms to variable's declared type.
  1050                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1051                     initEnv.info.lint = lint;
  1052                     // In order to catch self-references, we set the variable's
  1053                     // declaration position to maximal possible value, effectively
  1054                     // marking the variable as undefined.
  1055                     initEnv.info.enclVar = v;
  1056                     attribExpr(tree.init, initEnv, v.type);
  1059             result = tree.type = v.type;
  1061         finally {
  1062             chk.setLint(prevLint);
  1066     public void visitSkip(JCSkip tree) {
  1067         result = null;
  1070     public void visitBlock(JCBlock tree) {
  1071         if (env.info.scope.owner.kind == TYP) {
  1072             // Block is a static or instance initializer;
  1073             // let the owner of the environment be a freshly
  1074             // created BLOCK-method.
  1075             Env<AttrContext> localEnv =
  1076                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1077             localEnv.info.scope.owner =
  1078                 new MethodSymbol(tree.flags | BLOCK |
  1079                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1080                     env.info.scope.owner);
  1081             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1083             // Attribute all type annotations in the block
  1084             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1085             annotate.flush();
  1088                 // Store init and clinit type annotations with the ClassSymbol
  1089                 // to allow output in Gen.normalizeDefs.
  1090                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1091                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1092                 if ((tree.flags & STATIC) != 0) {
  1093                     cs.appendClassInitTypeAttributes(tas);
  1094                 } else {
  1095                     cs.appendInitTypeAttributes(tas);
  1099             attribStats(tree.stats, localEnv);
  1100         } else {
  1101             // Create a new local environment with a local scope.
  1102             Env<AttrContext> localEnv =
  1103                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1104             try {
  1105                 attribStats(tree.stats, localEnv);
  1106             } finally {
  1107                 localEnv.info.scope.leave();
  1110         result = null;
  1113     public void visitDoLoop(JCDoWhileLoop tree) {
  1114         attribStat(tree.body, env.dup(tree));
  1115         attribExpr(tree.cond, env, syms.booleanType);
  1116         result = null;
  1119     public void visitWhileLoop(JCWhileLoop tree) {
  1120         attribExpr(tree.cond, env, syms.booleanType);
  1121         attribStat(tree.body, env.dup(tree));
  1122         result = null;
  1125     public void visitForLoop(JCForLoop tree) {
  1126         Env<AttrContext> loopEnv =
  1127             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1128         try {
  1129             attribStats(tree.init, loopEnv);
  1130             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1131             loopEnv.tree = tree; // before, we were not in loop!
  1132             attribStats(tree.step, loopEnv);
  1133             attribStat(tree.body, loopEnv);
  1134             result = null;
  1136         finally {
  1137             loopEnv.info.scope.leave();
  1141     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1142         Env<AttrContext> loopEnv =
  1143             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1144         try {
  1145             //the Formal Parameter of a for-each loop is not in the scope when
  1146             //attributing the for-each expression; we mimick this by attributing
  1147             //the for-each expression first (against original scope).
  1148             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
  1149             attribStat(tree.var, loopEnv);
  1150             chk.checkNonVoid(tree.pos(), exprType);
  1151             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1152             if (elemtype == null) {
  1153                 // or perhaps expr implements Iterable<T>?
  1154                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1155                 if (base == null) {
  1156                     log.error(tree.expr.pos(),
  1157                             "foreach.not.applicable.to.type",
  1158                             exprType,
  1159                             diags.fragment("type.req.array.or.iterable"));
  1160                     elemtype = types.createErrorType(exprType);
  1161                 } else {
  1162                     List<Type> iterableParams = base.allparams();
  1163                     elemtype = iterableParams.isEmpty()
  1164                         ? syms.objectType
  1165                         : types.wildUpperBound(iterableParams.head);
  1168             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1169             loopEnv.tree = tree; // before, we were not in loop!
  1170             attribStat(tree.body, loopEnv);
  1171             result = null;
  1173         finally {
  1174             loopEnv.info.scope.leave();
  1178     public void visitLabelled(JCLabeledStatement tree) {
  1179         // Check that label is not used in an enclosing statement
  1180         Env<AttrContext> env1 = env;
  1181         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1182             if (env1.tree.hasTag(LABELLED) &&
  1183                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1184                 log.error(tree.pos(), "label.already.in.use",
  1185                           tree.label);
  1186                 break;
  1188             env1 = env1.next;
  1191         attribStat(tree.body, env.dup(tree));
  1192         result = null;
  1195     public void visitSwitch(JCSwitch tree) {
  1196         Type seltype = attribExpr(tree.selector, env);
  1198         Env<AttrContext> switchEnv =
  1199             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1201         try {
  1203             boolean enumSwitch =
  1204                 allowEnums &&
  1205                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1206             boolean stringSwitch = false;
  1207             if (types.isSameType(seltype, syms.stringType)) {
  1208                 if (allowStringsInSwitch) {
  1209                     stringSwitch = true;
  1210                 } else {
  1211                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1214             if (!enumSwitch && !stringSwitch)
  1215                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1217             // Attribute all cases and
  1218             // check that there are no duplicate case labels or default clauses.
  1219             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1220             boolean hasDefault = false;      // Is there a default label?
  1221             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1222                 JCCase c = l.head;
  1223                 Env<AttrContext> caseEnv =
  1224                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1225                 try {
  1226                     if (c.pat != null) {
  1227                         if (enumSwitch) {
  1228                             Symbol sym = enumConstant(c.pat, seltype);
  1229                             if (sym == null) {
  1230                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1231                             } else if (!labels.add(sym)) {
  1232                                 log.error(c.pos(), "duplicate.case.label");
  1234                         } else {
  1235                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1236                             if (!pattype.hasTag(ERROR)) {
  1237                                 if (pattype.constValue() == null) {
  1238                                     log.error(c.pat.pos(),
  1239                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1240                                 } else if (labels.contains(pattype.constValue())) {
  1241                                     log.error(c.pos(), "duplicate.case.label");
  1242                                 } else {
  1243                                     labels.add(pattype.constValue());
  1247                     } else if (hasDefault) {
  1248                         log.error(c.pos(), "duplicate.default.label");
  1249                     } else {
  1250                         hasDefault = true;
  1252                     attribStats(c.stats, caseEnv);
  1253                 } finally {
  1254                     caseEnv.info.scope.leave();
  1255                     addVars(c.stats, switchEnv.info.scope);
  1259             result = null;
  1261         finally {
  1262             switchEnv.info.scope.leave();
  1265     // where
  1266         /** Add any variables defined in stats to the switch scope. */
  1267         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1268             for (;stats.nonEmpty(); stats = stats.tail) {
  1269                 JCTree stat = stats.head;
  1270                 if (stat.hasTag(VARDEF))
  1271                     switchScope.enter(((JCVariableDecl) stat).sym);
  1274     // where
  1275     /** Return the selected enumeration constant symbol, or null. */
  1276     private Symbol enumConstant(JCTree tree, Type enumType) {
  1277         if (!tree.hasTag(IDENT)) {
  1278             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1279             return syms.errSymbol;
  1281         JCIdent ident = (JCIdent)tree;
  1282         Name name = ident.name;
  1283         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1284              e.scope != null; e = e.next()) {
  1285             if (e.sym.kind == VAR) {
  1286                 Symbol s = ident.sym = e.sym;
  1287                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1288                 ident.type = s.type;
  1289                 return ((s.flags_field & Flags.ENUM) == 0)
  1290                     ? null : s;
  1293         return null;
  1296     public void visitSynchronized(JCSynchronized tree) {
  1297         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1298         attribStat(tree.body, env);
  1299         result = null;
  1302     public void visitTry(JCTry tree) {
  1303         // Create a new local environment with a local
  1304         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1305         try {
  1306             boolean isTryWithResource = tree.resources.nonEmpty();
  1307             // Create a nested environment for attributing the try block if needed
  1308             Env<AttrContext> tryEnv = isTryWithResource ?
  1309                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1310                 localEnv;
  1311             try {
  1312                 // Attribute resource declarations
  1313                 for (JCTree resource : tree.resources) {
  1314                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1315                         @Override
  1316                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1317                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1319                     };
  1320                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1321                     if (resource.hasTag(VARDEF)) {
  1322                         attribStat(resource, tryEnv);
  1323                         twrResult.check(resource, resource.type);
  1325                         //check that resource type cannot throw InterruptedException
  1326                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1328                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1329                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1330                     } else {
  1331                         attribTree(resource, tryEnv, twrResult);
  1334                 // Attribute body
  1335                 attribStat(tree.body, tryEnv);
  1336             } finally {
  1337                 if (isTryWithResource)
  1338                     tryEnv.info.scope.leave();
  1341             // Attribute catch clauses
  1342             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1343                 JCCatch c = l.head;
  1344                 Env<AttrContext> catchEnv =
  1345                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1346                 try {
  1347                     Type ctype = attribStat(c.param, catchEnv);
  1348                     if (TreeInfo.isMultiCatch(c)) {
  1349                         //multi-catch parameter is implicitly marked as final
  1350                         c.param.sym.flags_field |= FINAL | UNION;
  1352                     if (c.param.sym.kind == Kinds.VAR) {
  1353                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1355                     chk.checkType(c.param.vartype.pos(),
  1356                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1357                                   syms.throwableType);
  1358                     attribStat(c.body, catchEnv);
  1359                 } finally {
  1360                     catchEnv.info.scope.leave();
  1364             // Attribute finalizer
  1365             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1366             result = null;
  1368         finally {
  1369             localEnv.info.scope.leave();
  1373     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1374         if (!resource.isErroneous() &&
  1375             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1376             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1377             Symbol close = syms.noSymbol;
  1378             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1379             try {
  1380                 close = rs.resolveQualifiedMethod(pos,
  1381                         env,
  1382                         resource,
  1383                         names.close,
  1384                         List.<Type>nil(),
  1385                         List.<Type>nil());
  1387             finally {
  1388                 log.popDiagnosticHandler(discardHandler);
  1390             if (close.kind == MTH &&
  1391                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1392                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1393                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1394                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1399     public void visitConditional(JCConditional tree) {
  1400         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1402         tree.polyKind = (!allowPoly ||
  1403                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1404                 isBooleanOrNumeric(env, tree)) ?
  1405                 PolyKind.STANDALONE : PolyKind.POLY;
  1407         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1408             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1409             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1410             result = tree.type = types.createErrorType(resultInfo.pt);
  1411             return;
  1414         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1415                 unknownExprInfo :
  1416                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1417                     //this will use enclosing check context to check compatibility of
  1418                     //subexpression against target type; if we are in a method check context,
  1419                     //depending on whether boxing is allowed, we could have incompatibilities
  1420                     @Override
  1421                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1422                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1424                 });
  1426         Type truetype = attribTree(tree.truepart, env, condInfo);
  1427         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1429         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1430         if (condtype.constValue() != null &&
  1431                 truetype.constValue() != null &&
  1432                 falsetype.constValue() != null &&
  1433                 !owntype.hasTag(NONE)) {
  1434             //constant folding
  1435             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1437         result = check(tree, owntype, VAL, resultInfo);
  1439     //where
  1440         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1441             switch (tree.getTag()) {
  1442                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1443                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1444                               ((JCLiteral)tree).typetag == BOT;
  1445                 case LAMBDA: case REFERENCE: return false;
  1446                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1447                 case CONDEXPR:
  1448                     JCConditional condTree = (JCConditional)tree;
  1449                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1450                             isBooleanOrNumeric(env, condTree.falsepart);
  1451                 case APPLY:
  1452                     JCMethodInvocation speculativeMethodTree =
  1453                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1454                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1455                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1456                 case NEWCLASS:
  1457                     JCExpression className =
  1458                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1459                     JCExpression speculativeNewClassTree =
  1460                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1461                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1462                 default:
  1463                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1464                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1465                     return speculativeType.isPrimitive();
  1468         //where
  1469             TreeTranslator removeClassParams = new TreeTranslator() {
  1470                 @Override
  1471                 public void visitTypeApply(JCTypeApply tree) {
  1472                     result = translate(tree.clazz);
  1474             };
  1476         /** Compute the type of a conditional expression, after
  1477          *  checking that it exists.  See JLS 15.25. Does not take into
  1478          *  account the special case where condition and both arms
  1479          *  are constants.
  1481          *  @param pos      The source position to be used for error
  1482          *                  diagnostics.
  1483          *  @param thentype The type of the expression's then-part.
  1484          *  @param elsetype The type of the expression's else-part.
  1485          */
  1486         private Type condType(DiagnosticPosition pos,
  1487                                Type thentype, Type elsetype) {
  1488             // If same type, that is the result
  1489             if (types.isSameType(thentype, elsetype))
  1490                 return thentype.baseType();
  1492             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1493                 ? thentype : types.unboxedType(thentype);
  1494             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1495                 ? elsetype : types.unboxedType(elsetype);
  1497             // Otherwise, if both arms can be converted to a numeric
  1498             // type, return the least numeric type that fits both arms
  1499             // (i.e. return larger of the two, or return int if one
  1500             // arm is short, the other is char).
  1501             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1502                 // If one arm has an integer subrange type (i.e., byte,
  1503                 // short, or char), and the other is an integer constant
  1504                 // that fits into the subrange, return the subrange type.
  1505                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1506                     elseUnboxed.hasTag(INT) &&
  1507                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1508                     return thenUnboxed.baseType();
  1510                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1511                     thenUnboxed.hasTag(INT) &&
  1512                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1513                     return elseUnboxed.baseType();
  1516                 for (TypeTag tag : primitiveTags) {
  1517                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1518                     if (types.isSubtype(thenUnboxed, candidate) &&
  1519                         types.isSubtype(elseUnboxed, candidate)) {
  1520                         return candidate;
  1525             // Those were all the cases that could result in a primitive
  1526             if (allowBoxing) {
  1527                 if (thentype.isPrimitive())
  1528                     thentype = types.boxedClass(thentype).type;
  1529                 if (elsetype.isPrimitive())
  1530                     elsetype = types.boxedClass(elsetype).type;
  1533             if (types.isSubtype(thentype, elsetype))
  1534                 return elsetype.baseType();
  1535             if (types.isSubtype(elsetype, thentype))
  1536                 return thentype.baseType();
  1538             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1539                 log.error(pos, "neither.conditional.subtype",
  1540                           thentype, elsetype);
  1541                 return thentype.baseType();
  1544             // both are known to be reference types.  The result is
  1545             // lub(thentype,elsetype). This cannot fail, as it will
  1546             // always be possible to infer "Object" if nothing better.
  1547             return types.lub(thentype.baseType(), elsetype.baseType());
  1550     final static TypeTag[] primitiveTags = new TypeTag[]{
  1551         BYTE,
  1552         CHAR,
  1553         SHORT,
  1554         INT,
  1555         LONG,
  1556         FLOAT,
  1557         DOUBLE,
  1558         BOOLEAN,
  1559     };
  1561     public void visitIf(JCIf tree) {
  1562         attribExpr(tree.cond, env, syms.booleanType);
  1563         attribStat(tree.thenpart, env);
  1564         if (tree.elsepart != null)
  1565             attribStat(tree.elsepart, env);
  1566         chk.checkEmptyIf(tree);
  1567         result = null;
  1570     public void visitExec(JCExpressionStatement tree) {
  1571         //a fresh environment is required for 292 inference to work properly ---
  1572         //see Infer.instantiatePolymorphicSignatureInstance()
  1573         Env<AttrContext> localEnv = env.dup(tree);
  1574         attribExpr(tree.expr, localEnv);
  1575         result = null;
  1578     public void visitBreak(JCBreak tree) {
  1579         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1580         result = null;
  1583     public void visitContinue(JCContinue tree) {
  1584         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1585         result = null;
  1587     //where
  1588         /** Return the target of a break or continue statement, if it exists,
  1589          *  report an error if not.
  1590          *  Note: The target of a labelled break or continue is the
  1591          *  (non-labelled) statement tree referred to by the label,
  1592          *  not the tree representing the labelled statement itself.
  1594          *  @param pos     The position to be used for error diagnostics
  1595          *  @param tag     The tag of the jump statement. This is either
  1596          *                 Tree.BREAK or Tree.CONTINUE.
  1597          *  @param label   The label of the jump statement, or null if no
  1598          *                 label is given.
  1599          *  @param env     The environment current at the jump statement.
  1600          */
  1601         private JCTree findJumpTarget(DiagnosticPosition pos,
  1602                                     JCTree.Tag tag,
  1603                                     Name label,
  1604                                     Env<AttrContext> env) {
  1605             // Search environments outwards from the point of jump.
  1606             Env<AttrContext> env1 = env;
  1607             LOOP:
  1608             while (env1 != null) {
  1609                 switch (env1.tree.getTag()) {
  1610                     case LABELLED:
  1611                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1612                         if (label == labelled.label) {
  1613                             // If jump is a continue, check that target is a loop.
  1614                             if (tag == CONTINUE) {
  1615                                 if (!labelled.body.hasTag(DOLOOP) &&
  1616                                         !labelled.body.hasTag(WHILELOOP) &&
  1617                                         !labelled.body.hasTag(FORLOOP) &&
  1618                                         !labelled.body.hasTag(FOREACHLOOP))
  1619                                     log.error(pos, "not.loop.label", label);
  1620                                 // Found labelled statement target, now go inwards
  1621                                 // to next non-labelled tree.
  1622                                 return TreeInfo.referencedStatement(labelled);
  1623                             } else {
  1624                                 return labelled;
  1627                         break;
  1628                     case DOLOOP:
  1629                     case WHILELOOP:
  1630                     case FORLOOP:
  1631                     case FOREACHLOOP:
  1632                         if (label == null) return env1.tree;
  1633                         break;
  1634                     case SWITCH:
  1635                         if (label == null && tag == BREAK) return env1.tree;
  1636                         break;
  1637                     case LAMBDA:
  1638                     case METHODDEF:
  1639                     case CLASSDEF:
  1640                         break LOOP;
  1641                     default:
  1643                 env1 = env1.next;
  1645             if (label != null)
  1646                 log.error(pos, "undef.label", label);
  1647             else if (tag == CONTINUE)
  1648                 log.error(pos, "cont.outside.loop");
  1649             else
  1650                 log.error(pos, "break.outside.switch.loop");
  1651             return null;
  1654     public void visitReturn(JCReturn tree) {
  1655         // Check that there is an enclosing method which is
  1656         // nested within than the enclosing class.
  1657         if (env.info.returnResult == null) {
  1658             log.error(tree.pos(), "ret.outside.meth");
  1659         } else {
  1660             // Attribute return expression, if it exists, and check that
  1661             // it conforms to result type of enclosing method.
  1662             if (tree.expr != null) {
  1663                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1664                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1665                               diags.fragment("unexpected.ret.val"));
  1667                 attribTree(tree.expr, env, env.info.returnResult);
  1668             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1669                     !env.info.returnResult.pt.hasTag(NONE)) {
  1670                 env.info.returnResult.checkContext.report(tree.pos(),
  1671                               diags.fragment("missing.ret.val"));
  1674         result = null;
  1677     public void visitThrow(JCThrow tree) {
  1678         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1679         if (allowPoly) {
  1680             chk.checkType(tree, owntype, syms.throwableType);
  1682         result = null;
  1685     public void visitAssert(JCAssert tree) {
  1686         attribExpr(tree.cond, env, syms.booleanType);
  1687         if (tree.detail != null) {
  1688             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1690         result = null;
  1693      /** Visitor method for method invocations.
  1694      *  NOTE: The method part of an application will have in its type field
  1695      *        the return type of the method, not the method's type itself!
  1696      */
  1697     public void visitApply(JCMethodInvocation tree) {
  1698         // The local environment of a method application is
  1699         // a new environment nested in the current one.
  1700         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1702         // The types of the actual method arguments.
  1703         List<Type> argtypes;
  1705         // The types of the actual method type arguments.
  1706         List<Type> typeargtypes = null;
  1708         Name methName = TreeInfo.name(tree.meth);
  1710         boolean isConstructorCall =
  1711             methName == names._this || methName == names._super;
  1713         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1714         if (isConstructorCall) {
  1715             // We are seeing a ...this(...) or ...super(...) call.
  1716             // Check that this is the first statement in a constructor.
  1717             if (checkFirstConstructorStat(tree, env)) {
  1719                 // Record the fact
  1720                 // that this is a constructor call (using isSelfCall).
  1721                 localEnv.info.isSelfCall = true;
  1723                 // Attribute arguments, yielding list of argument types.
  1724                 attribArgs(tree.args, localEnv, argtypesBuf);
  1725                 argtypes = argtypesBuf.toList();
  1726                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1728                 // Variable `site' points to the class in which the called
  1729                 // constructor is defined.
  1730                 Type site = env.enclClass.sym.type;
  1731                 if (methName == names._super) {
  1732                     if (site == syms.objectType) {
  1733                         log.error(tree.meth.pos(), "no.superclass", site);
  1734                         site = types.createErrorType(syms.objectType);
  1735                     } else {
  1736                         site = types.supertype(site);
  1740                 if (site.hasTag(CLASS)) {
  1741                     Type encl = site.getEnclosingType();
  1742                     while (encl != null && encl.hasTag(TYPEVAR))
  1743                         encl = encl.getUpperBound();
  1744                     if (encl.hasTag(CLASS)) {
  1745                         // we are calling a nested class
  1747                         if (tree.meth.hasTag(SELECT)) {
  1748                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1750                             // We are seeing a prefixed call, of the form
  1751                             //     <expr>.super(...).
  1752                             // Check that the prefix expression conforms
  1753                             // to the outer instance type of the class.
  1754                             chk.checkRefType(qualifier.pos(),
  1755                                              attribExpr(qualifier, localEnv,
  1756                                                         encl));
  1757                         } else if (methName == names._super) {
  1758                             // qualifier omitted; check for existence
  1759                             // of an appropriate implicit qualifier.
  1760                             rs.resolveImplicitThis(tree.meth.pos(),
  1761                                                    localEnv, site, true);
  1763                     } else if (tree.meth.hasTag(SELECT)) {
  1764                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1765                                   site.tsym);
  1768                     // if we're calling a java.lang.Enum constructor,
  1769                     // prefix the implicit String and int parameters
  1770                     if (site.tsym == syms.enumSym && allowEnums)
  1771                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1773                     // Resolve the called constructor under the assumption
  1774                     // that we are referring to a superclass instance of the
  1775                     // current instance (JLS ???).
  1776                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1777                     localEnv.info.selectSuper = true;
  1778                     localEnv.info.pendingResolutionPhase = null;
  1779                     Symbol sym = rs.resolveConstructor(
  1780                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1781                     localEnv.info.selectSuper = selectSuperPrev;
  1783                     // Set method symbol to resolved constructor...
  1784                     TreeInfo.setSymbol(tree.meth, sym);
  1786                     // ...and check that it is legal in the current context.
  1787                     // (this will also set the tree's type)
  1788                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1789                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1791                 // Otherwise, `site' is an error type and we do nothing
  1793             result = tree.type = syms.voidType;
  1794         } else {
  1795             // Otherwise, we are seeing a regular method call.
  1796             // Attribute the arguments, yielding list of argument types, ...
  1797             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1798             argtypes = argtypesBuf.toList();
  1799             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1801             // ... and attribute the method using as a prototype a methodtype
  1802             // whose formal argument types is exactly the list of actual
  1803             // arguments (this will also set the method symbol).
  1804             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1805             localEnv.info.pendingResolutionPhase = null;
  1806             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1808             // Compute the result type.
  1809             Type restype = mtype.getReturnType();
  1810             if (restype.hasTag(WILDCARD))
  1811                 throw new AssertionError(mtype);
  1813             Type qualifier = (tree.meth.hasTag(SELECT))
  1814                     ? ((JCFieldAccess) tree.meth).selected.type
  1815                     : env.enclClass.sym.type;
  1816             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1818             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1820             // Check that value of resulting type is admissible in the
  1821             // current context.  Also, capture the return type
  1822             result = check(tree, capture(restype), VAL, resultInfo);
  1824         chk.validate(tree.typeargs, localEnv);
  1826     //where
  1827         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1828             if (allowCovariantReturns &&
  1829                     methodName == names.clone &&
  1830                 types.isArray(qualifierType)) {
  1831                 // as a special case, array.clone() has a result that is
  1832                 // the same as static type of the array being cloned
  1833                 return qualifierType;
  1834             } else if (allowGenerics &&
  1835                     methodName == names.getClass &&
  1836                     argtypes.isEmpty()) {
  1837                 // as a special case, x.getClass() has type Class<? extends |X|>
  1838                 return new ClassType(restype.getEnclosingType(),
  1839                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1840                                                                BoundKind.EXTENDS,
  1841                                                                syms.boundClass)),
  1842                               restype.tsym);
  1843             } else {
  1844                 return restype;
  1848         /** Check that given application node appears as first statement
  1849          *  in a constructor call.
  1850          *  @param tree   The application node
  1851          *  @param env    The environment current at the application.
  1852          */
  1853         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1854             JCMethodDecl enclMethod = env.enclMethod;
  1855             if (enclMethod != null && enclMethod.name == names.init) {
  1856                 JCBlock body = enclMethod.body;
  1857                 if (body.stats.head.hasTag(EXEC) &&
  1858                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1859                     return true;
  1861             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1862                       TreeInfo.name(tree.meth));
  1863             return false;
  1866         /** Obtain a method type with given argument types.
  1867          */
  1868         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1869             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1870             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1873     public void visitNewClass(final JCNewClass tree) {
  1874         Type owntype = types.createErrorType(tree.type);
  1876         // The local environment of a class creation is
  1877         // a new environment nested in the current one.
  1878         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1880         // The anonymous inner class definition of the new expression,
  1881         // if one is defined by it.
  1882         JCClassDecl cdef = tree.def;
  1884         // If enclosing class is given, attribute it, and
  1885         // complete class name to be fully qualified
  1886         JCExpression clazz = tree.clazz; // Class field following new
  1887         JCExpression clazzid;            // Identifier in class field
  1888         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1889         annoclazzid = null;
  1891         if (clazz.hasTag(TYPEAPPLY)) {
  1892             clazzid = ((JCTypeApply) clazz).clazz;
  1893             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1894                 annoclazzid = (JCAnnotatedType) clazzid;
  1895                 clazzid = annoclazzid.underlyingType;
  1897         } else {
  1898             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1899                 annoclazzid = (JCAnnotatedType) clazz;
  1900                 clazzid = annoclazzid.underlyingType;
  1901             } else {
  1902                 clazzid = clazz;
  1906         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1908         if (tree.encl != null) {
  1909             // We are seeing a qualified new, of the form
  1910             //    <expr>.new C <...> (...) ...
  1911             // In this case, we let clazz stand for the name of the
  1912             // allocated class C prefixed with the type of the qualifier
  1913             // expression, so that we can
  1914             // resolve it with standard techniques later. I.e., if
  1915             // <expr> has type T, then <expr>.new C <...> (...)
  1916             // yields a clazz T.C.
  1917             Type encltype = chk.checkRefType(tree.encl.pos(),
  1918                                              attribExpr(tree.encl, env));
  1919             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1920             // from expr to the combined type, or not? Yes, do this.
  1921             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1922                                                  ((JCIdent) clazzid).name);
  1924             EndPosTable endPosTable = this.env.toplevel.endPositions;
  1925             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  1926             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1927                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1928                 List<JCAnnotation> annos = annoType.annotations;
  1930                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1931                     clazzid1 = make.at(tree.pos).
  1932                         TypeApply(clazzid1,
  1933                                   ((JCTypeApply) clazz).arguments);
  1936                 clazzid1 = make.at(tree.pos).
  1937                     AnnotatedType(annos, clazzid1);
  1938             } else if (clazz.hasTag(TYPEAPPLY)) {
  1939                 clazzid1 = make.at(tree.pos).
  1940                     TypeApply(clazzid1,
  1941                               ((JCTypeApply) clazz).arguments);
  1944             clazz = clazzid1;
  1947         // Attribute clazz expression and store
  1948         // symbol + type back into the attributed tree.
  1949         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1950             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1951             attribType(clazz, env);
  1953         clazztype = chk.checkDiamond(tree, clazztype);
  1954         chk.validate(clazz, localEnv);
  1955         if (tree.encl != null) {
  1956             // We have to work in this case to store
  1957             // symbol + type back into the attributed tree.
  1958             tree.clazz.type = clazztype;
  1959             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1960             clazzid.type = ((JCIdent) clazzid).sym.type;
  1961             if (annoclazzid != null) {
  1962                 annoclazzid.type = clazzid.type;
  1964             if (!clazztype.isErroneous()) {
  1965                 if (cdef != null && clazztype.tsym.isInterface()) {
  1966                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1967                 } else if (clazztype.tsym.isStatic()) {
  1968                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1971         } else if (!clazztype.tsym.isInterface() &&
  1972                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1973             // Check for the existence of an apropos outer instance
  1974             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1977         // Attribute constructor arguments.
  1978         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1979         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  1980         List<Type> argtypes = argtypesBuf.toList();
  1981         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1983         // If we have made no mistakes in the class type...
  1984         if (clazztype.hasTag(CLASS)) {
  1985             // Enums may not be instantiated except implicitly
  1986             if (allowEnums &&
  1987                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1988                 (!env.tree.hasTag(VARDEF) ||
  1989                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1990                  ((JCVariableDecl) env.tree).init != tree))
  1991                 log.error(tree.pos(), "enum.cant.be.instantiated");
  1992             // Check that class is not abstract
  1993             if (cdef == null &&
  1994                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1995                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  1996                           clazztype.tsym);
  1997             } else if (cdef != null && clazztype.tsym.isInterface()) {
  1998                 // Check that no constructor arguments are given to
  1999                 // anonymous classes implementing an interface
  2000                 if (!argtypes.isEmpty())
  2001                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2003                 if (!typeargtypes.isEmpty())
  2004                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2006                 // Error recovery: pretend no arguments were supplied.
  2007                 argtypes = List.nil();
  2008                 typeargtypes = List.nil();
  2009             } else if (TreeInfo.isDiamond(tree)) {
  2010                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2011                             clazztype.tsym.type.getTypeArguments(),
  2012                             clazztype.tsym);
  2014                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2015                 diamondEnv.info.selectSuper = cdef != null;
  2016                 diamondEnv.info.pendingResolutionPhase = null;
  2018                 //if the type of the instance creation expression is a class type
  2019                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2020                 //of the resolved constructor will be a partially instantiated type
  2021                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2022                             diamondEnv,
  2023                             site,
  2024                             argtypes,
  2025                             typeargtypes);
  2026                 tree.constructor = constructor.baseSymbol();
  2028                 final TypeSymbol csym = clazztype.tsym;
  2029                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2030                     @Override
  2031                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2032                         enclosingContext.report(tree.clazz,
  2033                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2035                 });
  2036                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2037                 constructorType = checkId(tree, site,
  2038                         constructor,
  2039                         diamondEnv,
  2040                         diamondResult);
  2042                 tree.clazz.type = types.createErrorType(clazztype);
  2043                 if (!constructorType.isErroneous()) {
  2044                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2045                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2047                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2050             // Resolve the called constructor under the assumption
  2051             // that we are referring to a superclass instance of the
  2052             // current instance (JLS ???).
  2053             else {
  2054                 //the following code alters some of the fields in the current
  2055                 //AttrContext - hence, the current context must be dup'ed in
  2056                 //order to avoid downstream failures
  2057                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2058                 rsEnv.info.selectSuper = cdef != null;
  2059                 rsEnv.info.pendingResolutionPhase = null;
  2060                 tree.constructor = rs.resolveConstructor(
  2061                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2062                 if (cdef == null) { //do not check twice!
  2063                     tree.constructorType = checkId(tree,
  2064                             clazztype,
  2065                             tree.constructor,
  2066                             rsEnv,
  2067                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2068                     if (rsEnv.info.lastResolveVarargs())
  2069                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2071                 if (cdef == null &&
  2072                         !clazztype.isErroneous() &&
  2073                         clazztype.getTypeArguments().nonEmpty() &&
  2074                         findDiamonds) {
  2075                     findDiamond(localEnv, tree, clazztype);
  2079             if (cdef != null) {
  2080                 // We are seeing an anonymous class instance creation.
  2081                 // In this case, the class instance creation
  2082                 // expression
  2083                 //
  2084                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2085                 //
  2086                 // is represented internally as
  2087                 //
  2088                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2089                 //
  2090                 // This expression is then *transformed* as follows:
  2091                 //
  2092                 // (1) add a STATIC flag to the class definition
  2093                 //     if the current environment is static
  2094                 // (2) add an extends or implements clause
  2095                 // (3) add a constructor.
  2096                 //
  2097                 // For instance, if C is a class, and ET is the type of E,
  2098                 // the expression
  2099                 //
  2100                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2101                 //
  2102                 // is translated to (where X is a fresh name and typarams is the
  2103                 // parameter list of the super constructor):
  2104                 //
  2105                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2106                 //     X extends C<typargs2> {
  2107                 //       <typarams> X(ET e, args) {
  2108                 //         e.<typeargs1>super(args)
  2109                 //       }
  2110                 //       ...
  2111                 //     }
  2112                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2114                 if (clazztype.tsym.isInterface()) {
  2115                     cdef.implementing = List.of(clazz);
  2116                 } else {
  2117                     cdef.extending = clazz;
  2120                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2121                     isSerializable(clazztype)) {
  2122                     localEnv.info.isSerializable = true;
  2125                 attribStat(cdef, localEnv);
  2127                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2129                 // If an outer instance is given,
  2130                 // prefix it to the constructor arguments
  2131                 // and delete it from the new expression
  2132                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2133                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2134                     argtypes = argtypes.prepend(tree.encl.type);
  2135                     tree.encl = null;
  2138                 // Reassign clazztype and recompute constructor.
  2139                 clazztype = cdef.sym.type;
  2140                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2141                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2142                 Assert.check(sym.kind < AMBIGUOUS);
  2143                 tree.constructor = sym;
  2144                 tree.constructorType = checkId(tree,
  2145                     clazztype,
  2146                     tree.constructor,
  2147                     localEnv,
  2148                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2151             if (tree.constructor != null && tree.constructor.kind == MTH)
  2152                 owntype = clazztype;
  2154         result = check(tree, owntype, VAL, resultInfo);
  2155         chk.validate(tree.typeargs, localEnv);
  2157     //where
  2158         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2159             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2160             List<JCExpression> prevTypeargs = ta.arguments;
  2161             try {
  2162                 //create a 'fake' diamond AST node by removing type-argument trees
  2163                 ta.arguments = List.nil();
  2164                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2165                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2166                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2167                 Type polyPt = allowPoly ?
  2168                         syms.objectType :
  2169                         clazztype;
  2170                 if (!inferred.isErroneous() &&
  2171                     (allowPoly && pt() == Infer.anyPoly ?
  2172                         types.isSameType(inferred, clazztype) :
  2173                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
  2174                     String key = types.isSameType(clazztype, inferred) ?
  2175                         "diamond.redundant.args" :
  2176                         "diamond.redundant.args.1";
  2177                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2179             } finally {
  2180                 ta.arguments = prevTypeargs;
  2184             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2185                 if (allowLambda &&
  2186                         identifyLambdaCandidate &&
  2187                         clazztype.hasTag(CLASS) &&
  2188                         !pt().hasTag(NONE) &&
  2189                         types.isFunctionalInterface(clazztype.tsym)) {
  2190                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2191                     int count = 0;
  2192                     boolean found = false;
  2193                     for (Symbol sym : csym.members().getElements()) {
  2194                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2195                                 sym.isConstructor()) continue;
  2196                         count++;
  2197                         if (sym.kind != MTH ||
  2198                                 !sym.name.equals(descriptor.name)) continue;
  2199                         Type mtype = types.memberType(clazztype, sym);
  2200                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2201                             found = true;
  2204                     if (found && count == 1) {
  2205                         log.note(tree.def, "potential.lambda.found");
  2210     /** Make an attributed null check tree.
  2211      */
  2212     public JCExpression makeNullCheck(JCExpression arg) {
  2213         // optimization: X.this is never null; skip null check
  2214         Name name = TreeInfo.name(arg);
  2215         if (name == names._this || name == names._super) return arg;
  2217         JCTree.Tag optag = NULLCHK;
  2218         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2219         tree.operator = syms.nullcheck;
  2220         tree.type = arg.type;
  2221         return tree;
  2224     public void visitNewArray(JCNewArray tree) {
  2225         Type owntype = types.createErrorType(tree.type);
  2226         Env<AttrContext> localEnv = env.dup(tree);
  2227         Type elemtype;
  2228         if (tree.elemtype != null) {
  2229             elemtype = attribType(tree.elemtype, localEnv);
  2230             chk.validate(tree.elemtype, localEnv);
  2231             owntype = elemtype;
  2232             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2233                 attribExpr(l.head, localEnv, syms.intType);
  2234                 owntype = new ArrayType(owntype, syms.arrayClass);
  2236         } else {
  2237             // we are seeing an untyped aggregate { ... }
  2238             // this is allowed only if the prototype is an array
  2239             if (pt().hasTag(ARRAY)) {
  2240                 elemtype = types.elemtype(pt());
  2241             } else {
  2242                 if (!pt().hasTag(ERROR)) {
  2243                     log.error(tree.pos(), "illegal.initializer.for.type",
  2244                               pt());
  2246                 elemtype = types.createErrorType(pt());
  2249         if (tree.elems != null) {
  2250             attribExprs(tree.elems, localEnv, elemtype);
  2251             owntype = new ArrayType(elemtype, syms.arrayClass);
  2253         if (!types.isReifiable(elemtype))
  2254             log.error(tree.pos(), "generic.array.creation");
  2255         result = check(tree, owntype, VAL, resultInfo);
  2258     /*
  2259      * A lambda expression can only be attributed when a target-type is available.
  2260      * In addition, if the target-type is that of a functional interface whose
  2261      * descriptor contains inference variables in argument position the lambda expression
  2262      * is 'stuck' (see DeferredAttr).
  2263      */
  2264     @Override
  2265     public void visitLambda(final JCLambda that) {
  2266         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2267             if (pt().hasTag(NONE)) {
  2268                 //lambda only allowed in assignment or method invocation/cast context
  2269                 log.error(that.pos(), "unexpected.lambda");
  2271             result = that.type = types.createErrorType(pt());
  2272             return;
  2274         //create an environment for attribution of the lambda expression
  2275         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2276         boolean needsRecovery =
  2277                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2278         try {
  2279             Type currentTarget = pt();
  2280             if (needsRecovery && isSerializable(currentTarget)) {
  2281                 localEnv.info.isSerializable = true;
  2283             List<Type> explicitParamTypes = null;
  2284             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2285                 //attribute lambda parameters
  2286                 attribStats(that.params, localEnv);
  2287                 explicitParamTypes = TreeInfo.types(that.params);
  2290             Type lambdaType;
  2291             if (pt() != Type.recoveryType) {
  2292                 /* We need to adjust the target. If the target is an
  2293                  * intersection type, for example: SAM & I1 & I2 ...
  2294                  * the target will be updated to SAM
  2295                  */
  2296                 currentTarget = targetChecker.visit(currentTarget, that);
  2297                 if (explicitParamTypes != null) {
  2298                     currentTarget = infer.instantiateFunctionalInterface(that,
  2299                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2301                 currentTarget = types.removeWildcards(currentTarget);
  2302                 lambdaType = types.findDescriptorType(currentTarget);
  2303             } else {
  2304                 currentTarget = Type.recoveryType;
  2305                 lambdaType = fallbackDescriptorType(that);
  2308             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2310             if (lambdaType.hasTag(FORALL)) {
  2311                 //lambda expression target desc cannot be a generic method
  2312                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2313                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2314                 result = that.type = types.createErrorType(pt());
  2315                 return;
  2318             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2319                 //add param type info in the AST
  2320                 List<Type> actuals = lambdaType.getParameterTypes();
  2321                 List<JCVariableDecl> params = that.params;
  2323                 boolean arityMismatch = false;
  2325                 while (params.nonEmpty()) {
  2326                     if (actuals.isEmpty()) {
  2327                         //not enough actuals to perform lambda parameter inference
  2328                         arityMismatch = true;
  2330                     //reset previously set info
  2331                     Type argType = arityMismatch ?
  2332                             syms.errType :
  2333                             actuals.head;
  2334                     params.head.vartype = make.at(params.head).Type(argType);
  2335                     params.head.sym = null;
  2336                     actuals = actuals.isEmpty() ?
  2337                             actuals :
  2338                             actuals.tail;
  2339                     params = params.tail;
  2342                 //attribute lambda parameters
  2343                 attribStats(that.params, localEnv);
  2345                 if (arityMismatch) {
  2346                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2347                         result = that.type = types.createErrorType(currentTarget);
  2348                         return;
  2352             //from this point on, no recovery is needed; if we are in assignment context
  2353             //we will be able to attribute the whole lambda body, regardless of errors;
  2354             //if we are in a 'check' method context, and the lambda is not compatible
  2355             //with the target-type, it will be recovered anyway in Attr.checkId
  2356             needsRecovery = false;
  2358             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2359                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2360                     new FunctionalReturnContext(resultInfo.checkContext);
  2362             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2363                 recoveryInfo :
  2364                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2365             localEnv.info.returnResult = bodyResultInfo;
  2367             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2368                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2369             } else {
  2370                 JCBlock body = (JCBlock)that.body;
  2371                 attribStats(body.stats, localEnv);
  2374             result = check(that, currentTarget, VAL, resultInfo);
  2376             boolean isSpeculativeRound =
  2377                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2379             preFlow(that);
  2380             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2382             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2384             if (!isSpeculativeRound) {
  2385                 //add thrown types as bounds to the thrown types free variables if needed:
  2386                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2387                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2388                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
  2390                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2393                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2395             result = check(that, currentTarget, VAL, resultInfo);
  2396         } catch (Types.FunctionDescriptorLookupError ex) {
  2397             JCDiagnostic cause = ex.getDiagnostic();
  2398             resultInfo.checkContext.report(that, cause);
  2399             result = that.type = types.createErrorType(pt());
  2400             return;
  2401         } finally {
  2402             localEnv.info.scope.leave();
  2403             if (needsRecovery) {
  2404                 attribTree(that, env, recoveryInfo);
  2408     //where
  2409         void preFlow(JCLambda tree) {
  2410             new PostAttrAnalyzer() {
  2411                 @Override
  2412                 public void scan(JCTree tree) {
  2413                     if (tree == null ||
  2414                             (tree.type != null &&
  2415                             tree.type == Type.stuckType)) {
  2416                         //don't touch stuck expressions!
  2417                         return;
  2419                     super.scan(tree);
  2421             }.scan(tree);
  2424         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2426             @Override
  2427             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2428                 return t.isCompound() ?
  2429                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2432             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2433                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2434                 Type target = null;
  2435                 for (Type bound : ict.getExplicitComponents()) {
  2436                     TypeSymbol boundSym = bound.tsym;
  2437                     if (types.isFunctionalInterface(boundSym) &&
  2438                             types.findDescriptorSymbol(boundSym) == desc) {
  2439                         target = bound;
  2440                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2441                         //bound must be an interface
  2442                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2445                 return target != null ?
  2446                         target :
  2447                         ict.getExplicitComponents().head; //error recovery
  2450             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2451                 ListBuffer<Type> targs = new ListBuffer<>();
  2452                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2453                 for (Type i : ict.interfaces_field) {
  2454                     if (i.isParameterized()) {
  2455                         targs.appendList(i.tsym.type.allparams());
  2457                     supertypes.append(i.tsym.type);
  2459                 IntersectionClassType notionalIntf =
  2460                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2461                 notionalIntf.allparams_field = targs.toList();
  2462                 notionalIntf.tsym.flags_field |= INTERFACE;
  2463                 return notionalIntf.tsym;
  2466             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2467                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2468                         diags.fragment(key, args)));
  2470         };
  2472         private Type fallbackDescriptorType(JCExpression tree) {
  2473             switch (tree.getTag()) {
  2474                 case LAMBDA:
  2475                     JCLambda lambda = (JCLambda)tree;
  2476                     List<Type> argtypes = List.nil();
  2477                     for (JCVariableDecl param : lambda.params) {
  2478                         argtypes = param.vartype != null ?
  2479                                 argtypes.append(param.vartype.type) :
  2480                                 argtypes.append(syms.errType);
  2482                     return new MethodType(argtypes, Type.recoveryType,
  2483                             List.of(syms.throwableType), syms.methodClass);
  2484                 case REFERENCE:
  2485                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2486                             List.of(syms.throwableType), syms.methodClass);
  2487                 default:
  2488                     Assert.error("Cannot get here!");
  2490             return null;
  2493         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2494                 final InferenceContext inferenceContext, final Type... ts) {
  2495             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2498         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2499                 final InferenceContext inferenceContext, final List<Type> ts) {
  2500             if (inferenceContext.free(ts)) {
  2501                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2502                     @Override
  2503                     public void typesInferred(InferenceContext inferenceContext) {
  2504                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2506                 });
  2507             } else {
  2508                 for (Type t : ts) {
  2509                     rs.checkAccessibleType(env, t);
  2514         /**
  2515          * Lambda/method reference have a special check context that ensures
  2516          * that i.e. a lambda return type is compatible with the expected
  2517          * type according to both the inherited context and the assignment
  2518          * context.
  2519          */
  2520         class FunctionalReturnContext extends Check.NestedCheckContext {
  2522             FunctionalReturnContext(CheckContext enclosingContext) {
  2523                 super(enclosingContext);
  2526             @Override
  2527             public boolean compatible(Type found, Type req, Warner warn) {
  2528                 //return type must be compatible in both current context and assignment context
  2529                 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
  2532             @Override
  2533             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2534                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2538         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2540             JCExpression expr;
  2542             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2543                 super(enclosingContext);
  2544                 this.expr = expr;
  2547             @Override
  2548             public boolean compatible(Type found, Type req, Warner warn) {
  2549                 //a void return is compatible with an expression statement lambda
  2550                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2551                         super.compatible(found, req, warn);
  2555         /**
  2556         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2557         * are compatible with the expected functional interface descriptor. This means that:
  2558         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2559         * types must be compatible with the return type of the expected descriptor.
  2560         */
  2561         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2562             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2564             //return values have already been checked - but if lambda has no return
  2565             //values, we must ensure that void/value compatibility is correct;
  2566             //this amounts at checking that, if a lambda body can complete normally,
  2567             //the descriptor's return type must be void
  2568             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2569                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2570                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2571                         diags.fragment("missing.ret.val", returnType)));
  2574             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
  2575             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2576                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2580         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
  2581          * static field and that lambda has type annotations, these annotations will
  2582          * also be stored at these fake clinit methods.
  2584          * LambdaToMethod also use fake clinit methods so they can be reused.
  2585          * Also as LTM is a phase subsequent to attribution, the methods from
  2586          * clinits can be safely removed by LTM to save memory.
  2587          */
  2588         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
  2590         public MethodSymbol removeClinit(ClassSymbol sym) {
  2591             return clinits.remove(sym);
  2594         /* This method returns an environment to be used to attribute a lambda
  2595          * expression.
  2597          * The owner of this environment is a method symbol. If the current owner
  2598          * is not a method, for example if the lambda is used to initialize
  2599          * a field, then if the field is:
  2601          * - an instance field, we use the first constructor.
  2602          * - a static field, we create a fake clinit method.
  2603          */
  2604         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2605             Env<AttrContext> lambdaEnv;
  2606             Symbol owner = env.info.scope.owner;
  2607             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2608                 //field initializer
  2609                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2610                 ClassSymbol enclClass = owner.enclClass();
  2611                 /* if the field isn't static, then we can get the first constructor
  2612                  * and use it as the owner of the environment. This is what
  2613                  * LTM code is doing to look for type annotations so we are fine.
  2614                  */
  2615                 if ((owner.flags() & STATIC) == 0) {
  2616                     for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
  2617                         lambdaEnv.info.scope.owner = s;
  2618                         break;
  2620                 } else {
  2621                     /* if the field is static then we need to create a fake clinit
  2622                      * method, this method can later be reused by LTM.
  2623                      */
  2624                     MethodSymbol clinit = clinits.get(enclClass);
  2625                     if (clinit == null) {
  2626                         Type clinitType = new MethodType(List.<Type>nil(),
  2627                                 syms.voidType, List.<Type>nil(), syms.methodClass);
  2628                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
  2629                                 names.clinit, clinitType, enclClass);
  2630                         clinit.params = List.<VarSymbol>nil();
  2631                         clinits.put(enclClass, clinit);
  2633                     lambdaEnv.info.scope.owner = clinit;
  2635             } else {
  2636                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2638             return lambdaEnv;
  2641     @Override
  2642     public void visitReference(final JCMemberReference that) {
  2643         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2644             if (pt().hasTag(NONE)) {
  2645                 //method reference only allowed in assignment or method invocation/cast context
  2646                 log.error(that.pos(), "unexpected.mref");
  2648             result = that.type = types.createErrorType(pt());
  2649             return;
  2651         final Env<AttrContext> localEnv = env.dup(that);
  2652         try {
  2653             //attribute member reference qualifier - if this is a constructor
  2654             //reference, the expected kind must be a type
  2655             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2657             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2658                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2659                 if (!exprType.isErroneous() &&
  2660                     exprType.isRaw() &&
  2661                     that.typeargs != null) {
  2662                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2663                         diags.fragment("mref.infer.and.explicit.params"));
  2664                     exprType = types.createErrorType(exprType);
  2668             if (exprType.isErroneous()) {
  2669                 //if the qualifier expression contains problems,
  2670                 //give up attribution of method reference
  2671                 result = that.type = exprType;
  2672                 return;
  2675             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2676                 //if the qualifier is a type, validate it; raw warning check is
  2677                 //omitted as we don't know at this stage as to whether this is a
  2678                 //raw selector (because of inference)
  2679                 chk.validate(that.expr, env, false);
  2682             //attrib type-arguments
  2683             List<Type> typeargtypes = List.nil();
  2684             if (that.typeargs != null) {
  2685                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2688             Type desc;
  2689             Type currentTarget = pt();
  2690             boolean isTargetSerializable =
  2691                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2692                     isSerializable(currentTarget);
  2693             if (currentTarget != Type.recoveryType) {
  2694                 currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that));
  2695                 desc = types.findDescriptorType(currentTarget);
  2696             } else {
  2697                 currentTarget = Type.recoveryType;
  2698                 desc = fallbackDescriptorType(that);
  2701             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
  2702             List<Type> argtypes = desc.getParameterTypes();
  2703             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2705             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2706                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2709             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2710             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2711             try {
  2712                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
  2713                         that.name, argtypes, typeargtypes, referenceCheck,
  2714                         resultInfo.checkContext.inferenceContext(),
  2715                         resultInfo.checkContext.deferredAttrContext().mode);
  2716             } finally {
  2717                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2720             Symbol refSym = refResult.fst;
  2721             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2723             if (refSym.kind != MTH) {
  2724                 boolean targetError;
  2725                 switch (refSym.kind) {
  2726                     case ABSENT_MTH:
  2727                         targetError = false;
  2728                         break;
  2729                     case WRONG_MTH:
  2730                     case WRONG_MTHS:
  2731                     case AMBIGUOUS:
  2732                     case HIDDEN:
  2733                     case STATICERR:
  2734                     case MISSING_ENCL:
  2735                     case WRONG_STATICNESS:
  2736                         targetError = true;
  2737                         break;
  2738                     default:
  2739                         Assert.error("unexpected result kind " + refSym.kind);
  2740                         targetError = false;
  2743                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2744                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2746                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2747                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2749                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2750                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2752                 if (targetError && currentTarget == Type.recoveryType) {
  2753                     //a target error doesn't make sense during recovery stage
  2754                     //as we don't know what actual parameter types are
  2755                     result = that.type = currentTarget;
  2756                     return;
  2757                 } else {
  2758                     if (targetError) {
  2759                         resultInfo.checkContext.report(that, diag);
  2760                     } else {
  2761                         log.report(diag);
  2763                     result = that.type = types.createErrorType(currentTarget);
  2764                     return;
  2768             that.sym = refSym.baseSymbol();
  2769             that.kind = lookupHelper.referenceKind(that.sym);
  2770             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2772             if (desc.getReturnType() == Type.recoveryType) {
  2773                 // stop here
  2774                 result = that.type = currentTarget;
  2775                 return;
  2778             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2780                 if (that.getMode() == ReferenceMode.INVOKE &&
  2781                         TreeInfo.isStaticSelector(that.expr, names) &&
  2782                         that.kind.isUnbound() &&
  2783                         !desc.getParameterTypes().head.isParameterized()) {
  2784                     chk.checkRaw(that.expr, localEnv);
  2787                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2788                         exprType.getTypeArguments().nonEmpty()) {
  2789                     //static ref with class type-args
  2790                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2791                             diags.fragment("static.mref.with.targs"));
  2792                     result = that.type = types.createErrorType(currentTarget);
  2793                     return;
  2796                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2797                         !that.kind.isUnbound()) {
  2798                     //no static bound mrefs
  2799                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2800                             diags.fragment("static.bound.mref"));
  2801                     result = that.type = types.createErrorType(currentTarget);
  2802                     return;
  2805                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2806                     // Check that super-qualified symbols are not abstract (JLS)
  2807                     rs.checkNonAbstract(that.pos(), that.sym);
  2810                 if (isTargetSerializable) {
  2811                     chk.checkElemAccessFromSerializableLambda(that);
  2815             ResultInfo checkInfo =
  2816                     resultInfo.dup(newMethodTemplate(
  2817                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2818                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
  2819                         new FunctionalReturnContext(resultInfo.checkContext));
  2821             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2823             if (that.kind.isUnbound() &&
  2824                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2825                 //re-generate inference constraints for unbound receiver
  2826                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
  2827                     //cannot happen as this has already been checked - we just need
  2828                     //to regenerate the inference constraints, as that has been lost
  2829                     //as a result of the call to inferenceContext.save()
  2830                     Assert.error("Can't get here");
  2834             if (!refType.isErroneous()) {
  2835                 refType = types.createMethodTypeWithReturn(refType,
  2836                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2839             //go ahead with standard method reference compatibility check - note that param check
  2840             //is a no-op (as this has been taken care during method applicability)
  2841             boolean isSpeculativeRound =
  2842                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2843             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2844             if (!isSpeculativeRound) {
  2845                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
  2847             result = check(that, currentTarget, VAL, resultInfo);
  2848         } catch (Types.FunctionDescriptorLookupError ex) {
  2849             JCDiagnostic cause = ex.getDiagnostic();
  2850             resultInfo.checkContext.report(that, cause);
  2851             result = that.type = types.createErrorType(pt());
  2852             return;
  2855     //where
  2856         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2857             //if this is a constructor reference, the expected kind must be a type
  2858             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2862     @SuppressWarnings("fallthrough")
  2863     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2864         Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2866         Type resType;
  2867         switch (tree.getMode()) {
  2868             case NEW:
  2869                 if (!tree.expr.type.isRaw()) {
  2870                     resType = tree.expr.type;
  2871                     break;
  2873             default:
  2874                 resType = refType.getReturnType();
  2877         Type incompatibleReturnType = resType;
  2879         if (returnType.hasTag(VOID)) {
  2880             incompatibleReturnType = null;
  2883         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2884             if (resType.isErroneous() ||
  2885                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2886                 incompatibleReturnType = null;
  2890         if (incompatibleReturnType != null) {
  2891             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2892                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2895         if (!speculativeAttr) {
  2896             List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
  2897             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2898                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2903     /**
  2904      * Set functional type info on the underlying AST. Note: as the target descriptor
  2905      * might contain inference variables, we might need to register an hook in the
  2906      * current inference context.
  2907      */
  2908     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  2909             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  2910         if (checkContext.inferenceContext().free(descriptorType)) {
  2911             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2912                 public void typesInferred(InferenceContext inferenceContext) {
  2913                     setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  2914                             inferenceContext.asInstType(primaryTarget), checkContext);
  2916             });
  2917         } else {
  2918             ListBuffer<Type> targets = new ListBuffer<>();
  2919             if (pt.hasTag(CLASS)) {
  2920                 if (pt.isCompound()) {
  2921                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  2922                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2923                         if (t != primaryTarget) {
  2924                             targets.append(types.removeWildcards(t));
  2927                 } else {
  2928                     targets.append(types.removeWildcards(primaryTarget));
  2931             fExpr.targets = targets.toList();
  2932             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2933                     pt != Type.recoveryType) {
  2934                 //check that functional interface class is well-formed
  2935                 try {
  2936                     /* Types.makeFunctionalInterfaceClass() may throw an exception
  2937                      * when it's executed post-inference. See the listener code
  2938                      * above.
  2939                      */
  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);
  2945                 } catch (Types.FunctionDescriptorLookupError ex) {
  2946                     JCDiagnostic cause = ex.getDiagnostic();
  2947                     resultInfo.checkContext.report(env.tree, cause);
  2953     public void visitParens(JCParens tree) {
  2954         Type owntype = attribTree(tree.expr, env, resultInfo);
  2955         result = check(tree, owntype, pkind(), resultInfo);
  2956         Symbol sym = TreeInfo.symbol(tree);
  2957         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2958             log.error(tree.pos(), "illegal.start.of.type");
  2961     public void visitAssign(JCAssign tree) {
  2962         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2963         Type capturedType = capture(owntype);
  2964         attribExpr(tree.rhs, env, owntype);
  2965         result = check(tree, capturedType, VAL, resultInfo);
  2968     public void visitAssignop(JCAssignOp tree) {
  2969         // Attribute arguments.
  2970         Type owntype = attribTree(tree.lhs, env, varInfo);
  2971         Type operand = attribExpr(tree.rhs, env);
  2972         // Find operator.
  2973         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2974             tree.pos(), tree.getTag().noAssignOp(), env,
  2975             owntype, operand);
  2977         if (operator.kind == MTH &&
  2978                 !owntype.isErroneous() &&
  2979                 !operand.isErroneous()) {
  2980             chk.checkOperator(tree.pos(),
  2981                               (OperatorSymbol)operator,
  2982                               tree.getTag().noAssignOp(),
  2983                               owntype,
  2984                               operand);
  2985             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2986             chk.checkCastable(tree.rhs.pos(),
  2987                               operator.type.getReturnType(),
  2988                               owntype);
  2990         result = check(tree, owntype, VAL, resultInfo);
  2993     public void visitUnary(JCUnary tree) {
  2994         // Attribute arguments.
  2995         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2996             ? attribTree(tree.arg, env, varInfo)
  2997             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2999         // Find operator.
  3000         Symbol operator = tree.operator =
  3001             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  3003         Type owntype = types.createErrorType(tree.type);
  3004         if (operator.kind == MTH &&
  3005                 !argtype.isErroneous()) {
  3006             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3007                 ? tree.arg.type
  3008                 : operator.type.getReturnType();
  3009             int opc = ((OperatorSymbol)operator).opcode;
  3011             // If the argument is constant, fold it.
  3012             if (argtype.constValue() != null) {
  3013                 Type ctype = cfolder.fold1(opc, argtype);
  3014                 if (ctype != null) {
  3015                     owntype = cfolder.coerce(ctype, owntype);
  3019         result = check(tree, owntype, VAL, resultInfo);
  3022     public void visitBinary(JCBinary tree) {
  3023         // Attribute arguments.
  3024         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3025         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3027         // Find operator.
  3028         Symbol operator = tree.operator =
  3029             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3031         Type owntype = types.createErrorType(tree.type);
  3032         if (operator.kind == MTH &&
  3033                 !left.isErroneous() &&
  3034                 !right.isErroneous()) {
  3035             owntype = operator.type.getReturnType();
  3036             // This will figure out when unboxing can happen and
  3037             // choose the right comparison operator.
  3038             int opc = chk.checkOperator(tree.lhs.pos(),
  3039                                         (OperatorSymbol)operator,
  3040                                         tree.getTag(),
  3041                                         left,
  3042                                         right);
  3044             // If both arguments are constants, fold them.
  3045             if (left.constValue() != null && right.constValue() != null) {
  3046                 Type ctype = cfolder.fold2(opc, left, right);
  3047                 if (ctype != null) {
  3048                     owntype = cfolder.coerce(ctype, owntype);
  3052             // Check that argument types of a reference ==, != are
  3053             // castable to each other, (JLS 15.21).  Note: unboxing
  3054             // comparisons will not have an acmp* opc at this point.
  3055             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3056                 if (!types.isEqualityComparable(left, right,
  3057                                                 new Warner(tree.pos()))) {
  3058                     log.error(tree.pos(), "incomparable.types", left, right);
  3062             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3064         result = check(tree, owntype, VAL, resultInfo);
  3067     public void visitTypeCast(final JCTypeCast tree) {
  3068         Type clazztype = attribType(tree.clazz, env);
  3069         chk.validate(tree.clazz, env, false);
  3070         //a fresh environment is required for 292 inference to work properly ---
  3071         //see Infer.instantiatePolymorphicSignatureInstance()
  3072         Env<AttrContext> localEnv = env.dup(tree);
  3073         //should we propagate the target type?
  3074         final ResultInfo castInfo;
  3075         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3076         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3077         if (isPoly) {
  3078             //expression is a poly - we need to propagate target type info
  3079             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3080                 @Override
  3081                 public boolean compatible(Type found, Type req, Warner warn) {
  3082                     return types.isCastable(found, req, warn);
  3084             });
  3085         } else {
  3086             //standalone cast - target-type info is not propagated
  3087             castInfo = unknownExprInfo;
  3089         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3090         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3091         if (exprtype.constValue() != null)
  3092             owntype = cfolder.coerce(exprtype, owntype);
  3093         result = check(tree, capture(owntype), VAL, resultInfo);
  3094         if (!isPoly)
  3095             chk.checkRedundantCast(localEnv, tree);
  3098     public void visitTypeTest(JCInstanceOf tree) {
  3099         Type exprtype = chk.checkNullOrRefType(
  3100             tree.expr.pos(), attribExpr(tree.expr, env));
  3101         Type clazztype = attribType(tree.clazz, env);
  3102         if (!clazztype.hasTag(TYPEVAR)) {
  3103             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3105         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3106             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3107             clazztype = types.createErrorType(clazztype);
  3109         chk.validate(tree.clazz, env, false);
  3110         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3111         result = check(tree, syms.booleanType, VAL, resultInfo);
  3114     public void visitIndexed(JCArrayAccess tree) {
  3115         Type owntype = types.createErrorType(tree.type);
  3116         Type atype = attribExpr(tree.indexed, env);
  3117         attribExpr(tree.index, env, syms.intType);
  3118         if (types.isArray(atype))
  3119             owntype = types.elemtype(atype);
  3120         else if (!atype.hasTag(ERROR))
  3121             log.error(tree.pos(), "array.req.but.found", atype);
  3122         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3123         result = check(tree, owntype, VAR, resultInfo);
  3126     public void visitIdent(JCIdent tree) {
  3127         Symbol sym;
  3129         // Find symbol
  3130         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3131             // If we are looking for a method, the prototype `pt' will be a
  3132             // method type with the type of the call's arguments as parameters.
  3133             env.info.pendingResolutionPhase = null;
  3134             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3135         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3136             sym = tree.sym;
  3137         } else {
  3138             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3140         tree.sym = sym;
  3142         // (1) Also find the environment current for the class where
  3143         //     sym is defined (`symEnv').
  3144         // Only for pre-tiger versions (1.4 and earlier):
  3145         // (2) Also determine whether we access symbol out of an anonymous
  3146         //     class in a this or super call.  This is illegal for instance
  3147         //     members since such classes don't carry a this$n link.
  3148         //     (`noOuterThisPath').
  3149         Env<AttrContext> symEnv = env;
  3150         boolean noOuterThisPath = false;
  3151         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3152             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3153             sym.owner.kind == TYP &&
  3154             tree.name != names._this && tree.name != names._super) {
  3156             // Find environment in which identifier is defined.
  3157             while (symEnv.outer != null &&
  3158                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3159                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3160                     noOuterThisPath = !allowAnonOuterThis;
  3161                 symEnv = symEnv.outer;
  3165         // If symbol is a variable, ...
  3166         if (sym.kind == VAR) {
  3167             VarSymbol v = (VarSymbol)sym;
  3169             // ..., evaluate its initializer, if it has one, and check for
  3170             // illegal forward reference.
  3171             checkInit(tree, env, v, false);
  3173             // If we are expecting a variable (as opposed to a value), check
  3174             // that the variable is assignable in the current environment.
  3175             if (pkind() == VAR)
  3176                 checkAssignable(tree.pos(), v, null, env);
  3179         // In a constructor body,
  3180         // if symbol is a field or instance method, check that it is
  3181         // not accessed before the supertype constructor is called.
  3182         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3183             (sym.kind & (VAR | MTH)) != 0 &&
  3184             sym.owner.kind == TYP &&
  3185             (sym.flags() & STATIC) == 0) {
  3186             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3188         Env<AttrContext> env1 = env;
  3189         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3190             // If the found symbol is inaccessible, then it is
  3191             // accessed through an enclosing instance.  Locate this
  3192             // enclosing instance:
  3193             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3194                 env1 = env1.outer;
  3197         if (env.info.isSerializable) {
  3198             chk.checkElemAccessFromSerializableLambda(tree);
  3201         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3204     public void visitSelect(JCFieldAccess tree) {
  3205         // Determine the expected kind of the qualifier expression.
  3206         int skind = 0;
  3207         if (tree.name == names._this || tree.name == names._super ||
  3208             tree.name == names._class)
  3210             skind = TYP;
  3211         } else {
  3212             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3213             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3214             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3217         // Attribute the qualifier expression, and determine its symbol (if any).
  3218         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3219         if ((pkind() & (PCK | TYP)) == 0)
  3220             site = capture(site); // Capture field access
  3222         // don't allow T.class T[].class, etc
  3223         if (skind == TYP) {
  3224             Type elt = site;
  3225             while (elt.hasTag(ARRAY))
  3226                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3227             if (elt.hasTag(TYPEVAR)) {
  3228                 log.error(tree.pos(), "type.var.cant.be.deref");
  3229                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
  3230                 tree.sym = tree.type.tsym;
  3231                 return ;
  3235         // If qualifier symbol is a type or `super', assert `selectSuper'
  3236         // for the selection. This is relevant for determining whether
  3237         // protected symbols are accessible.
  3238         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3239         boolean selectSuperPrev = env.info.selectSuper;
  3240         env.info.selectSuper =
  3241             sitesym != null &&
  3242             sitesym.name == names._super;
  3244         // Determine the symbol represented by the selection.
  3245         env.info.pendingResolutionPhase = null;
  3246         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3247         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
  3248             log.error(tree.selected.pos(), "not.encl.class", site.tsym);
  3249             sym = syms.errSymbol;
  3251         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3252             site = capture(site);
  3253             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3255         boolean varArgs = env.info.lastResolveVarargs();
  3256         tree.sym = sym;
  3258         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3259             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3260             site = capture(site);
  3263         // If that symbol is a variable, ...
  3264         if (sym.kind == VAR) {
  3265             VarSymbol v = (VarSymbol)sym;
  3267             // ..., evaluate its initializer, if it has one, and check for
  3268             // illegal forward reference.
  3269             checkInit(tree, env, v, true);
  3271             // If we are expecting a variable (as opposed to a value), check
  3272             // that the variable is assignable in the current environment.
  3273             if (pkind() == VAR)
  3274                 checkAssignable(tree.pos(), v, tree.selected, env);
  3277         if (sitesym != null &&
  3278                 sitesym.kind == VAR &&
  3279                 ((VarSymbol)sitesym).isResourceVariable() &&
  3280                 sym.kind == MTH &&
  3281                 sym.name.equals(names.close) &&
  3282                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3283                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3284             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3287         // Disallow selecting a type from an expression
  3288         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3289             tree.type = check(tree.selected, pt(),
  3290                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3293         if (isType(sitesym)) {
  3294             if (sym.name == names._this) {
  3295                 // If `C' is the currently compiled class, check that
  3296                 // C.this' does not appear in a call to a super(...)
  3297                 if (env.info.isSelfCall &&
  3298                     site.tsym == env.enclClass.sym) {
  3299                     chk.earlyRefError(tree.pos(), sym);
  3301             } else {
  3302                 // Check if type-qualified fields or methods are static (JLS)
  3303                 if ((sym.flags() & STATIC) == 0 &&
  3304                     !env.next.tree.hasTag(REFERENCE) &&
  3305                     sym.name != names._super &&
  3306                     (sym.kind == VAR || sym.kind == MTH)) {
  3307                     rs.accessBase(rs.new StaticError(sym),
  3308                               tree.pos(), site, sym.name, true);
  3311             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
  3312                     sym.isStatic() && sym.kind == MTH) {
  3313                 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
  3315         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3316             // If the qualified item is not a type and the selected item is static, report
  3317             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3318             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3321         // If we are selecting an instance member via a `super', ...
  3322         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3324             // Check that super-qualified symbols are not abstract (JLS)
  3325             rs.checkNonAbstract(tree.pos(), sym);
  3327             if (site.isRaw()) {
  3328                 // Determine argument types for site.
  3329                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3330                 if (site1 != null) site = site1;
  3334         if (env.info.isSerializable) {
  3335             chk.checkElemAccessFromSerializableLambda(tree);
  3338         env.info.selectSuper = selectSuperPrev;
  3339         result = checkId(tree, site, sym, env, resultInfo);
  3341     //where
  3342         /** Determine symbol referenced by a Select expression,
  3344          *  @param tree   The select tree.
  3345          *  @param site   The type of the selected expression,
  3346          *  @param env    The current environment.
  3347          *  @param resultInfo The current result.
  3348          */
  3349         private Symbol selectSym(JCFieldAccess tree,
  3350                                  Symbol location,
  3351                                  Type site,
  3352                                  Env<AttrContext> env,
  3353                                  ResultInfo resultInfo) {
  3354             DiagnosticPosition pos = tree.pos();
  3355             Name name = tree.name;
  3356             switch (site.getTag()) {
  3357             case PACKAGE:
  3358                 return rs.accessBase(
  3359                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3360                     pos, location, site, name, true);
  3361             case ARRAY:
  3362             case CLASS:
  3363                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3364                     return rs.resolveQualifiedMethod(
  3365                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3366                 } else if (name == names._this || name == names._super) {
  3367                     return rs.resolveSelf(pos, env, site.tsym, name);
  3368                 } else if (name == names._class) {
  3369                     // In this case, we have already made sure in
  3370                     // visitSelect that qualifier expression is a type.
  3371                     Type t = syms.classType;
  3372                     List<Type> typeargs = allowGenerics
  3373                         ? List.of(types.erasure(site))
  3374                         : List.<Type>nil();
  3375                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3376                     return new VarSymbol(
  3377                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3378                 } else {
  3379                     // We are seeing a plain identifier as selector.
  3380                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3381                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3382                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3383                     return sym;
  3385             case WILDCARD:
  3386                 throw new AssertionError(tree);
  3387             case TYPEVAR:
  3388                 // Normally, site.getUpperBound() shouldn't be null.
  3389                 // It should only happen during memberEnter/attribBase
  3390                 // when determining the super type which *must* beac
  3391                 // done before attributing the type variables.  In
  3392                 // other words, we are seeing this illegal program:
  3393                 // class B<T> extends A<T.foo> {}
  3394                 Symbol sym = (site.getUpperBound() != null)
  3395                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3396                     : null;
  3397                 if (sym == null) {
  3398                     log.error(pos, "type.var.cant.be.deref");
  3399                     return syms.errSymbol;
  3400                 } else {
  3401                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3402                         rs.new AccessError(env, site, sym) :
  3403                                 sym;
  3404                     rs.accessBase(sym2, pos, location, site, name, true);
  3405                     return sym;
  3407             case ERROR:
  3408                 // preserve identifier names through errors
  3409                 return types.createErrorType(name, site.tsym, site).tsym;
  3410             default:
  3411                 // The qualifier expression is of a primitive type -- only
  3412                 // .class is allowed for these.
  3413                 if (name == names._class) {
  3414                     // In this case, we have already made sure in Select that
  3415                     // qualifier expression is a type.
  3416                     Type t = syms.classType;
  3417                     Type arg = types.boxedClass(site).type;
  3418                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3419                     return new VarSymbol(
  3420                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3421                 } else {
  3422                     log.error(pos, "cant.deref", site);
  3423                     return syms.errSymbol;
  3428         /** Determine type of identifier or select expression and check that
  3429          *  (1) the referenced symbol is not deprecated
  3430          *  (2) the symbol's type is safe (@see checkSafe)
  3431          *  (3) if symbol is a variable, check that its type and kind are
  3432          *      compatible with the prototype and protokind.
  3433          *  (4) if symbol is an instance field of a raw type,
  3434          *      which is being assigned to, issue an unchecked warning if its
  3435          *      type changes under erasure.
  3436          *  (5) if symbol is an instance method of a raw type, issue an
  3437          *      unchecked warning if its argument types change under erasure.
  3438          *  If checks succeed:
  3439          *    If symbol is a constant, return its constant type
  3440          *    else if symbol is a method, return its result type
  3441          *    otherwise return its type.
  3442          *  Otherwise return errType.
  3444          *  @param tree       The syntax tree representing the identifier
  3445          *  @param site       If this is a select, the type of the selected
  3446          *                    expression, otherwise the type of the current class.
  3447          *  @param sym        The symbol representing the identifier.
  3448          *  @param env        The current environment.
  3449          *  @param resultInfo    The expected result
  3450          */
  3451         Type checkId(JCTree tree,
  3452                      Type site,
  3453                      Symbol sym,
  3454                      Env<AttrContext> env,
  3455                      ResultInfo resultInfo) {
  3456             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3457                     checkMethodId(tree, site, sym, env, resultInfo) :
  3458                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3461         Type checkMethodId(JCTree tree,
  3462                      Type site,
  3463                      Symbol sym,
  3464                      Env<AttrContext> env,
  3465                      ResultInfo resultInfo) {
  3466             boolean isPolymorhicSignature =
  3467                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3468             return isPolymorhicSignature ?
  3469                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3470                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3473         Type checkSigPolyMethodId(JCTree tree,
  3474                      Type site,
  3475                      Symbol sym,
  3476                      Env<AttrContext> env,
  3477                      ResultInfo resultInfo) {
  3478             //recover original symbol for signature polymorphic methods
  3479             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3480             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3481             return sym.type;
  3484         Type checkMethodIdInternal(JCTree tree,
  3485                      Type site,
  3486                      Symbol sym,
  3487                      Env<AttrContext> env,
  3488                      ResultInfo resultInfo) {
  3489             if ((resultInfo.pkind & POLY) != 0) {
  3490                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3491                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3492                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3493                 return owntype;
  3494             } else {
  3495                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3499         Type checkIdInternal(JCTree tree,
  3500                      Type site,
  3501                      Symbol sym,
  3502                      Type pt,
  3503                      Env<AttrContext> env,
  3504                      ResultInfo resultInfo) {
  3505             if (pt.isErroneous()) {
  3506                 return types.createErrorType(site);
  3508             Type owntype; // The computed type of this identifier occurrence.
  3509             switch (sym.kind) {
  3510             case TYP:
  3511                 // For types, the computed type equals the symbol's type,
  3512                 // except for two situations:
  3513                 owntype = sym.type;
  3514                 if (owntype.hasTag(CLASS)) {
  3515                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3516                     Type ownOuter = owntype.getEnclosingType();
  3518                     // (a) If the symbol's type is parameterized, erase it
  3519                     // because no type parameters were given.
  3520                     // We recover generic outer type later in visitTypeApply.
  3521                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3522                         owntype = types.erasure(owntype);
  3525                     // (b) If the symbol's type is an inner class, then
  3526                     // we have to interpret its outer type as a superclass
  3527                     // of the site type. Example:
  3528                     //
  3529                     // class Tree<A> { class Visitor { ... } }
  3530                     // class PointTree extends Tree<Point> { ... }
  3531                     // ...PointTree.Visitor...
  3532                     //
  3533                     // Then the type of the last expression above is
  3534                     // Tree<Point>.Visitor.
  3535                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3536                         Type normOuter = site;
  3537                         if (normOuter.hasTag(CLASS)) {
  3538                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3540                         if (normOuter == null) // perhaps from an import
  3541                             normOuter = types.erasure(ownOuter);
  3542                         if (normOuter != ownOuter)
  3543                             owntype = new ClassType(
  3544                                 normOuter, List.<Type>nil(), owntype.tsym);
  3547                 break;
  3548             case VAR:
  3549                 VarSymbol v = (VarSymbol)sym;
  3550                 // Test (4): if symbol is an instance field of a raw type,
  3551                 // which is being assigned to, issue an unchecked warning if
  3552                 // its type changes under erasure.
  3553                 if (allowGenerics &&
  3554                     resultInfo.pkind == VAR &&
  3555                     v.owner.kind == TYP &&
  3556                     (v.flags() & STATIC) == 0 &&
  3557                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3558                     Type s = types.asOuterSuper(site, v.owner);
  3559                     if (s != null &&
  3560                         s.isRaw() &&
  3561                         !types.isSameType(v.type, v.erasure(types))) {
  3562                         chk.warnUnchecked(tree.pos(),
  3563                                           "unchecked.assign.to.var",
  3564                                           v, s);
  3567                 // The computed type of a variable is the type of the
  3568                 // variable symbol, taken as a member of the site type.
  3569                 owntype = (sym.owner.kind == TYP &&
  3570                            sym.name != names._this && sym.name != names._super)
  3571                     ? types.memberType(site, sym)
  3572                     : sym.type;
  3574                 // If the variable is a constant, record constant value in
  3575                 // computed type.
  3576                 if (v.getConstValue() != null && isStaticReference(tree))
  3577                     owntype = owntype.constType(v.getConstValue());
  3579                 if (resultInfo.pkind == VAL) {
  3580                     owntype = capture(owntype); // capture "names as expressions"
  3582                 break;
  3583             case MTH: {
  3584                 owntype = checkMethod(site, sym,
  3585                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3586                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3587                         resultInfo.pt.getTypeArguments());
  3588                 break;
  3590             case PCK: case ERR:
  3591                 owntype = sym.type;
  3592                 break;
  3593             default:
  3594                 throw new AssertionError("unexpected kind: " + sym.kind +
  3595                                          " in tree " + tree);
  3598             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3599             // (for constructors, the error was given when the constructor was
  3600             // resolved)
  3602             if (sym.name != names.init) {
  3603                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3604                 chk.checkSunAPI(tree.pos(), sym);
  3605                 chk.checkProfile(tree.pos(), sym);
  3608             // Test (3): if symbol is a variable, check that its type and
  3609             // kind are compatible with the prototype and protokind.
  3610             return check(tree, owntype, sym.kind, resultInfo);
  3613         /** Check that variable is initialized and evaluate the variable's
  3614          *  initializer, if not yet done. Also check that variable is not
  3615          *  referenced before it is defined.
  3616          *  @param tree    The tree making up the variable reference.
  3617          *  @param env     The current environment.
  3618          *  @param v       The variable's symbol.
  3619          */
  3620         private void checkInit(JCTree tree,
  3621                                Env<AttrContext> env,
  3622                                VarSymbol v,
  3623                                boolean onlyWarning) {
  3624 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3625 //                             tree.pos + " " + v.pos + " " +
  3626 //                             Resolve.isStatic(env));//DEBUG
  3628             // A forward reference is diagnosed if the declaration position
  3629             // of the variable is greater than the current tree position
  3630             // and the tree and variable definition occur in the same class
  3631             // definition.  Note that writes don't count as references.
  3632             // This check applies only to class and instance
  3633             // variables.  Local variables follow different scope rules,
  3634             // and are subject to definite assignment checking.
  3635             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3636                 v.owner.kind == TYP &&
  3637                 enclosingInitEnv(env) != null &&
  3638                 v.owner == env.info.scope.owner.enclClass() &&
  3639                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3640                 (!env.tree.hasTag(ASSIGN) ||
  3641                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3642                 String suffix = (env.info.enclVar == v) ?
  3643                                 "self.ref" : "forward.ref";
  3644                 if (!onlyWarning || isStaticEnumField(v)) {
  3645                     log.error(tree.pos(), "illegal." + suffix);
  3646                 } else if (useBeforeDeclarationWarning) {
  3647                     log.warning(tree.pos(), suffix, v);
  3651             v.getConstValue(); // ensure initializer is evaluated
  3653             checkEnumInitializer(tree, env, v);
  3656         /**
  3657          * Returns the enclosing init environment associated with this env (if any). An init env
  3658          * can be either a field declaration env or a static/instance initializer env.
  3659          */
  3660         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
  3661             while (true) {
  3662                 switch (env.tree.getTag()) {
  3663                     case VARDEF:
  3664                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
  3665                         if (vdecl.sym.owner.kind == TYP) {
  3666                             //field
  3667                             return env;
  3669                         break;
  3670                     case BLOCK:
  3671                         if (env.next.tree.hasTag(CLASSDEF)) {
  3672                             //instance/static initializer
  3673                             return env;
  3675                         break;
  3676                     case METHODDEF:
  3677                     case CLASSDEF:
  3678                     case TOPLEVEL:
  3679                         return null;
  3681                 Assert.checkNonNull(env.next);
  3682                 env = env.next;
  3686         /**
  3687          * Check for illegal references to static members of enum.  In
  3688          * an enum type, constructors and initializers may not
  3689          * reference its static members unless they are constant.
  3691          * @param tree    The tree making up the variable reference.
  3692          * @param env     The current environment.
  3693          * @param v       The variable's symbol.
  3694          * @jls  section 8.9 Enums
  3695          */
  3696         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3697             // JLS:
  3698             //
  3699             // "It is a compile-time error to reference a static field
  3700             // of an enum type that is not a compile-time constant
  3701             // (15.28) from constructors, instance initializer blocks,
  3702             // or instance variable initializer expressions of that
  3703             // type. It is a compile-time error for the constructors,
  3704             // instance initializer blocks, or instance variable
  3705             // initializer expressions of an enum constant e to refer
  3706             // to itself or to an enum constant of the same type that
  3707             // is declared to the right of e."
  3708             if (isStaticEnumField(v)) {
  3709                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3711                 if (enclClass == null || enclClass.owner == null)
  3712                     return;
  3714                 // See if the enclosing class is the enum (or a
  3715                 // subclass thereof) declaring v.  If not, this
  3716                 // reference is OK.
  3717                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3718                     return;
  3720                 // If the reference isn't from an initializer, then
  3721                 // the reference is OK.
  3722                 if (!Resolve.isInitializer(env))
  3723                     return;
  3725                 log.error(tree.pos(), "illegal.enum.static.ref");
  3729         /** Is the given symbol a static, non-constant field of an Enum?
  3730          *  Note: enum literals should not be regarded as such
  3731          */
  3732         private boolean isStaticEnumField(VarSymbol v) {
  3733             return Flags.isEnum(v.owner) &&
  3734                    Flags.isStatic(v) &&
  3735                    !Flags.isConstant(v) &&
  3736                    v.name != names._class;
  3739     Warner noteWarner = new Warner();
  3741     /**
  3742      * Check that method arguments conform to its instantiation.
  3743      **/
  3744     public Type checkMethod(Type site,
  3745                             final Symbol sym,
  3746                             ResultInfo resultInfo,
  3747                             Env<AttrContext> env,
  3748                             final List<JCExpression> argtrees,
  3749                             List<Type> argtypes,
  3750                             List<Type> typeargtypes) {
  3751         // Test (5): if symbol is an instance method of a raw type, issue
  3752         // an unchecked warning if its argument types change under erasure.
  3753         if (allowGenerics &&
  3754             (sym.flags() & STATIC) == 0 &&
  3755             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3756             Type s = types.asOuterSuper(site, sym.owner);
  3757             if (s != null && s.isRaw() &&
  3758                 !types.isSameTypes(sym.type.getParameterTypes(),
  3759                                    sym.erasure(types).getParameterTypes())) {
  3760                 chk.warnUnchecked(env.tree.pos(),
  3761                                   "unchecked.call.mbr.of.raw.type",
  3762                                   sym, s);
  3766         if (env.info.defaultSuperCallSite != null) {
  3767             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3768                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3769                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3770                 List<MethodSymbol> icand_sup =
  3771                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3772                 if (icand_sup.nonEmpty() &&
  3773                         icand_sup.head != sym &&
  3774                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3775                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3776                         diags.fragment("overridden.default", sym, sup));
  3777                     break;
  3780             env.info.defaultSuperCallSite = null;
  3783         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3784             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3785             if (app.meth.hasTag(SELECT) &&
  3786                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3787                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3791         // Compute the identifier's instantiated type.
  3792         // For methods, we need to compute the instance type by
  3793         // Resolve.instantiate from the symbol's type as well as
  3794         // any type arguments and value arguments.
  3795         noteWarner.clear();
  3796         try {
  3797             Type owntype = rs.checkMethod(
  3798                     env,
  3799                     site,
  3800                     sym,
  3801                     resultInfo,
  3802                     argtypes,
  3803                     typeargtypes,
  3804                     noteWarner);
  3806             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3807                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3809             argtypes = Type.map(argtypes, checkDeferredMap);
  3811             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3812                 chk.warnUnchecked(env.tree.pos(),
  3813                         "unchecked.meth.invocation.applied",
  3814                         kindName(sym),
  3815                         sym.name,
  3816                         rs.methodArguments(sym.type.getParameterTypes()),
  3817                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3818                         kindName(sym.location()),
  3819                         sym.location());
  3820                owntype = new MethodType(owntype.getParameterTypes(),
  3821                        types.erasure(owntype.getReturnType()),
  3822                        types.erasure(owntype.getThrownTypes()),
  3823                        syms.methodClass);
  3826             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3827                     resultInfo.checkContext.inferenceContext());
  3828         } catch (Infer.InferenceException ex) {
  3829             //invalid target type - propagate exception outwards or report error
  3830             //depending on the current check context
  3831             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3832             return types.createErrorType(site);
  3833         } catch (Resolve.InapplicableMethodException ex) {
  3834             final JCDiagnostic diag = ex.getDiagnostic();
  3835             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  3836                 @Override
  3837                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3838                     return new Pair<Symbol, JCDiagnostic>(sym, diag);
  3840             };
  3841             List<Type> argtypes2 = Type.map(argtypes,
  3842                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3843             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3844                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  3845             log.report(errDiag);
  3846             return types.createErrorType(site);
  3850     public void visitLiteral(JCLiteral tree) {
  3851         result = check(
  3852             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3854     //where
  3855     /** Return the type of a literal with given type tag.
  3856      */
  3857     Type litType(TypeTag tag) {
  3858         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3861     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3862         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3865     public void visitTypeArray(JCArrayTypeTree tree) {
  3866         Type etype = attribType(tree.elemtype, env);
  3867         Type type = new ArrayType(etype, syms.arrayClass);
  3868         result = check(tree, type, TYP, resultInfo);
  3871     /** Visitor method for parameterized types.
  3872      *  Bound checking is left until later, since types are attributed
  3873      *  before supertype structure is completely known
  3874      */
  3875     public void visitTypeApply(JCTypeApply tree) {
  3876         Type owntype = types.createErrorType(tree.type);
  3878         // Attribute functor part of application and make sure it's a class.
  3879         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3881         // Attribute type parameters
  3882         List<Type> actuals = attribTypes(tree.arguments, env);
  3884         if (clazztype.hasTag(CLASS)) {
  3885             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3886             if (actuals.isEmpty()) //diamond
  3887                 actuals = formals;
  3889             if (actuals.length() == formals.length()) {
  3890                 List<Type> a = actuals;
  3891                 List<Type> f = formals;
  3892                 while (a.nonEmpty()) {
  3893                     a.head = a.head.withTypeVar(f.head);
  3894                     a = a.tail;
  3895                     f = f.tail;
  3897                 // Compute the proper generic outer
  3898                 Type clazzOuter = clazztype.getEnclosingType();
  3899                 if (clazzOuter.hasTag(CLASS)) {
  3900                     Type site;
  3901                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3902                     if (clazz.hasTag(IDENT)) {
  3903                         site = env.enclClass.sym.type;
  3904                     } else if (clazz.hasTag(SELECT)) {
  3905                         site = ((JCFieldAccess) clazz).selected.type;
  3906                     } else throw new AssertionError(""+tree);
  3907                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3908                         if (site.hasTag(CLASS))
  3909                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3910                         if (site == null)
  3911                             site = types.erasure(clazzOuter);
  3912                         clazzOuter = site;
  3915                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3916             } else {
  3917                 if (formals.length() != 0) {
  3918                     log.error(tree.pos(), "wrong.number.type.args",
  3919                               Integer.toString(formals.length()));
  3920                 } else {
  3921                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3923                 owntype = types.createErrorType(tree.type);
  3926         result = check(tree, owntype, TYP, resultInfo);
  3929     public void visitTypeUnion(JCTypeUnion tree) {
  3930         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  3931         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3932         for (JCExpression typeTree : tree.alternatives) {
  3933             Type ctype = attribType(typeTree, env);
  3934             ctype = chk.checkType(typeTree.pos(),
  3935                           chk.checkClassType(typeTree.pos(), ctype),
  3936                           syms.throwableType);
  3937             if (!ctype.isErroneous()) {
  3938                 //check that alternatives of a union type are pairwise
  3939                 //unrelated w.r.t. subtyping
  3940                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3941                     for (Type t : multicatchTypes) {
  3942                         boolean sub = types.isSubtype(ctype, t);
  3943                         boolean sup = types.isSubtype(t, ctype);
  3944                         if (sub || sup) {
  3945                             //assume 'a' <: 'b'
  3946                             Type a = sub ? ctype : t;
  3947                             Type b = sub ? t : ctype;
  3948                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3952                 multicatchTypes.append(ctype);
  3953                 if (all_multicatchTypes != null)
  3954                     all_multicatchTypes.append(ctype);
  3955             } else {
  3956                 if (all_multicatchTypes == null) {
  3957                     all_multicatchTypes = new ListBuffer<>();
  3958                     all_multicatchTypes.appendList(multicatchTypes);
  3960                 all_multicatchTypes.append(ctype);
  3963         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3964         if (t.hasTag(CLASS)) {
  3965             List<Type> alternatives =
  3966                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3967             t = new UnionClassType((ClassType) t, alternatives);
  3969         tree.type = result = t;
  3972     public void visitTypeIntersection(JCTypeIntersection tree) {
  3973         attribTypes(tree.bounds, env);
  3974         tree.type = result = checkIntersection(tree, tree.bounds);
  3977     public void visitTypeParameter(JCTypeParameter tree) {
  3978         TypeVar typeVar = (TypeVar) tree.type;
  3980         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3981             annotateType(tree, tree.annotations);
  3984         if (!typeVar.bound.isErroneous()) {
  3985             //fixup type-parameter bound computed in 'attribTypeVariables'
  3986             typeVar.bound = checkIntersection(tree, tree.bounds);
  3990     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3991         Set<Type> boundSet = new HashSet<Type>();
  3992         if (bounds.nonEmpty()) {
  3993             // accept class or interface or typevar as first bound.
  3994             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3995             boundSet.add(types.erasure(bounds.head.type));
  3996             if (bounds.head.type.isErroneous()) {
  3997                 return bounds.head.type;
  3999             else if (bounds.head.type.hasTag(TYPEVAR)) {
  4000                 // if first bound was a typevar, do not accept further bounds.
  4001                 if (bounds.tail.nonEmpty()) {
  4002                     log.error(bounds.tail.head.pos(),
  4003                               "type.var.may.not.be.followed.by.other.bounds");
  4004                     return bounds.head.type;
  4006             } else {
  4007                 // if first bound was a class or interface, accept only interfaces
  4008                 // as further bounds.
  4009                 for (JCExpression bound : bounds.tail) {
  4010                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  4011                     if (bound.type.isErroneous()) {
  4012                         bounds = List.of(bound);
  4014                     else if (bound.type.hasTag(CLASS)) {
  4015                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4021         if (bounds.length() == 0) {
  4022             return syms.objectType;
  4023         } else if (bounds.length() == 1) {
  4024             return bounds.head.type;
  4025         } else {
  4026             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4027             // ... the variable's bound is a class type flagged COMPOUND
  4028             // (see comment for TypeVar.bound).
  4029             // In this case, generate a class tree that represents the
  4030             // bound class, ...
  4031             JCExpression extending;
  4032             List<JCExpression> implementing;
  4033             if (!bounds.head.type.isInterface()) {
  4034                 extending = bounds.head;
  4035                 implementing = bounds.tail;
  4036             } else {
  4037                 extending = null;
  4038                 implementing = bounds;
  4040             JCClassDecl cd = make.at(tree).ClassDef(
  4041                 make.Modifiers(PUBLIC | ABSTRACT),
  4042                 names.empty, List.<JCTypeParameter>nil(),
  4043                 extending, implementing, List.<JCTree>nil());
  4045             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4046             Assert.check((c.flags() & COMPOUND) != 0);
  4047             cd.sym = c;
  4048             c.sourcefile = env.toplevel.sourcefile;
  4050             // ... and attribute the bound class
  4051             c.flags_field |= UNATTRIBUTED;
  4052             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4053             typeEnvs.put(c, cenv);
  4054             attribClass(c);
  4055             return owntype;
  4059     public void visitWildcard(JCWildcard tree) {
  4060         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4061         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4062             ? syms.objectType
  4063             : attribType(tree.inner, env);
  4064         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4065                                               tree.kind.kind,
  4066                                               syms.boundClass),
  4067                        TYP, resultInfo);
  4070     public void visitAnnotation(JCAnnotation tree) {
  4071         Assert.error("should be handled in Annotate");
  4074     public void visitAnnotatedType(JCAnnotatedType tree) {
  4075         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4076         this.attribAnnotationTypes(tree.annotations, env);
  4077         annotateType(tree, tree.annotations);
  4078         result = tree.type = underlyingType;
  4081     /**
  4082      * Apply the annotations to the particular type.
  4083      */
  4084     public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
  4085         annotate.typeAnnotation(new Annotate.Worker() {
  4086             @Override
  4087             public String toString() {
  4088                 return "annotate " + annotations + " onto " + tree;
  4090             @Override
  4091             public void run() {
  4092                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4093                 if (annotations.size() == compounds.size()) {
  4094                     // All annotations were successfully converted into compounds
  4095                     tree.type = tree.type.unannotatedType().annotatedType(compounds);
  4098         });
  4101     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4102         if (annotations.isEmpty()) {
  4103             return List.nil();
  4106         ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  4107         for (JCAnnotation anno : annotations) {
  4108             if (anno.attribute != null) {
  4109                 // TODO: this null-check is only needed for an obscure
  4110                 // ordering issue, where annotate.flush is called when
  4111                 // the attribute is not set yet. For an example failure
  4112                 // try the referenceinfos/NestedTypes.java test.
  4113                 // Any better solutions?
  4114                 buf.append((Attribute.TypeCompound) anno.attribute);
  4116             // Eventually we will want to throw an exception here, but
  4117             // we can't do that just yet, because it gets triggered
  4118             // when attempting to attach an annotation that isn't
  4119             // defined.
  4121         return buf.toList();
  4124     public void visitErroneous(JCErroneous tree) {
  4125         if (tree.errs != null)
  4126             for (JCTree err : tree.errs)
  4127                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4128         result = tree.type = syms.errType;
  4131     /** Default visitor method for all other trees.
  4132      */
  4133     public void visitTree(JCTree tree) {
  4134         throw new AssertionError();
  4137     /**
  4138      * Attribute an env for either a top level tree or class declaration.
  4139      */
  4140     public void attrib(Env<AttrContext> env) {
  4141         if (env.tree.hasTag(TOPLEVEL))
  4142             attribTopLevel(env);
  4143         else
  4144             attribClass(env.tree.pos(), env.enclClass.sym);
  4147     /**
  4148      * Attribute a top level tree. These trees are encountered when the
  4149      * package declaration has annotations.
  4150      */
  4151     public void attribTopLevel(Env<AttrContext> env) {
  4152         JCCompilationUnit toplevel = env.toplevel;
  4153         try {
  4154             annotate.flush();
  4155         } catch (CompletionFailure ex) {
  4156             chk.completionError(toplevel.pos(), ex);
  4160     /** Main method: attribute class definition associated with given class symbol.
  4161      *  reporting completion failures at the given position.
  4162      *  @param pos The source position at which completion errors are to be
  4163      *             reported.
  4164      *  @param c   The class symbol whose definition will be attributed.
  4165      */
  4166     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4167         try {
  4168             annotate.flush();
  4169             attribClass(c);
  4170         } catch (CompletionFailure ex) {
  4171             chk.completionError(pos, ex);
  4175     /** Attribute class definition associated with given class symbol.
  4176      *  @param c   The class symbol whose definition will be attributed.
  4177      */
  4178     void attribClass(ClassSymbol c) throws CompletionFailure {
  4179         if (c.type.hasTag(ERROR)) return;
  4181         // Check for cycles in the inheritance graph, which can arise from
  4182         // ill-formed class files.
  4183         chk.checkNonCyclic(null, c.type);
  4185         Type st = types.supertype(c.type);
  4186         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4187             // First, attribute superclass.
  4188             if (st.hasTag(CLASS))
  4189                 attribClass((ClassSymbol)st.tsym);
  4191             // Next attribute owner, if it is a class.
  4192             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4193                 attribClass((ClassSymbol)c.owner);
  4196         // The previous operations might have attributed the current class
  4197         // if there was a cycle. So we test first whether the class is still
  4198         // UNATTRIBUTED.
  4199         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4200             c.flags_field &= ~UNATTRIBUTED;
  4202             // Get environment current at the point of class definition.
  4203             Env<AttrContext> env = typeEnvs.get(c);
  4205             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
  4206             // because the annotations were not available at the time the env was created. Therefore,
  4207             // we look up the environment chain for the first enclosing environment for which the
  4208             // lint value is set. Typically, this is the parent env, but might be further if there
  4209             // are any envs created as a result of TypeParameter nodes.
  4210             Env<AttrContext> lintEnv = env;
  4211             while (lintEnv.info.lint == null)
  4212                 lintEnv = lintEnv.next;
  4214             // Having found the enclosing lint value, we can initialize the lint value for this class
  4215             env.info.lint = lintEnv.info.lint.augment(c);
  4217             Lint prevLint = chk.setLint(env.info.lint);
  4218             JavaFileObject prev = log.useSource(c.sourcefile);
  4219             ResultInfo prevReturnRes = env.info.returnResult;
  4221             try {
  4222                 deferredLintHandler.flush(env.tree);
  4223                 env.info.returnResult = null;
  4224                 // java.lang.Enum may not be subclassed by a non-enum
  4225                 if (st.tsym == syms.enumSym &&
  4226                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4227                     log.error(env.tree.pos(), "enum.no.subclassing");
  4229                 // Enums may not be extended by source-level classes
  4230                 if (st.tsym != null &&
  4231                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4232                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4233                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4236                 if (isSerializable(c.type)) {
  4237                     env.info.isSerializable = true;
  4240                 attribClassBody(env, c);
  4242                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4243                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4244                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
  4245             } finally {
  4246                 env.info.returnResult = prevReturnRes;
  4247                 log.useSource(prev);
  4248                 chk.setLint(prevLint);
  4254     public void visitImport(JCImport tree) {
  4255         // nothing to do
  4258     /** Finish the attribution of a class. */
  4259     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4260         JCClassDecl tree = (JCClassDecl)env.tree;
  4261         Assert.check(c == tree.sym);
  4263         // Validate type parameters, supertype and interfaces.
  4264         attribStats(tree.typarams, env);
  4265         if (!c.isAnonymous()) {
  4266             //already checked if anonymous
  4267             chk.validate(tree.typarams, env);
  4268             chk.validate(tree.extending, env);
  4269             chk.validate(tree.implementing, env);
  4272         // If this is a non-abstract class, check that it has no abstract
  4273         // methods or unimplemented methods of an implemented interface.
  4274         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4275             if (!relax)
  4276                 chk.checkAllDefined(tree.pos(), c);
  4279         if ((c.flags() & ANNOTATION) != 0) {
  4280             if (tree.implementing.nonEmpty())
  4281                 log.error(tree.implementing.head.pos(),
  4282                           "cant.extend.intf.annotation");
  4283             if (tree.typarams.nonEmpty())
  4284                 log.error(tree.typarams.head.pos(),
  4285                           "intf.annotation.cant.have.type.params");
  4287             // If this annotation has a @Repeatable, validate
  4288             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4289             if (repeatable != null) {
  4290                 // get diagnostic position for error reporting
  4291                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4292                 Assert.checkNonNull(cbPos);
  4294                 chk.validateRepeatable(c, repeatable, cbPos);
  4296         } else {
  4297             // Check that all extended classes and interfaces
  4298             // are compatible (i.e. no two define methods with same arguments
  4299             // yet different return types).  (JLS 8.4.6.3)
  4300             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4301             if (allowDefaultMethods) {
  4302                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4306         // Check that class does not import the same parameterized interface
  4307         // with two different argument lists.
  4308         chk.checkClassBounds(tree.pos(), c.type);
  4310         tree.type = c.type;
  4312         for (List<JCTypeParameter> l = tree.typarams;
  4313              l.nonEmpty(); l = l.tail) {
  4314              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4317         // Check that a generic class doesn't extend Throwable
  4318         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4319             log.error(tree.extending.pos(), "generic.throwable");
  4321         // Check that all methods which implement some
  4322         // method conform to the method they implement.
  4323         chk.checkImplementations(tree);
  4325         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4326         checkAutoCloseable(tree.pos(), env, c.type);
  4328         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4329             // Attribute declaration
  4330             attribStat(l.head, env);
  4331             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4332             // Make an exception for static constants.
  4333             if (c.owner.kind != PCK &&
  4334                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4335                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4336                 Symbol sym = null;
  4337                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4338                 if (sym == null ||
  4339                     sym.kind != VAR ||
  4340                     ((VarSymbol) sym).getConstValue() == null)
  4341                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4345         // Check for cycles among non-initial constructors.
  4346         chk.checkCyclicConstructors(tree);
  4348         // Check for cycles among annotation elements.
  4349         chk.checkNonCyclicElements(tree);
  4351         // Check for proper use of serialVersionUID
  4352         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4353             isSerializable(c.type) &&
  4354             (c.flags() & Flags.ENUM) == 0 &&
  4355             checkForSerial(c)) {
  4356             checkSerialVersionUID(tree, c);
  4358         if (allowTypeAnnos) {
  4359             // Correctly organize the postions of the type annotations
  4360             typeAnnotations.organizeTypeAnnotationsBodies(tree);
  4362             // Check type annotations applicability rules
  4363             validateTypeAnnotations(tree, false);
  4366         // where
  4367         boolean checkForSerial(ClassSymbol c) {
  4368             if ((c.flags() & ABSTRACT) == 0) {
  4369                 return true;
  4370             } else {
  4371                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4375         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4376             @Override
  4377             public boolean accepts(Symbol s) {
  4378                 return s.kind == Kinds.MTH &&
  4379                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4381         };
  4383         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4384         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4385             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4386                 if (types.isSameType(al.head.annotationType.type, t))
  4387                     return al.head.pos();
  4390             return null;
  4393         /** check if a type is a subtype of Serializable, if that is available. */
  4394         boolean isSerializable(Type t) {
  4395             try {
  4396                 syms.serializableType.complete();
  4398             catch (CompletionFailure e) {
  4399                 return false;
  4401             return types.isSubtype(t, syms.serializableType);
  4404         /** Check that an appropriate serialVersionUID member is defined. */
  4405         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4407             // check for presence of serialVersionUID
  4408             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4409             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4410             if (e.scope == null) {
  4411                 log.warning(LintCategory.SERIAL,
  4412                         tree.pos(), "missing.SVUID", c);
  4413                 return;
  4416             // check that it is static final
  4417             VarSymbol svuid = (VarSymbol)e.sym;
  4418             if ((svuid.flags() & (STATIC | FINAL)) !=
  4419                 (STATIC | FINAL))
  4420                 log.warning(LintCategory.SERIAL,
  4421                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4423             // check that it is long
  4424             else if (!svuid.type.hasTag(LONG))
  4425                 log.warning(LintCategory.SERIAL,
  4426                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4428             // check constant
  4429             else if (svuid.getConstValue() == null)
  4430                 log.warning(LintCategory.SERIAL,
  4431                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4434     private Type capture(Type type) {
  4435         return types.capture(type);
  4438     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
  4439         tree.accept(new TypeAnnotationsValidator(sigOnly));
  4441     //where
  4442     private final class TypeAnnotationsValidator extends TreeScanner {
  4444         private final boolean sigOnly;
  4445         public TypeAnnotationsValidator(boolean sigOnly) {
  4446             this.sigOnly = sigOnly;
  4449         public void visitAnnotation(JCAnnotation tree) {
  4450             chk.validateTypeAnnotation(tree, false);
  4451             super.visitAnnotation(tree);
  4453         public void visitAnnotatedType(JCAnnotatedType tree) {
  4454             if (!tree.underlyingType.type.isErroneous()) {
  4455                 super.visitAnnotatedType(tree);
  4458         public void visitTypeParameter(JCTypeParameter tree) {
  4459             chk.validateTypeAnnotations(tree.annotations, true);
  4460             scan(tree.bounds);
  4461             // Don't call super.
  4462             // This is needed because above we call validateTypeAnnotation with
  4463             // false, which would forbid annotations on type parameters.
  4464             // super.visitTypeParameter(tree);
  4466         public void visitMethodDef(JCMethodDecl tree) {
  4467             if (tree.recvparam != null &&
  4468                     !tree.recvparam.vartype.type.isErroneous()) {
  4469                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4470                         tree.recvparam.vartype.type.tsym);
  4472             if (tree.restype != null && tree.restype.type != null) {
  4473                 validateAnnotatedType(tree.restype, tree.restype.type);
  4475             if (sigOnly) {
  4476                 scan(tree.mods);
  4477                 scan(tree.restype);
  4478                 scan(tree.typarams);
  4479                 scan(tree.recvparam);
  4480                 scan(tree.params);
  4481                 scan(tree.thrown);
  4482             } else {
  4483                 scan(tree.defaultValue);
  4484                 scan(tree.body);
  4487         public void visitVarDef(final JCVariableDecl tree) {
  4488             if (tree.sym != null && tree.sym.type != null)
  4489                 validateAnnotatedType(tree.vartype, tree.sym.type);
  4490             scan(tree.mods);
  4491             scan(tree.vartype);
  4492             if (!sigOnly) {
  4493                 scan(tree.init);
  4496         public void visitTypeCast(JCTypeCast tree) {
  4497             if (tree.clazz != null && tree.clazz.type != null)
  4498                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4499             super.visitTypeCast(tree);
  4501         public void visitTypeTest(JCInstanceOf tree) {
  4502             if (tree.clazz != null && tree.clazz.type != null)
  4503                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4504             super.visitTypeTest(tree);
  4506         public void visitNewClass(JCNewClass tree) {
  4507             if (tree.clazz != null && tree.clazz.type != null) {
  4508                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4509                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  4510                             tree.clazz.type.tsym);
  4512                 if (tree.def != null) {
  4513                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
  4516                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4518             super.visitNewClass(tree);
  4520         public void visitNewArray(JCNewArray tree) {
  4521             if (tree.elemtype != null && tree.elemtype.type != null) {
  4522                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4523                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  4524                             tree.elemtype.type.tsym);
  4526                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
  4528             super.visitNewArray(tree);
  4530         public void visitClassDef(JCClassDecl tree) {
  4531             if (sigOnly) {
  4532                 scan(tree.mods);
  4533                 scan(tree.typarams);
  4534                 scan(tree.extending);
  4535                 scan(tree.implementing);
  4537             for (JCTree member : tree.defs) {
  4538                 if (member.hasTag(Tag.CLASSDEF)) {
  4539                     continue;
  4541                 scan(member);
  4544         public void visitBlock(JCBlock tree) {
  4545             if (!sigOnly) {
  4546                 scan(tree.stats);
  4550         /* I would want to model this after
  4551          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4552          * and override visitSelect and visitTypeApply.
  4553          * However, we only set the annotated type in the top-level type
  4554          * of the symbol.
  4555          * Therefore, we need to override each individual location where a type
  4556          * can occur.
  4557          */
  4558         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4559             // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
  4561             if (type.isPrimitiveOrVoid()) {
  4562                 return;
  4565             JCTree enclTr = errtree;
  4566             Type enclTy = type;
  4568             boolean repeat = true;
  4569             while (repeat) {
  4570                 if (enclTr.hasTag(TYPEAPPLY)) {
  4571                     List<Type> tyargs = enclTy.getTypeArguments();
  4572                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
  4573                     if (trargs.length() > 0) {
  4574                         // Nothing to do for diamonds
  4575                         if (tyargs.length() == trargs.length()) {
  4576                             for (int i = 0; i < tyargs.length(); ++i) {
  4577                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
  4580                         // If the lengths don't match, it's either a diamond
  4581                         // or some nested type that redundantly provides
  4582                         // type arguments in the tree.
  4585                     // Look at the clazz part of a generic type
  4586                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
  4589                 if (enclTr.hasTag(SELECT)) {
  4590                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
  4591                     if (enclTy != null &&
  4592                             !enclTy.hasTag(NONE)) {
  4593                         enclTy = enclTy.getEnclosingType();
  4595                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
  4596                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
  4597                     if (enclTy == null ||
  4598                             enclTy.hasTag(NONE)) {
  4599                         if (at.getAnnotations().size() == 1) {
  4600                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
  4601                         } else {
  4602                             ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
  4603                             for (JCAnnotation an : at.getAnnotations()) {
  4604                                 comps.add(an.attribute);
  4606                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
  4608                         repeat = false;
  4610                     enclTr = at.underlyingType;
  4611                     // enclTy doesn't need to be changed
  4612                 } else if (enclTr.hasTag(IDENT)) {
  4613                     repeat = false;
  4614                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
  4615                     JCWildcard wc = (JCWildcard) enclTr;
  4616                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
  4617                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
  4618                     } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
  4619                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
  4620                     } else {
  4621                         // Nothing to do for UNBOUND
  4623                     repeat = false;
  4624                 } else if (enclTr.hasTag(TYPEARRAY)) {
  4625                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
  4626                     validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
  4627                     repeat = false;
  4628                 } else if (enclTr.hasTag(TYPEUNION)) {
  4629                     JCTypeUnion ut = (JCTypeUnion) enclTr;
  4630                     for (JCTree t : ut.getTypeAlternatives()) {
  4631                         validateAnnotatedType(t, t.type);
  4633                     repeat = false;
  4634                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
  4635                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
  4636                     for (JCTree t : it.getBounds()) {
  4637                         validateAnnotatedType(t, t.type);
  4639                     repeat = false;
  4640                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
  4641                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  4642                     repeat = false;
  4643                 } else {
  4644                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
  4645                             " within: "+ errtree + " with kind: " + errtree.getKind());
  4650         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  4651                 Symbol sym) {
  4652             // Ensure that no declaration annotations are present.
  4653             // Note that a tree type might be an AnnotatedType with
  4654             // empty annotations, if only declaration annotations were given.
  4655             // This method will raise an error for such a type.
  4656             for (JCAnnotation ai : annotations) {
  4657                 if (!ai.type.isErroneous() &&
  4658                         typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  4659                     log.error(ai.pos(), "annotation.type.not.applicable");
  4663     };
  4665     // <editor-fold desc="post-attribution visitor">
  4667     /**
  4668      * Handle missing types/symbols in an AST. This routine is useful when
  4669      * the compiler has encountered some errors (which might have ended up
  4670      * terminating attribution abruptly); if the compiler is used in fail-over
  4671      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4672      * prevents NPE to be progagated during subsequent compilation steps.
  4673      */
  4674     public void postAttr(JCTree tree) {
  4675         new PostAttrAnalyzer().scan(tree);
  4678     class PostAttrAnalyzer extends TreeScanner {
  4680         private void initTypeIfNeeded(JCTree that) {
  4681             if (that.type == null) {
  4682                 if (that.hasTag(METHODDEF)) {
  4683                     that.type = dummyMethodType((JCMethodDecl)that);
  4684                 } else {
  4685                     that.type = syms.unknownType;
  4690         /* Construct a dummy method type. If we have a method declaration,
  4691          * and the declared return type is void, then use that return type
  4692          * instead of UNKNOWN to avoid spurious error messages in lambda
  4693          * bodies (see:JDK-8041704).
  4694          */
  4695         private Type dummyMethodType(JCMethodDecl md) {
  4696             Type restype = syms.unknownType;
  4697             if (md != null && md.restype.hasTag(TYPEIDENT)) {
  4698                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
  4699                 if (prim.typetag == VOID)
  4700                     restype = syms.voidType;
  4702             return new MethodType(List.<Type>nil(), restype,
  4703                                   List.<Type>nil(), syms.methodClass);
  4705         private Type dummyMethodType() {
  4706             return dummyMethodType(null);
  4709         @Override
  4710         public void scan(JCTree tree) {
  4711             if (tree == null) return;
  4712             if (tree instanceof JCExpression) {
  4713                 initTypeIfNeeded(tree);
  4715             super.scan(tree);
  4718         @Override
  4719         public void visitIdent(JCIdent that) {
  4720             if (that.sym == null) {
  4721                 that.sym = syms.unknownSymbol;
  4725         @Override
  4726         public void visitSelect(JCFieldAccess that) {
  4727             if (that.sym == null) {
  4728                 that.sym = syms.unknownSymbol;
  4730             super.visitSelect(that);
  4733         @Override
  4734         public void visitClassDef(JCClassDecl that) {
  4735             initTypeIfNeeded(that);
  4736             if (that.sym == null) {
  4737                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4739             super.visitClassDef(that);
  4742         @Override
  4743         public void visitMethodDef(JCMethodDecl that) {
  4744             initTypeIfNeeded(that);
  4745             if (that.sym == null) {
  4746                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4748             super.visitMethodDef(that);
  4751         @Override
  4752         public void visitVarDef(JCVariableDecl that) {
  4753             initTypeIfNeeded(that);
  4754             if (that.sym == null) {
  4755                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4756                 that.sym.adr = 0;
  4758             super.visitVarDef(that);
  4761         @Override
  4762         public void visitNewClass(JCNewClass that) {
  4763             if (that.constructor == null) {
  4764                 that.constructor = new MethodSymbol(0, names.init,
  4765                         dummyMethodType(), syms.noSymbol);
  4767             if (that.constructorType == null) {
  4768                 that.constructorType = syms.unknownType;
  4770             super.visitNewClass(that);
  4773         @Override
  4774         public void visitAssignop(JCAssignOp that) {
  4775             if (that.operator == null) {
  4776                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4777                         -1, syms.noSymbol);
  4779             super.visitAssignop(that);
  4782         @Override
  4783         public void visitBinary(JCBinary that) {
  4784             if (that.operator == null) {
  4785                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4786                         -1, syms.noSymbol);
  4788             super.visitBinary(that);
  4791         @Override
  4792         public void visitUnary(JCUnary that) {
  4793             if (that.operator == null) {
  4794                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4795                         -1, syms.noSymbol);
  4797             super.visitUnary(that);
  4800         @Override
  4801         public void visitLambda(JCLambda that) {
  4802             super.visitLambda(that);
  4803             if (that.targets == null) {
  4804                 that.targets = List.nil();
  4808         @Override
  4809         public void visitReference(JCMemberReference that) {
  4810             super.visitReference(that);
  4811             if (that.sym == null) {
  4812                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
  4813                         syms.noSymbol);
  4815             if (that.targets == null) {
  4816                 that.targets = List.nil();
  4820     // </editor-fold>

mercurial