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

Mon, 16 Oct 2017 16:07:48 +0800

author
aoqi
date
Mon, 16 Oct 2017 16:07:48 +0800
changeset 2893
ca5783d9a597
parent 2814
380f6c17ea01
parent 2702
9ca8d8713094
child 3295
859dc787b52b
permissions
-rw-r--r--

merge

     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 and anonymous classes have not been entered yet, so we need to
   829         // do it now.
   830         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0) {
   831             enter.classEnter(tree, env);
   832         } else {
   833             // If this class declaration is part of a class level annotation,
   834             // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
   835             // order to simplify later steps and allow for sensible error
   836             // messages.
   837             if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
   838                 enter.classEnter(tree, env);
   839         }
   841         ClassSymbol c = tree.sym;
   842         if (c == null) {
   843             // exit in case something drastic went wrong during enter.
   844             result = null;
   845         } else {
   846             // make sure class has been completed:
   847             c.complete();
   849             // If this class appears as an anonymous class
   850             // in a superclass constructor call where
   851             // no explicit outer instance is given,
   852             // disable implicit outer instance from being passed.
   853             // (This would be an illegal access to "this before super").
   854             if (env.info.isSelfCall &&
   855                 env.tree.hasTag(NEWCLASS) &&
   856                 ((JCNewClass) env.tree).encl == null)
   857             {
   858                 c.flags_field |= NOOUTERTHIS;
   859             }
   860             attribClass(tree.pos(), c);
   861             result = tree.type = c.type;
   862         }
   863     }
   865     public void visitMethodDef(JCMethodDecl tree) {
   866         MethodSymbol m = tree.sym;
   867         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   869         Lint lint = env.info.lint.augment(m);
   870         Lint prevLint = chk.setLint(lint);
   871         MethodSymbol prevMethod = chk.setMethod(m);
   872         try {
   873             deferredLintHandler.flush(tree.pos());
   874             chk.checkDeprecatedAnnotation(tree.pos(), m);
   877             // Create a new environment with local scope
   878             // for attributing the method.
   879             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   880             localEnv.info.lint = lint;
   882             attribStats(tree.typarams, localEnv);
   884             // If we override any other methods, check that we do so properly.
   885             // JLS ???
   886             if (m.isStatic()) {
   887                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   888             } else {
   889                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   890             }
   891             chk.checkOverride(tree, m);
   893             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   894                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   895             }
   897             // Enter all type parameters into the local method scope.
   898             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   899                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   901             ClassSymbol owner = env.enclClass.sym;
   902             if ((owner.flags() & ANNOTATION) != 0 &&
   903                 tree.params.nonEmpty())
   904                 log.error(tree.params.head.pos(),
   905                           "intf.annotation.members.cant.have.params");
   907             // Attribute all value parameters.
   908             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   909                 attribStat(l.head, localEnv);
   910             }
   912             chk.checkVarargsMethodDecl(localEnv, tree);
   914             // Check that type parameters are well-formed.
   915             chk.validate(tree.typarams, localEnv);
   917             // Check that result type is well-formed.
   918             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
   919                 chk.validate(tree.restype, localEnv);
   921             // Check that receiver type is well-formed.
   922             if (tree.recvparam != null) {
   923                 // Use a new environment to check the receiver parameter.
   924                 // Otherwise I get "might not have been initialized" errors.
   925                 // Is there a better way?
   926                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   927                 attribType(tree.recvparam, newEnv);
   928                 chk.validate(tree.recvparam, newEnv);
   929             }
   931             // annotation method checks
   932             if ((owner.flags() & ANNOTATION) != 0) {
   933                 // annotation method cannot have throws clause
   934                 if (tree.thrown.nonEmpty()) {
   935                     log.error(tree.thrown.head.pos(),
   936                             "throws.not.allowed.in.intf.annotation");
   937                 }
   938                 // annotation method cannot declare type-parameters
   939                 if (tree.typarams.nonEmpty()) {
   940                     log.error(tree.typarams.head.pos(),
   941                             "intf.annotation.members.cant.have.type.params");
   942                 }
   943                 // validate annotation method's return type (could be an annotation type)
   944                 chk.validateAnnotationType(tree.restype);
   945                 // ensure that annotation method does not clash with members of Object/Annotation
   946                 chk.validateAnnotationMethod(tree.pos(), m);
   947             }
   949             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   950                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   952             if (tree.body == null) {
   953                 // Empty bodies are only allowed for
   954                 // abstract, native, or interface methods, or for methods
   955                 // in a retrofit signature class.
   956                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   957                     !relax)
   958                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   959                 if (tree.defaultValue != null) {
   960                     if ((owner.flags() & ANNOTATION) == 0)
   961                         log.error(tree.pos(),
   962                                   "default.allowed.in.intf.annotation.member");
   963                 }
   964             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   965                 if ((owner.flags() & INTERFACE) != 0) {
   966                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   967                 } else {
   968                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   969                 }
   970             } else if ((tree.mods.flags & NATIVE) != 0) {
   971                 log.error(tree.pos(), "native.meth.cant.have.body");
   972             } else {
   973                 // Add an implicit super() call unless an explicit call to
   974                 // super(...) or this(...) is given
   975                 // or we are compiling class java.lang.Object.
   976                 if (tree.name == names.init && owner.type != syms.objectType) {
   977                     JCBlock body = tree.body;
   978                     if (body.stats.isEmpty() ||
   979                         !TreeInfo.isSelfCall(body.stats.head)) {
   980                         body.stats = body.stats.
   981                             prepend(memberEnter.SuperCall(make.at(body.pos),
   982                                                           List.<Type>nil(),
   983                                                           List.<JCVariableDecl>nil(),
   984                                                           false));
   985                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
   986                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
   987                                TreeInfo.isSuperCall(body.stats.head)) {
   988                         // enum constructors are not allowed to call super
   989                         // directly, so make sure there aren't any super calls
   990                         // in enum constructors, except in the compiler
   991                         // generated one.
   992                         log.error(tree.body.stats.head.pos(),
   993                                   "call.to.super.not.allowed.in.enum.ctor",
   994                                   env.enclClass.sym);
   995                     }
   996                 }
   998                 // Attribute all type annotations in the body
   999                 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
  1000                 annotate.flush();
  1002                 // Attribute method body.
  1003                 attribStat(tree.body, localEnv);
  1006             localEnv.info.scope.leave();
  1007             result = tree.type = m.type;
  1009         finally {
  1010             chk.setLint(prevLint);
  1011             chk.setMethod(prevMethod);
  1015     public void visitVarDef(JCVariableDecl tree) {
  1016         // Local variables have not been entered yet, so we need to do it now:
  1017         if (env.info.scope.owner.kind == MTH) {
  1018             if (tree.sym != null) {
  1019                 // parameters have already been entered
  1020                 env.info.scope.enter(tree.sym);
  1021             } else {
  1022                 try {
  1023                     annotate.enterStart();
  1024                     memberEnter.memberEnter(tree, env);
  1025                 } finally {
  1026                     annotate.enterDone();
  1029         } else {
  1030             if (tree.init != null) {
  1031                 // Field initializer expression need to be entered.
  1032                 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
  1033                 annotate.flush();
  1037         VarSymbol v = tree.sym;
  1038         Lint lint = env.info.lint.augment(v);
  1039         Lint prevLint = chk.setLint(lint);
  1041         // Check that the variable's declared type is well-formed.
  1042         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1043                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1044                 (tree.sym.flags() & PARAMETER) != 0;
  1045         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1047         try {
  1048             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1049             deferredLintHandler.flush(tree.pos());
  1050             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1052             if (tree.init != null) {
  1053                 if ((v.flags_field & FINAL) == 0 ||
  1054                     !memberEnter.needsLazyConstValue(tree.init)) {
  1055                     // Not a compile-time constant
  1056                     // Attribute initializer in a new environment
  1057                     // with the declared variable as owner.
  1058                     // Check that initializer conforms to variable's declared type.
  1059                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1060                     initEnv.info.lint = lint;
  1061                     // In order to catch self-references, we set the variable's
  1062                     // declaration position to maximal possible value, effectively
  1063                     // marking the variable as undefined.
  1064                     initEnv.info.enclVar = v;
  1065                     attribExpr(tree.init, initEnv, v.type);
  1068             result = tree.type = v.type;
  1070         finally {
  1071             chk.setLint(prevLint);
  1075     public void visitSkip(JCSkip tree) {
  1076         result = null;
  1079     public void visitBlock(JCBlock tree) {
  1080         if (env.info.scope.owner.kind == TYP) {
  1081             // Block is a static or instance initializer;
  1082             // let the owner of the environment be a freshly
  1083             // created BLOCK-method.
  1084             Env<AttrContext> localEnv =
  1085                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1086             localEnv.info.scope.owner =
  1087                 new MethodSymbol(tree.flags | BLOCK |
  1088                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1089                     env.info.scope.owner);
  1090             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1092             // Attribute all type annotations in the block
  1093             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1094             annotate.flush();
  1097                 // Store init and clinit type annotations with the ClassSymbol
  1098                 // to allow output in Gen.normalizeDefs.
  1099                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1100                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1101                 if ((tree.flags & STATIC) != 0) {
  1102                     cs.appendClassInitTypeAttributes(tas);
  1103                 } else {
  1104                     cs.appendInitTypeAttributes(tas);
  1108             attribStats(tree.stats, localEnv);
  1109         } else {
  1110             // Create a new local environment with a local scope.
  1111             Env<AttrContext> localEnv =
  1112                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1113             try {
  1114                 attribStats(tree.stats, localEnv);
  1115             } finally {
  1116                 localEnv.info.scope.leave();
  1119         result = null;
  1122     public void visitDoLoop(JCDoWhileLoop tree) {
  1123         attribStat(tree.body, env.dup(tree));
  1124         attribExpr(tree.cond, env, syms.booleanType);
  1125         result = null;
  1128     public void visitWhileLoop(JCWhileLoop tree) {
  1129         attribExpr(tree.cond, env, syms.booleanType);
  1130         attribStat(tree.body, env.dup(tree));
  1131         result = null;
  1134     public void visitForLoop(JCForLoop tree) {
  1135         Env<AttrContext> loopEnv =
  1136             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1137         try {
  1138             attribStats(tree.init, loopEnv);
  1139             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1140             loopEnv.tree = tree; // before, we were not in loop!
  1141             attribStats(tree.step, loopEnv);
  1142             attribStat(tree.body, loopEnv);
  1143             result = null;
  1145         finally {
  1146             loopEnv.info.scope.leave();
  1150     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1151         Env<AttrContext> loopEnv =
  1152             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1153         try {
  1154             //the Formal Parameter of a for-each loop is not in the scope when
  1155             //attributing the for-each expression; we mimick this by attributing
  1156             //the for-each expression first (against original scope).
  1157             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
  1158             attribStat(tree.var, loopEnv);
  1159             chk.checkNonVoid(tree.pos(), exprType);
  1160             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1161             if (elemtype == null) {
  1162                 // or perhaps expr implements Iterable<T>?
  1163                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1164                 if (base == null) {
  1165                     log.error(tree.expr.pos(),
  1166                             "foreach.not.applicable.to.type",
  1167                             exprType,
  1168                             diags.fragment("type.req.array.or.iterable"));
  1169                     elemtype = types.createErrorType(exprType);
  1170                 } else {
  1171                     List<Type> iterableParams = base.allparams();
  1172                     elemtype = iterableParams.isEmpty()
  1173                         ? syms.objectType
  1174                         : types.wildUpperBound(iterableParams.head);
  1177             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1178             loopEnv.tree = tree; // before, we were not in loop!
  1179             attribStat(tree.body, loopEnv);
  1180             result = null;
  1182         finally {
  1183             loopEnv.info.scope.leave();
  1187     public void visitLabelled(JCLabeledStatement tree) {
  1188         // Check that label is not used in an enclosing statement
  1189         Env<AttrContext> env1 = env;
  1190         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1191             if (env1.tree.hasTag(LABELLED) &&
  1192                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1193                 log.error(tree.pos(), "label.already.in.use",
  1194                           tree.label);
  1195                 break;
  1197             env1 = env1.next;
  1200         attribStat(tree.body, env.dup(tree));
  1201         result = null;
  1204     public void visitSwitch(JCSwitch tree) {
  1205         Type seltype = attribExpr(tree.selector, env);
  1207         Env<AttrContext> switchEnv =
  1208             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1210         try {
  1212             boolean enumSwitch =
  1213                 allowEnums &&
  1214                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1215             boolean stringSwitch = false;
  1216             if (types.isSameType(seltype, syms.stringType)) {
  1217                 if (allowStringsInSwitch) {
  1218                     stringSwitch = true;
  1219                 } else {
  1220                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1223             if (!enumSwitch && !stringSwitch)
  1224                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1226             // Attribute all cases and
  1227             // check that there are no duplicate case labels or default clauses.
  1228             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1229             boolean hasDefault = false;      // Is there a default label?
  1230             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1231                 JCCase c = l.head;
  1232                 Env<AttrContext> caseEnv =
  1233                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1234                 try {
  1235                     if (c.pat != null) {
  1236                         if (enumSwitch) {
  1237                             Symbol sym = enumConstant(c.pat, seltype);
  1238                             if (sym == null) {
  1239                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1240                             } else if (!labels.add(sym)) {
  1241                                 log.error(c.pos(), "duplicate.case.label");
  1243                         } else {
  1244                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1245                             if (!pattype.hasTag(ERROR)) {
  1246                                 if (pattype.constValue() == null) {
  1247                                     log.error(c.pat.pos(),
  1248                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1249                                 } else if (labels.contains(pattype.constValue())) {
  1250                                     log.error(c.pos(), "duplicate.case.label");
  1251                                 } else {
  1252                                     labels.add(pattype.constValue());
  1256                     } else if (hasDefault) {
  1257                         log.error(c.pos(), "duplicate.default.label");
  1258                     } else {
  1259                         hasDefault = true;
  1261                     attribStats(c.stats, caseEnv);
  1262                 } finally {
  1263                     caseEnv.info.scope.leave();
  1264                     addVars(c.stats, switchEnv.info.scope);
  1268             result = null;
  1270         finally {
  1271             switchEnv.info.scope.leave();
  1274     // where
  1275         /** Add any variables defined in stats to the switch scope. */
  1276         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1277             for (;stats.nonEmpty(); stats = stats.tail) {
  1278                 JCTree stat = stats.head;
  1279                 if (stat.hasTag(VARDEF))
  1280                     switchScope.enter(((JCVariableDecl) stat).sym);
  1283     // where
  1284     /** Return the selected enumeration constant symbol, or null. */
  1285     private Symbol enumConstant(JCTree tree, Type enumType) {
  1286         if (!tree.hasTag(IDENT)) {
  1287             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1288             return syms.errSymbol;
  1290         JCIdent ident = (JCIdent)tree;
  1291         Name name = ident.name;
  1292         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1293              e.scope != null; e = e.next()) {
  1294             if (e.sym.kind == VAR) {
  1295                 Symbol s = ident.sym = e.sym;
  1296                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1297                 ident.type = s.type;
  1298                 return ((s.flags_field & Flags.ENUM) == 0)
  1299                     ? null : s;
  1302         return null;
  1305     public void visitSynchronized(JCSynchronized tree) {
  1306         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1307         attribStat(tree.body, env);
  1308         result = null;
  1311     public void visitTry(JCTry tree) {
  1312         // Create a new local environment with a local
  1313         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1314         try {
  1315             boolean isTryWithResource = tree.resources.nonEmpty();
  1316             // Create a nested environment for attributing the try block if needed
  1317             Env<AttrContext> tryEnv = isTryWithResource ?
  1318                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1319                 localEnv;
  1320             try {
  1321                 // Attribute resource declarations
  1322                 for (JCTree resource : tree.resources) {
  1323                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1324                         @Override
  1325                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1326                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1328                     };
  1329                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1330                     if (resource.hasTag(VARDEF)) {
  1331                         attribStat(resource, tryEnv);
  1332                         twrResult.check(resource, resource.type);
  1334                         //check that resource type cannot throw InterruptedException
  1335                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1337                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1338                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1339                     } else {
  1340                         attribTree(resource, tryEnv, twrResult);
  1343                 // Attribute body
  1344                 attribStat(tree.body, tryEnv);
  1345             } finally {
  1346                 if (isTryWithResource)
  1347                     tryEnv.info.scope.leave();
  1350             // Attribute catch clauses
  1351             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1352                 JCCatch c = l.head;
  1353                 Env<AttrContext> catchEnv =
  1354                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1355                 try {
  1356                     Type ctype = attribStat(c.param, catchEnv);
  1357                     if (TreeInfo.isMultiCatch(c)) {
  1358                         //multi-catch parameter is implicitly marked as final
  1359                         c.param.sym.flags_field |= FINAL | UNION;
  1361                     if (c.param.sym.kind == Kinds.VAR) {
  1362                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1364                     chk.checkType(c.param.vartype.pos(),
  1365                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1366                                   syms.throwableType);
  1367                     attribStat(c.body, catchEnv);
  1368                 } finally {
  1369                     catchEnv.info.scope.leave();
  1373             // Attribute finalizer
  1374             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1375             result = null;
  1377         finally {
  1378             localEnv.info.scope.leave();
  1382     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1383         if (!resource.isErroneous() &&
  1384             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1385             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1386             Symbol close = syms.noSymbol;
  1387             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1388             try {
  1389                 close = rs.resolveQualifiedMethod(pos,
  1390                         env,
  1391                         resource,
  1392                         names.close,
  1393                         List.<Type>nil(),
  1394                         List.<Type>nil());
  1396             finally {
  1397                 log.popDiagnosticHandler(discardHandler);
  1399             if (close.kind == MTH &&
  1400                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1401                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1402                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1403                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1408     public void visitConditional(JCConditional tree) {
  1409         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1411         tree.polyKind = (!allowPoly ||
  1412                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1413                 isBooleanOrNumeric(env, tree)) ?
  1414                 PolyKind.STANDALONE : PolyKind.POLY;
  1416         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1417             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1418             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1419             result = tree.type = types.createErrorType(resultInfo.pt);
  1420             return;
  1423         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1424                 unknownExprInfo :
  1425                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1426                     //this will use enclosing check context to check compatibility of
  1427                     //subexpression against target type; if we are in a method check context,
  1428                     //depending on whether boxing is allowed, we could have incompatibilities
  1429                     @Override
  1430                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1431                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1433                 });
  1435         Type truetype = attribTree(tree.truepart, env, condInfo);
  1436         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1438         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1439         if (condtype.constValue() != null &&
  1440                 truetype.constValue() != null &&
  1441                 falsetype.constValue() != null &&
  1442                 !owntype.hasTag(NONE)) {
  1443             //constant folding
  1444             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1446         result = check(tree, owntype, VAL, resultInfo);
  1448     //where
  1449         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1450             switch (tree.getTag()) {
  1451                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1452                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1453                               ((JCLiteral)tree).typetag == BOT;
  1454                 case LAMBDA: case REFERENCE: return false;
  1455                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1456                 case CONDEXPR:
  1457                     JCConditional condTree = (JCConditional)tree;
  1458                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1459                             isBooleanOrNumeric(env, condTree.falsepart);
  1460                 case APPLY:
  1461                     JCMethodInvocation speculativeMethodTree =
  1462                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1463                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1464                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1465                 case NEWCLASS:
  1466                     JCExpression className =
  1467                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1468                     JCExpression speculativeNewClassTree =
  1469                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1470                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1471                 default:
  1472                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1473                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1474                     return speculativeType.isPrimitive();
  1477         //where
  1478             TreeTranslator removeClassParams = new TreeTranslator() {
  1479                 @Override
  1480                 public void visitTypeApply(JCTypeApply tree) {
  1481                     result = translate(tree.clazz);
  1483             };
  1485         /** Compute the type of a conditional expression, after
  1486          *  checking that it exists.  See JLS 15.25. Does not take into
  1487          *  account the special case where condition and both arms
  1488          *  are constants.
  1490          *  @param pos      The source position to be used for error
  1491          *                  diagnostics.
  1492          *  @param thentype The type of the expression's then-part.
  1493          *  @param elsetype The type of the expression's else-part.
  1494          */
  1495         private Type condType(DiagnosticPosition pos,
  1496                                Type thentype, Type elsetype) {
  1497             // If same type, that is the result
  1498             if (types.isSameType(thentype, elsetype))
  1499                 return thentype.baseType();
  1501             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1502                 ? thentype : types.unboxedType(thentype);
  1503             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1504                 ? elsetype : types.unboxedType(elsetype);
  1506             // Otherwise, if both arms can be converted to a numeric
  1507             // type, return the least numeric type that fits both arms
  1508             // (i.e. return larger of the two, or return int if one
  1509             // arm is short, the other is char).
  1510             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1511                 // If one arm has an integer subrange type (i.e., byte,
  1512                 // short, or char), and the other is an integer constant
  1513                 // that fits into the subrange, return the subrange type.
  1514                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1515                     elseUnboxed.hasTag(INT) &&
  1516                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1517                     return thenUnboxed.baseType();
  1519                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1520                     thenUnboxed.hasTag(INT) &&
  1521                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1522                     return elseUnboxed.baseType();
  1525                 for (TypeTag tag : primitiveTags) {
  1526                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1527                     if (types.isSubtype(thenUnboxed, candidate) &&
  1528                         types.isSubtype(elseUnboxed, candidate)) {
  1529                         return candidate;
  1534             // Those were all the cases that could result in a primitive
  1535             if (allowBoxing) {
  1536                 if (thentype.isPrimitive())
  1537                     thentype = types.boxedClass(thentype).type;
  1538                 if (elsetype.isPrimitive())
  1539                     elsetype = types.boxedClass(elsetype).type;
  1542             if (types.isSubtype(thentype, elsetype))
  1543                 return elsetype.baseType();
  1544             if (types.isSubtype(elsetype, thentype))
  1545                 return thentype.baseType();
  1547             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1548                 log.error(pos, "neither.conditional.subtype",
  1549                           thentype, elsetype);
  1550                 return thentype.baseType();
  1553             // both are known to be reference types.  The result is
  1554             // lub(thentype,elsetype). This cannot fail, as it will
  1555             // always be possible to infer "Object" if nothing better.
  1556             return types.lub(thentype.baseType(), elsetype.baseType());
  1559     final static TypeTag[] primitiveTags = new TypeTag[]{
  1560         BYTE,
  1561         CHAR,
  1562         SHORT,
  1563         INT,
  1564         LONG,
  1565         FLOAT,
  1566         DOUBLE,
  1567         BOOLEAN,
  1568     };
  1570     public void visitIf(JCIf tree) {
  1571         attribExpr(tree.cond, env, syms.booleanType);
  1572         attribStat(tree.thenpart, env);
  1573         if (tree.elsepart != null)
  1574             attribStat(tree.elsepart, env);
  1575         chk.checkEmptyIf(tree);
  1576         result = null;
  1579     public void visitExec(JCExpressionStatement tree) {
  1580         //a fresh environment is required for 292 inference to work properly ---
  1581         //see Infer.instantiatePolymorphicSignatureInstance()
  1582         Env<AttrContext> localEnv = env.dup(tree);
  1583         attribExpr(tree.expr, localEnv);
  1584         result = null;
  1587     public void visitBreak(JCBreak tree) {
  1588         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1589         result = null;
  1592     public void visitContinue(JCContinue tree) {
  1593         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1594         result = null;
  1596     //where
  1597         /** Return the target of a break or continue statement, if it exists,
  1598          *  report an error if not.
  1599          *  Note: The target of a labelled break or continue is the
  1600          *  (non-labelled) statement tree referred to by the label,
  1601          *  not the tree representing the labelled statement itself.
  1603          *  @param pos     The position to be used for error diagnostics
  1604          *  @param tag     The tag of the jump statement. This is either
  1605          *                 Tree.BREAK or Tree.CONTINUE.
  1606          *  @param label   The label of the jump statement, or null if no
  1607          *                 label is given.
  1608          *  @param env     The environment current at the jump statement.
  1609          */
  1610         private JCTree findJumpTarget(DiagnosticPosition pos,
  1611                                     JCTree.Tag tag,
  1612                                     Name label,
  1613                                     Env<AttrContext> env) {
  1614             // Search environments outwards from the point of jump.
  1615             Env<AttrContext> env1 = env;
  1616             LOOP:
  1617             while (env1 != null) {
  1618                 switch (env1.tree.getTag()) {
  1619                     case LABELLED:
  1620                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1621                         if (label == labelled.label) {
  1622                             // If jump is a continue, check that target is a loop.
  1623                             if (tag == CONTINUE) {
  1624                                 if (!labelled.body.hasTag(DOLOOP) &&
  1625                                         !labelled.body.hasTag(WHILELOOP) &&
  1626                                         !labelled.body.hasTag(FORLOOP) &&
  1627                                         !labelled.body.hasTag(FOREACHLOOP))
  1628                                     log.error(pos, "not.loop.label", label);
  1629                                 // Found labelled statement target, now go inwards
  1630                                 // to next non-labelled tree.
  1631                                 return TreeInfo.referencedStatement(labelled);
  1632                             } else {
  1633                                 return labelled;
  1636                         break;
  1637                     case DOLOOP:
  1638                     case WHILELOOP:
  1639                     case FORLOOP:
  1640                     case FOREACHLOOP:
  1641                         if (label == null) return env1.tree;
  1642                         break;
  1643                     case SWITCH:
  1644                         if (label == null && tag == BREAK) return env1.tree;
  1645                         break;
  1646                     case LAMBDA:
  1647                     case METHODDEF:
  1648                     case CLASSDEF:
  1649                         break LOOP;
  1650                     default:
  1652                 env1 = env1.next;
  1654             if (label != null)
  1655                 log.error(pos, "undef.label", label);
  1656             else if (tag == CONTINUE)
  1657                 log.error(pos, "cont.outside.loop");
  1658             else
  1659                 log.error(pos, "break.outside.switch.loop");
  1660             return null;
  1663     public void visitReturn(JCReturn tree) {
  1664         // Check that there is an enclosing method which is
  1665         // nested within than the enclosing class.
  1666         if (env.info.returnResult == null) {
  1667             log.error(tree.pos(), "ret.outside.meth");
  1668         } else {
  1669             // Attribute return expression, if it exists, and check that
  1670             // it conforms to result type of enclosing method.
  1671             if (tree.expr != null) {
  1672                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1673                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1674                               diags.fragment("unexpected.ret.val"));
  1676                 attribTree(tree.expr, env, env.info.returnResult);
  1677             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1678                     !env.info.returnResult.pt.hasTag(NONE)) {
  1679                 env.info.returnResult.checkContext.report(tree.pos(),
  1680                               diags.fragment("missing.ret.val"));
  1683         result = null;
  1686     public void visitThrow(JCThrow tree) {
  1687         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1688         if (allowPoly) {
  1689             chk.checkType(tree, owntype, syms.throwableType);
  1691         result = null;
  1694     public void visitAssert(JCAssert tree) {
  1695         attribExpr(tree.cond, env, syms.booleanType);
  1696         if (tree.detail != null) {
  1697             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1699         result = null;
  1702      /** Visitor method for method invocations.
  1703      *  NOTE: The method part of an application will have in its type field
  1704      *        the return type of the method, not the method's type itself!
  1705      */
  1706     public void visitApply(JCMethodInvocation tree) {
  1707         // The local environment of a method application is
  1708         // a new environment nested in the current one.
  1709         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1711         // The types of the actual method arguments.
  1712         List<Type> argtypes;
  1714         // The types of the actual method type arguments.
  1715         List<Type> typeargtypes = null;
  1717         Name methName = TreeInfo.name(tree.meth);
  1719         boolean isConstructorCall =
  1720             methName == names._this || methName == names._super;
  1722         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1723         if (isConstructorCall) {
  1724             // We are seeing a ...this(...) or ...super(...) call.
  1725             // Check that this is the first statement in a constructor.
  1726             if (checkFirstConstructorStat(tree, env)) {
  1728                 // Record the fact
  1729                 // that this is a constructor call (using isSelfCall).
  1730                 localEnv.info.isSelfCall = true;
  1732                 // Attribute arguments, yielding list of argument types.
  1733                 attribArgs(tree.args, localEnv, argtypesBuf);
  1734                 argtypes = argtypesBuf.toList();
  1735                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1737                 // Variable `site' points to the class in which the called
  1738                 // constructor is defined.
  1739                 Type site = env.enclClass.sym.type;
  1740                 if (methName == names._super) {
  1741                     if (site == syms.objectType) {
  1742                         log.error(tree.meth.pos(), "no.superclass", site);
  1743                         site = types.createErrorType(syms.objectType);
  1744                     } else {
  1745                         site = types.supertype(site);
  1749                 if (site.hasTag(CLASS)) {
  1750                     Type encl = site.getEnclosingType();
  1751                     while (encl != null && encl.hasTag(TYPEVAR))
  1752                         encl = encl.getUpperBound();
  1753                     if (encl.hasTag(CLASS)) {
  1754                         // we are calling a nested class
  1756                         if (tree.meth.hasTag(SELECT)) {
  1757                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1759                             // We are seeing a prefixed call, of the form
  1760                             //     <expr>.super(...).
  1761                             // Check that the prefix expression conforms
  1762                             // to the outer instance type of the class.
  1763                             chk.checkRefType(qualifier.pos(),
  1764                                              attribExpr(qualifier, localEnv,
  1765                                                         encl));
  1766                         } else if (methName == names._super) {
  1767                             // qualifier omitted; check for existence
  1768                             // of an appropriate implicit qualifier.
  1769                             rs.resolveImplicitThis(tree.meth.pos(),
  1770                                                    localEnv, site, true);
  1772                     } else if (tree.meth.hasTag(SELECT)) {
  1773                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1774                                   site.tsym);
  1777                     // if we're calling a java.lang.Enum constructor,
  1778                     // prefix the implicit String and int parameters
  1779                     if (site.tsym == syms.enumSym && allowEnums)
  1780                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1782                     // Resolve the called constructor under the assumption
  1783                     // that we are referring to a superclass instance of the
  1784                     // current instance (JLS ???).
  1785                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1786                     localEnv.info.selectSuper = true;
  1787                     localEnv.info.pendingResolutionPhase = null;
  1788                     Symbol sym = rs.resolveConstructor(
  1789                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1790                     localEnv.info.selectSuper = selectSuperPrev;
  1792                     // Set method symbol to resolved constructor...
  1793                     TreeInfo.setSymbol(tree.meth, sym);
  1795                     // ...and check that it is legal in the current context.
  1796                     // (this will also set the tree's type)
  1797                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1798                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1800                 // Otherwise, `site' is an error type and we do nothing
  1802             result = tree.type = syms.voidType;
  1803         } else {
  1804             // Otherwise, we are seeing a regular method call.
  1805             // Attribute the arguments, yielding list of argument types, ...
  1806             int kind = attribArgs(tree.args, localEnv, argtypesBuf);
  1807             argtypes = argtypesBuf.toList();
  1808             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1810             // ... and attribute the method using as a prototype a methodtype
  1811             // whose formal argument types is exactly the list of actual
  1812             // arguments (this will also set the method symbol).
  1813             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1814             localEnv.info.pendingResolutionPhase = null;
  1815             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1817             // Compute the result type.
  1818             Type restype = mtype.getReturnType();
  1819             if (restype.hasTag(WILDCARD))
  1820                 throw new AssertionError(mtype);
  1822             Type qualifier = (tree.meth.hasTag(SELECT))
  1823                     ? ((JCFieldAccess) tree.meth).selected.type
  1824                     : env.enclClass.sym.type;
  1825             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1827             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1829             // Check that value of resulting type is admissible in the
  1830             // current context.  Also, capture the return type
  1831             result = check(tree, capture(restype), VAL, resultInfo);
  1833         chk.validate(tree.typeargs, localEnv);
  1835     //where
  1836         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1837             if (allowCovariantReturns &&
  1838                     methodName == names.clone &&
  1839                 types.isArray(qualifierType)) {
  1840                 // as a special case, array.clone() has a result that is
  1841                 // the same as static type of the array being cloned
  1842                 return qualifierType;
  1843             } else if (allowGenerics &&
  1844                     methodName == names.getClass &&
  1845                     argtypes.isEmpty()) {
  1846                 // as a special case, x.getClass() has type Class<? extends |X|>
  1847                 return new ClassType(restype.getEnclosingType(),
  1848                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1849                                                                BoundKind.EXTENDS,
  1850                                                                syms.boundClass)),
  1851                               restype.tsym);
  1852             } else {
  1853                 return restype;
  1857         /** Check that given application node appears as first statement
  1858          *  in a constructor call.
  1859          *  @param tree   The application node
  1860          *  @param env    The environment current at the application.
  1861          */
  1862         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1863             JCMethodDecl enclMethod = env.enclMethod;
  1864             if (enclMethod != null && enclMethod.name == names.init) {
  1865                 JCBlock body = enclMethod.body;
  1866                 if (body.stats.head.hasTag(EXEC) &&
  1867                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1868                     return true;
  1870             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1871                       TreeInfo.name(tree.meth));
  1872             return false;
  1875         /** Obtain a method type with given argument types.
  1876          */
  1877         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1878             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1879             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1882     public void visitNewClass(final JCNewClass tree) {
  1883         Type owntype = types.createErrorType(tree.type);
  1885         // The local environment of a class creation is
  1886         // a new environment nested in the current one.
  1887         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1889         // The anonymous inner class definition of the new expression,
  1890         // if one is defined by it.
  1891         JCClassDecl cdef = tree.def;
  1893         // If enclosing class is given, attribute it, and
  1894         // complete class name to be fully qualified
  1895         JCExpression clazz = tree.clazz; // Class field following new
  1896         JCExpression clazzid;            // Identifier in class field
  1897         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1898         annoclazzid = null;
  1900         if (clazz.hasTag(TYPEAPPLY)) {
  1901             clazzid = ((JCTypeApply) clazz).clazz;
  1902             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1903                 annoclazzid = (JCAnnotatedType) clazzid;
  1904                 clazzid = annoclazzid.underlyingType;
  1906         } else {
  1907             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1908                 annoclazzid = (JCAnnotatedType) clazz;
  1909                 clazzid = annoclazzid.underlyingType;
  1910             } else {
  1911                 clazzid = clazz;
  1915         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1917         if (tree.encl != null) {
  1918             // We are seeing a qualified new, of the form
  1919             //    <expr>.new C <...> (...) ...
  1920             // In this case, we let clazz stand for the name of the
  1921             // allocated class C prefixed with the type of the qualifier
  1922             // expression, so that we can
  1923             // resolve it with standard techniques later. I.e., if
  1924             // <expr> has type T, then <expr>.new C <...> (...)
  1925             // yields a clazz T.C.
  1926             Type encltype = chk.checkRefType(tree.encl.pos(),
  1927                                              attribExpr(tree.encl, env));
  1928             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1929             // from expr to the combined type, or not? Yes, do this.
  1930             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1931                                                  ((JCIdent) clazzid).name);
  1933             EndPosTable endPosTable = this.env.toplevel.endPositions;
  1934             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  1935             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1936                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1937                 List<JCAnnotation> annos = annoType.annotations;
  1939                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1940                     clazzid1 = make.at(tree.pos).
  1941                         TypeApply(clazzid1,
  1942                                   ((JCTypeApply) clazz).arguments);
  1945                 clazzid1 = make.at(tree.pos).
  1946                     AnnotatedType(annos, clazzid1);
  1947             } else if (clazz.hasTag(TYPEAPPLY)) {
  1948                 clazzid1 = make.at(tree.pos).
  1949                     TypeApply(clazzid1,
  1950                               ((JCTypeApply) clazz).arguments);
  1953             clazz = clazzid1;
  1956         // Attribute clazz expression and store
  1957         // symbol + type back into the attributed tree.
  1958         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1959             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1960             attribType(clazz, env);
  1962         clazztype = chk.checkDiamond(tree, clazztype);
  1963         chk.validate(clazz, localEnv);
  1964         if (tree.encl != null) {
  1965             // We have to work in this case to store
  1966             // symbol + type back into the attributed tree.
  1967             tree.clazz.type = clazztype;
  1968             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1969             clazzid.type = ((JCIdent) clazzid).sym.type;
  1970             if (annoclazzid != null) {
  1971                 annoclazzid.type = clazzid.type;
  1973             if (!clazztype.isErroneous()) {
  1974                 if (cdef != null && clazztype.tsym.isInterface()) {
  1975                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1976                 } else if (clazztype.tsym.isStatic()) {
  1977                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1980         } else if (!clazztype.tsym.isInterface() &&
  1981                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1982             // Check for the existence of an apropos outer instance
  1983             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1986         // Attribute constructor arguments.
  1987         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1988         int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
  1989         List<Type> argtypes = argtypesBuf.toList();
  1990         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  1992         // If we have made no mistakes in the class type...
  1993         if (clazztype.hasTag(CLASS)) {
  1994             // Enums may not be instantiated except implicitly
  1995             if (allowEnums &&
  1996                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
  1997                 (!env.tree.hasTag(VARDEF) ||
  1998                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
  1999                  ((JCVariableDecl) env.tree).init != tree))
  2000                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2001             // Check that class is not abstract
  2002             if (cdef == null &&
  2003                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2004                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2005                           clazztype.tsym);
  2006             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2007                 // Check that no constructor arguments are given to
  2008                 // anonymous classes implementing an interface
  2009                 if (!argtypes.isEmpty())
  2010                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2012                 if (!typeargtypes.isEmpty())
  2013                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2015                 // Error recovery: pretend no arguments were supplied.
  2016                 argtypes = List.nil();
  2017                 typeargtypes = List.nil();
  2018             } else if (TreeInfo.isDiamond(tree)) {
  2019                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2020                             clazztype.tsym.type.getTypeArguments(),
  2021                             clazztype.tsym);
  2023                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2024                 diamondEnv.info.selectSuper = cdef != null;
  2025                 diamondEnv.info.pendingResolutionPhase = null;
  2027                 //if the type of the instance creation expression is a class type
  2028                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2029                 //of the resolved constructor will be a partially instantiated type
  2030                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2031                             diamondEnv,
  2032                             site,
  2033                             argtypes,
  2034                             typeargtypes);
  2035                 tree.constructor = constructor.baseSymbol();
  2037                 final TypeSymbol csym = clazztype.tsym;
  2038                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2039                     @Override
  2040                     public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2041                         enclosingContext.report(tree.clazz,
  2042                                 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
  2044                 });
  2045                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2046                 constructorType = checkId(tree, site,
  2047                         constructor,
  2048                         diamondEnv,
  2049                         diamondResult);
  2051                 tree.clazz.type = types.createErrorType(clazztype);
  2052                 if (!constructorType.isErroneous()) {
  2053                     tree.clazz.type = clazztype = constructorType.getReturnType();
  2054                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2056                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2059             // Resolve the called constructor under the assumption
  2060             // that we are referring to a superclass instance of the
  2061             // current instance (JLS ???).
  2062             else {
  2063                 //the following code alters some of the fields in the current
  2064                 //AttrContext - hence, the current context must be dup'ed in
  2065                 //order to avoid downstream failures
  2066                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2067                 rsEnv.info.selectSuper = cdef != null;
  2068                 rsEnv.info.pendingResolutionPhase = null;
  2069                 tree.constructor = rs.resolveConstructor(
  2070                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2071                 if (cdef == null) { //do not check twice!
  2072                     tree.constructorType = checkId(tree,
  2073                             clazztype,
  2074                             tree.constructor,
  2075                             rsEnv,
  2076                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2077                     if (rsEnv.info.lastResolveVarargs())
  2078                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2080                 if (cdef == null &&
  2081                         !clazztype.isErroneous() &&
  2082                         clazztype.getTypeArguments().nonEmpty() &&
  2083                         findDiamonds) {
  2084                     findDiamond(localEnv, tree, clazztype);
  2088             if (cdef != null) {
  2089                 // We are seeing an anonymous class instance creation.
  2090                 // In this case, the class instance creation
  2091                 // expression
  2092                 //
  2093                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2094                 //
  2095                 // is represented internally as
  2096                 //
  2097                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2098                 //
  2099                 // This expression is then *transformed* as follows:
  2100                 //
  2101                 // (1) add a STATIC flag to the class definition
  2102                 //     if the current environment is static
  2103                 // (2) add an extends or implements clause
  2104                 // (3) add a constructor.
  2105                 //
  2106                 // For instance, if C is a class, and ET is the type of E,
  2107                 // the expression
  2108                 //
  2109                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2110                 //
  2111                 // is translated to (where X is a fresh name and typarams is the
  2112                 // parameter list of the super constructor):
  2113                 //
  2114                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2115                 //     X extends C<typargs2> {
  2116                 //       <typarams> X(ET e, args) {
  2117                 //         e.<typeargs1>super(args)
  2118                 //       }
  2119                 //       ...
  2120                 //     }
  2121                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2123                 if (clazztype.tsym.isInterface()) {
  2124                     cdef.implementing = List.of(clazz);
  2125                 } else {
  2126                     cdef.extending = clazz;
  2129                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2130                     isSerializable(clazztype)) {
  2131                     localEnv.info.isSerializable = true;
  2134                 attribStat(cdef, localEnv);
  2136                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2138                 // If an outer instance is given,
  2139                 // prefix it to the constructor arguments
  2140                 // and delete it from the new expression
  2141                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2142                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2143                     argtypes = argtypes.prepend(tree.encl.type);
  2144                     tree.encl = null;
  2147                 // Reassign clazztype and recompute constructor.
  2148                 clazztype = cdef.sym.type;
  2149                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2150                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2151                 Assert.check(sym.kind < AMBIGUOUS);
  2152                 tree.constructor = sym;
  2153                 tree.constructorType = checkId(tree,
  2154                     clazztype,
  2155                     tree.constructor,
  2156                     localEnv,
  2157                     new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2160             if (tree.constructor != null && tree.constructor.kind == MTH)
  2161                 owntype = clazztype;
  2163         result = check(tree, owntype, VAL, resultInfo);
  2164         chk.validate(tree.typeargs, localEnv);
  2166     //where
  2167         void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2168             JCTypeApply ta = (JCTypeApply)tree.clazz;
  2169             List<JCExpression> prevTypeargs = ta.arguments;
  2170             try {
  2171                 //create a 'fake' diamond AST node by removing type-argument trees
  2172                 ta.arguments = List.nil();
  2173                 ResultInfo findDiamondResult = new ResultInfo(VAL,
  2174                         resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2175                 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2176                 Type polyPt = allowPoly ?
  2177                         syms.objectType :
  2178                         clazztype;
  2179                 if (!inferred.isErroneous() &&
  2180                     (allowPoly && pt() == Infer.anyPoly ?
  2181                         types.isSameType(inferred, clazztype) :
  2182                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
  2183                     String key = types.isSameType(clazztype, inferred) ?
  2184                         "diamond.redundant.args" :
  2185                         "diamond.redundant.args.1";
  2186                     log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2188             } finally {
  2189                 ta.arguments = prevTypeargs;
  2193             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2194                 if (allowLambda &&
  2195                         identifyLambdaCandidate &&
  2196                         clazztype.hasTag(CLASS) &&
  2197                         !pt().hasTag(NONE) &&
  2198                         types.isFunctionalInterface(clazztype.tsym)) {
  2199                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2200                     int count = 0;
  2201                     boolean found = false;
  2202                     for (Symbol sym : csym.members().getElements()) {
  2203                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2204                                 sym.isConstructor()) continue;
  2205                         count++;
  2206                         if (sym.kind != MTH ||
  2207                                 !sym.name.equals(descriptor.name)) continue;
  2208                         Type mtype = types.memberType(clazztype, sym);
  2209                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2210                             found = true;
  2213                     if (found && count == 1) {
  2214                         log.note(tree.def, "potential.lambda.found");
  2219     /** Make an attributed null check tree.
  2220      */
  2221     public JCExpression makeNullCheck(JCExpression arg) {
  2222         // optimization: X.this is never null; skip null check
  2223         Name name = TreeInfo.name(arg);
  2224         if (name == names._this || name == names._super) return arg;
  2226         JCTree.Tag optag = NULLCHK;
  2227         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2228         tree.operator = syms.nullcheck;
  2229         tree.type = arg.type;
  2230         return tree;
  2233     public void visitNewArray(JCNewArray tree) {
  2234         Type owntype = types.createErrorType(tree.type);
  2235         Env<AttrContext> localEnv = env.dup(tree);
  2236         Type elemtype;
  2237         if (tree.elemtype != null) {
  2238             elemtype = attribType(tree.elemtype, localEnv);
  2239             chk.validate(tree.elemtype, localEnv);
  2240             owntype = elemtype;
  2241             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2242                 attribExpr(l.head, localEnv, syms.intType);
  2243                 owntype = new ArrayType(owntype, syms.arrayClass);
  2245         } else {
  2246             // we are seeing an untyped aggregate { ... }
  2247             // this is allowed only if the prototype is an array
  2248             if (pt().hasTag(ARRAY)) {
  2249                 elemtype = types.elemtype(pt());
  2250             } else {
  2251                 if (!pt().hasTag(ERROR)) {
  2252                     log.error(tree.pos(), "illegal.initializer.for.type",
  2253                               pt());
  2255                 elemtype = types.createErrorType(pt());
  2258         if (tree.elems != null) {
  2259             attribExprs(tree.elems, localEnv, elemtype);
  2260             owntype = new ArrayType(elemtype, syms.arrayClass);
  2262         if (!types.isReifiable(elemtype))
  2263             log.error(tree.pos(), "generic.array.creation");
  2264         result = check(tree, owntype, VAL, resultInfo);
  2267     /*
  2268      * A lambda expression can only be attributed when a target-type is available.
  2269      * In addition, if the target-type is that of a functional interface whose
  2270      * descriptor contains inference variables in argument position the lambda expression
  2271      * is 'stuck' (see DeferredAttr).
  2272      */
  2273     @Override
  2274     public void visitLambda(final JCLambda that) {
  2275         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2276             if (pt().hasTag(NONE)) {
  2277                 //lambda only allowed in assignment or method invocation/cast context
  2278                 log.error(that.pos(), "unexpected.lambda");
  2280             result = that.type = types.createErrorType(pt());
  2281             return;
  2283         //create an environment for attribution of the lambda expression
  2284         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2285         boolean needsRecovery =
  2286                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2287         try {
  2288             Type currentTarget = pt();
  2289             if (needsRecovery && isSerializable(currentTarget)) {
  2290                 localEnv.info.isSerializable = true;
  2292             List<Type> explicitParamTypes = null;
  2293             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2294                 //attribute lambda parameters
  2295                 attribStats(that.params, localEnv);
  2296                 explicitParamTypes = TreeInfo.types(that.params);
  2299             Type lambdaType;
  2300             if (pt() != Type.recoveryType) {
  2301                 /* We need to adjust the target. If the target is an
  2302                  * intersection type, for example: SAM & I1 & I2 ...
  2303                  * the target will be updated to SAM
  2304                  */
  2305                 currentTarget = targetChecker.visit(currentTarget, that);
  2306                 if (explicitParamTypes != null) {
  2307                     currentTarget = infer.instantiateFunctionalInterface(that,
  2308                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2310                 currentTarget = types.removeWildcards(currentTarget);
  2311                 lambdaType = types.findDescriptorType(currentTarget);
  2312             } else {
  2313                 currentTarget = Type.recoveryType;
  2314                 lambdaType = fallbackDescriptorType(that);
  2317             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2319             if (lambdaType.hasTag(FORALL)) {
  2320                 //lambda expression target desc cannot be a generic method
  2321                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2322                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2323                 result = that.type = types.createErrorType(pt());
  2324                 return;
  2327             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2328                 //add param type info in the AST
  2329                 List<Type> actuals = lambdaType.getParameterTypes();
  2330                 List<JCVariableDecl> params = that.params;
  2332                 boolean arityMismatch = false;
  2334                 while (params.nonEmpty()) {
  2335                     if (actuals.isEmpty()) {
  2336                         //not enough actuals to perform lambda parameter inference
  2337                         arityMismatch = true;
  2339                     //reset previously set info
  2340                     Type argType = arityMismatch ?
  2341                             syms.errType :
  2342                             actuals.head;
  2343                     params.head.vartype = make.at(params.head).Type(argType);
  2344                     params.head.sym = null;
  2345                     actuals = actuals.isEmpty() ?
  2346                             actuals :
  2347                             actuals.tail;
  2348                     params = params.tail;
  2351                 //attribute lambda parameters
  2352                 attribStats(that.params, localEnv);
  2354                 if (arityMismatch) {
  2355                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2356                         result = that.type = types.createErrorType(currentTarget);
  2357                         return;
  2361             //from this point on, no recovery is needed; if we are in assignment context
  2362             //we will be able to attribute the whole lambda body, regardless of errors;
  2363             //if we are in a 'check' method context, and the lambda is not compatible
  2364             //with the target-type, it will be recovered anyway in Attr.checkId
  2365             needsRecovery = false;
  2367             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2368                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2369                     new FunctionalReturnContext(resultInfo.checkContext);
  2371             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2372                 recoveryInfo :
  2373                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2374             localEnv.info.returnResult = bodyResultInfo;
  2376             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2377                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2378             } else {
  2379                 JCBlock body = (JCBlock)that.body;
  2380                 attribStats(body.stats, localEnv);
  2383             result = check(that, currentTarget, VAL, resultInfo);
  2385             boolean isSpeculativeRound =
  2386                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2388             preFlow(that);
  2389             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2391             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2393             if (!isSpeculativeRound) {
  2394                 //add thrown types as bounds to the thrown types free variables if needed:
  2395                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2396                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2397                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
  2399                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2402                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2404             result = check(that, currentTarget, VAL, resultInfo);
  2405         } catch (Types.FunctionDescriptorLookupError ex) {
  2406             JCDiagnostic cause = ex.getDiagnostic();
  2407             resultInfo.checkContext.report(that, cause);
  2408             result = that.type = types.createErrorType(pt());
  2409             return;
  2410         } finally {
  2411             localEnv.info.scope.leave();
  2412             if (needsRecovery) {
  2413                 attribTree(that, env, recoveryInfo);
  2417     //where
  2418         void preFlow(JCLambda tree) {
  2419             new PostAttrAnalyzer() {
  2420                 @Override
  2421                 public void scan(JCTree tree) {
  2422                     if (tree == null ||
  2423                             (tree.type != null &&
  2424                             tree.type == Type.stuckType)) {
  2425                         //don't touch stuck expressions!
  2426                         return;
  2428                     super.scan(tree);
  2430             }.scan(tree);
  2433         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2435             @Override
  2436             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2437                 return t.isCompound() ?
  2438                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2441             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2442                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2443                 Type target = null;
  2444                 for (Type bound : ict.getExplicitComponents()) {
  2445                     TypeSymbol boundSym = bound.tsym;
  2446                     if (types.isFunctionalInterface(boundSym) &&
  2447                             types.findDescriptorSymbol(boundSym) == desc) {
  2448                         target = bound;
  2449                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2450                         //bound must be an interface
  2451                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2454                 return target != null ?
  2455                         target :
  2456                         ict.getExplicitComponents().head; //error recovery
  2459             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2460                 ListBuffer<Type> targs = new ListBuffer<>();
  2461                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2462                 for (Type i : ict.interfaces_field) {
  2463                     if (i.isParameterized()) {
  2464                         targs.appendList(i.tsym.type.allparams());
  2466                     supertypes.append(i.tsym.type);
  2468                 IntersectionClassType notionalIntf =
  2469                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2470                 notionalIntf.allparams_field = targs.toList();
  2471                 notionalIntf.tsym.flags_field |= INTERFACE;
  2472                 return notionalIntf.tsym;
  2475             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2476                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2477                         diags.fragment(key, args)));
  2479         };
  2481         private Type fallbackDescriptorType(JCExpression tree) {
  2482             switch (tree.getTag()) {
  2483                 case LAMBDA:
  2484                     JCLambda lambda = (JCLambda)tree;
  2485                     List<Type> argtypes = List.nil();
  2486                     for (JCVariableDecl param : lambda.params) {
  2487                         argtypes = param.vartype != null ?
  2488                                 argtypes.append(param.vartype.type) :
  2489                                 argtypes.append(syms.errType);
  2491                     return new MethodType(argtypes, Type.recoveryType,
  2492                             List.of(syms.throwableType), syms.methodClass);
  2493                 case REFERENCE:
  2494                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2495                             List.of(syms.throwableType), syms.methodClass);
  2496                 default:
  2497                     Assert.error("Cannot get here!");
  2499             return null;
  2502         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2503                 final InferenceContext inferenceContext, final Type... ts) {
  2504             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2507         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2508                 final InferenceContext inferenceContext, final List<Type> ts) {
  2509             if (inferenceContext.free(ts)) {
  2510                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2511                     @Override
  2512                     public void typesInferred(InferenceContext inferenceContext) {
  2513                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2515                 });
  2516             } else {
  2517                 for (Type t : ts) {
  2518                     rs.checkAccessibleType(env, t);
  2523         /**
  2524          * Lambda/method reference have a special check context that ensures
  2525          * that i.e. a lambda return type is compatible with the expected
  2526          * type according to both the inherited context and the assignment
  2527          * context.
  2528          */
  2529         class FunctionalReturnContext extends Check.NestedCheckContext {
  2531             FunctionalReturnContext(CheckContext enclosingContext) {
  2532                 super(enclosingContext);
  2535             @Override
  2536             public boolean compatible(Type found, Type req, Warner warn) {
  2537                 //return type must be compatible in both current context and assignment context
  2538                 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
  2541             @Override
  2542             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2543                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2547         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2549             JCExpression expr;
  2551             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2552                 super(enclosingContext);
  2553                 this.expr = expr;
  2556             @Override
  2557             public boolean compatible(Type found, Type req, Warner warn) {
  2558                 //a void return is compatible with an expression statement lambda
  2559                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2560                         super.compatible(found, req, warn);
  2564         /**
  2565         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2566         * are compatible with the expected functional interface descriptor. This means that:
  2567         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2568         * types must be compatible with the return type of the expected descriptor.
  2569         */
  2570         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2571             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2573             //return values have already been checked - but if lambda has no return
  2574             //values, we must ensure that void/value compatibility is correct;
  2575             //this amounts at checking that, if a lambda body can complete normally,
  2576             //the descriptor's return type must be void
  2577             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2578                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2579                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2580                         diags.fragment("missing.ret.val", returnType)));
  2583             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
  2584             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2585                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2589         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
  2590          * static field and that lambda has type annotations, these annotations will
  2591          * also be stored at these fake clinit methods.
  2593          * LambdaToMethod also use fake clinit methods so they can be reused.
  2594          * Also as LTM is a phase subsequent to attribution, the methods from
  2595          * clinits can be safely removed by LTM to save memory.
  2596          */
  2597         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
  2599         public MethodSymbol removeClinit(ClassSymbol sym) {
  2600             return clinits.remove(sym);
  2603         /* This method returns an environment to be used to attribute a lambda
  2604          * expression.
  2606          * The owner of this environment is a method symbol. If the current owner
  2607          * is not a method, for example if the lambda is used to initialize
  2608          * a field, then if the field is:
  2610          * - an instance field, we use the first constructor.
  2611          * - a static field, we create a fake clinit method.
  2612          */
  2613         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2614             Env<AttrContext> lambdaEnv;
  2615             Symbol owner = env.info.scope.owner;
  2616             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2617                 //field initializer
  2618                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2619                 ClassSymbol enclClass = owner.enclClass();
  2620                 /* if the field isn't static, then we can get the first constructor
  2621                  * and use it as the owner of the environment. This is what
  2622                  * LTM code is doing to look for type annotations so we are fine.
  2623                  */
  2624                 if ((owner.flags() & STATIC) == 0) {
  2625                     for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
  2626                         lambdaEnv.info.scope.owner = s;
  2627                         break;
  2629                 } else {
  2630                     /* if the field is static then we need to create a fake clinit
  2631                      * method, this method can later be reused by LTM.
  2632                      */
  2633                     MethodSymbol clinit = clinits.get(enclClass);
  2634                     if (clinit == null) {
  2635                         Type clinitType = new MethodType(List.<Type>nil(),
  2636                                 syms.voidType, List.<Type>nil(), syms.methodClass);
  2637                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
  2638                                 names.clinit, clinitType, enclClass);
  2639                         clinit.params = List.<VarSymbol>nil();
  2640                         clinits.put(enclClass, clinit);
  2642                     lambdaEnv.info.scope.owner = clinit;
  2644             } else {
  2645                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2647             return lambdaEnv;
  2650     @Override
  2651     public void visitReference(final JCMemberReference that) {
  2652         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2653             if (pt().hasTag(NONE)) {
  2654                 //method reference only allowed in assignment or method invocation/cast context
  2655                 log.error(that.pos(), "unexpected.mref");
  2657             result = that.type = types.createErrorType(pt());
  2658             return;
  2660         final Env<AttrContext> localEnv = env.dup(that);
  2661         try {
  2662             //attribute member reference qualifier - if this is a constructor
  2663             //reference, the expected kind must be a type
  2664             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2666             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2667                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2668                 if (!exprType.isErroneous() &&
  2669                     exprType.isRaw() &&
  2670                     that.typeargs != null) {
  2671                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2672                         diags.fragment("mref.infer.and.explicit.params"));
  2673                     exprType = types.createErrorType(exprType);
  2677             if (exprType.isErroneous()) {
  2678                 //if the qualifier expression contains problems,
  2679                 //give up attribution of method reference
  2680                 result = that.type = exprType;
  2681                 return;
  2684             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2685                 //if the qualifier is a type, validate it; raw warning check is
  2686                 //omitted as we don't know at this stage as to whether this is a
  2687                 //raw selector (because of inference)
  2688                 chk.validate(that.expr, env, false);
  2691             //attrib type-arguments
  2692             List<Type> typeargtypes = List.nil();
  2693             if (that.typeargs != null) {
  2694                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2697             Type desc;
  2698             Type currentTarget = pt();
  2699             boolean isTargetSerializable =
  2700                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2701                     isSerializable(currentTarget);
  2702             if (currentTarget != Type.recoveryType) {
  2703                 currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that));
  2704                 desc = types.findDescriptorType(currentTarget);
  2705             } else {
  2706                 currentTarget = Type.recoveryType;
  2707                 desc = fallbackDescriptorType(that);
  2710             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
  2711             List<Type> argtypes = desc.getParameterTypes();
  2712             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  2714             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  2715                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  2718             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  2719             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  2720             try {
  2721                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
  2722                         that.name, argtypes, typeargtypes, referenceCheck,
  2723                         resultInfo.checkContext.inferenceContext(),
  2724                         resultInfo.checkContext.deferredAttrContext().mode);
  2725             } finally {
  2726                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  2729             Symbol refSym = refResult.fst;
  2730             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2732             if (refSym.kind != MTH) {
  2733                 boolean targetError;
  2734                 switch (refSym.kind) {
  2735                     case ABSENT_MTH:
  2736                         targetError = false;
  2737                         break;
  2738                     case WRONG_MTH:
  2739                     case WRONG_MTHS:
  2740                     case AMBIGUOUS:
  2741                     case HIDDEN:
  2742                     case STATICERR:
  2743                     case MISSING_ENCL:
  2744                     case WRONG_STATICNESS:
  2745                         targetError = true;
  2746                         break;
  2747                     default:
  2748                         Assert.error("unexpected result kind " + refSym.kind);
  2749                         targetError = false;
  2752                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2753                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2755                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2756                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2758                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2759                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2761                 if (targetError && currentTarget == Type.recoveryType) {
  2762                     //a target error doesn't make sense during recovery stage
  2763                     //as we don't know what actual parameter types are
  2764                     result = that.type = currentTarget;
  2765                     return;
  2766                 } else {
  2767                     if (targetError) {
  2768                         resultInfo.checkContext.report(that, diag);
  2769                     } else {
  2770                         log.report(diag);
  2772                     result = that.type = types.createErrorType(currentTarget);
  2773                     return;
  2777             that.sym = refSym.baseSymbol();
  2778             that.kind = lookupHelper.referenceKind(that.sym);
  2779             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2781             if (desc.getReturnType() == Type.recoveryType) {
  2782                 // stop here
  2783                 result = that.type = currentTarget;
  2784                 return;
  2787             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2789                 if (that.getMode() == ReferenceMode.INVOKE &&
  2790                         TreeInfo.isStaticSelector(that.expr, names) &&
  2791                         that.kind.isUnbound() &&
  2792                         !desc.getParameterTypes().head.isParameterized()) {
  2793                     chk.checkRaw(that.expr, localEnv);
  2796                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2797                         exprType.getTypeArguments().nonEmpty()) {
  2798                     //static ref with class type-args
  2799                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2800                             diags.fragment("static.mref.with.targs"));
  2801                     result = that.type = types.createErrorType(currentTarget);
  2802                     return;
  2805                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2806                         !that.kind.isUnbound()) {
  2807                     //no static bound mrefs
  2808                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2809                             diags.fragment("static.bound.mref"));
  2810                     result = that.type = types.createErrorType(currentTarget);
  2811                     return;
  2814                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2815                     // Check that super-qualified symbols are not abstract (JLS)
  2816                     rs.checkNonAbstract(that.pos(), that.sym);
  2819                 if (isTargetSerializable) {
  2820                     chk.checkElemAccessFromSerializableLambda(that);
  2824             ResultInfo checkInfo =
  2825                     resultInfo.dup(newMethodTemplate(
  2826                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2827                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
  2828                         new FunctionalReturnContext(resultInfo.checkContext));
  2830             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2832             if (that.kind.isUnbound() &&
  2833                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  2834                 //re-generate inference constraints for unbound receiver
  2835                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
  2836                     //cannot happen as this has already been checked - we just need
  2837                     //to regenerate the inference constraints, as that has been lost
  2838                     //as a result of the call to inferenceContext.save()
  2839                     Assert.error("Can't get here");
  2843             if (!refType.isErroneous()) {
  2844                 refType = types.createMethodTypeWithReturn(refType,
  2845                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2848             //go ahead with standard method reference compatibility check - note that param check
  2849             //is a no-op (as this has been taken care during method applicability)
  2850             boolean isSpeculativeRound =
  2851                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2852             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2853             if (!isSpeculativeRound) {
  2854                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
  2856             result = check(that, currentTarget, VAL, resultInfo);
  2857         } catch (Types.FunctionDescriptorLookupError ex) {
  2858             JCDiagnostic cause = ex.getDiagnostic();
  2859             resultInfo.checkContext.report(that, cause);
  2860             result = that.type = types.createErrorType(pt());
  2861             return;
  2864     //where
  2865         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2866             //if this is a constructor reference, the expected kind must be a type
  2867             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2871     @SuppressWarnings("fallthrough")
  2872     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2873         Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2875         Type resType;
  2876         switch (tree.getMode()) {
  2877             case NEW:
  2878                 if (!tree.expr.type.isRaw()) {
  2879                     resType = tree.expr.type;
  2880                     break;
  2882             default:
  2883                 resType = refType.getReturnType();
  2886         Type incompatibleReturnType = resType;
  2888         if (returnType.hasTag(VOID)) {
  2889             incompatibleReturnType = null;
  2892         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2893             if (resType.isErroneous() ||
  2894                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2895                 incompatibleReturnType = null;
  2899         if (incompatibleReturnType != null) {
  2900             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2901                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2904         if (!speculativeAttr) {
  2905             List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
  2906             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2907                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2912     /**
  2913      * Set functional type info on the underlying AST. Note: as the target descriptor
  2914      * might contain inference variables, we might need to register an hook in the
  2915      * current inference context.
  2916      */
  2917     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  2918             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  2919         if (checkContext.inferenceContext().free(descriptorType)) {
  2920             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2921                 public void typesInferred(InferenceContext inferenceContext) {
  2922                     setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  2923                             inferenceContext.asInstType(primaryTarget), checkContext);
  2925             });
  2926         } else {
  2927             ListBuffer<Type> targets = new ListBuffer<>();
  2928             if (pt.hasTag(CLASS)) {
  2929                 if (pt.isCompound()) {
  2930                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  2931                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2932                         if (t != primaryTarget) {
  2933                             targets.append(types.removeWildcards(t));
  2936                 } else {
  2937                     targets.append(types.removeWildcards(primaryTarget));
  2940             fExpr.targets = targets.toList();
  2941             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2942                     pt != Type.recoveryType) {
  2943                 //check that functional interface class is well-formed
  2944                 try {
  2945                     /* Types.makeFunctionalInterfaceClass() may throw an exception
  2946                      * when it's executed post-inference. See the listener code
  2947                      * above.
  2948                      */
  2949                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
  2950                             names.empty, List.of(fExpr.targets.head), ABSTRACT);
  2951                     if (csym != null) {
  2952                         chk.checkImplementations(env.tree, csym, csym);
  2954                 } catch (Types.FunctionDescriptorLookupError ex) {
  2955                     JCDiagnostic cause = ex.getDiagnostic();
  2956                     resultInfo.checkContext.report(env.tree, cause);
  2962     public void visitParens(JCParens tree) {
  2963         Type owntype = attribTree(tree.expr, env, resultInfo);
  2964         result = check(tree, owntype, pkind(), resultInfo);
  2965         Symbol sym = TreeInfo.symbol(tree);
  2966         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2967             log.error(tree.pos(), "illegal.start.of.type");
  2970     public void visitAssign(JCAssign tree) {
  2971         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2972         Type capturedType = capture(owntype);
  2973         attribExpr(tree.rhs, env, owntype);
  2974         result = check(tree, capturedType, VAL, resultInfo);
  2977     public void visitAssignop(JCAssignOp tree) {
  2978         // Attribute arguments.
  2979         Type owntype = attribTree(tree.lhs, env, varInfo);
  2980         Type operand = attribExpr(tree.rhs, env);
  2981         // Find operator.
  2982         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2983             tree.pos(), tree.getTag().noAssignOp(), env,
  2984             owntype, operand);
  2986         if (operator.kind == MTH &&
  2987                 !owntype.isErroneous() &&
  2988                 !operand.isErroneous()) {
  2989             chk.checkOperator(tree.pos(),
  2990                               (OperatorSymbol)operator,
  2991                               tree.getTag().noAssignOp(),
  2992                               owntype,
  2993                               operand);
  2994             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2995             chk.checkCastable(tree.rhs.pos(),
  2996                               operator.type.getReturnType(),
  2997                               owntype);
  2999         result = check(tree, owntype, VAL, resultInfo);
  3002     public void visitUnary(JCUnary tree) {
  3003         // Attribute arguments.
  3004         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  3005             ? attribTree(tree.arg, env, varInfo)
  3006             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  3008         // Find operator.
  3009         Symbol operator = tree.operator =
  3010             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  3012         Type owntype = types.createErrorType(tree.type);
  3013         if (operator.kind == MTH &&
  3014                 !argtype.isErroneous()) {
  3015             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3016                 ? tree.arg.type
  3017                 : operator.type.getReturnType();
  3018             int opc = ((OperatorSymbol)operator).opcode;
  3020             // If the argument is constant, fold it.
  3021             if (argtype.constValue() != null) {
  3022                 Type ctype = cfolder.fold1(opc, argtype);
  3023                 if (ctype != null) {
  3024                     owntype = cfolder.coerce(ctype, owntype);
  3028         result = check(tree, owntype, VAL, resultInfo);
  3031     public void visitBinary(JCBinary tree) {
  3032         // Attribute arguments.
  3033         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3034         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  3036         // Find operator.
  3037         Symbol operator = tree.operator =
  3038             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  3040         Type owntype = types.createErrorType(tree.type);
  3041         if (operator.kind == MTH &&
  3042                 !left.isErroneous() &&
  3043                 !right.isErroneous()) {
  3044             owntype = operator.type.getReturnType();
  3045             // This will figure out when unboxing can happen and
  3046             // choose the right comparison operator.
  3047             int opc = chk.checkOperator(tree.lhs.pos(),
  3048                                         (OperatorSymbol)operator,
  3049                                         tree.getTag(),
  3050                                         left,
  3051                                         right);
  3053             // If both arguments are constants, fold them.
  3054             if (left.constValue() != null && right.constValue() != null) {
  3055                 Type ctype = cfolder.fold2(opc, left, right);
  3056                 if (ctype != null) {
  3057                     owntype = cfolder.coerce(ctype, owntype);
  3061             // Check that argument types of a reference ==, != are
  3062             // castable to each other, (JLS 15.21).  Note: unboxing
  3063             // comparisons will not have an acmp* opc at this point.
  3064             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3065                 if (!types.isEqualityComparable(left, right,
  3066                                                 new Warner(tree.pos()))) {
  3067                     log.error(tree.pos(), "incomparable.types", left, right);
  3071             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3073         result = check(tree, owntype, VAL, resultInfo);
  3076     public void visitTypeCast(final JCTypeCast tree) {
  3077         Type clazztype = attribType(tree.clazz, env);
  3078         chk.validate(tree.clazz, env, false);
  3079         //a fresh environment is required for 292 inference to work properly ---
  3080         //see Infer.instantiatePolymorphicSignatureInstance()
  3081         Env<AttrContext> localEnv = env.dup(tree);
  3082         //should we propagate the target type?
  3083         final ResultInfo castInfo;
  3084         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3085         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
  3086         if (isPoly) {
  3087             //expression is a poly - we need to propagate target type info
  3088             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3089                 @Override
  3090                 public boolean compatible(Type found, Type req, Warner warn) {
  3091                     return types.isCastable(found, req, warn);
  3093             });
  3094         } else {
  3095             //standalone cast - target-type info is not propagated
  3096             castInfo = unknownExprInfo;
  3098         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3099         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3100         if (exprtype.constValue() != null)
  3101             owntype = cfolder.coerce(exprtype, owntype);
  3102         result = check(tree, capture(owntype), VAL, resultInfo);
  3103         if (!isPoly)
  3104             chk.checkRedundantCast(localEnv, tree);
  3107     public void visitTypeTest(JCInstanceOf tree) {
  3108         Type exprtype = chk.checkNullOrRefType(
  3109             tree.expr.pos(), attribExpr(tree.expr, env));
  3110         Type clazztype = attribType(tree.clazz, env);
  3111         if (!clazztype.hasTag(TYPEVAR)) {
  3112             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3114         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3115             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3116             clazztype = types.createErrorType(clazztype);
  3118         chk.validate(tree.clazz, env, false);
  3119         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3120         result = check(tree, syms.booleanType, VAL, resultInfo);
  3123     public void visitIndexed(JCArrayAccess tree) {
  3124         Type owntype = types.createErrorType(tree.type);
  3125         Type atype = attribExpr(tree.indexed, env);
  3126         attribExpr(tree.index, env, syms.intType);
  3127         if (types.isArray(atype))
  3128             owntype = types.elemtype(atype);
  3129         else if (!atype.hasTag(ERROR))
  3130             log.error(tree.pos(), "array.req.but.found", atype);
  3131         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3132         result = check(tree, owntype, VAR, resultInfo);
  3135     public void visitIdent(JCIdent tree) {
  3136         Symbol sym;
  3138         // Find symbol
  3139         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3140             // If we are looking for a method, the prototype `pt' will be a
  3141             // method type with the type of the call's arguments as parameters.
  3142             env.info.pendingResolutionPhase = null;
  3143             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3144         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3145             sym = tree.sym;
  3146         } else {
  3147             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3149         tree.sym = sym;
  3151         // (1) Also find the environment current for the class where
  3152         //     sym is defined (`symEnv').
  3153         // Only for pre-tiger versions (1.4 and earlier):
  3154         // (2) Also determine whether we access symbol out of an anonymous
  3155         //     class in a this or super call.  This is illegal for instance
  3156         //     members since such classes don't carry a this$n link.
  3157         //     (`noOuterThisPath').
  3158         Env<AttrContext> symEnv = env;
  3159         boolean noOuterThisPath = false;
  3160         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3161             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3162             sym.owner.kind == TYP &&
  3163             tree.name != names._this && tree.name != names._super) {
  3165             // Find environment in which identifier is defined.
  3166             while (symEnv.outer != null &&
  3167                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3168                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3169                     noOuterThisPath = !allowAnonOuterThis;
  3170                 symEnv = symEnv.outer;
  3174         // If symbol is a variable, ...
  3175         if (sym.kind == VAR) {
  3176             VarSymbol v = (VarSymbol)sym;
  3178             // ..., evaluate its initializer, if it has one, and check for
  3179             // illegal forward reference.
  3180             checkInit(tree, env, v, false);
  3182             // If we are expecting a variable (as opposed to a value), check
  3183             // that the variable is assignable in the current environment.
  3184             if (pkind() == VAR)
  3185                 checkAssignable(tree.pos(), v, null, env);
  3188         // In a constructor body,
  3189         // if symbol is a field or instance method, check that it is
  3190         // not accessed before the supertype constructor is called.
  3191         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3192             (sym.kind & (VAR | MTH)) != 0 &&
  3193             sym.owner.kind == TYP &&
  3194             (sym.flags() & STATIC) == 0) {
  3195             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3197         Env<AttrContext> env1 = env;
  3198         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3199             // If the found symbol is inaccessible, then it is
  3200             // accessed through an enclosing instance.  Locate this
  3201             // enclosing instance:
  3202             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3203                 env1 = env1.outer;
  3206         if (env.info.isSerializable) {
  3207             chk.checkElemAccessFromSerializableLambda(tree);
  3210         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3213     public void visitSelect(JCFieldAccess tree) {
  3214         // Determine the expected kind of the qualifier expression.
  3215         int skind = 0;
  3216         if (tree.name == names._this || tree.name == names._super ||
  3217             tree.name == names._class)
  3219             skind = TYP;
  3220         } else {
  3221             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3222             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3223             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3226         // Attribute the qualifier expression, and determine its symbol (if any).
  3227         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3228         if ((pkind() & (PCK | TYP)) == 0)
  3229             site = capture(site); // Capture field access
  3231         // don't allow T.class T[].class, etc
  3232         if (skind == TYP) {
  3233             Type elt = site;
  3234             while (elt.hasTag(ARRAY))
  3235                 elt = ((ArrayType)elt.unannotatedType()).elemtype;
  3236             if (elt.hasTag(TYPEVAR)) {
  3237                 log.error(tree.pos(), "type.var.cant.be.deref");
  3238                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
  3239                 tree.sym = tree.type.tsym;
  3240                 return ;
  3244         // If qualifier symbol is a type or `super', assert `selectSuper'
  3245         // for the selection. This is relevant for determining whether
  3246         // protected symbols are accessible.
  3247         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3248         boolean selectSuperPrev = env.info.selectSuper;
  3249         env.info.selectSuper =
  3250             sitesym != null &&
  3251             sitesym.name == names._super;
  3253         // Determine the symbol represented by the selection.
  3254         env.info.pendingResolutionPhase = null;
  3255         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3256         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
  3257             log.error(tree.selected.pos(), "not.encl.class", site.tsym);
  3258             sym = syms.errSymbol;
  3260         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3261             site = capture(site);
  3262             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3264         boolean varArgs = env.info.lastResolveVarargs();
  3265         tree.sym = sym;
  3267         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3268             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3269             site = capture(site);
  3272         // If that symbol is a variable, ...
  3273         if (sym.kind == VAR) {
  3274             VarSymbol v = (VarSymbol)sym;
  3276             // ..., evaluate its initializer, if it has one, and check for
  3277             // illegal forward reference.
  3278             checkInit(tree, env, v, true);
  3280             // If we are expecting a variable (as opposed to a value), check
  3281             // that the variable is assignable in the current environment.
  3282             if (pkind() == VAR)
  3283                 checkAssignable(tree.pos(), v, tree.selected, env);
  3286         if (sitesym != null &&
  3287                 sitesym.kind == VAR &&
  3288                 ((VarSymbol)sitesym).isResourceVariable() &&
  3289                 sym.kind == MTH &&
  3290                 sym.name.equals(names.close) &&
  3291                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3292                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3293             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3296         // Disallow selecting a type from an expression
  3297         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3298             tree.type = check(tree.selected, pt(),
  3299                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3302         if (isType(sitesym)) {
  3303             if (sym.name == names._this) {
  3304                 // If `C' is the currently compiled class, check that
  3305                 // C.this' does not appear in a call to a super(...)
  3306                 if (env.info.isSelfCall &&
  3307                     site.tsym == env.enclClass.sym) {
  3308                     chk.earlyRefError(tree.pos(), sym);
  3310             } else {
  3311                 // Check if type-qualified fields or methods are static (JLS)
  3312                 if ((sym.flags() & STATIC) == 0 &&
  3313                     !env.next.tree.hasTag(REFERENCE) &&
  3314                     sym.name != names._super &&
  3315                     (sym.kind == VAR || sym.kind == MTH)) {
  3316                     rs.accessBase(rs.new StaticError(sym),
  3317                               tree.pos(), site, sym.name, true);
  3320             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
  3321                     sym.isStatic() && sym.kind == MTH) {
  3322                 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
  3324         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3325             // If the qualified item is not a type and the selected item is static, report
  3326             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3327             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3330         // If we are selecting an instance member via a `super', ...
  3331         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3333             // Check that super-qualified symbols are not abstract (JLS)
  3334             rs.checkNonAbstract(tree.pos(), sym);
  3336             if (site.isRaw()) {
  3337                 // Determine argument types for site.
  3338                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3339                 if (site1 != null) site = site1;
  3343         if (env.info.isSerializable) {
  3344             chk.checkElemAccessFromSerializableLambda(tree);
  3347         env.info.selectSuper = selectSuperPrev;
  3348         result = checkId(tree, site, sym, env, resultInfo);
  3350     //where
  3351         /** Determine symbol referenced by a Select expression,
  3353          *  @param tree   The select tree.
  3354          *  @param site   The type of the selected expression,
  3355          *  @param env    The current environment.
  3356          *  @param resultInfo The current result.
  3357          */
  3358         private Symbol selectSym(JCFieldAccess tree,
  3359                                  Symbol location,
  3360                                  Type site,
  3361                                  Env<AttrContext> env,
  3362                                  ResultInfo resultInfo) {
  3363             DiagnosticPosition pos = tree.pos();
  3364             Name name = tree.name;
  3365             switch (site.getTag()) {
  3366             case PACKAGE:
  3367                 return rs.accessBase(
  3368                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3369                     pos, location, site, name, true);
  3370             case ARRAY:
  3371             case CLASS:
  3372                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3373                     return rs.resolveQualifiedMethod(
  3374                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3375                 } else if (name == names._this || name == names._super) {
  3376                     return rs.resolveSelf(pos, env, site.tsym, name);
  3377                 } else if (name == names._class) {
  3378                     // In this case, we have already made sure in
  3379                     // visitSelect that qualifier expression is a type.
  3380                     Type t = syms.classType;
  3381                     List<Type> typeargs = allowGenerics
  3382                         ? List.of(types.erasure(site))
  3383                         : List.<Type>nil();
  3384                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3385                     return new VarSymbol(
  3386                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3387                 } else {
  3388                     // We are seeing a plain identifier as selector.
  3389                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3390                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3391                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3392                     return sym;
  3394             case WILDCARD:
  3395                 throw new AssertionError(tree);
  3396             case TYPEVAR:
  3397                 // Normally, site.getUpperBound() shouldn't be null.
  3398                 // It should only happen during memberEnter/attribBase
  3399                 // when determining the super type which *must* beac
  3400                 // done before attributing the type variables.  In
  3401                 // other words, we are seeing this illegal program:
  3402                 // class B<T> extends A<T.foo> {}
  3403                 Symbol sym = (site.getUpperBound() != null)
  3404                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3405                     : null;
  3406                 if (sym == null) {
  3407                     log.error(pos, "type.var.cant.be.deref");
  3408                     return syms.errSymbol;
  3409                 } else {
  3410                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3411                         rs.new AccessError(env, site, sym) :
  3412                                 sym;
  3413                     rs.accessBase(sym2, pos, location, site, name, true);
  3414                     return sym;
  3416             case ERROR:
  3417                 // preserve identifier names through errors
  3418                 return types.createErrorType(name, site.tsym, site).tsym;
  3419             default:
  3420                 // The qualifier expression is of a primitive type -- only
  3421                 // .class is allowed for these.
  3422                 if (name == names._class) {
  3423                     // In this case, we have already made sure in Select that
  3424                     // qualifier expression is a type.
  3425                     Type t = syms.classType;
  3426                     Type arg = types.boxedClass(site).type;
  3427                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3428                     return new VarSymbol(
  3429                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3430                 } else {
  3431                     log.error(pos, "cant.deref", site);
  3432                     return syms.errSymbol;
  3437         /** Determine type of identifier or select expression and check that
  3438          *  (1) the referenced symbol is not deprecated
  3439          *  (2) the symbol's type is safe (@see checkSafe)
  3440          *  (3) if symbol is a variable, check that its type and kind are
  3441          *      compatible with the prototype and protokind.
  3442          *  (4) if symbol is an instance field of a raw type,
  3443          *      which is being assigned to, issue an unchecked warning if its
  3444          *      type changes under erasure.
  3445          *  (5) if symbol is an instance method of a raw type, issue an
  3446          *      unchecked warning if its argument types change under erasure.
  3447          *  If checks succeed:
  3448          *    If symbol is a constant, return its constant type
  3449          *    else if symbol is a method, return its result type
  3450          *    otherwise return its type.
  3451          *  Otherwise return errType.
  3453          *  @param tree       The syntax tree representing the identifier
  3454          *  @param site       If this is a select, the type of the selected
  3455          *                    expression, otherwise the type of the current class.
  3456          *  @param sym        The symbol representing the identifier.
  3457          *  @param env        The current environment.
  3458          *  @param resultInfo    The expected result
  3459          */
  3460         Type checkId(JCTree tree,
  3461                      Type site,
  3462                      Symbol sym,
  3463                      Env<AttrContext> env,
  3464                      ResultInfo resultInfo) {
  3465             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3466                     checkMethodId(tree, site, sym, env, resultInfo) :
  3467                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3470         Type checkMethodId(JCTree tree,
  3471                      Type site,
  3472                      Symbol sym,
  3473                      Env<AttrContext> env,
  3474                      ResultInfo resultInfo) {
  3475             boolean isPolymorhicSignature =
  3476                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3477             return isPolymorhicSignature ?
  3478                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3479                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3482         Type checkSigPolyMethodId(JCTree tree,
  3483                      Type site,
  3484                      Symbol sym,
  3485                      Env<AttrContext> env,
  3486                      ResultInfo resultInfo) {
  3487             //recover original symbol for signature polymorphic methods
  3488             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3489             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3490             return sym.type;
  3493         Type checkMethodIdInternal(JCTree tree,
  3494                      Type site,
  3495                      Symbol sym,
  3496                      Env<AttrContext> env,
  3497                      ResultInfo resultInfo) {
  3498             if ((resultInfo.pkind & POLY) != 0) {
  3499                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3500                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3501                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3502                 return owntype;
  3503             } else {
  3504                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3508         Type checkIdInternal(JCTree tree,
  3509                      Type site,
  3510                      Symbol sym,
  3511                      Type pt,
  3512                      Env<AttrContext> env,
  3513                      ResultInfo resultInfo) {
  3514             if (pt.isErroneous()) {
  3515                 return types.createErrorType(site);
  3517             Type owntype; // The computed type of this identifier occurrence.
  3518             switch (sym.kind) {
  3519             case TYP:
  3520                 // For types, the computed type equals the symbol's type,
  3521                 // except for two situations:
  3522                 owntype = sym.type;
  3523                 if (owntype.hasTag(CLASS)) {
  3524                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3525                     Type ownOuter = owntype.getEnclosingType();
  3527                     // (a) If the symbol's type is parameterized, erase it
  3528                     // because no type parameters were given.
  3529                     // We recover generic outer type later in visitTypeApply.
  3530                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3531                         owntype = types.erasure(owntype);
  3534                     // (b) If the symbol's type is an inner class, then
  3535                     // we have to interpret its outer type as a superclass
  3536                     // of the site type. Example:
  3537                     //
  3538                     // class Tree<A> { class Visitor { ... } }
  3539                     // class PointTree extends Tree<Point> { ... }
  3540                     // ...PointTree.Visitor...
  3541                     //
  3542                     // Then the type of the last expression above is
  3543                     // Tree<Point>.Visitor.
  3544                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3545                         Type normOuter = site;
  3546                         if (normOuter.hasTag(CLASS)) {
  3547                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3549                         if (normOuter == null) // perhaps from an import
  3550                             normOuter = types.erasure(ownOuter);
  3551                         if (normOuter != ownOuter)
  3552                             owntype = new ClassType(
  3553                                 normOuter, List.<Type>nil(), owntype.tsym);
  3556                 break;
  3557             case VAR:
  3558                 VarSymbol v = (VarSymbol)sym;
  3559                 // Test (4): if symbol is an instance field of a raw type,
  3560                 // which is being assigned to, issue an unchecked warning if
  3561                 // its type changes under erasure.
  3562                 if (allowGenerics &&
  3563                     resultInfo.pkind == VAR &&
  3564                     v.owner.kind == TYP &&
  3565                     (v.flags() & STATIC) == 0 &&
  3566                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3567                     Type s = types.asOuterSuper(site, v.owner);
  3568                     if (s != null &&
  3569                         s.isRaw() &&
  3570                         !types.isSameType(v.type, v.erasure(types))) {
  3571                         chk.warnUnchecked(tree.pos(),
  3572                                           "unchecked.assign.to.var",
  3573                                           v, s);
  3576                 // The computed type of a variable is the type of the
  3577                 // variable symbol, taken as a member of the site type.
  3578                 owntype = (sym.owner.kind == TYP &&
  3579                            sym.name != names._this && sym.name != names._super)
  3580                     ? types.memberType(site, sym)
  3581                     : sym.type;
  3583                 // If the variable is a constant, record constant value in
  3584                 // computed type.
  3585                 if (v.getConstValue() != null && isStaticReference(tree))
  3586                     owntype = owntype.constType(v.getConstValue());
  3588                 if (resultInfo.pkind == VAL) {
  3589                     owntype = capture(owntype); // capture "names as expressions"
  3591                 break;
  3592             case MTH: {
  3593                 owntype = checkMethod(site, sym,
  3594                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3595                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3596                         resultInfo.pt.getTypeArguments());
  3597                 break;
  3599             case PCK: case ERR:
  3600                 owntype = sym.type;
  3601                 break;
  3602             default:
  3603                 throw new AssertionError("unexpected kind: " + sym.kind +
  3604                                          " in tree " + tree);
  3607             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3608             // (for constructors, the error was given when the constructor was
  3609             // resolved)
  3611             if (sym.name != names.init) {
  3612                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3613                 chk.checkSunAPI(tree.pos(), sym);
  3614                 chk.checkProfile(tree.pos(), sym);
  3617             // Test (3): if symbol is a variable, check that its type and
  3618             // kind are compatible with the prototype and protokind.
  3619             return check(tree, owntype, sym.kind, resultInfo);
  3622         /** Check that variable is initialized and evaluate the variable's
  3623          *  initializer, if not yet done. Also check that variable is not
  3624          *  referenced before it is defined.
  3625          *  @param tree    The tree making up the variable reference.
  3626          *  @param env     The current environment.
  3627          *  @param v       The variable's symbol.
  3628          */
  3629         private void checkInit(JCTree tree,
  3630                                Env<AttrContext> env,
  3631                                VarSymbol v,
  3632                                boolean onlyWarning) {
  3633 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3634 //                             tree.pos + " " + v.pos + " " +
  3635 //                             Resolve.isStatic(env));//DEBUG
  3637             // A forward reference is diagnosed if the declaration position
  3638             // of the variable is greater than the current tree position
  3639             // and the tree and variable definition occur in the same class
  3640             // definition.  Note that writes don't count as references.
  3641             // This check applies only to class and instance
  3642             // variables.  Local variables follow different scope rules,
  3643             // and are subject to definite assignment checking.
  3644             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3645                 v.owner.kind == TYP &&
  3646                 enclosingInitEnv(env) != null &&
  3647                 v.owner == env.info.scope.owner.enclClass() &&
  3648                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3649                 (!env.tree.hasTag(ASSIGN) ||
  3650                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3651                 String suffix = (env.info.enclVar == v) ?
  3652                                 "self.ref" : "forward.ref";
  3653                 if (!onlyWarning || isStaticEnumField(v)) {
  3654                     log.error(tree.pos(), "illegal." + suffix);
  3655                 } else if (useBeforeDeclarationWarning) {
  3656                     log.warning(tree.pos(), suffix, v);
  3660             v.getConstValue(); // ensure initializer is evaluated
  3662             checkEnumInitializer(tree, env, v);
  3665         /**
  3666          * Returns the enclosing init environment associated with this env (if any). An init env
  3667          * can be either a field declaration env or a static/instance initializer env.
  3668          */
  3669         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
  3670             while (true) {
  3671                 switch (env.tree.getTag()) {
  3672                     case VARDEF:
  3673                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
  3674                         if (vdecl.sym.owner.kind == TYP) {
  3675                             //field
  3676                             return env;
  3678                         break;
  3679                     case BLOCK:
  3680                         if (env.next.tree.hasTag(CLASSDEF)) {
  3681                             //instance/static initializer
  3682                             return env;
  3684                         break;
  3685                     case METHODDEF:
  3686                     case CLASSDEF:
  3687                     case TOPLEVEL:
  3688                         return null;
  3690                 Assert.checkNonNull(env.next);
  3691                 env = env.next;
  3695         /**
  3696          * Check for illegal references to static members of enum.  In
  3697          * an enum type, constructors and initializers may not
  3698          * reference its static members unless they are constant.
  3700          * @param tree    The tree making up the variable reference.
  3701          * @param env     The current environment.
  3702          * @param v       The variable's symbol.
  3703          * @jls  section 8.9 Enums
  3704          */
  3705         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3706             // JLS:
  3707             //
  3708             // "It is a compile-time error to reference a static field
  3709             // of an enum type that is not a compile-time constant
  3710             // (15.28) from constructors, instance initializer blocks,
  3711             // or instance variable initializer expressions of that
  3712             // type. It is a compile-time error for the constructors,
  3713             // instance initializer blocks, or instance variable
  3714             // initializer expressions of an enum constant e to refer
  3715             // to itself or to an enum constant of the same type that
  3716             // is declared to the right of e."
  3717             if (isStaticEnumField(v)) {
  3718                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3720                 if (enclClass == null || enclClass.owner == null)
  3721                     return;
  3723                 // See if the enclosing class is the enum (or a
  3724                 // subclass thereof) declaring v.  If not, this
  3725                 // reference is OK.
  3726                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3727                     return;
  3729                 // If the reference isn't from an initializer, then
  3730                 // the reference is OK.
  3731                 if (!Resolve.isInitializer(env))
  3732                     return;
  3734                 log.error(tree.pos(), "illegal.enum.static.ref");
  3738         /** Is the given symbol a static, non-constant field of an Enum?
  3739          *  Note: enum literals should not be regarded as such
  3740          */
  3741         private boolean isStaticEnumField(VarSymbol v) {
  3742             return Flags.isEnum(v.owner) &&
  3743                    Flags.isStatic(v) &&
  3744                    !Flags.isConstant(v) &&
  3745                    v.name != names._class;
  3748     Warner noteWarner = new Warner();
  3750     /**
  3751      * Check that method arguments conform to its instantiation.
  3752      **/
  3753     public Type checkMethod(Type site,
  3754                             final Symbol sym,
  3755                             ResultInfo resultInfo,
  3756                             Env<AttrContext> env,
  3757                             final List<JCExpression> argtrees,
  3758                             List<Type> argtypes,
  3759                             List<Type> typeargtypes) {
  3760         // Test (5): if symbol is an instance method of a raw type, issue
  3761         // an unchecked warning if its argument types change under erasure.
  3762         if (allowGenerics &&
  3763             (sym.flags() & STATIC) == 0 &&
  3764             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3765             Type s = types.asOuterSuper(site, sym.owner);
  3766             if (s != null && s.isRaw() &&
  3767                 !types.isSameTypes(sym.type.getParameterTypes(),
  3768                                    sym.erasure(types).getParameterTypes())) {
  3769                 chk.warnUnchecked(env.tree.pos(),
  3770                                   "unchecked.call.mbr.of.raw.type",
  3771                                   sym, s);
  3775         if (env.info.defaultSuperCallSite != null) {
  3776             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3777                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3778                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3779                 List<MethodSymbol> icand_sup =
  3780                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3781                 if (icand_sup.nonEmpty() &&
  3782                         icand_sup.head != sym &&
  3783                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3784                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3785                         diags.fragment("overridden.default", sym, sup));
  3786                     break;
  3789             env.info.defaultSuperCallSite = null;
  3792         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3793             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3794             if (app.meth.hasTag(SELECT) &&
  3795                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3796                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3800         // Compute the identifier's instantiated type.
  3801         // For methods, we need to compute the instance type by
  3802         // Resolve.instantiate from the symbol's type as well as
  3803         // any type arguments and value arguments.
  3804         noteWarner.clear();
  3805         try {
  3806             Type owntype = rs.checkMethod(
  3807                     env,
  3808                     site,
  3809                     sym,
  3810                     resultInfo,
  3811                     argtypes,
  3812                     typeargtypes,
  3813                     noteWarner);
  3815             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3816                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3818             argtypes = Type.map(argtypes, checkDeferredMap);
  3820             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3821                 chk.warnUnchecked(env.tree.pos(),
  3822                         "unchecked.meth.invocation.applied",
  3823                         kindName(sym),
  3824                         sym.name,
  3825                         rs.methodArguments(sym.type.getParameterTypes()),
  3826                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3827                         kindName(sym.location()),
  3828                         sym.location());
  3829                owntype = new MethodType(owntype.getParameterTypes(),
  3830                        types.erasure(owntype.getReturnType()),
  3831                        types.erasure(owntype.getThrownTypes()),
  3832                        syms.methodClass);
  3835             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3836                     resultInfo.checkContext.inferenceContext());
  3837         } catch (Infer.InferenceException ex) {
  3838             //invalid target type - propagate exception outwards or report error
  3839             //depending on the current check context
  3840             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3841             return types.createErrorType(site);
  3842         } catch (Resolve.InapplicableMethodException ex) {
  3843             final JCDiagnostic diag = ex.getDiagnostic();
  3844             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  3845                 @Override
  3846                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  3847                     return new Pair<Symbol, JCDiagnostic>(sym, diag);
  3849             };
  3850             List<Type> argtypes2 = Type.map(argtypes,
  3851                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3852             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  3853                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  3854             log.report(errDiag);
  3855             return types.createErrorType(site);
  3859     public void visitLiteral(JCLiteral tree) {
  3860         result = check(
  3861             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3863     //where
  3864     /** Return the type of a literal with given type tag.
  3865      */
  3866     Type litType(TypeTag tag) {
  3867         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3870     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3871         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3874     public void visitTypeArray(JCArrayTypeTree tree) {
  3875         Type etype = attribType(tree.elemtype, env);
  3876         Type type = new ArrayType(etype, syms.arrayClass);
  3877         result = check(tree, type, TYP, resultInfo);
  3880     /** Visitor method for parameterized types.
  3881      *  Bound checking is left until later, since types are attributed
  3882      *  before supertype structure is completely known
  3883      */
  3884     public void visitTypeApply(JCTypeApply tree) {
  3885         Type owntype = types.createErrorType(tree.type);
  3887         // Attribute functor part of application and make sure it's a class.
  3888         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3890         // Attribute type parameters
  3891         List<Type> actuals = attribTypes(tree.arguments, env);
  3893         if (clazztype.hasTag(CLASS)) {
  3894             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3895             if (actuals.isEmpty()) //diamond
  3896                 actuals = formals;
  3898             if (actuals.length() == formals.length()) {
  3899                 List<Type> a = actuals;
  3900                 List<Type> f = formals;
  3901                 while (a.nonEmpty()) {
  3902                     a.head = a.head.withTypeVar(f.head);
  3903                     a = a.tail;
  3904                     f = f.tail;
  3906                 // Compute the proper generic outer
  3907                 Type clazzOuter = clazztype.getEnclosingType();
  3908                 if (clazzOuter.hasTag(CLASS)) {
  3909                     Type site;
  3910                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3911                     if (clazz.hasTag(IDENT)) {
  3912                         site = env.enclClass.sym.type;
  3913                     } else if (clazz.hasTag(SELECT)) {
  3914                         site = ((JCFieldAccess) clazz).selected.type;
  3915                     } else throw new AssertionError(""+tree);
  3916                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3917                         if (site.hasTag(CLASS))
  3918                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3919                         if (site == null)
  3920                             site = types.erasure(clazzOuter);
  3921                         clazzOuter = site;
  3924                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3925             } else {
  3926                 if (formals.length() != 0) {
  3927                     log.error(tree.pos(), "wrong.number.type.args",
  3928                               Integer.toString(formals.length()));
  3929                 } else {
  3930                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3932                 owntype = types.createErrorType(tree.type);
  3935         result = check(tree, owntype, TYP, resultInfo);
  3938     public void visitTypeUnion(JCTypeUnion tree) {
  3939         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  3940         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3941         for (JCExpression typeTree : tree.alternatives) {
  3942             Type ctype = attribType(typeTree, env);
  3943             ctype = chk.checkType(typeTree.pos(),
  3944                           chk.checkClassType(typeTree.pos(), ctype),
  3945                           syms.throwableType);
  3946             if (!ctype.isErroneous()) {
  3947                 //check that alternatives of a union type are pairwise
  3948                 //unrelated w.r.t. subtyping
  3949                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3950                     for (Type t : multicatchTypes) {
  3951                         boolean sub = types.isSubtype(ctype, t);
  3952                         boolean sup = types.isSubtype(t, ctype);
  3953                         if (sub || sup) {
  3954                             //assume 'a' <: 'b'
  3955                             Type a = sub ? ctype : t;
  3956                             Type b = sub ? t : ctype;
  3957                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3961                 multicatchTypes.append(ctype);
  3962                 if (all_multicatchTypes != null)
  3963                     all_multicatchTypes.append(ctype);
  3964             } else {
  3965                 if (all_multicatchTypes == null) {
  3966                     all_multicatchTypes = new ListBuffer<>();
  3967                     all_multicatchTypes.appendList(multicatchTypes);
  3969                 all_multicatchTypes.append(ctype);
  3972         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3973         if (t.hasTag(CLASS)) {
  3974             List<Type> alternatives =
  3975                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3976             t = new UnionClassType((ClassType) t, alternatives);
  3978         tree.type = result = t;
  3981     public void visitTypeIntersection(JCTypeIntersection tree) {
  3982         attribTypes(tree.bounds, env);
  3983         tree.type = result = checkIntersection(tree, tree.bounds);
  3986     public void visitTypeParameter(JCTypeParameter tree) {
  3987         TypeVar typeVar = (TypeVar) tree.type;
  3989         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3990             annotateType(tree, tree.annotations);
  3993         if (!typeVar.bound.isErroneous()) {
  3994             //fixup type-parameter bound computed in 'attribTypeVariables'
  3995             typeVar.bound = checkIntersection(tree, tree.bounds);
  3999     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  4000         Set<Type> boundSet = new HashSet<Type>();
  4001         if (bounds.nonEmpty()) {
  4002             // accept class or interface or typevar as first bound.
  4003             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  4004             boundSet.add(types.erasure(bounds.head.type));
  4005             if (bounds.head.type.isErroneous()) {
  4006                 return bounds.head.type;
  4008             else if (bounds.head.type.hasTag(TYPEVAR)) {
  4009                 // if first bound was a typevar, do not accept further bounds.
  4010                 if (bounds.tail.nonEmpty()) {
  4011                     log.error(bounds.tail.head.pos(),
  4012                               "type.var.may.not.be.followed.by.other.bounds");
  4013                     return bounds.head.type;
  4015             } else {
  4016                 // if first bound was a class or interface, accept only interfaces
  4017                 // as further bounds.
  4018                 for (JCExpression bound : bounds.tail) {
  4019                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  4020                     if (bound.type.isErroneous()) {
  4021                         bounds = List.of(bound);
  4023                     else if (bound.type.hasTag(CLASS)) {
  4024                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4030         if (bounds.length() == 0) {
  4031             return syms.objectType;
  4032         } else if (bounds.length() == 1) {
  4033             return bounds.head.type;
  4034         } else {
  4035             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  4036             // ... the variable's bound is a class type flagged COMPOUND
  4037             // (see comment for TypeVar.bound).
  4038             // In this case, generate a class tree that represents the
  4039             // bound class, ...
  4040             JCExpression extending;
  4041             List<JCExpression> implementing;
  4042             if (!bounds.head.type.isInterface()) {
  4043                 extending = bounds.head;
  4044                 implementing = bounds.tail;
  4045             } else {
  4046                 extending = null;
  4047                 implementing = bounds;
  4049             JCClassDecl cd = make.at(tree).ClassDef(
  4050                 make.Modifiers(PUBLIC | ABSTRACT),
  4051                 names.empty, List.<JCTypeParameter>nil(),
  4052                 extending, implementing, List.<JCTree>nil());
  4054             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4055             Assert.check((c.flags() & COMPOUND) != 0);
  4056             cd.sym = c;
  4057             c.sourcefile = env.toplevel.sourcefile;
  4059             // ... and attribute the bound class
  4060             c.flags_field |= UNATTRIBUTED;
  4061             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4062             typeEnvs.put(c, cenv);
  4063             attribClass(c);
  4064             return owntype;
  4068     public void visitWildcard(JCWildcard tree) {
  4069         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4070         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4071             ? syms.objectType
  4072             : attribType(tree.inner, env);
  4073         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4074                                               tree.kind.kind,
  4075                                               syms.boundClass),
  4076                        TYP, resultInfo);
  4079     public void visitAnnotation(JCAnnotation tree) {
  4080         Assert.error("should be handled in Annotate");
  4083     public void visitAnnotatedType(JCAnnotatedType tree) {
  4084         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4085         this.attribAnnotationTypes(tree.annotations, env);
  4086         annotateType(tree, tree.annotations);
  4087         result = tree.type = underlyingType;
  4090     /**
  4091      * Apply the annotations to the particular type.
  4092      */
  4093     public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
  4094         annotate.typeAnnotation(new Annotate.Worker() {
  4095             @Override
  4096             public String toString() {
  4097                 return "annotate " + annotations + " onto " + tree;
  4099             @Override
  4100             public void run() {
  4101                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4102                 if (annotations.size() == compounds.size()) {
  4103                     // All annotations were successfully converted into compounds
  4104                     tree.type = tree.type.unannotatedType().annotatedType(compounds);
  4107         });
  4110     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4111         if (annotations.isEmpty()) {
  4112             return List.nil();
  4115         ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
  4116         for (JCAnnotation anno : annotations) {
  4117             if (anno.attribute != null) {
  4118                 // TODO: this null-check is only needed for an obscure
  4119                 // ordering issue, where annotate.flush is called when
  4120                 // the attribute is not set yet. For an example failure
  4121                 // try the referenceinfos/NestedTypes.java test.
  4122                 // Any better solutions?
  4123                 buf.append((Attribute.TypeCompound) anno.attribute);
  4125             // Eventually we will want to throw an exception here, but
  4126             // we can't do that just yet, because it gets triggered
  4127             // when attempting to attach an annotation that isn't
  4128             // defined.
  4130         return buf.toList();
  4133     public void visitErroneous(JCErroneous tree) {
  4134         if (tree.errs != null)
  4135             for (JCTree err : tree.errs)
  4136                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4137         result = tree.type = syms.errType;
  4140     /** Default visitor method for all other trees.
  4141      */
  4142     public void visitTree(JCTree tree) {
  4143         throw new AssertionError();
  4146     /**
  4147      * Attribute an env for either a top level tree or class declaration.
  4148      */
  4149     public void attrib(Env<AttrContext> env) {
  4150         if (env.tree.hasTag(TOPLEVEL))
  4151             attribTopLevel(env);
  4152         else
  4153             attribClass(env.tree.pos(), env.enclClass.sym);
  4156     /**
  4157      * Attribute a top level tree. These trees are encountered when the
  4158      * package declaration has annotations.
  4159      */
  4160     public void attribTopLevel(Env<AttrContext> env) {
  4161         JCCompilationUnit toplevel = env.toplevel;
  4162         try {
  4163             annotate.flush();
  4164         } catch (CompletionFailure ex) {
  4165             chk.completionError(toplevel.pos(), ex);
  4169     /** Main method: attribute class definition associated with given class symbol.
  4170      *  reporting completion failures at the given position.
  4171      *  @param pos The source position at which completion errors are to be
  4172      *             reported.
  4173      *  @param c   The class symbol whose definition will be attributed.
  4174      */
  4175     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4176         try {
  4177             annotate.flush();
  4178             attribClass(c);
  4179         } catch (CompletionFailure ex) {
  4180             chk.completionError(pos, ex);
  4184     /** Attribute class definition associated with given class symbol.
  4185      *  @param c   The class symbol whose definition will be attributed.
  4186      */
  4187     void attribClass(ClassSymbol c) throws CompletionFailure {
  4188         if (c.type.hasTag(ERROR)) return;
  4190         // Check for cycles in the inheritance graph, which can arise from
  4191         // ill-formed class files.
  4192         chk.checkNonCyclic(null, c.type);
  4194         Type st = types.supertype(c.type);
  4195         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4196             // First, attribute superclass.
  4197             if (st.hasTag(CLASS))
  4198                 attribClass((ClassSymbol)st.tsym);
  4200             // Next attribute owner, if it is a class.
  4201             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4202                 attribClass((ClassSymbol)c.owner);
  4205         // The previous operations might have attributed the current class
  4206         // if there was a cycle. So we test first whether the class is still
  4207         // UNATTRIBUTED.
  4208         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4209             c.flags_field &= ~UNATTRIBUTED;
  4211             // Get environment current at the point of class definition.
  4212             Env<AttrContext> env = typeEnvs.get(c);
  4214             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
  4215             // because the annotations were not available at the time the env was created. Therefore,
  4216             // we look up the environment chain for the first enclosing environment for which the
  4217             // lint value is set. Typically, this is the parent env, but might be further if there
  4218             // are any envs created as a result of TypeParameter nodes.
  4219             Env<AttrContext> lintEnv = env;
  4220             while (lintEnv.info.lint == null)
  4221                 lintEnv = lintEnv.next;
  4223             // Having found the enclosing lint value, we can initialize the lint value for this class
  4224             env.info.lint = lintEnv.info.lint.augment(c);
  4226             Lint prevLint = chk.setLint(env.info.lint);
  4227             JavaFileObject prev = log.useSource(c.sourcefile);
  4228             ResultInfo prevReturnRes = env.info.returnResult;
  4230             try {
  4231                 deferredLintHandler.flush(env.tree);
  4232                 env.info.returnResult = null;
  4233                 // java.lang.Enum may not be subclassed by a non-enum
  4234                 if (st.tsym == syms.enumSym &&
  4235                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4236                     log.error(env.tree.pos(), "enum.no.subclassing");
  4238                 // Enums may not be extended by source-level classes
  4239                 if (st.tsym != null &&
  4240                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4241                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4242                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4245                 if (isSerializable(c.type)) {
  4246                     env.info.isSerializable = true;
  4249                 attribClassBody(env, c);
  4251                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4252                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4253                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
  4254             } finally {
  4255                 env.info.returnResult = prevReturnRes;
  4256                 log.useSource(prev);
  4257                 chk.setLint(prevLint);
  4263     public void visitImport(JCImport tree) {
  4264         // nothing to do
  4267     /** Finish the attribution of a class. */
  4268     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4269         JCClassDecl tree = (JCClassDecl)env.tree;
  4270         Assert.check(c == tree.sym);
  4272         // Validate type parameters, supertype and interfaces.
  4273         attribStats(tree.typarams, env);
  4274         if (!c.isAnonymous()) {
  4275             //already checked if anonymous
  4276             chk.validate(tree.typarams, env);
  4277             chk.validate(tree.extending, env);
  4278             chk.validate(tree.implementing, env);
  4281         c.markAbstractIfNeeded(types);
  4283         // If this is a non-abstract class, check that it has no abstract
  4284         // methods or unimplemented methods of an implemented interface.
  4285         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4286             if (!relax)
  4287                 chk.checkAllDefined(tree.pos(), c);
  4290         if ((c.flags() & ANNOTATION) != 0) {
  4291             if (tree.implementing.nonEmpty())
  4292                 log.error(tree.implementing.head.pos(),
  4293                           "cant.extend.intf.annotation");
  4294             if (tree.typarams.nonEmpty())
  4295                 log.error(tree.typarams.head.pos(),
  4296                           "intf.annotation.cant.have.type.params");
  4298             // If this annotation has a @Repeatable, validate
  4299             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4300             if (repeatable != null) {
  4301                 // get diagnostic position for error reporting
  4302                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4303                 Assert.checkNonNull(cbPos);
  4305                 chk.validateRepeatable(c, repeatable, cbPos);
  4307         } else {
  4308             // Check that all extended classes and interfaces
  4309             // are compatible (i.e. no two define methods with same arguments
  4310             // yet different return types).  (JLS 8.4.6.3)
  4311             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4312             if (allowDefaultMethods) {
  4313                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4317         // Check that class does not import the same parameterized interface
  4318         // with two different argument lists.
  4319         chk.checkClassBounds(tree.pos(), c.type);
  4321         tree.type = c.type;
  4323         for (List<JCTypeParameter> l = tree.typarams;
  4324              l.nonEmpty(); l = l.tail) {
  4325              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4328         // Check that a generic class doesn't extend Throwable
  4329         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4330             log.error(tree.extending.pos(), "generic.throwable");
  4332         // Check that all methods which implement some
  4333         // method conform to the method they implement.
  4334         chk.checkImplementations(tree);
  4336         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4337         checkAutoCloseable(tree.pos(), env, c.type);
  4339         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4340             // Attribute declaration
  4341             attribStat(l.head, env);
  4342             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4343             // Make an exception for static constants.
  4344             if (c.owner.kind != PCK &&
  4345                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4346                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4347                 Symbol sym = null;
  4348                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4349                 if (sym == null ||
  4350                     sym.kind != VAR ||
  4351                     ((VarSymbol) sym).getConstValue() == null)
  4352                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4356         // Check for cycles among non-initial constructors.
  4357         chk.checkCyclicConstructors(tree);
  4359         // Check for cycles among annotation elements.
  4360         chk.checkNonCyclicElements(tree);
  4362         // Check for proper use of serialVersionUID
  4363         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4364             isSerializable(c.type) &&
  4365             (c.flags() & Flags.ENUM) == 0 &&
  4366             checkForSerial(c)) {
  4367             checkSerialVersionUID(tree, c);
  4369         if (allowTypeAnnos) {
  4370             // Correctly organize the postions of the type annotations
  4371             typeAnnotations.organizeTypeAnnotationsBodies(tree);
  4373             // Check type annotations applicability rules
  4374             validateTypeAnnotations(tree, false);
  4377         // where
  4378         boolean checkForSerial(ClassSymbol c) {
  4379             if ((c.flags() & ABSTRACT) == 0) {
  4380                 return true;
  4381             } else {
  4382                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4386         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
  4387             @Override
  4388             public boolean accepts(Symbol s) {
  4389                 return s.kind == Kinds.MTH &&
  4390                        (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4392         };
  4394         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4395         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4396             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4397                 if (types.isSameType(al.head.annotationType.type, t))
  4398                     return al.head.pos();
  4401             return null;
  4404         /** check if a type is a subtype of Serializable, if that is available. */
  4405         boolean isSerializable(Type t) {
  4406             try {
  4407                 syms.serializableType.complete();
  4409             catch (CompletionFailure e) {
  4410                 return false;
  4412             return types.isSubtype(t, syms.serializableType);
  4415         /** Check that an appropriate serialVersionUID member is defined. */
  4416         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4418             // check for presence of serialVersionUID
  4419             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4420             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4421             if (e.scope == null) {
  4422                 log.warning(LintCategory.SERIAL,
  4423                         tree.pos(), "missing.SVUID", c);
  4424                 return;
  4427             // check that it is static final
  4428             VarSymbol svuid = (VarSymbol)e.sym;
  4429             if ((svuid.flags() & (STATIC | FINAL)) !=
  4430                 (STATIC | FINAL))
  4431                 log.warning(LintCategory.SERIAL,
  4432                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4434             // check that it is long
  4435             else if (!svuid.type.hasTag(LONG))
  4436                 log.warning(LintCategory.SERIAL,
  4437                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4439             // check constant
  4440             else if (svuid.getConstValue() == null)
  4441                 log.warning(LintCategory.SERIAL,
  4442                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4445     private Type capture(Type type) {
  4446         return types.capture(type);
  4449     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
  4450         tree.accept(new TypeAnnotationsValidator(sigOnly));
  4452     //where
  4453     private final class TypeAnnotationsValidator extends TreeScanner {
  4455         private final boolean sigOnly;
  4456         public TypeAnnotationsValidator(boolean sigOnly) {
  4457             this.sigOnly = sigOnly;
  4460         public void visitAnnotation(JCAnnotation tree) {
  4461             chk.validateTypeAnnotation(tree, false);
  4462             super.visitAnnotation(tree);
  4464         public void visitAnnotatedType(JCAnnotatedType tree) {
  4465             if (!tree.underlyingType.type.isErroneous()) {
  4466                 super.visitAnnotatedType(tree);
  4469         public void visitTypeParameter(JCTypeParameter tree) {
  4470             chk.validateTypeAnnotations(tree.annotations, true);
  4471             scan(tree.bounds);
  4472             // Don't call super.
  4473             // This is needed because above we call validateTypeAnnotation with
  4474             // false, which would forbid annotations on type parameters.
  4475             // super.visitTypeParameter(tree);
  4477         public void visitMethodDef(JCMethodDecl tree) {
  4478             if (tree.recvparam != null &&
  4479                     !tree.recvparam.vartype.type.isErroneous()) {
  4480                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4481                         tree.recvparam.vartype.type.tsym);
  4483             if (tree.restype != null && tree.restype.type != null) {
  4484                 validateAnnotatedType(tree.restype, tree.restype.type);
  4486             if (sigOnly) {
  4487                 scan(tree.mods);
  4488                 scan(tree.restype);
  4489                 scan(tree.typarams);
  4490                 scan(tree.recvparam);
  4491                 scan(tree.params);
  4492                 scan(tree.thrown);
  4493             } else {
  4494                 scan(tree.defaultValue);
  4495                 scan(tree.body);
  4498         public void visitVarDef(final JCVariableDecl tree) {
  4499             if (tree.sym != null && tree.sym.type != null)
  4500                 validateAnnotatedType(tree.vartype, tree.sym.type);
  4501             scan(tree.mods);
  4502             scan(tree.vartype);
  4503             if (!sigOnly) {
  4504                 scan(tree.init);
  4507         public void visitTypeCast(JCTypeCast tree) {
  4508             if (tree.clazz != null && tree.clazz.type != null)
  4509                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4510             super.visitTypeCast(tree);
  4512         public void visitTypeTest(JCInstanceOf tree) {
  4513             if (tree.clazz != null && tree.clazz.type != null)
  4514                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4515             super.visitTypeTest(tree);
  4517         public void visitNewClass(JCNewClass tree) {
  4518             if (tree.clazz != null && tree.clazz.type != null) {
  4519                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4520                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  4521                             tree.clazz.type.tsym);
  4523                 if (tree.def != null) {
  4524                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
  4527                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4529             super.visitNewClass(tree);
  4531         public void visitNewArray(JCNewArray tree) {
  4532             if (tree.elemtype != null && tree.elemtype.type != null) {
  4533                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4534                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  4535                             tree.elemtype.type.tsym);
  4537                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
  4539             super.visitNewArray(tree);
  4541         public void visitClassDef(JCClassDecl tree) {
  4542             if (sigOnly) {
  4543                 scan(tree.mods);
  4544                 scan(tree.typarams);
  4545                 scan(tree.extending);
  4546                 scan(tree.implementing);
  4548             for (JCTree member : tree.defs) {
  4549                 if (member.hasTag(Tag.CLASSDEF)) {
  4550                     continue;
  4552                 scan(member);
  4555         public void visitBlock(JCBlock tree) {
  4556             if (!sigOnly) {
  4557                 scan(tree.stats);
  4561         /* I would want to model this after
  4562          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4563          * and override visitSelect and visitTypeApply.
  4564          * However, we only set the annotated type in the top-level type
  4565          * of the symbol.
  4566          * Therefore, we need to override each individual location where a type
  4567          * can occur.
  4568          */
  4569         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4570             // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
  4572             if (type.isPrimitiveOrVoid()) {
  4573                 return;
  4576             JCTree enclTr = errtree;
  4577             Type enclTy = type;
  4579             boolean repeat = true;
  4580             while (repeat) {
  4581                 if (enclTr.hasTag(TYPEAPPLY)) {
  4582                     List<Type> tyargs = enclTy.getTypeArguments();
  4583                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
  4584                     if (trargs.length() > 0) {
  4585                         // Nothing to do for diamonds
  4586                         if (tyargs.length() == trargs.length()) {
  4587                             for (int i = 0; i < tyargs.length(); ++i) {
  4588                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
  4591                         // If the lengths don't match, it's either a diamond
  4592                         // or some nested type that redundantly provides
  4593                         // type arguments in the tree.
  4596                     // Look at the clazz part of a generic type
  4597                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
  4600                 if (enclTr.hasTag(SELECT)) {
  4601                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
  4602                     if (enclTy != null &&
  4603                             !enclTy.hasTag(NONE)) {
  4604                         enclTy = enclTy.getEnclosingType();
  4606                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
  4607                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
  4608                     if (enclTy == null ||
  4609                             enclTy.hasTag(NONE)) {
  4610                         if (at.getAnnotations().size() == 1) {
  4611                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
  4612                         } else {
  4613                             ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
  4614                             for (JCAnnotation an : at.getAnnotations()) {
  4615                                 comps.add(an.attribute);
  4617                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
  4619                         repeat = false;
  4621                     enclTr = at.underlyingType;
  4622                     // enclTy doesn't need to be changed
  4623                 } else if (enclTr.hasTag(IDENT)) {
  4624                     repeat = false;
  4625                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
  4626                     JCWildcard wc = (JCWildcard) enclTr;
  4627                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
  4628                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
  4629                     } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
  4630                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
  4631                     } else {
  4632                         // Nothing to do for UNBOUND
  4634                     repeat = false;
  4635                 } else if (enclTr.hasTag(TYPEARRAY)) {
  4636                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
  4637                     validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
  4638                     repeat = false;
  4639                 } else if (enclTr.hasTag(TYPEUNION)) {
  4640                     JCTypeUnion ut = (JCTypeUnion) enclTr;
  4641                     for (JCTree t : ut.getTypeAlternatives()) {
  4642                         validateAnnotatedType(t, t.type);
  4644                     repeat = false;
  4645                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
  4646                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
  4647                     for (JCTree t : it.getBounds()) {
  4648                         validateAnnotatedType(t, t.type);
  4650                     repeat = false;
  4651                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
  4652                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  4653                     repeat = false;
  4654                 } else {
  4655                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
  4656                             " within: "+ errtree + " with kind: " + errtree.getKind());
  4661         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  4662                 Symbol sym) {
  4663             // Ensure that no declaration annotations are present.
  4664             // Note that a tree type might be an AnnotatedType with
  4665             // empty annotations, if only declaration annotations were given.
  4666             // This method will raise an error for such a type.
  4667             for (JCAnnotation ai : annotations) {
  4668                 if (!ai.type.isErroneous() &&
  4669                         typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  4670                     log.error(ai.pos(), "annotation.type.not.applicable");
  4674     };
  4676     // <editor-fold desc="post-attribution visitor">
  4678     /**
  4679      * Handle missing types/symbols in an AST. This routine is useful when
  4680      * the compiler has encountered some errors (which might have ended up
  4681      * terminating attribution abruptly); if the compiler is used in fail-over
  4682      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4683      * prevents NPE to be progagated during subsequent compilation steps.
  4684      */
  4685     public void postAttr(JCTree tree) {
  4686         new PostAttrAnalyzer().scan(tree);
  4689     class PostAttrAnalyzer extends TreeScanner {
  4691         private void initTypeIfNeeded(JCTree that) {
  4692             if (that.type == null) {
  4693                 if (that.hasTag(METHODDEF)) {
  4694                     that.type = dummyMethodType((JCMethodDecl)that);
  4695                 } else {
  4696                     that.type = syms.unknownType;
  4701         /* Construct a dummy method type. If we have a method declaration,
  4702          * and the declared return type is void, then use that return type
  4703          * instead of UNKNOWN to avoid spurious error messages in lambda
  4704          * bodies (see:JDK-8041704).
  4705          */
  4706         private Type dummyMethodType(JCMethodDecl md) {
  4707             Type restype = syms.unknownType;
  4708             if (md != null && md.restype.hasTag(TYPEIDENT)) {
  4709                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
  4710                 if (prim.typetag == VOID)
  4711                     restype = syms.voidType;
  4713             return new MethodType(List.<Type>nil(), restype,
  4714                                   List.<Type>nil(), syms.methodClass);
  4716         private Type dummyMethodType() {
  4717             return dummyMethodType(null);
  4720         @Override
  4721         public void scan(JCTree tree) {
  4722             if (tree == null) return;
  4723             if (tree instanceof JCExpression) {
  4724                 initTypeIfNeeded(tree);
  4726             super.scan(tree);
  4729         @Override
  4730         public void visitIdent(JCIdent that) {
  4731             if (that.sym == null) {
  4732                 that.sym = syms.unknownSymbol;
  4736         @Override
  4737         public void visitSelect(JCFieldAccess that) {
  4738             if (that.sym == null) {
  4739                 that.sym = syms.unknownSymbol;
  4741             super.visitSelect(that);
  4744         @Override
  4745         public void visitClassDef(JCClassDecl that) {
  4746             initTypeIfNeeded(that);
  4747             if (that.sym == null) {
  4748                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4750             super.visitClassDef(that);
  4753         @Override
  4754         public void visitMethodDef(JCMethodDecl that) {
  4755             initTypeIfNeeded(that);
  4756             if (that.sym == null) {
  4757                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4759             super.visitMethodDef(that);
  4762         @Override
  4763         public void visitVarDef(JCVariableDecl that) {
  4764             initTypeIfNeeded(that);
  4765             if (that.sym == null) {
  4766                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4767                 that.sym.adr = 0;
  4769             super.visitVarDef(that);
  4772         @Override
  4773         public void visitNewClass(JCNewClass that) {
  4774             if (that.constructor == null) {
  4775                 that.constructor = new MethodSymbol(0, names.init,
  4776                         dummyMethodType(), syms.noSymbol);
  4778             if (that.constructorType == null) {
  4779                 that.constructorType = syms.unknownType;
  4781             super.visitNewClass(that);
  4784         @Override
  4785         public void visitAssignop(JCAssignOp that) {
  4786             if (that.operator == null) {
  4787                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4788                         -1, syms.noSymbol);
  4790             super.visitAssignop(that);
  4793         @Override
  4794         public void visitBinary(JCBinary that) {
  4795             if (that.operator == null) {
  4796                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4797                         -1, syms.noSymbol);
  4799             super.visitBinary(that);
  4802         @Override
  4803         public void visitUnary(JCUnary that) {
  4804             if (that.operator == null) {
  4805                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  4806                         -1, syms.noSymbol);
  4808             super.visitUnary(that);
  4811         @Override
  4812         public void visitLambda(JCLambda that) {
  4813             super.visitLambda(that);
  4814             if (that.targets == null) {
  4815                 that.targets = List.nil();
  4819         @Override
  4820         public void visitReference(JCMemberReference that) {
  4821             super.visitReference(that);
  4822             if (that.sym == null) {
  4823                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
  4824                         syms.noSymbol);
  4826             if (that.targets == null) {
  4827                 that.targets = List.nil();
  4831     // </editor-fold>

mercurial