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

Thu, 06 Jun 2013 15:37:23 +0100

author
mcimadamore
date
Thu, 06 Jun 2013 15:37:23 +0100
changeset 1813
f218bb5ebd53
parent 1812
f8472e561a97
child 1820
6b48ebae2569
permissions
-rw-r--r--

8015648: Duplicate variable in lambda causes javac crash
Summary: Missing flag in synthetic lambda blog is causing duplicates symbol to go undetected
Reviewed-by: jjg, vromero

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import javax.lang.model.element.ElementKind;
    31 import javax.lang.model.type.TypeKind;
    32 import javax.tools.JavaFileObject;
    34 import com.sun.source.tree.IdentifierTree;
    35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    36 import com.sun.source.tree.MemberSelectTree;
    37 import com.sun.source.tree.TreeVisitor;
    38 import com.sun.source.util.SimpleTreeVisitor;
    39 import com.sun.tools.javac.code.*;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.comp.Check.CheckContext;
    44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    45 import com.sun.tools.javac.comp.Infer.InferenceContext;
    46 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    47 import com.sun.tools.javac.jvm.*;
    48 import com.sun.tools.javac.tree.*;
    49 import com.sun.tools.javac.tree.JCTree.*;
    50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    51 import com.sun.tools.javac.util.*;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    53 import com.sun.tools.javac.util.List;
    54 import static com.sun.tools.javac.code.Flags.*;
    55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    56 import static com.sun.tools.javac.code.Flags.BLOCK;
    57 import static com.sun.tools.javac.code.Kinds.*;
    58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
    59 import static com.sun.tools.javac.code.TypeTag.*;
    60 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    61 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    63 /** This is the main context-dependent analysis phase in GJC. It
    64  *  encompasses name resolution, type checking and constant folding as
    65  *  subtasks. Some subtasks involve auxiliary classes.
    66  *  @see Check
    67  *  @see Resolve
    68  *  @see ConstFold
    69  *  @see Infer
    70  *
    71  *  <p><b>This is NOT part of any supported API.
    72  *  If you write code that depends on this, you do so at your own risk.
    73  *  This code and its internal interfaces are subject to change or
    74  *  deletion without notice.</b>
    75  */
    76 public class Attr extends JCTree.Visitor {
    77     protected static final Context.Key<Attr> attrKey =
    78         new Context.Key<Attr>();
    80     final Names names;
    81     final Log log;
    82     final Symtab syms;
    83     final Resolve rs;
    84     final Infer infer;
    85     final DeferredAttr deferredAttr;
    86     final Check chk;
    87     final Flow flow;
    88     final MemberEnter memberEnter;
    89     final TreeMaker make;
    90     final ConstFold cfolder;
    91     final Enter enter;
    92     final Target target;
    93     final Types types;
    94     final JCDiagnostic.Factory diags;
    95     final Annotate annotate;
    96     final DeferredLintHandler deferredLintHandler;
    98     public static Attr instance(Context context) {
    99         Attr instance = context.get(attrKey);
   100         if (instance == null)
   101             instance = new Attr(context);
   102         return instance;
   103     }
   105     protected Attr(Context context) {
   106         context.put(attrKey, this);
   108         names = Names.instance(context);
   109         log = Log.instance(context);
   110         syms = Symtab.instance(context);
   111         rs = Resolve.instance(context);
   112         chk = Check.instance(context);
   113         flow = Flow.instance(context);
   114         memberEnter = MemberEnter.instance(context);
   115         make = TreeMaker.instance(context);
   116         enter = Enter.instance(context);
   117         infer = Infer.instance(context);
   118         deferredAttr = DeferredAttr.instance(context);
   119         cfolder = ConstFold.instance(context);
   120         target = Target.instance(context);
   121         types = Types.instance(context);
   122         diags = JCDiagnostic.Factory.instance(context);
   123         annotate = Annotate.instance(context);
   124         deferredLintHandler = DeferredLintHandler.instance(context);
   126         Options options = Options.instance(context);
   128         Source source = Source.instance(context);
   129         allowGenerics = source.allowGenerics();
   130         allowVarargs = source.allowVarargs();
   131         allowEnums = source.allowEnums();
   132         allowBoxing = source.allowBoxing();
   133         allowCovariantReturns = source.allowCovariantReturns();
   134         allowAnonOuterThis = source.allowAnonOuterThis();
   135         allowStringsInSwitch = source.allowStringsInSwitch();
   136         allowPoly = source.allowPoly();
   137         allowLambda = source.allowLambda();
   138         allowDefaultMethods = source.allowDefaultMethods();
   139         sourceName = source.name;
   140         relax = (options.isSet("-retrofit") ||
   141                  options.isSet("-relax"));
   142         findDiamonds = options.get("findDiamond") != null &&
   143                  source.allowDiamond();
   144         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   145         identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
   147         statInfo = new ResultInfo(NIL, Type.noType);
   148         varInfo = new ResultInfo(VAR, Type.noType);
   149         unknownExprInfo = new ResultInfo(VAL, Type.noType);
   150         unknownTypeInfo = new ResultInfo(TYP, Type.noType);
   151         unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
   152         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   153     }
   155     /** Switch: relax some constraints for retrofit mode.
   156      */
   157     boolean relax;
   159     /** Switch: support target-typing inference
   160      */
   161     boolean allowPoly;
   163     /** Switch: support generics?
   164      */
   165     boolean allowGenerics;
   167     /** Switch: allow variable-arity methods.
   168      */
   169     boolean allowVarargs;
   171     /** Switch: support enums?
   172      */
   173     boolean allowEnums;
   175     /** Switch: support boxing and unboxing?
   176      */
   177     boolean allowBoxing;
   179     /** Switch: support covariant result types?
   180      */
   181     boolean allowCovariantReturns;
   183     /** Switch: support lambda expressions ?
   184      */
   185     boolean allowLambda;
   187     /** Switch: support default methods ?
   188      */
   189     boolean allowDefaultMethods;
   191     /** Switch: allow references to surrounding object from anonymous
   192      * objects during constructor call?
   193      */
   194     boolean allowAnonOuterThis;
   196     /** Switch: generates a warning if diamond can be safely applied
   197      *  to a given new expression
   198      */
   199     boolean findDiamonds;
   201     /**
   202      * Internally enables/disables diamond finder feature
   203      */
   204     static final boolean allowDiamondFinder = true;
   206     /**
   207      * Switch: warn about use of variable before declaration?
   208      * RFE: 6425594
   209      */
   210     boolean useBeforeDeclarationWarning;
   212     /**
   213      * Switch: generate warnings whenever an anonymous inner class that is convertible
   214      * to a lambda expression is found
   215      */
   216     boolean identifyLambdaCandidate;
   218     /**
   219      * Switch: allow strings in switch?
   220      */
   221     boolean allowStringsInSwitch;
   223     /**
   224      * Switch: name of source level; used for error reporting.
   225      */
   226     String sourceName;
   228     /** Check kind and type of given tree against protokind and prototype.
   229      *  If check succeeds, store type in tree and return it.
   230      *  If check fails, store errType in tree and return it.
   231      *  No checks are performed if the prototype is a method type.
   232      *  It is not necessary in this case since we know that kind and type
   233      *  are correct.
   234      *
   235      *  @param tree     The tree whose kind and type is checked
   236      *  @param ownkind  The computed kind of the tree
   237      *  @param resultInfo  The expected result of the tree
   238      */
   239     Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
   240         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   241         Type owntype = found;
   242         if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
   243             if (inferenceContext.free(found)) {
   244                 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
   245                     @Override
   246                     public void typesInferred(InferenceContext inferenceContext) {
   247                         ResultInfo pendingResult =
   248                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   249                         check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   250                     }
   251                 });
   252                 return tree.type = resultInfo.pt;
   253             } else {
   254                 if ((ownkind & ~resultInfo.pkind) == 0) {
   255                     owntype = resultInfo.check(tree, owntype);
   256                 } else {
   257                     log.error(tree.pos(), "unexpected.type",
   258                             kindNames(resultInfo.pkind),
   259                             kindName(ownkind));
   260                     owntype = types.createErrorType(owntype);
   261                 }
   262             }
   263         }
   264         tree.type = owntype;
   265         return owntype;
   266     }
   268     /** Is given blank final variable assignable, i.e. in a scope where it
   269      *  may be assigned to even though it is final?
   270      *  @param v      The blank final variable.
   271      *  @param env    The current environment.
   272      */
   273     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   274         Symbol owner = owner(env);
   275            // owner refers to the innermost variable, method or
   276            // initializer block declaration at this point.
   277         return
   278             v.owner == owner
   279             ||
   280             ((owner.name == names.init ||    // i.e. we are in a constructor
   281               owner.kind == VAR ||           // i.e. we are in a variable initializer
   282               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   283              &&
   284              v.owner == owner.owner
   285              &&
   286              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   287     }
   289     /**
   290      * Return the innermost enclosing owner symbol in a given attribution context
   291      */
   292     Symbol owner(Env<AttrContext> env) {
   293         while (true) {
   294             switch (env.tree.getTag()) {
   295                 case VARDEF:
   296                     //a field can be owner
   297                     VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
   298                     if (vsym.owner.kind == TYP) {
   299                         return vsym;
   300                     }
   301                     break;
   302                 case METHODDEF:
   303                     //method def is always an owner
   304                     return ((JCMethodDecl)env.tree).sym;
   305                 case CLASSDEF:
   306                     //class def is always an owner
   307                     return ((JCClassDecl)env.tree).sym;
   308                 case LAMBDA:
   309                     //a lambda is an owner - return a fresh synthetic method symbol
   310                     return new MethodSymbol(0, names.empty, null, syms.methodClass);
   311                 case BLOCK:
   312                     //static/instance init blocks are owner
   313                     Symbol blockSym = env.info.scope.owner;
   314                     if ((blockSym.flags() & BLOCK) != 0) {
   315                         return blockSym;
   316                     }
   317                     break;
   318                 case TOPLEVEL:
   319                     //toplevel is always an owner (for pkge decls)
   320                     return env.info.scope.owner;
   321             }
   322             Assert.checkNonNull(env.next);
   323             env = env.next;
   324         }
   325     }
   327     /** Check that variable can be assigned to.
   328      *  @param pos    The current source code position.
   329      *  @param v      The assigned varaible
   330      *  @param base   If the variable is referred to in a Select, the part
   331      *                to the left of the `.', null otherwise.
   332      *  @param env    The current environment.
   333      */
   334     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   335         if ((v.flags() & FINAL) != 0 &&
   336             ((v.flags() & HASINIT) != 0
   337              ||
   338              !((base == null ||
   339                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   340                isAssignableAsBlankFinal(v, env)))) {
   341             if (v.isResourceVariable()) { //TWR resource
   342                 log.error(pos, "try.resource.may.not.be.assigned", v);
   343             } else {
   344                 log.error(pos, "cant.assign.val.to.final.var", v);
   345             }
   346         }
   347     }
   349     /** Does tree represent a static reference to an identifier?
   350      *  It is assumed that tree is either a SELECT or an IDENT.
   351      *  We have to weed out selects from non-type names here.
   352      *  @param tree    The candidate tree.
   353      */
   354     boolean isStaticReference(JCTree tree) {
   355         if (tree.hasTag(SELECT)) {
   356             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   357             if (lsym == null || lsym.kind != TYP) {
   358                 return false;
   359             }
   360         }
   361         return true;
   362     }
   364     /** Is this symbol a type?
   365      */
   366     static boolean isType(Symbol sym) {
   367         return sym != null && sym.kind == TYP;
   368     }
   370     /** The current `this' symbol.
   371      *  @param env    The current environment.
   372      */
   373     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   374         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   375     }
   377     /** Attribute a parsed identifier.
   378      * @param tree Parsed identifier name
   379      * @param topLevel The toplevel to use
   380      */
   381     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   382         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   383         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   384                                            syms.errSymbol.name,
   385                                            null, null, null, null);
   386         localEnv.enclClass.sym = syms.errSymbol;
   387         return tree.accept(identAttributer, localEnv);
   388     }
   389     // where
   390         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   391         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   392             @Override
   393             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   394                 Symbol site = visit(node.getExpression(), env);
   395                 if (site.kind == ERR)
   396                     return site;
   397                 Name name = (Name)node.getIdentifier();
   398                 if (site.kind == PCK) {
   399                     env.toplevel.packge = (PackageSymbol)site;
   400                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
   401                 } else {
   402                     env.enclClass.sym = (ClassSymbol)site;
   403                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   404                 }
   405             }
   407             @Override
   408             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   409                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
   410             }
   411         }
   413     public Type coerce(Type etype, Type ttype) {
   414         return cfolder.coerce(etype, ttype);
   415     }
   417     public Type attribType(JCTree node, TypeSymbol sym) {
   418         Env<AttrContext> env = enter.typeEnvs.get(sym);
   419         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   420         return attribTree(node, localEnv, unknownTypeInfo);
   421     }
   423     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   424         // Attribute qualifying package or class.
   425         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   426         return attribTree(s.selected,
   427                        env,
   428                        new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
   429                        Type.noType));
   430     }
   432     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   433         breakTree = tree;
   434         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   435         try {
   436             attribExpr(expr, env);
   437         } catch (BreakAttr b) {
   438             return b.env;
   439         } catch (AssertionError ae) {
   440             if (ae.getCause() instanceof BreakAttr) {
   441                 return ((BreakAttr)(ae.getCause())).env;
   442             } else {
   443                 throw ae;
   444             }
   445         } finally {
   446             breakTree = null;
   447             log.useSource(prev);
   448         }
   449         return env;
   450     }
   452     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   453         breakTree = tree;
   454         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   455         try {
   456             attribStat(stmt, env);
   457         } catch (BreakAttr b) {
   458             return b.env;
   459         } catch (AssertionError ae) {
   460             if (ae.getCause() instanceof BreakAttr) {
   461                 return ((BreakAttr)(ae.getCause())).env;
   462             } else {
   463                 throw ae;
   464             }
   465         } finally {
   466             breakTree = null;
   467             log.useSource(prev);
   468         }
   469         return env;
   470     }
   472     private JCTree breakTree = null;
   474     private static class BreakAttr extends RuntimeException {
   475         static final long serialVersionUID = -6924771130405446405L;
   476         private Env<AttrContext> env;
   477         private BreakAttr(Env<AttrContext> env) {
   478             this.env = copyEnv(env);
   479         }
   481         private Env<AttrContext> copyEnv(Env<AttrContext> env) {
   482             Env<AttrContext> newEnv =
   483                     env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   484             if (newEnv.outer != null) {
   485                 newEnv.outer = copyEnv(newEnv.outer);
   486             }
   487             return newEnv;
   488         }
   490         private Scope copyScope(Scope sc) {
   491             Scope newScope = new Scope(sc.owner);
   492             List<Symbol> elemsList = List.nil();
   493             while (sc != null) {
   494                 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
   495                     elemsList = elemsList.prepend(e.sym);
   496                 }
   497                 sc = sc.next;
   498             }
   499             for (Symbol s : elemsList) {
   500                 newScope.enter(s);
   501             }
   502             return newScope;
   503         }
   504     }
   506     class ResultInfo {
   507         final int pkind;
   508         final Type pt;
   509         final CheckContext checkContext;
   511         ResultInfo(int pkind, Type pt) {
   512             this(pkind, pt, chk.basicHandler);
   513         }
   515         protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
   516             this.pkind = pkind;
   517             this.pt = pt;
   518             this.checkContext = checkContext;
   519         }
   521         protected Type check(final DiagnosticPosition pos, final Type found) {
   522             return chk.checkType(pos, found, pt, checkContext);
   523         }
   525         protected ResultInfo dup(Type newPt) {
   526             return new ResultInfo(pkind, newPt, checkContext);
   527         }
   529         protected ResultInfo dup(CheckContext newContext) {
   530             return new ResultInfo(pkind, pt, newContext);
   531         }
   532     }
   534     class RecoveryInfo extends ResultInfo {
   536         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   537             super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
   538                 @Override
   539                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   540                     return deferredAttrContext;
   541                 }
   542                 @Override
   543                 public boolean compatible(Type found, Type req, Warner warn) {
   544                     return true;
   545                 }
   546                 @Override
   547                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   548                     chk.basicHandler.report(pos, details);
   549                 }
   550             });
   551         }
   553         @Override
   554         protected Type check(DiagnosticPosition pos, Type found) {
   555             return chk.checkNonVoid(pos, super.check(pos, found));
   556         }
   557     }
   559     final ResultInfo statInfo;
   560     final ResultInfo varInfo;
   561     final ResultInfo unknownExprInfo;
   562     final ResultInfo unknownTypeInfo;
   563     final ResultInfo unknownTypeExprInfo;
   564     final ResultInfo recoveryInfo;
   566     Type pt() {
   567         return resultInfo.pt;
   568     }
   570     int pkind() {
   571         return resultInfo.pkind;
   572     }
   574 /* ************************************************************************
   575  * Visitor methods
   576  *************************************************************************/
   578     /** Visitor argument: the current environment.
   579      */
   580     Env<AttrContext> env;
   582     /** Visitor argument: the currently expected attribution result.
   583      */
   584     ResultInfo resultInfo;
   586     /** Visitor result: the computed type.
   587      */
   588     Type result;
   590     /** Visitor method: attribute a tree, catching any completion failure
   591      *  exceptions. Return the tree's type.
   592      *
   593      *  @param tree    The tree to be visited.
   594      *  @param env     The environment visitor argument.
   595      *  @param resultInfo   The result info visitor argument.
   596      */
   597     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   598         Env<AttrContext> prevEnv = this.env;
   599         ResultInfo prevResult = this.resultInfo;
   600         try {
   601             this.env = env;
   602             this.resultInfo = resultInfo;
   603             tree.accept(this);
   604             if (tree == breakTree &&
   605                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   606                 throw new BreakAttr(env);
   607             }
   608             return result;
   609         } catch (CompletionFailure ex) {
   610             tree.type = syms.errType;
   611             return chk.completionError(tree.pos(), ex);
   612         } finally {
   613             this.env = prevEnv;
   614             this.resultInfo = prevResult;
   615         }
   616     }
   618     /** Derived visitor method: attribute an expression tree.
   619      */
   620     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   621         return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
   622     }
   624     /** Derived visitor method: attribute an expression tree with
   625      *  no constraints on the computed type.
   626      */
   627     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   628         return attribTree(tree, env, unknownExprInfo);
   629     }
   631     /** Derived visitor method: attribute a type tree.
   632      */
   633     public Type attribType(JCTree tree, Env<AttrContext> env) {
   634         Type result = attribType(tree, env, Type.noType);
   635         return result;
   636     }
   638     /** Derived visitor method: attribute a type tree.
   639      */
   640     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   641         Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
   642         return result;
   643     }
   645     /** Derived visitor method: attribute a statement or definition tree.
   646      */
   647     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   648         return attribTree(tree, env, statInfo);
   649     }
   651     /** Attribute a list of expressions, returning a list of types.
   652      */
   653     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   654         ListBuffer<Type> ts = new ListBuffer<Type>();
   655         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   656             ts.append(attribExpr(l.head, env, pt));
   657         return ts.toList();
   658     }
   660     /** Attribute a list of statements, returning nothing.
   661      */
   662     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   663         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   664             attribStat(l.head, env);
   665     }
   667     /** Attribute the arguments in a method call, returning a list of types.
   668      */
   669     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
   670         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   671         for (JCExpression arg : trees) {
   672             Type argtype = allowPoly && deferredAttr.isDeferred(env, arg) ?
   673                     deferredAttr.new DeferredType(arg, env) :
   674                     chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
   675             argtypes.append(argtype);
   676         }
   677         return argtypes.toList();
   678     }
   680     /** Attribute a type argument list, returning a list of types.
   681      *  Caller is responsible for calling checkRefTypes.
   682      */
   683     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   684         ListBuffer<Type> argtypes = new ListBuffer<Type>();
   685         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   686             argtypes.append(attribType(l.head, env));
   687         return argtypes.toList();
   688     }
   690     /** Attribute a type argument list, returning a list of types.
   691      *  Check that all the types are references.
   692      */
   693     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   694         List<Type> types = attribAnyTypes(trees, env);
   695         return chk.checkRefTypes(trees, types);
   696     }
   698     /**
   699      * Attribute type variables (of generic classes or methods).
   700      * Compound types are attributed later in attribBounds.
   701      * @param typarams the type variables to enter
   702      * @param env      the current environment
   703      */
   704     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   705         for (JCTypeParameter tvar : typarams) {
   706             TypeVar a = (TypeVar)tvar.type;
   707             a.tsym.flags_field |= UNATTRIBUTED;
   708             a.bound = Type.noType;
   709             if (!tvar.bounds.isEmpty()) {
   710                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   711                 for (JCExpression bound : tvar.bounds.tail)
   712                     bounds = bounds.prepend(attribType(bound, env));
   713                 types.setBounds(a, bounds.reverse());
   714             } else {
   715                 // if no bounds are given, assume a single bound of
   716                 // java.lang.Object.
   717                 types.setBounds(a, List.of(syms.objectType));
   718             }
   719             a.tsym.flags_field &= ~UNATTRIBUTED;
   720         }
   721         for (JCTypeParameter tvar : typarams) {
   722             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   723         }
   724     }
   726     /**
   727      * Attribute the type references in a list of annotations.
   728      */
   729     void attribAnnotationTypes(List<JCAnnotation> annotations,
   730                                Env<AttrContext> env) {
   731         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   732             JCAnnotation a = al.head;
   733             attribType(a.annotationType, env);
   734         }
   735     }
   737     /**
   738      * Attribute a "lazy constant value".
   739      *  @param env         The env for the const value
   740      *  @param initializer The initializer for the const value
   741      *  @param type        The expected type, or null
   742      *  @see VarSymbol#setLazyConstValue
   743      */
   744     public Object attribLazyConstantValue(Env<AttrContext> env,
   745                                       JCTree.JCExpression initializer,
   746                                       Type type) {
   748         // in case no lint value has been set up for this env, scan up
   749         // env stack looking for smallest enclosing env for which it is set.
   750         Env<AttrContext> lintEnv = env;
   751         while (lintEnv.info.lint == null)
   752             lintEnv = lintEnv.next;
   754         // Having found the enclosing lint value, we can initialize the lint value for this class
   755         // ... but ...
   756         // There's a problem with evaluating annotations in the right order, such that
   757         // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
   758         // null. In that case, calling augment will throw an NPE. To avoid this, for now we
   759         // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
   760         if (env.info.enclVar.annotationsPendingCompletion()) {
   761             env.info.lint = lintEnv.info.lint;
   762         } else {
   763             env.info.lint = lintEnv.info.lint.augment(env.info.enclVar);
   764         }
   766         Lint prevLint = chk.setLint(env.info.lint);
   767         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   769         try {
   770             // Use null as symbol to not attach the type annotation to any symbol.
   771             // The initializer will later also be visited and then we'll attach
   772             // to the symbol.
   773             // This prevents having multiple type annotations, just because of
   774             // lazy constant value evaluation.
   775             memberEnter.typeAnnotate(initializer, env, null);
   776             annotate.flush();
   777             Type itype = attribExpr(initializer, env, type);
   778             if (itype.constValue() != null)
   779                 return coerce(itype, type).constValue();
   780             else
   781                 return null;
   782         } finally {
   783             env.info.lint = prevLint;
   784             log.useSource(prevSource);
   785         }
   786     }
   788     /** Attribute type reference in an `extends' or `implements' clause.
   789      *  Supertypes of anonymous inner classes are usually already attributed.
   790      *
   791      *  @param tree              The tree making up the type reference.
   792      *  @param env               The environment current at the reference.
   793      *  @param classExpected     true if only a class is expected here.
   794      *  @param interfaceExpected true if only an interface is expected here.
   795      */
   796     Type attribBase(JCTree tree,
   797                     Env<AttrContext> env,
   798                     boolean classExpected,
   799                     boolean interfaceExpected,
   800                     boolean checkExtensible) {
   801         Type t = tree.type != null ?
   802             tree.type :
   803             attribType(tree, env);
   804         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   805     }
   806     Type checkBase(Type t,
   807                    JCTree tree,
   808                    Env<AttrContext> env,
   809                    boolean classExpected,
   810                    boolean interfaceExpected,
   811                    boolean checkExtensible) {
   812         if (t.isErroneous())
   813             return t;
   814         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   815             // check that type variable is already visible
   816             if (t.getUpperBound() == null) {
   817                 log.error(tree.pos(), "illegal.forward.ref");
   818                 return types.createErrorType(t);
   819             }
   820         } else {
   821             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
   822         }
   823         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   824             log.error(tree.pos(), "intf.expected.here");
   825             // return errType is necessary since otherwise there might
   826             // be undetected cycles which cause attribution to loop
   827             return types.createErrorType(t);
   828         } else if (checkExtensible &&
   829                    classExpected &&
   830                    (t.tsym.flags() & INTERFACE) != 0) {
   831                 log.error(tree.pos(), "no.intf.expected.here");
   832             return types.createErrorType(t);
   833         }
   834         if (checkExtensible &&
   835             ((t.tsym.flags() & FINAL) != 0)) {
   836             log.error(tree.pos(),
   837                       "cant.inherit.from.final", t.tsym);
   838         }
   839         chk.checkNonCyclic(tree.pos(), t);
   840         return t;
   841     }
   843     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   844         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
   845         id.type = env.info.scope.owner.type;
   846         id.sym = env.info.scope.owner;
   847         return id.type;
   848     }
   850     public void visitClassDef(JCClassDecl tree) {
   851         // Local classes have not been entered yet, so we need to do it now:
   852         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
   853             enter.classEnter(tree, env);
   855         ClassSymbol c = tree.sym;
   856         if (c == null) {
   857             // exit in case something drastic went wrong during enter.
   858             result = null;
   859         } else {
   860             // make sure class has been completed:
   861             c.complete();
   863             // If this class appears as an anonymous class
   864             // in a superclass constructor call where
   865             // no explicit outer instance is given,
   866             // disable implicit outer instance from being passed.
   867             // (This would be an illegal access to "this before super").
   868             if (env.info.isSelfCall &&
   869                 env.tree.hasTag(NEWCLASS) &&
   870                 ((JCNewClass) env.tree).encl == null)
   871             {
   872                 c.flags_field |= NOOUTERTHIS;
   873             }
   874             attribClass(tree.pos(), c);
   875             result = tree.type = c.type;
   876         }
   877     }
   879     public void visitMethodDef(JCMethodDecl tree) {
   880         MethodSymbol m = tree.sym;
   881         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   883         Lint lint = env.info.lint.augment(m);
   884         Lint prevLint = chk.setLint(lint);
   885         MethodSymbol prevMethod = chk.setMethod(m);
   886         try {
   887             deferredLintHandler.flush(tree.pos());
   888             chk.checkDeprecatedAnnotation(tree.pos(), m);
   891             // Create a new environment with local scope
   892             // for attributing the method.
   893             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
   894             localEnv.info.lint = lint;
   896             attribStats(tree.typarams, localEnv);
   898             // If we override any other methods, check that we do so properly.
   899             // JLS ???
   900             if (m.isStatic()) {
   901                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
   902             } else {
   903                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
   904             }
   905             chk.checkOverride(tree, m);
   907             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
   908                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
   909             }
   911             // Enter all type parameters into the local method scope.
   912             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   913                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   915             ClassSymbol owner = env.enclClass.sym;
   916             if ((owner.flags() & ANNOTATION) != 0 &&
   917                 tree.params.nonEmpty())
   918                 log.error(tree.params.head.pos(),
   919                           "intf.annotation.members.cant.have.params");
   921             // Attribute all value parameters.
   922             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   923                 attribStat(l.head, localEnv);
   924             }
   926             chk.checkVarargsMethodDecl(localEnv, tree);
   928             // Check that type parameters are well-formed.
   929             chk.validate(tree.typarams, localEnv);
   931             // Check that result type is well-formed.
   932             chk.validate(tree.restype, localEnv);
   934             // Check that receiver type is well-formed.
   935             if (tree.recvparam != null) {
   936                 // Use a new environment to check the receiver parameter.
   937                 // Otherwise I get "might not have been initialized" errors.
   938                 // Is there a better way?
   939                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
   940                 attribType(tree.recvparam, newEnv);
   941                 chk.validate(tree.recvparam, newEnv);
   942             }
   944             // annotation method checks
   945             if ((owner.flags() & ANNOTATION) != 0) {
   946                 // annotation method cannot have throws clause
   947                 if (tree.thrown.nonEmpty()) {
   948                     log.error(tree.thrown.head.pos(),
   949                             "throws.not.allowed.in.intf.annotation");
   950                 }
   951                 // annotation method cannot declare type-parameters
   952                 if (tree.typarams.nonEmpty()) {
   953                     log.error(tree.typarams.head.pos(),
   954                             "intf.annotation.members.cant.have.type.params");
   955                 }
   956                 // validate annotation method's return type (could be an annotation type)
   957                 chk.validateAnnotationType(tree.restype);
   958                 // ensure that annotation method does not clash with members of Object/Annotation
   959                 chk.validateAnnotationMethod(tree.pos(), m);
   961                 if (tree.defaultValue != null) {
   962                     // if default value is an annotation, check it is a well-formed
   963                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   964                     chk.validateAnnotationTree(tree.defaultValue);
   965                 }
   966             }
   968             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
   969                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
   971             if (tree.body == null) {
   972                 // Empty bodies are only allowed for
   973                 // abstract, native, or interface methods, or for methods
   974                 // in a retrofit signature class.
   975                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
   976                     !relax)
   977                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
   978                 if (tree.defaultValue != null) {
   979                     if ((owner.flags() & ANNOTATION) == 0)
   980                         log.error(tree.pos(),
   981                                   "default.allowed.in.intf.annotation.member");
   982                 }
   983             } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
   984                 if ((owner.flags() & INTERFACE) != 0) {
   985                     log.error(tree.body.pos(), "intf.meth.cant.have.body");
   986                 } else {
   987                     log.error(tree.pos(), "abstract.meth.cant.have.body");
   988                 }
   989             } else if ((tree.mods.flags & NATIVE) != 0) {
   990                 log.error(tree.pos(), "native.meth.cant.have.body");
   991             } else {
   992                 // Add an implicit super() call unless an explicit call to
   993                 // super(...) or this(...) is given
   994                 // or we are compiling class java.lang.Object.
   995                 if (tree.name == names.init && owner.type != syms.objectType) {
   996                     JCBlock body = tree.body;
   997                     if (body.stats.isEmpty() ||
   998                         !TreeInfo.isSelfCall(body.stats.head)) {
   999                         body.stats = body.stats.
  1000                             prepend(memberEnter.SuperCall(make.at(body.pos),
  1001                                                           List.<Type>nil(),
  1002                                                           List.<JCVariableDecl>nil(),
  1003                                                           false));
  1004                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1005                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1006                                TreeInfo.isSuperCall(body.stats.head)) {
  1007                         // enum constructors are not allowed to call super
  1008                         // directly, so make sure there aren't any super calls
  1009                         // in enum constructors, except in the compiler
  1010                         // generated one.
  1011                         log.error(tree.body.stats.head.pos(),
  1012                                   "call.to.super.not.allowed.in.enum.ctor",
  1013                                   env.enclClass.sym);
  1017                 // Attribute all type annotations in the body
  1018                 memberEnter.typeAnnotate(tree.body, localEnv, m);
  1019                 annotate.flush();
  1021                 // Attribute method body.
  1022                 attribStat(tree.body, localEnv);
  1025             localEnv.info.scope.leave();
  1026             result = tree.type = m.type;
  1027             chk.validateAnnotations(tree.mods.annotations, m);
  1029         finally {
  1030             chk.setLint(prevLint);
  1031             chk.setMethod(prevMethod);
  1035     public void visitVarDef(JCVariableDecl tree) {
  1036         // Local variables have not been entered yet, so we need to do it now:
  1037         if (env.info.scope.owner.kind == MTH) {
  1038             if (tree.sym != null) {
  1039                 // parameters have already been entered
  1040                 env.info.scope.enter(tree.sym);
  1041             } else {
  1042                 memberEnter.memberEnter(tree, env);
  1043                 annotate.flush();
  1045         } else {
  1046             if (tree.init != null) {
  1047                 // Field initializer expression need to be entered.
  1048                 memberEnter.typeAnnotate(tree.init, env, tree.sym);
  1049                 annotate.flush();
  1053         VarSymbol v = tree.sym;
  1054         Lint lint = env.info.lint.augment(v);
  1055         Lint prevLint = chk.setLint(lint);
  1057         // Check that the variable's declared type is well-formed.
  1058         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1059                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1060                 (tree.sym.flags() & PARAMETER) != 0;
  1061         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1062         deferredLintHandler.flush(tree.pos());
  1064         try {
  1065             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1067             if (tree.init != null) {
  1068                 if ((v.flags_field & FINAL) != 0 &&
  1069                         !tree.init.hasTag(NEWCLASS) &&
  1070                         !tree.init.hasTag(LAMBDA) &&
  1071                         !tree.init.hasTag(REFERENCE)) {
  1072                     // In this case, `v' is final.  Ensure that it's initializer is
  1073                     // evaluated.
  1074                     v.getConstValue(); // ensure initializer is evaluated
  1075                 } else {
  1076                     // Attribute initializer in a new environment
  1077                     // with the declared variable as owner.
  1078                     // Check that initializer conforms to variable's declared type.
  1079                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1080                     initEnv.info.lint = lint;
  1081                     // In order to catch self-references, we set the variable's
  1082                     // declaration position to maximal possible value, effectively
  1083                     // marking the variable as undefined.
  1084                     initEnv.info.enclVar = v;
  1085                     attribExpr(tree.init, initEnv, v.type);
  1088             result = tree.type = v.type;
  1089             chk.validateAnnotations(tree.mods.annotations, v);
  1091         finally {
  1092             chk.setLint(prevLint);
  1096     public void visitSkip(JCSkip tree) {
  1097         result = null;
  1100     public void visitBlock(JCBlock tree) {
  1101         if (env.info.scope.owner.kind == TYP) {
  1102             // Block is a static or instance initializer;
  1103             // let the owner of the environment be a freshly
  1104             // created BLOCK-method.
  1105             Env<AttrContext> localEnv =
  1106                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
  1107             localEnv.info.scope.owner =
  1108                 new MethodSymbol(tree.flags | BLOCK |
  1109                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1110                     env.info.scope.owner);
  1111             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1113             // Attribute all type annotations in the block
  1114             memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner);
  1115             annotate.flush();
  1118                 // Store init and clinit type annotations with the ClassSymbol
  1119                 // to allow output in Gen.normalizeDefs.
  1120                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1121                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1122                 if ((tree.flags & STATIC) != 0) {
  1123                     cs.appendClassInitTypeAttributes(tas);
  1124                 } else {
  1125                     cs.appendInitTypeAttributes(tas);
  1129             attribStats(tree.stats, localEnv);
  1130         } else {
  1131             // Create a new local environment with a local scope.
  1132             Env<AttrContext> localEnv =
  1133                 env.dup(tree, env.info.dup(env.info.scope.dup()));
  1134             try {
  1135                 attribStats(tree.stats, localEnv);
  1136             } finally {
  1137                 localEnv.info.scope.leave();
  1140         result = null;
  1143     public void visitDoLoop(JCDoWhileLoop tree) {
  1144         attribStat(tree.body, env.dup(tree));
  1145         attribExpr(tree.cond, env, syms.booleanType);
  1146         result = null;
  1149     public void visitWhileLoop(JCWhileLoop tree) {
  1150         attribExpr(tree.cond, env, syms.booleanType);
  1151         attribStat(tree.body, env.dup(tree));
  1152         result = null;
  1155     public void visitForLoop(JCForLoop tree) {
  1156         Env<AttrContext> loopEnv =
  1157             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1158         try {
  1159             attribStats(tree.init, loopEnv);
  1160             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1161             loopEnv.tree = tree; // before, we were not in loop!
  1162             attribStats(tree.step, loopEnv);
  1163             attribStat(tree.body, loopEnv);
  1164             result = null;
  1166         finally {
  1167             loopEnv.info.scope.leave();
  1171     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1172         Env<AttrContext> loopEnv =
  1173             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1174         try {
  1175             //the Formal Parameter of a for-each loop is not in the scope when
  1176             //attributing the for-each expression; we mimick this by attributing
  1177             //the for-each expression first (against original scope).
  1178             Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
  1179             attribStat(tree.var, loopEnv);
  1180             chk.checkNonVoid(tree.pos(), exprType);
  1181             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1182             if (elemtype == null) {
  1183                 // or perhaps expr implements Iterable<T>?
  1184                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1185                 if (base == null) {
  1186                     log.error(tree.expr.pos(),
  1187                             "foreach.not.applicable.to.type",
  1188                             exprType,
  1189                             diags.fragment("type.req.array.or.iterable"));
  1190                     elemtype = types.createErrorType(exprType);
  1191                 } else {
  1192                     List<Type> iterableParams = base.allparams();
  1193                     elemtype = iterableParams.isEmpty()
  1194                         ? syms.objectType
  1195                         : types.upperBound(iterableParams.head);
  1198             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1199             loopEnv.tree = tree; // before, we were not in loop!
  1200             attribStat(tree.body, loopEnv);
  1201             result = null;
  1203         finally {
  1204             loopEnv.info.scope.leave();
  1208     public void visitLabelled(JCLabeledStatement tree) {
  1209         // Check that label is not used in an enclosing statement
  1210         Env<AttrContext> env1 = env;
  1211         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1212             if (env1.tree.hasTag(LABELLED) &&
  1213                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1214                 log.error(tree.pos(), "label.already.in.use",
  1215                           tree.label);
  1216                 break;
  1218             env1 = env1.next;
  1221         attribStat(tree.body, env.dup(tree));
  1222         result = null;
  1225     public void visitSwitch(JCSwitch tree) {
  1226         Type seltype = attribExpr(tree.selector, env);
  1228         Env<AttrContext> switchEnv =
  1229             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1231         try {
  1233             boolean enumSwitch =
  1234                 allowEnums &&
  1235                 (seltype.tsym.flags() & Flags.ENUM) != 0;
  1236             boolean stringSwitch = false;
  1237             if (types.isSameType(seltype, syms.stringType)) {
  1238                 if (allowStringsInSwitch) {
  1239                     stringSwitch = true;
  1240                 } else {
  1241                     log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1244             if (!enumSwitch && !stringSwitch)
  1245                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1247             // Attribute all cases and
  1248             // check that there are no duplicate case labels or default clauses.
  1249             Set<Object> labels = new HashSet<Object>(); // The set of case labels.
  1250             boolean hasDefault = false;      // Is there a default label?
  1251             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1252                 JCCase c = l.head;
  1253                 Env<AttrContext> caseEnv =
  1254                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1255                 try {
  1256                     if (c.pat != null) {
  1257                         if (enumSwitch) {
  1258                             Symbol sym = enumConstant(c.pat, seltype);
  1259                             if (sym == null) {
  1260                                 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1261                             } else if (!labels.add(sym)) {
  1262                                 log.error(c.pos(), "duplicate.case.label");
  1264                         } else {
  1265                             Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1266                             if (!pattype.hasTag(ERROR)) {
  1267                                 if (pattype.constValue() == null) {
  1268                                     log.error(c.pat.pos(),
  1269                                               (stringSwitch ? "string.const.req" : "const.expr.req"));
  1270                                 } else if (labels.contains(pattype.constValue())) {
  1271                                     log.error(c.pos(), "duplicate.case.label");
  1272                                 } else {
  1273                                     labels.add(pattype.constValue());
  1277                     } else if (hasDefault) {
  1278                         log.error(c.pos(), "duplicate.default.label");
  1279                     } else {
  1280                         hasDefault = true;
  1282                     attribStats(c.stats, caseEnv);
  1283                 } finally {
  1284                     caseEnv.info.scope.leave();
  1285                     addVars(c.stats, switchEnv.info.scope);
  1289             result = null;
  1291         finally {
  1292             switchEnv.info.scope.leave();
  1295     // where
  1296         /** Add any variables defined in stats to the switch scope. */
  1297         private static void addVars(List<JCStatement> stats, Scope switchScope) {
  1298             for (;stats.nonEmpty(); stats = stats.tail) {
  1299                 JCTree stat = stats.head;
  1300                 if (stat.hasTag(VARDEF))
  1301                     switchScope.enter(((JCVariableDecl) stat).sym);
  1304     // where
  1305     /** Return the selected enumeration constant symbol, or null. */
  1306     private Symbol enumConstant(JCTree tree, Type enumType) {
  1307         if (!tree.hasTag(IDENT)) {
  1308             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
  1309             return syms.errSymbol;
  1311         JCIdent ident = (JCIdent)tree;
  1312         Name name = ident.name;
  1313         for (Scope.Entry e = enumType.tsym.members().lookup(name);
  1314              e.scope != null; e = e.next()) {
  1315             if (e.sym.kind == VAR) {
  1316                 Symbol s = ident.sym = e.sym;
  1317                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1318                 ident.type = s.type;
  1319                 return ((s.flags_field & Flags.ENUM) == 0)
  1320                     ? null : s;
  1323         return null;
  1326     public void visitSynchronized(JCSynchronized tree) {
  1327         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1328         attribStat(tree.body, env);
  1329         result = null;
  1332     public void visitTry(JCTry tree) {
  1333         // Create a new local environment with a local
  1334         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1335         try {
  1336             boolean isTryWithResource = tree.resources.nonEmpty();
  1337             // Create a nested environment for attributing the try block if needed
  1338             Env<AttrContext> tryEnv = isTryWithResource ?
  1339                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1340                 localEnv;
  1341             try {
  1342                 // Attribute resource declarations
  1343                 for (JCTree resource : tree.resources) {
  1344                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1345                         @Override
  1346                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1347                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1349                     };
  1350                     ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
  1351                     if (resource.hasTag(VARDEF)) {
  1352                         attribStat(resource, tryEnv);
  1353                         twrResult.check(resource, resource.type);
  1355                         //check that resource type cannot throw InterruptedException
  1356                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1358                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1359                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1360                     } else {
  1361                         attribTree(resource, tryEnv, twrResult);
  1364                 // Attribute body
  1365                 attribStat(tree.body, tryEnv);
  1366             } finally {
  1367                 if (isTryWithResource)
  1368                     tryEnv.info.scope.leave();
  1371             // Attribute catch clauses
  1372             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1373                 JCCatch c = l.head;
  1374                 Env<AttrContext> catchEnv =
  1375                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1376                 try {
  1377                     Type ctype = attribStat(c.param, catchEnv);
  1378                     if (TreeInfo.isMultiCatch(c)) {
  1379                         //multi-catch parameter is implicitly marked as final
  1380                         c.param.sym.flags_field |= FINAL | UNION;
  1382                     if (c.param.sym.kind == Kinds.VAR) {
  1383                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1385                     chk.checkType(c.param.vartype.pos(),
  1386                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1387                                   syms.throwableType);
  1388                     attribStat(c.body, catchEnv);
  1389                 } finally {
  1390                     catchEnv.info.scope.leave();
  1394             // Attribute finalizer
  1395             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1396             result = null;
  1398         finally {
  1399             localEnv.info.scope.leave();
  1403     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1404         if (!resource.isErroneous() &&
  1405             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1406             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1407             Symbol close = syms.noSymbol;
  1408             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1409             try {
  1410                 close = rs.resolveQualifiedMethod(pos,
  1411                         env,
  1412                         resource,
  1413                         names.close,
  1414                         List.<Type>nil(),
  1415                         List.<Type>nil());
  1417             finally {
  1418                 log.popDiagnosticHandler(discardHandler);
  1420             if (close.kind == MTH &&
  1421                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1422                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1423                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1424                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1429     public void visitConditional(JCConditional tree) {
  1430         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1432         tree.polyKind = (!allowPoly ||
  1433                 pt().hasTag(NONE) && pt() != Type.recoveryType ||
  1434                 isBooleanOrNumeric(env, tree)) ?
  1435                 PolyKind.STANDALONE : PolyKind.POLY;
  1437         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1438             //cannot get here (i.e. it means we are returning from void method - which is already an error)
  1439             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1440             result = tree.type = types.createErrorType(resultInfo.pt);
  1441             return;
  1444         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1445                 unknownExprInfo :
  1446                 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
  1447                     //this will use enclosing check context to check compatibility of
  1448                     //subexpression against target type; if we are in a method check context,
  1449                     //depending on whether boxing is allowed, we could have incompatibilities
  1450                     @Override
  1451                     public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1452                         enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1454                 });
  1456         Type truetype = attribTree(tree.truepart, env, condInfo);
  1457         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1459         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1460         if (condtype.constValue() != null &&
  1461                 truetype.constValue() != null &&
  1462                 falsetype.constValue() != null &&
  1463                 !owntype.hasTag(NONE)) {
  1464             //constant folding
  1465             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1467         result = check(tree, owntype, VAL, resultInfo);
  1469     //where
  1470         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1471             switch (tree.getTag()) {
  1472                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1473                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1474                               ((JCLiteral)tree).typetag == BOT;
  1475                 case LAMBDA: case REFERENCE: return false;
  1476                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1477                 case CONDEXPR:
  1478                     JCConditional condTree = (JCConditional)tree;
  1479                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1480                             isBooleanOrNumeric(env, condTree.falsepart);
  1481                 case APPLY:
  1482                     JCMethodInvocation speculativeMethodTree =
  1483                             (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
  1484                     Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
  1485                     return types.unboxedTypeOrType(owntype).isPrimitive();
  1486                 case NEWCLASS:
  1487                     JCExpression className =
  1488                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1489                     JCExpression speculativeNewClassTree =
  1490                             (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
  1491                     return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
  1492                 default:
  1493                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
  1494                     speculativeType = types.unboxedTypeOrType(speculativeType);
  1495                     return speculativeType.isPrimitive();
  1498         //where
  1499             TreeTranslator removeClassParams = new TreeTranslator() {
  1500                 @Override
  1501                 public void visitTypeApply(JCTypeApply tree) {
  1502                     result = translate(tree.clazz);
  1504             };
  1506         /** Compute the type of a conditional expression, after
  1507          *  checking that it exists.  See JLS 15.25. Does not take into
  1508          *  account the special case where condition and both arms
  1509          *  are constants.
  1511          *  @param pos      The source position to be used for error
  1512          *                  diagnostics.
  1513          *  @param thentype The type of the expression's then-part.
  1514          *  @param elsetype The type of the expression's else-part.
  1515          */
  1516         private Type condType(DiagnosticPosition pos,
  1517                                Type thentype, Type elsetype) {
  1518             // If same type, that is the result
  1519             if (types.isSameType(thentype, elsetype))
  1520                 return thentype.baseType();
  1522             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
  1523                 ? thentype : types.unboxedType(thentype);
  1524             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
  1525                 ? elsetype : types.unboxedType(elsetype);
  1527             // Otherwise, if both arms can be converted to a numeric
  1528             // type, return the least numeric type that fits both arms
  1529             // (i.e. return larger of the two, or return int if one
  1530             // arm is short, the other is char).
  1531             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1532                 // If one arm has an integer subrange type (i.e., byte,
  1533                 // short, or char), and the other is an integer constant
  1534                 // that fits into the subrange, return the subrange type.
  1535                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
  1536                     types.isAssignable(elseUnboxed, thenUnboxed))
  1537                     return thenUnboxed.baseType();
  1538                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
  1539                     types.isAssignable(thenUnboxed, elseUnboxed))
  1540                     return elseUnboxed.baseType();
  1542                 for (TypeTag tag : TypeTag.values()) {
  1543                     if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
  1544                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1545                     if (candidate != null &&
  1546                         candidate.isPrimitive() &&
  1547                         types.isSubtype(thenUnboxed, candidate) &&
  1548                         types.isSubtype(elseUnboxed, candidate))
  1549                         return candidate;
  1553             // Those were all the cases that could result in a primitive
  1554             if (allowBoxing) {
  1555                 if (thentype.isPrimitive())
  1556                     thentype = types.boxedClass(thentype).type;
  1557                 if (elsetype.isPrimitive())
  1558                     elsetype = types.boxedClass(elsetype).type;
  1561             if (types.isSubtype(thentype, elsetype))
  1562                 return elsetype.baseType();
  1563             if (types.isSubtype(elsetype, thentype))
  1564                 return thentype.baseType();
  1566             if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1567                 log.error(pos, "neither.conditional.subtype",
  1568                           thentype, elsetype);
  1569                 return thentype.baseType();
  1572             // both are known to be reference types.  The result is
  1573             // lub(thentype,elsetype). This cannot fail, as it will
  1574             // always be possible to infer "Object" if nothing better.
  1575             return types.lub(thentype.baseType(), elsetype.baseType());
  1578     public void visitIf(JCIf tree) {
  1579         attribExpr(tree.cond, env, syms.booleanType);
  1580         attribStat(tree.thenpart, env);
  1581         if (tree.elsepart != null)
  1582             attribStat(tree.elsepart, env);
  1583         chk.checkEmptyIf(tree);
  1584         result = null;
  1587     public void visitExec(JCExpressionStatement tree) {
  1588         //a fresh environment is required for 292 inference to work properly ---
  1589         //see Infer.instantiatePolymorphicSignatureInstance()
  1590         Env<AttrContext> localEnv = env.dup(tree);
  1591         attribExpr(tree.expr, localEnv);
  1592         result = null;
  1595     public void visitBreak(JCBreak tree) {
  1596         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1597         result = null;
  1600     public void visitContinue(JCContinue tree) {
  1601         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1602         result = null;
  1604     //where
  1605         /** Return the target of a break or continue statement, if it exists,
  1606          *  report an error if not.
  1607          *  Note: The target of a labelled break or continue is the
  1608          *  (non-labelled) statement tree referred to by the label,
  1609          *  not the tree representing the labelled statement itself.
  1611          *  @param pos     The position to be used for error diagnostics
  1612          *  @param tag     The tag of the jump statement. This is either
  1613          *                 Tree.BREAK or Tree.CONTINUE.
  1614          *  @param label   The label of the jump statement, or null if no
  1615          *                 label is given.
  1616          *  @param env     The environment current at the jump statement.
  1617          */
  1618         private JCTree findJumpTarget(DiagnosticPosition pos,
  1619                                     JCTree.Tag tag,
  1620                                     Name label,
  1621                                     Env<AttrContext> env) {
  1622             // Search environments outwards from the point of jump.
  1623             Env<AttrContext> env1 = env;
  1624             LOOP:
  1625             while (env1 != null) {
  1626                 switch (env1.tree.getTag()) {
  1627                     case LABELLED:
  1628                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1629                         if (label == labelled.label) {
  1630                             // If jump is a continue, check that target is a loop.
  1631                             if (tag == CONTINUE) {
  1632                                 if (!labelled.body.hasTag(DOLOOP) &&
  1633                                         !labelled.body.hasTag(WHILELOOP) &&
  1634                                         !labelled.body.hasTag(FORLOOP) &&
  1635                                         !labelled.body.hasTag(FOREACHLOOP))
  1636                                     log.error(pos, "not.loop.label", label);
  1637                                 // Found labelled statement target, now go inwards
  1638                                 // to next non-labelled tree.
  1639                                 return TreeInfo.referencedStatement(labelled);
  1640                             } else {
  1641                                 return labelled;
  1644                         break;
  1645                     case DOLOOP:
  1646                     case WHILELOOP:
  1647                     case FORLOOP:
  1648                     case FOREACHLOOP:
  1649                         if (label == null) return env1.tree;
  1650                         break;
  1651                     case SWITCH:
  1652                         if (label == null && tag == BREAK) return env1.tree;
  1653                         break;
  1654                     case LAMBDA:
  1655                     case METHODDEF:
  1656                     case CLASSDEF:
  1657                         break LOOP;
  1658                     default:
  1660                 env1 = env1.next;
  1662             if (label != null)
  1663                 log.error(pos, "undef.label", label);
  1664             else if (tag == CONTINUE)
  1665                 log.error(pos, "cont.outside.loop");
  1666             else
  1667                 log.error(pos, "break.outside.switch.loop");
  1668             return null;
  1671     public void visitReturn(JCReturn tree) {
  1672         // Check that there is an enclosing method which is
  1673         // nested within than the enclosing class.
  1674         if (env.info.returnResult == null) {
  1675             log.error(tree.pos(), "ret.outside.meth");
  1676         } else {
  1677             // Attribute return expression, if it exists, and check that
  1678             // it conforms to result type of enclosing method.
  1679             if (tree.expr != null) {
  1680                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1681                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1682                               diags.fragment("unexpected.ret.val"));
  1684                 attribTree(tree.expr, env, env.info.returnResult);
  1685             } else if (!env.info.returnResult.pt.hasTag(VOID)) {
  1686                 env.info.returnResult.checkContext.report(tree.pos(),
  1687                               diags.fragment("missing.ret.val"));
  1690         result = null;
  1693     public void visitThrow(JCThrow tree) {
  1694         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1695         if (allowPoly) {
  1696             chk.checkType(tree, owntype, syms.throwableType);
  1698         result = null;
  1701     public void visitAssert(JCAssert tree) {
  1702         attribExpr(tree.cond, env, syms.booleanType);
  1703         if (tree.detail != null) {
  1704             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1706         result = null;
  1709      /** Visitor method for method invocations.
  1710      *  NOTE: The method part of an application will have in its type field
  1711      *        the return type of the method, not the method's type itself!
  1712      */
  1713     public void visitApply(JCMethodInvocation tree) {
  1714         // The local environment of a method application is
  1715         // a new environment nested in the current one.
  1716         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1718         // The types of the actual method arguments.
  1719         List<Type> argtypes;
  1721         // The types of the actual method type arguments.
  1722         List<Type> typeargtypes = null;
  1724         Name methName = TreeInfo.name(tree.meth);
  1726         boolean isConstructorCall =
  1727             methName == names._this || methName == names._super;
  1729         if (isConstructorCall) {
  1730             // We are seeing a ...this(...) or ...super(...) call.
  1731             // Check that this is the first statement in a constructor.
  1732             if (checkFirstConstructorStat(tree, env)) {
  1734                 // Record the fact
  1735                 // that this is a constructor call (using isSelfCall).
  1736                 localEnv.info.isSelfCall = true;
  1738                 // Attribute arguments, yielding list of argument types.
  1739                 argtypes = attribArgs(tree.args, localEnv);
  1740                 typeargtypes = attribTypes(tree.typeargs, localEnv);
  1742                 // Variable `site' points to the class in which the called
  1743                 // constructor is defined.
  1744                 Type site = env.enclClass.sym.type;
  1745                 if (methName == names._super) {
  1746                     if (site == syms.objectType) {
  1747                         log.error(tree.meth.pos(), "no.superclass", site);
  1748                         site = types.createErrorType(syms.objectType);
  1749                     } else {
  1750                         site = types.supertype(site);
  1754                 if (site.hasTag(CLASS)) {
  1755                     Type encl = site.getEnclosingType();
  1756                     while (encl != null && encl.hasTag(TYPEVAR))
  1757                         encl = encl.getUpperBound();
  1758                     if (encl.hasTag(CLASS)) {
  1759                         // we are calling a nested class
  1761                         if (tree.meth.hasTag(SELECT)) {
  1762                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1764                             // We are seeing a prefixed call, of the form
  1765                             //     <expr>.super(...).
  1766                             // Check that the prefix expression conforms
  1767                             // to the outer instance type of the class.
  1768                             chk.checkRefType(qualifier.pos(),
  1769                                              attribExpr(qualifier, localEnv,
  1770                                                         encl));
  1771                         } else if (methName == names._super) {
  1772                             // qualifier omitted; check for existence
  1773                             // of an appropriate implicit qualifier.
  1774                             rs.resolveImplicitThis(tree.meth.pos(),
  1775                                                    localEnv, site, true);
  1777                     } else if (tree.meth.hasTag(SELECT)) {
  1778                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1779                                   site.tsym);
  1782                     // if we're calling a java.lang.Enum constructor,
  1783                     // prefix the implicit String and int parameters
  1784                     if (site.tsym == syms.enumSym && allowEnums)
  1785                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1787                     // Resolve the called constructor under the assumption
  1788                     // that we are referring to a superclass instance of the
  1789                     // current instance (JLS ???).
  1790                     boolean selectSuperPrev = localEnv.info.selectSuper;
  1791                     localEnv.info.selectSuper = true;
  1792                     localEnv.info.pendingResolutionPhase = null;
  1793                     Symbol sym = rs.resolveConstructor(
  1794                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1795                     localEnv.info.selectSuper = selectSuperPrev;
  1797                     // Set method symbol to resolved constructor...
  1798                     TreeInfo.setSymbol(tree.meth, sym);
  1800                     // ...and check that it is legal in the current context.
  1801                     // (this will also set the tree's type)
  1802                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1803                     checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
  1805                 // Otherwise, `site' is an error type and we do nothing
  1807             result = tree.type = syms.voidType;
  1808         } else {
  1809             // Otherwise, we are seeing a regular method call.
  1810             // Attribute the arguments, yielding list of argument types, ...
  1811             argtypes = attribArgs(tree.args, localEnv);
  1812             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1814             // ... and attribute the method using as a prototype a methodtype
  1815             // whose formal argument types is exactly the list of actual
  1816             // arguments (this will also set the method symbol).
  1817             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1818             localEnv.info.pendingResolutionPhase = null;
  1819             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
  1821             // Compute the result type.
  1822             Type restype = mtype.getReturnType();
  1823             if (restype.hasTag(WILDCARD))
  1824                 throw new AssertionError(mtype);
  1826             Type qualifier = (tree.meth.hasTag(SELECT))
  1827                     ? ((JCFieldAccess) tree.meth).selected.type
  1828                     : env.enclClass.sym.type;
  1829             restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
  1831             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1833             // Check that value of resulting type is admissible in the
  1834             // current context.  Also, capture the return type
  1835             result = check(tree, capture(restype), VAL, resultInfo);
  1837         chk.validate(tree.typeargs, localEnv);
  1839     //where
  1840         Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1841             if (allowCovariantReturns &&
  1842                     methodName == names.clone &&
  1843                 types.isArray(qualifierType)) {
  1844                 // as a special case, array.clone() has a result that is
  1845                 // the same as static type of the array being cloned
  1846                 return qualifierType;
  1847             } else if (allowGenerics &&
  1848                     methodName == names.getClass &&
  1849                     argtypes.isEmpty()) {
  1850                 // as a special case, x.getClass() has type Class<? extends |X|>
  1851                 return new ClassType(restype.getEnclosingType(),
  1852                               List.<Type>of(new WildcardType(types.erasure(qualifierType),
  1853                                                                BoundKind.EXTENDS,
  1854                                                                syms.boundClass)),
  1855                               restype.tsym);
  1856             } else {
  1857                 return restype;
  1861         /** Check that given application node appears as first statement
  1862          *  in a constructor call.
  1863          *  @param tree   The application node
  1864          *  @param env    The environment current at the application.
  1865          */
  1866         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  1867             JCMethodDecl enclMethod = env.enclMethod;
  1868             if (enclMethod != null && enclMethod.name == names.init) {
  1869                 JCBlock body = enclMethod.body;
  1870                 if (body.stats.head.hasTag(EXEC) &&
  1871                     ((JCExpressionStatement) body.stats.head).expr == tree)
  1872                     return true;
  1874             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  1875                       TreeInfo.name(tree.meth));
  1876             return false;
  1879         /** Obtain a method type with given argument types.
  1880          */
  1881         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  1882             MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
  1883             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  1886     public void visitNewClass(final JCNewClass tree) {
  1887         Type owntype = types.createErrorType(tree.type);
  1889         // The local environment of a class creation is
  1890         // a new environment nested in the current one.
  1891         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1893         // The anonymous inner class definition of the new expression,
  1894         // if one is defined by it.
  1895         JCClassDecl cdef = tree.def;
  1897         // If enclosing class is given, attribute it, and
  1898         // complete class name to be fully qualified
  1899         JCExpression clazz = tree.clazz; // Class field following new
  1900         JCExpression clazzid;            // Identifier in class field
  1901         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  1902         annoclazzid = null;
  1904         if (clazz.hasTag(TYPEAPPLY)) {
  1905             clazzid = ((JCTypeApply) clazz).clazz;
  1906             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  1907                 annoclazzid = (JCAnnotatedType) clazzid;
  1908                 clazzid = annoclazzid.underlyingType;
  1910         } else {
  1911             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1912                 annoclazzid = (JCAnnotatedType) clazz;
  1913                 clazzid = annoclazzid.underlyingType;
  1914             } else {
  1915                 clazzid = clazz;
  1919         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  1921         if (tree.encl != null) {
  1922             // We are seeing a qualified new, of the form
  1923             //    <expr>.new C <...> (...) ...
  1924             // In this case, we let clazz stand for the name of the
  1925             // allocated class C prefixed with the type of the qualifier
  1926             // expression, so that we can
  1927             // resolve it with standard techniques later. I.e., if
  1928             // <expr> has type T, then <expr>.new C <...> (...)
  1929             // yields a clazz T.C.
  1930             Type encltype = chk.checkRefType(tree.encl.pos(),
  1931                                              attribExpr(tree.encl, env));
  1932             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  1933             // from expr to the combined type, or not? Yes, do this.
  1934             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  1935                                                  ((JCIdent) clazzid).name);
  1937             if (clazz.hasTag(ANNOTATED_TYPE)) {
  1938                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  1939                 List<JCAnnotation> annos = annoType.annotations;
  1941                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  1942                     clazzid1 = make.at(tree.pos).
  1943                         TypeApply(clazzid1,
  1944                                   ((JCTypeApply) clazz).arguments);
  1947                 clazzid1 = make.at(tree.pos).
  1948                     AnnotatedType(annos, clazzid1);
  1949             } else if (clazz.hasTag(TYPEAPPLY)) {
  1950                 clazzid1 = make.at(tree.pos).
  1951                     TypeApply(clazzid1,
  1952                               ((JCTypeApply) clazz).arguments);
  1955             clazz = clazzid1;
  1958         // Attribute clazz expression and store
  1959         // symbol + type back into the attributed tree.
  1960         Type clazztype = TreeInfo.isEnumInit(env.tree) ?
  1961             attribIdentAsEnumType(env, (JCIdent)clazz) :
  1962             attribType(clazz, env);
  1964         clazztype = chk.checkDiamond(tree, clazztype);
  1965         chk.validate(clazz, localEnv);
  1966         if (tree.encl != null) {
  1967             // We have to work in this case to store
  1968             // symbol + type back into the attributed tree.
  1969             tree.clazz.type = clazztype;
  1970             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  1971             clazzid.type = ((JCIdent) clazzid).sym.type;
  1972             if (annoclazzid != null) {
  1973                 annoclazzid.type = clazzid.type;
  1975             if (!clazztype.isErroneous()) {
  1976                 if (cdef != null && clazztype.tsym.isInterface()) {
  1977                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  1978                 } else if (clazztype.tsym.isStatic()) {
  1979                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  1982         } else if (!clazztype.tsym.isInterface() &&
  1983                    clazztype.getEnclosingType().hasTag(CLASS)) {
  1984             // Check for the existence of an apropos outer instance
  1985             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  1988         // Attribute constructor arguments.
  1989         List<Type> argtypes = attribArgs(tree.args, localEnv);
  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(MTH, 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(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2077                     if (rsEnv.info.lastResolveVarargs())
  2078                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
  2080                 findDiamondIfNeeded(localEnv, tree, clazztype);
  2083             if (cdef != null) {
  2084                 // We are seeing an anonymous class instance creation.
  2085                 // In this case, the class instance creation
  2086                 // expression
  2087                 //
  2088                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2089                 //
  2090                 // is represented internally as
  2091                 //
  2092                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2093                 //
  2094                 // This expression is then *transformed* as follows:
  2095                 //
  2096                 // (1) add a STATIC flag to the class definition
  2097                 //     if the current environment is static
  2098                 // (2) add an extends or implements clause
  2099                 // (3) add a constructor.
  2100                 //
  2101                 // For instance, if C is a class, and ET is the type of E,
  2102                 // the expression
  2103                 //
  2104                 //    E.new <typeargs1>C<typargs2>(args) { ... }
  2105                 //
  2106                 // is translated to (where X is a fresh name and typarams is the
  2107                 // parameter list of the super constructor):
  2108                 //
  2109                 //   new <typeargs1>X(<*nullchk*>E, args) where
  2110                 //     X extends C<typargs2> {
  2111                 //       <typarams> X(ET e, args) {
  2112                 //         e.<typeargs1>super(args)
  2113                 //       }
  2114                 //       ...
  2115                 //     }
  2116                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
  2118                 if (clazztype.tsym.isInterface()) {
  2119                     cdef.implementing = List.of(clazz);
  2120                 } else {
  2121                     cdef.extending = clazz;
  2124                 attribStat(cdef, localEnv);
  2126                 checkLambdaCandidate(tree, cdef.sym, clazztype);
  2128                 // If an outer instance is given,
  2129                 // prefix it to the constructor arguments
  2130                 // and delete it from the new expression
  2131                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2132                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2133                     argtypes = argtypes.prepend(tree.encl.type);
  2134                     tree.encl = null;
  2137                 // Reassign clazztype and recompute constructor.
  2138                 clazztype = cdef.sym.type;
  2139                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2140                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
  2141                 Assert.check(sym.kind < AMBIGUOUS);
  2142                 tree.constructor = sym;
  2143                 tree.constructorType = checkId(tree,
  2144                     clazztype,
  2145                     tree.constructor,
  2146                     localEnv,
  2147                     new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
  2148             } else {
  2149                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  2150                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  2151                             tree.clazz.type.tsym);
  2155             if (tree.constructor != null && tree.constructor.kind == MTH)
  2156                 owntype = clazztype;
  2158         result = check(tree, owntype, VAL, resultInfo);
  2159         chk.validate(tree.typeargs, localEnv);
  2161     //where
  2162         void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
  2163             if (tree.def == null &&
  2164                     !clazztype.isErroneous() &&
  2165                     clazztype.getTypeArguments().nonEmpty() &&
  2166                     findDiamonds) {
  2167                 JCTypeApply ta = (JCTypeApply)tree.clazz;
  2168                 List<JCExpression> prevTypeargs = ta.arguments;
  2169                 try {
  2170                     //create a 'fake' diamond AST node by removing type-argument trees
  2171                     ta.arguments = List.nil();
  2172                     ResultInfo findDiamondResult = new ResultInfo(VAL,
  2173                             resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
  2174                     Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
  2175                     Type polyPt = allowPoly ?
  2176                             syms.objectType :
  2177                             clazztype;
  2178                     if (!inferred.isErroneous() &&
  2179                         types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings)) {
  2180                         String key = types.isSameType(clazztype, inferred) ?
  2181                             "diamond.redundant.args" :
  2182                             "diamond.redundant.args.1";
  2183                         log.warning(tree.clazz.pos(), key, clazztype, inferred);
  2185                 } finally {
  2186                     ta.arguments = prevTypeargs;
  2191             private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
  2192                 if (allowLambda &&
  2193                         identifyLambdaCandidate &&
  2194                         clazztype.hasTag(CLASS) &&
  2195                         !pt().hasTag(NONE) &&
  2196                         types.isFunctionalInterface(clazztype.tsym)) {
  2197                     Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
  2198                     int count = 0;
  2199                     boolean found = false;
  2200                     for (Symbol sym : csym.members().getElements()) {
  2201                         if ((sym.flags() & SYNTHETIC) != 0 ||
  2202                                 sym.isConstructor()) continue;
  2203                         count++;
  2204                         if (sym.kind != MTH ||
  2205                                 !sym.name.equals(descriptor.name)) continue;
  2206                         Type mtype = types.memberType(clazztype, sym);
  2207                         if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
  2208                             found = true;
  2211                     if (found && count == 1) {
  2212                         log.note(tree.def, "potential.lambda.found");
  2217     private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  2218             Symbol sym) {
  2219         // Ensure that no declaration annotations are present.
  2220         // Note that a tree type might be an AnnotatedType with
  2221         // empty annotations, if only declaration annotations were given.
  2222         // This method will raise an error for such a type.
  2223         for (JCAnnotation ai : annotations) {
  2224             if (TypeAnnotations.annotationType(syms, names, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  2225                 log.error(ai.pos(), "annotation.type.not.applicable");
  2231     /** Make an attributed null check tree.
  2232      */
  2233     public JCExpression makeNullCheck(JCExpression arg) {
  2234         // optimization: X.this is never null; skip null check
  2235         Name name = TreeInfo.name(arg);
  2236         if (name == names._this || name == names._super) return arg;
  2238         JCTree.Tag optag = NULLCHK;
  2239         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
  2240         tree.operator = syms.nullcheck;
  2241         tree.type = arg.type;
  2242         return tree;
  2245     public void visitNewArray(JCNewArray tree) {
  2246         Type owntype = types.createErrorType(tree.type);
  2247         Env<AttrContext> localEnv = env.dup(tree);
  2248         Type elemtype;
  2249         if (tree.elemtype != null) {
  2250             elemtype = attribType(tree.elemtype, localEnv);
  2251             chk.validate(tree.elemtype, localEnv);
  2252             owntype = elemtype;
  2253             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2254                 attribExpr(l.head, localEnv, syms.intType);
  2255                 owntype = new ArrayType(owntype, syms.arrayClass);
  2257             if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  2258                 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  2259                         tree.elemtype.type.tsym);
  2261         } else {
  2262             // we are seeing an untyped aggregate { ... }
  2263             // this is allowed only if the prototype is an array
  2264             if (pt().hasTag(ARRAY)) {
  2265                 elemtype = types.elemtype(pt());
  2266             } else {
  2267                 if (!pt().hasTag(ERROR)) {
  2268                     log.error(tree.pos(), "illegal.initializer.for.type",
  2269                               pt());
  2271                 elemtype = types.createErrorType(pt());
  2274         if (tree.elems != null) {
  2275             attribExprs(tree.elems, localEnv, elemtype);
  2276             owntype = new ArrayType(elemtype, syms.arrayClass);
  2278         if (!types.isReifiable(elemtype))
  2279             log.error(tree.pos(), "generic.array.creation");
  2280         result = check(tree, owntype, VAL, resultInfo);
  2283     /*
  2284      * A lambda expression can only be attributed when a target-type is available.
  2285      * In addition, if the target-type is that of a functional interface whose
  2286      * descriptor contains inference variables in argument position the lambda expression
  2287      * is 'stuck' (see DeferredAttr).
  2288      */
  2289     @Override
  2290     public void visitLambda(final JCLambda that) {
  2291         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2292             if (pt().hasTag(NONE)) {
  2293                 //lambda only allowed in assignment or method invocation/cast context
  2294                 log.error(that.pos(), "unexpected.lambda");
  2296             result = that.type = types.createErrorType(pt());
  2297             return;
  2299         //create an environment for attribution of the lambda expression
  2300         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2301         boolean needsRecovery =
  2302                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2303         try {
  2304             Type target = pt();
  2305             List<Type> explicitParamTypes = null;
  2306             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2307                 //attribute lambda parameters
  2308                 attribStats(that.params, localEnv);
  2309                 explicitParamTypes = TreeInfo.types(that.params);
  2310                 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
  2313             Type lambdaType;
  2314             if (pt() != Type.recoveryType) {
  2315                 target = targetChecker.visit(target, that);
  2316                 lambdaType = types.findDescriptorType(target);
  2317                 chk.checkFunctionalInterface(that, target);
  2318             } else {
  2319                 target = Type.recoveryType;
  2320                 lambdaType = fallbackDescriptorType(that);
  2323             setFunctionalInfo(that, pt(), lambdaType, target, resultInfo.checkContext.inferenceContext());
  2325             if (lambdaType.hasTag(FORALL)) {
  2326                 //lambda expression target desc cannot be a generic method
  2327                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2328                         lambdaType, kindName(target.tsym), target.tsym));
  2329                 result = that.type = types.createErrorType(pt());
  2330                 return;
  2333             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2334                 //add param type info in the AST
  2335                 List<Type> actuals = lambdaType.getParameterTypes();
  2336                 List<JCVariableDecl> params = that.params;
  2338                 boolean arityMismatch = false;
  2340                 while (params.nonEmpty()) {
  2341                     if (actuals.isEmpty()) {
  2342                         //not enough actuals to perform lambda parameter inference
  2343                         arityMismatch = true;
  2345                     //reset previously set info
  2346                     Type argType = arityMismatch ?
  2347                             syms.errType :
  2348                             actuals.head;
  2349                     params.head.vartype = make.at(params.head).Type(argType);
  2350                     params.head.sym = null;
  2351                     actuals = actuals.isEmpty() ?
  2352                             actuals :
  2353                             actuals.tail;
  2354                     params = params.tail;
  2357                 //attribute lambda parameters
  2358                 attribStats(that.params, localEnv);
  2360                 if (arityMismatch) {
  2361                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2362                         result = that.type = types.createErrorType(target);
  2363                         return;
  2367             //from this point on, no recovery is needed; if we are in assignment context
  2368             //we will be able to attribute the whole lambda body, regardless of errors;
  2369             //if we are in a 'check' method context, and the lambda is not compatible
  2370             //with the target-type, it will be recovered anyway in Attr.checkId
  2371             needsRecovery = false;
  2373             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2374                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2375                     new FunctionalReturnContext(resultInfo.checkContext);
  2377             ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
  2378                 recoveryInfo :
  2379                 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
  2380             localEnv.info.returnResult = bodyResultInfo;
  2382             Log.DeferredDiagnosticHandler lambdaDeferredHandler = new Log.DeferredDiagnosticHandler(log);
  2383             try {
  2384                 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2385                     attribTree(that.getBody(), localEnv, bodyResultInfo);
  2386                 } else {
  2387                     JCBlock body = (JCBlock)that.body;
  2388                     attribStats(body.stats, localEnv);
  2391                 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.SPECULATIVE) {
  2392                     //check for errors in lambda body
  2393                     for (JCDiagnostic deferredDiag : lambdaDeferredHandler.getDiagnostics()) {
  2394                         if (deferredDiag.getKind() == JCDiagnostic.Kind.ERROR) {
  2395                             resultInfo.checkContext
  2396                                     .report(that, diags.fragment("bad.arg.types.in.lambda", TreeInfo.types(that.params),
  2397                                     deferredDiag)); //hidden diag parameter
  2398                             //we mark the lambda as erroneous - this is crucial in the recovery step
  2399                             //as parameter-dependent type error won't be reported in that stage,
  2400                             //meaning that a lambda will be deemed erroeneous only if there is
  2401                             //a target-independent error (which will cause method diagnostic
  2402                             //to be skipped).
  2403                             result = that.type = types.createErrorType(target);
  2404                             return;
  2408             } finally {
  2409                 lambdaDeferredHandler.reportDeferredDiagnostics();
  2410                 log.popDiagnosticHandler(lambdaDeferredHandler);
  2413             result = check(that, target, VAL, resultInfo);
  2415             boolean isSpeculativeRound =
  2416                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2418             postAttr(that);
  2419             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2421             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
  2423             if (!isSpeculativeRound) {
  2424                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
  2426             result = check(that, target, VAL, resultInfo);
  2427         } catch (Types.FunctionDescriptorLookupError ex) {
  2428             JCDiagnostic cause = ex.getDiagnostic();
  2429             resultInfo.checkContext.report(that, cause);
  2430             result = that.type = types.createErrorType(pt());
  2431             return;
  2432         } finally {
  2433             localEnv.info.scope.leave();
  2434             if (needsRecovery) {
  2435                 attribTree(that, env, recoveryInfo);
  2439     //where
  2440         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2442             @Override
  2443             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2444                 return t.isCompound() ?
  2445                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2448             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2449                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2450                 Type target = null;
  2451                 for (Type bound : ict.getExplicitComponents()) {
  2452                     TypeSymbol boundSym = bound.tsym;
  2453                     if (types.isFunctionalInterface(boundSym) &&
  2454                             types.findDescriptorSymbol(boundSym) == desc) {
  2455                         target = bound;
  2456                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2457                         //bound must be an interface
  2458                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2461                 return target != null ?
  2462                         target :
  2463                         ict.getExplicitComponents().head; //error recovery
  2466             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2467                 ListBuffer<Type> targs = ListBuffer.lb();
  2468                 ListBuffer<Type> supertypes = ListBuffer.lb();
  2469                 for (Type i : ict.interfaces_field) {
  2470                     if (i.isParameterized()) {
  2471                         targs.appendList(i.tsym.type.allparams());
  2473                     supertypes.append(i.tsym.type);
  2475                 IntersectionClassType notionalIntf =
  2476                         (IntersectionClassType)types.makeCompoundType(supertypes.toList());
  2477                 notionalIntf.allparams_field = targs.toList();
  2478                 notionalIntf.tsym.flags_field |= INTERFACE;
  2479                 return notionalIntf.tsym;
  2482             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2483                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2484                         diags.fragment(key, args)));
  2486         };
  2488         private Type fallbackDescriptorType(JCExpression tree) {
  2489             switch (tree.getTag()) {
  2490                 case LAMBDA:
  2491                     JCLambda lambda = (JCLambda)tree;
  2492                     List<Type> argtypes = List.nil();
  2493                     for (JCVariableDecl param : lambda.params) {
  2494                         argtypes = param.vartype != null ?
  2495                                 argtypes.append(param.vartype.type) :
  2496                                 argtypes.append(syms.errType);
  2498                     return new MethodType(argtypes, Type.recoveryType,
  2499                             List.of(syms.throwableType), syms.methodClass);
  2500                 case REFERENCE:
  2501                     return new MethodType(List.<Type>nil(), Type.recoveryType,
  2502                             List.of(syms.throwableType), syms.methodClass);
  2503                 default:
  2504                     Assert.error("Cannot get here!");
  2506             return null;
  2509         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2510                 final InferenceContext inferenceContext, final Type... ts) {
  2511             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2514         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2515                 final InferenceContext inferenceContext, final List<Type> ts) {
  2516             if (inferenceContext.free(ts)) {
  2517                 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
  2518                     @Override
  2519                     public void typesInferred(InferenceContext inferenceContext) {
  2520                         checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
  2522                 });
  2523             } else {
  2524                 for (Type t : ts) {
  2525                     rs.checkAccessibleType(env, t);
  2530         /**
  2531          * Lambda/method reference have a special check context that ensures
  2532          * that i.e. a lambda return type is compatible with the expected
  2533          * type according to both the inherited context and the assignment
  2534          * context.
  2535          */
  2536         class FunctionalReturnContext extends Check.NestedCheckContext {
  2538             FunctionalReturnContext(CheckContext enclosingContext) {
  2539                 super(enclosingContext);
  2542             @Override
  2543             public boolean compatible(Type found, Type req, Warner warn) {
  2544                 //return type must be compatible in both current context and assignment context
  2545                 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
  2548             @Override
  2549             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2550                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2554         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2556             JCExpression expr;
  2558             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2559                 super(enclosingContext);
  2560                 this.expr = expr;
  2563             @Override
  2564             public boolean compatible(Type found, Type req, Warner warn) {
  2565                 //a void return is compatible with an expression statement lambda
  2566                 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
  2567                         super.compatible(found, req, warn);
  2571         /**
  2572         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2573         * are compatible with the expected functional interface descriptor. This means that:
  2574         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2575         * types must be compatible with the return type of the expected descriptor;
  2576         * (iii) thrown types must be 'included' in the thrown types list of the expected
  2577         * descriptor.
  2578         */
  2579         private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
  2580             Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2582             //return values have already been checked - but if lambda has no return
  2583             //values, we must ensure that void/value compatibility is correct;
  2584             //this amounts at checking that, if a lambda body can complete normally,
  2585             //the descriptor's return type must be void
  2586             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2587                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2588                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2589                         diags.fragment("missing.ret.val", returnType)));
  2592             List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
  2593             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2594                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2597             if (!speculativeAttr) {
  2598                 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2599                 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
  2600                     log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
  2605         private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2606             Env<AttrContext> lambdaEnv;
  2607             Symbol owner = env.info.scope.owner;
  2608             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2609                 //field initializer
  2610                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
  2611                 lambdaEnv.info.scope.owner =
  2612                     new MethodSymbol((owner.flags() & STATIC) | BLOCK, names.empty, null,
  2613                                      env.info.scope.owner);
  2614             } else {
  2615                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2617             return lambdaEnv;
  2620     @Override
  2621     public void visitReference(final JCMemberReference that) {
  2622         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2623             if (pt().hasTag(NONE)) {
  2624                 //method reference only allowed in assignment or method invocation/cast context
  2625                 log.error(that.pos(), "unexpected.mref");
  2627             result = that.type = types.createErrorType(pt());
  2628             return;
  2630         final Env<AttrContext> localEnv = env.dup(that);
  2631         try {
  2632             //attribute member reference qualifier - if this is a constructor
  2633             //reference, the expected kind must be a type
  2634             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2636             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2637                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2640             if (exprType.isErroneous()) {
  2641                 //if the qualifier expression contains problems,
  2642                 //give up attribution of method reference
  2643                 result = that.type = exprType;
  2644                 return;
  2647             if (TreeInfo.isStaticSelector(that.expr, names)) {
  2648                 //if the qualifier is a type, validate it; raw warning check is
  2649                 //omitted as we don't know at this stage as to whether this is a
  2650                 //raw selector (because of inference)
  2651                 chk.validate(that.expr, env, false);
  2654             //attrib type-arguments
  2655             List<Type> typeargtypes = List.nil();
  2656             if (that.typeargs != null) {
  2657                 typeargtypes = attribTypes(that.typeargs, localEnv);
  2660             Type target;
  2661             Type desc;
  2662             if (pt() != Type.recoveryType) {
  2663                 target = targetChecker.visit(pt(), that);
  2664                 desc = types.findDescriptorType(target);
  2665                 chk.checkFunctionalInterface(that, target);
  2666             } else {
  2667                 target = Type.recoveryType;
  2668                 desc = fallbackDescriptorType(that);
  2671             setFunctionalInfo(that, pt(), desc, target, resultInfo.checkContext.inferenceContext());
  2672             List<Type> argtypes = desc.getParameterTypes();
  2674             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult =
  2675                     rs.resolveMemberReference(that.pos(), localEnv, that,
  2676                         that.expr.type, that.name, argtypes, typeargtypes, true, rs.resolveMethodCheck);
  2678             Symbol refSym = refResult.fst;
  2679             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  2681             if (refSym.kind != MTH) {
  2682                 boolean targetError;
  2683                 switch (refSym.kind) {
  2684                     case ABSENT_MTH:
  2685                         targetError = false;
  2686                         break;
  2687                     case WRONG_MTH:
  2688                     case WRONG_MTHS:
  2689                     case AMBIGUOUS:
  2690                     case HIDDEN:
  2691                     case STATICERR:
  2692                     case MISSING_ENCL:
  2693                         targetError = true;
  2694                         break;
  2695                     default:
  2696                         Assert.error("unexpected result kind " + refSym.kind);
  2697                         targetError = false;
  2700                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  2701                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  2703                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  2704                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  2706                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  2707                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  2709                 if (targetError && target == Type.recoveryType) {
  2710                     //a target error doesn't make sense during recovery stage
  2711                     //as we don't know what actual parameter types are
  2712                     result = that.type = target;
  2713                     return;
  2714                 } else {
  2715                     if (targetError) {
  2716                         resultInfo.checkContext.report(that, diag);
  2717                     } else {
  2718                         log.report(diag);
  2720                     result = that.type = types.createErrorType(target);
  2721                     return;
  2725             that.sym = refSym.baseSymbol();
  2726             that.kind = lookupHelper.referenceKind(that.sym);
  2727             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  2729             if (desc.getReturnType() == Type.recoveryType) {
  2730                 // stop here
  2731                 result = that.type = target;
  2732                 return;
  2735             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2737                 if (that.getMode() == ReferenceMode.INVOKE &&
  2738                         TreeInfo.isStaticSelector(that.expr, names) &&
  2739                         that.kind.isUnbound() &&
  2740                         !desc.getParameterTypes().head.isParameterized()) {
  2741                     chk.checkRaw(that.expr, localEnv);
  2744                 if (!that.kind.isUnbound() &&
  2745                         that.getMode() == ReferenceMode.INVOKE &&
  2746                         TreeInfo.isStaticSelector(that.expr, names) &&
  2747                         !that.sym.isStatic()) {
  2748                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2749                             diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym));
  2750                     result = that.type = types.createErrorType(target);
  2751                     return;
  2754                 if (that.kind.isUnbound() &&
  2755                         that.getMode() == ReferenceMode.INVOKE &&
  2756                         TreeInfo.isStaticSelector(that.expr, names) &&
  2757                         that.sym.isStatic()) {
  2758                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2759                             diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym));
  2760                     result = that.type = types.createErrorType(target);
  2761                     return;
  2764                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  2765                         exprType.getTypeArguments().nonEmpty()) {
  2766                     //static ref with class type-args
  2767                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2768                             diags.fragment("static.mref.with.targs"));
  2769                     result = that.type = types.createErrorType(target);
  2770                     return;
  2773                 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
  2774                         !that.kind.isUnbound()) {
  2775                     //no static bound mrefs
  2776                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  2777                             diags.fragment("static.bound.mref"));
  2778                     result = that.type = types.createErrorType(target);
  2779                     return;
  2782                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  2783                     // Check that super-qualified symbols are not abstract (JLS)
  2784                     rs.checkNonAbstract(that.pos(), that.sym);
  2788             that.sym = refSym.baseSymbol();
  2789             that.kind = lookupHelper.referenceKind(that.sym);
  2791             ResultInfo checkInfo =
  2792                     resultInfo.dup(newMethodTemplate(
  2793                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  2794                         lookupHelper.argtypes,
  2795                         typeargtypes));
  2797             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  2799             if (!refType.isErroneous()) {
  2800                 refType = types.createMethodTypeWithReturn(refType,
  2801                         adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  2804             //go ahead with standard method reference compatibility check - note that param check
  2805             //is a no-op (as this has been taken care during method applicability)
  2806             boolean isSpeculativeRound =
  2807                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2808             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  2809             if (!isSpeculativeRound) {
  2810                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
  2812             result = check(that, target, VAL, resultInfo);
  2813         } catch (Types.FunctionDescriptorLookupError ex) {
  2814             JCDiagnostic cause = ex.getDiagnostic();
  2815             resultInfo.checkContext.report(that, cause);
  2816             result = that.type = types.createErrorType(pt());
  2817             return;
  2820     //where
  2821         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  2822             //if this is a constructor reference, the expected kind must be a type
  2823             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
  2827     @SuppressWarnings("fallthrough")
  2828     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  2829         Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
  2831         Type resType;
  2832         switch (tree.getMode()) {
  2833             case NEW:
  2834                 if (!tree.expr.type.isRaw()) {
  2835                     resType = tree.expr.type;
  2836                     break;
  2838             default:
  2839                 resType = refType.getReturnType();
  2842         Type incompatibleReturnType = resType;
  2844         if (returnType.hasTag(VOID)) {
  2845             incompatibleReturnType = null;
  2848         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  2849             if (resType.isErroneous() ||
  2850                     new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
  2851                 incompatibleReturnType = null;
  2855         if (incompatibleReturnType != null) {
  2856             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  2857                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  2860         if (!speculativeAttr) {
  2861             List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
  2862             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  2863                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  2868     /**
  2869      * Set functional type info on the underlying AST. Note: as the target descriptor
  2870      * might contain inference variables, we might need to register an hook in the
  2871      * current inference context.
  2872      */
  2873     private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt,
  2874             final Type descriptorType, final Type primaryTarget, InferenceContext inferenceContext) {
  2875         if (inferenceContext.free(descriptorType)) {
  2876             inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
  2877                 public void typesInferred(InferenceContext inferenceContext) {
  2878                     setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType),
  2879                             inferenceContext.asInstType(primaryTarget), inferenceContext);
  2881             });
  2882         } else {
  2883             ListBuffer<TypeSymbol> targets = ListBuffer.lb();
  2884             if (pt.hasTag(CLASS)) {
  2885                 if (pt.isCompound()) {
  2886                     targets.append(primaryTarget.tsym); //this goes first
  2887                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  2888                         if (t != primaryTarget) {
  2889                             targets.append(t.tsym);
  2892                 } else {
  2893                     targets.append(pt.tsym);
  2896             fExpr.targets = targets.toList();
  2897             fExpr.descriptorType = descriptorType;
  2901     public void visitParens(JCParens tree) {
  2902         Type owntype = attribTree(tree.expr, env, resultInfo);
  2903         result = check(tree, owntype, pkind(), resultInfo);
  2904         Symbol sym = TreeInfo.symbol(tree);
  2905         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
  2906             log.error(tree.pos(), "illegal.start.of.type");
  2909     public void visitAssign(JCAssign tree) {
  2910         Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
  2911         Type capturedType = capture(owntype);
  2912         attribExpr(tree.rhs, env, owntype);
  2913         result = check(tree, capturedType, VAL, resultInfo);
  2916     public void visitAssignop(JCAssignOp tree) {
  2917         // Attribute arguments.
  2918         Type owntype = attribTree(tree.lhs, env, varInfo);
  2919         Type operand = attribExpr(tree.rhs, env);
  2920         // Find operator.
  2921         Symbol operator = tree.operator = rs.resolveBinaryOperator(
  2922             tree.pos(), tree.getTag().noAssignOp(), env,
  2923             owntype, operand);
  2925         if (operator.kind == MTH &&
  2926                 !owntype.isErroneous() &&
  2927                 !operand.isErroneous()) {
  2928             chk.checkOperator(tree.pos(),
  2929                               (OperatorSymbol)operator,
  2930                               tree.getTag().noAssignOp(),
  2931                               owntype,
  2932                               operand);
  2933             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  2934             chk.checkCastable(tree.rhs.pos(),
  2935                               operator.type.getReturnType(),
  2936                               owntype);
  2938         result = check(tree, owntype, VAL, resultInfo);
  2941     public void visitUnary(JCUnary tree) {
  2942         // Attribute arguments.
  2943         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  2944             ? attribTree(tree.arg, env, varInfo)
  2945             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  2947         // Find operator.
  2948         Symbol operator = tree.operator =
  2949             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
  2951         Type owntype = types.createErrorType(tree.type);
  2952         if (operator.kind == MTH &&
  2953                 !argtype.isErroneous()) {
  2954             owntype = (tree.getTag().isIncOrDecUnaryOp())
  2955                 ? tree.arg.type
  2956                 : operator.type.getReturnType();
  2957             int opc = ((OperatorSymbol)operator).opcode;
  2959             // If the argument is constant, fold it.
  2960             if (argtype.constValue() != null) {
  2961                 Type ctype = cfolder.fold1(opc, argtype);
  2962                 if (ctype != null) {
  2963                     owntype = cfolder.coerce(ctype, owntype);
  2965                     // Remove constant types from arguments to
  2966                     // conserve space. The parser will fold concatenations
  2967                     // of string literals; the code here also
  2968                     // gets rid of intermediate results when some of the
  2969                     // operands are constant identifiers.
  2970                     if (tree.arg.type.tsym == syms.stringType.tsym) {
  2971                         tree.arg.type = syms.stringType;
  2976         result = check(tree, owntype, VAL, resultInfo);
  2979     public void visitBinary(JCBinary tree) {
  2980         // Attribute arguments.
  2981         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  2982         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
  2984         // Find operator.
  2985         Symbol operator = tree.operator =
  2986             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
  2988         Type owntype = types.createErrorType(tree.type);
  2989         if (operator.kind == MTH &&
  2990                 !left.isErroneous() &&
  2991                 !right.isErroneous()) {
  2992             owntype = operator.type.getReturnType();
  2993             int opc = chk.checkOperator(tree.lhs.pos(),
  2994                                         (OperatorSymbol)operator,
  2995                                         tree.getTag(),
  2996                                         left,
  2997                                         right);
  2999             // If both arguments are constants, fold them.
  3000             if (left.constValue() != null && right.constValue() != null) {
  3001                 Type ctype = cfolder.fold2(opc, left, right);
  3002                 if (ctype != null) {
  3003                     owntype = cfolder.coerce(ctype, owntype);
  3005                     // Remove constant types from arguments to
  3006                     // conserve space. The parser will fold concatenations
  3007                     // of string literals; the code here also
  3008                     // gets rid of intermediate results when some of the
  3009                     // operands are constant identifiers.
  3010                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
  3011                         tree.lhs.type = syms.stringType;
  3013                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
  3014                         tree.rhs.type = syms.stringType;
  3019             // Check that argument types of a reference ==, != are
  3020             // castable to each other, (JLS???).
  3021             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3022                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  3023                     log.error(tree.pos(), "incomparable.types", left, right);
  3027             chk.checkDivZero(tree.rhs.pos(), operator, right);
  3029         result = check(tree, owntype, VAL, resultInfo);
  3032     public void visitTypeCast(final JCTypeCast tree) {
  3033         Type clazztype = attribType(tree.clazz, env);
  3034         chk.validate(tree.clazz, env, false);
  3035         //a fresh environment is required for 292 inference to work properly ---
  3036         //see Infer.instantiatePolymorphicSignatureInstance()
  3037         Env<AttrContext> localEnv = env.dup(tree);
  3038         //should we propagate the target type?
  3039         final ResultInfo castInfo;
  3040         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3041         boolean isPoly = expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE);
  3042         if (isPoly) {
  3043             //expression is a poly - we need to propagate target type info
  3044             castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
  3045                 @Override
  3046                 public boolean compatible(Type found, Type req, Warner warn) {
  3047                     return types.isCastable(found, req, warn);
  3049             });
  3050         } else {
  3051             //standalone cast - target-type info is not propagated
  3052             castInfo = unknownExprInfo;
  3054         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3055         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3056         if (exprtype.constValue() != null)
  3057             owntype = cfolder.coerce(exprtype, owntype);
  3058         result = check(tree, capture(owntype), VAL, resultInfo);
  3059         if (!isPoly)
  3060             chk.checkRedundantCast(localEnv, tree);
  3063     public void visitTypeTest(JCInstanceOf tree) {
  3064         Type exprtype = chk.checkNullOrRefType(
  3065             tree.expr.pos(), attribExpr(tree.expr, env));
  3066         Type clazztype = chk.checkReifiableReferenceType(
  3067             tree.clazz.pos(), attribType(tree.clazz, env));
  3068         chk.validate(tree.clazz, env, false);
  3069         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3070         result = check(tree, syms.booleanType, VAL, resultInfo);
  3073     public void visitIndexed(JCArrayAccess tree) {
  3074         Type owntype = types.createErrorType(tree.type);
  3075         Type atype = attribExpr(tree.indexed, env);
  3076         attribExpr(tree.index, env, syms.intType);
  3077         if (types.isArray(atype))
  3078             owntype = types.elemtype(atype);
  3079         else if (!atype.hasTag(ERROR))
  3080             log.error(tree.pos(), "array.req.but.found", atype);
  3081         if ((pkind() & VAR) == 0) owntype = capture(owntype);
  3082         result = check(tree, owntype, VAR, resultInfo);
  3085     public void visitIdent(JCIdent tree) {
  3086         Symbol sym;
  3088         // Find symbol
  3089         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3090             // If we are looking for a method, the prototype `pt' will be a
  3091             // method type with the type of the call's arguments as parameters.
  3092             env.info.pendingResolutionPhase = null;
  3093             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3094         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3095             sym = tree.sym;
  3096         } else {
  3097             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3099         tree.sym = sym;
  3101         // (1) Also find the environment current for the class where
  3102         //     sym is defined (`symEnv').
  3103         // Only for pre-tiger versions (1.4 and earlier):
  3104         // (2) Also determine whether we access symbol out of an anonymous
  3105         //     class in a this or super call.  This is illegal for instance
  3106         //     members since such classes don't carry a this$n link.
  3107         //     (`noOuterThisPath').
  3108         Env<AttrContext> symEnv = env;
  3109         boolean noOuterThisPath = false;
  3110         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3111             (sym.kind & (VAR | MTH | TYP)) != 0 &&
  3112             sym.owner.kind == TYP &&
  3113             tree.name != names._this && tree.name != names._super) {
  3115             // Find environment in which identifier is defined.
  3116             while (symEnv.outer != null &&
  3117                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3118                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3119                     noOuterThisPath = !allowAnonOuterThis;
  3120                 symEnv = symEnv.outer;
  3124         // If symbol is a variable, ...
  3125         if (sym.kind == VAR) {
  3126             VarSymbol v = (VarSymbol)sym;
  3128             // ..., evaluate its initializer, if it has one, and check for
  3129             // illegal forward reference.
  3130             checkInit(tree, env, v, false);
  3132             // If we are expecting a variable (as opposed to a value), check
  3133             // that the variable is assignable in the current environment.
  3134             if (pkind() == VAR)
  3135                 checkAssignable(tree.pos(), v, null, env);
  3138         // In a constructor body,
  3139         // if symbol is a field or instance method, check that it is
  3140         // not accessed before the supertype constructor is called.
  3141         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3142             (sym.kind & (VAR | MTH)) != 0 &&
  3143             sym.owner.kind == TYP &&
  3144             (sym.flags() & STATIC) == 0) {
  3145             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
  3147         Env<AttrContext> env1 = env;
  3148         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
  3149             // If the found symbol is inaccessible, then it is
  3150             // accessed through an enclosing instance.  Locate this
  3151             // enclosing instance:
  3152             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3153                 env1 = env1.outer;
  3155         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3158     public void visitSelect(JCFieldAccess tree) {
  3159         // Determine the expected kind of the qualifier expression.
  3160         int skind = 0;
  3161         if (tree.name == names._this || tree.name == names._super ||
  3162             tree.name == names._class)
  3164             skind = TYP;
  3165         } else {
  3166             if ((pkind() & PCK) != 0) skind = skind | PCK;
  3167             if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
  3168             if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
  3171         // Attribute the qualifier expression, and determine its symbol (if any).
  3172         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
  3173         if ((pkind() & (PCK | TYP)) == 0)
  3174             site = capture(site); // Capture field access
  3176         // don't allow T.class T[].class, etc
  3177         if (skind == TYP) {
  3178             Type elt = site;
  3179             while (elt.hasTag(ARRAY))
  3180                 elt = ((ArrayType)elt).elemtype;
  3181             if (elt.hasTag(TYPEVAR)) {
  3182                 log.error(tree.pos(), "type.var.cant.be.deref");
  3183                 result = types.createErrorType(tree.type);
  3184                 return;
  3188         // If qualifier symbol is a type or `super', assert `selectSuper'
  3189         // for the selection. This is relevant for determining whether
  3190         // protected symbols are accessible.
  3191         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3192         boolean selectSuperPrev = env.info.selectSuper;
  3193         env.info.selectSuper =
  3194             sitesym != null &&
  3195             sitesym.name == names._super;
  3197         // Determine the symbol represented by the selection.
  3198         env.info.pendingResolutionPhase = null;
  3199         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3200         if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
  3201             site = capture(site);
  3202             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3204         boolean varArgs = env.info.lastResolveVarargs();
  3205         tree.sym = sym;
  3207         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3208             while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
  3209             site = capture(site);
  3212         // If that symbol is a variable, ...
  3213         if (sym.kind == VAR) {
  3214             VarSymbol v = (VarSymbol)sym;
  3216             // ..., evaluate its initializer, if it has one, and check for
  3217             // illegal forward reference.
  3218             checkInit(tree, env, v, true);
  3220             // If we are expecting a variable (as opposed to a value), check
  3221             // that the variable is assignable in the current environment.
  3222             if (pkind() == VAR)
  3223                 checkAssignable(tree.pos(), v, tree.selected, env);
  3226         if (sitesym != null &&
  3227                 sitesym.kind == VAR &&
  3228                 ((VarSymbol)sitesym).isResourceVariable() &&
  3229                 sym.kind == MTH &&
  3230                 sym.name.equals(names.close) &&
  3231                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3232                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3233             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3236         // Disallow selecting a type from an expression
  3237         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
  3238             tree.type = check(tree.selected, pt(),
  3239                               sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
  3242         if (isType(sitesym)) {
  3243             if (sym.name == names._this) {
  3244                 // If `C' is the currently compiled class, check that
  3245                 // C.this' does not appear in a call to a super(...)
  3246                 if (env.info.isSelfCall &&
  3247                     site.tsym == env.enclClass.sym) {
  3248                     chk.earlyRefError(tree.pos(), sym);
  3250             } else {
  3251                 // Check if type-qualified fields or methods are static (JLS)
  3252                 if ((sym.flags() & STATIC) == 0 &&
  3253                     !env.next.tree.hasTag(REFERENCE) &&
  3254                     sym.name != names._super &&
  3255                     (sym.kind == VAR || sym.kind == MTH)) {
  3256                     rs.accessBase(rs.new StaticError(sym),
  3257                               tree.pos(), site, sym.name, true);
  3260         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
  3261             // If the qualified item is not a type and the selected item is static, report
  3262             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3263             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
  3266         // If we are selecting an instance member via a `super', ...
  3267         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3269             // Check that super-qualified symbols are not abstract (JLS)
  3270             rs.checkNonAbstract(tree.pos(), sym);
  3272             if (site.isRaw()) {
  3273                 // Determine argument types for site.
  3274                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3275                 if (site1 != null) site = site1;
  3279         env.info.selectSuper = selectSuperPrev;
  3280         result = checkId(tree, site, sym, env, resultInfo);
  3282     //where
  3283         /** Determine symbol referenced by a Select expression,
  3285          *  @param tree   The select tree.
  3286          *  @param site   The type of the selected expression,
  3287          *  @param env    The current environment.
  3288          *  @param resultInfo The current result.
  3289          */
  3290         private Symbol selectSym(JCFieldAccess tree,
  3291                                  Symbol location,
  3292                                  Type site,
  3293                                  Env<AttrContext> env,
  3294                                  ResultInfo resultInfo) {
  3295             DiagnosticPosition pos = tree.pos();
  3296             Name name = tree.name;
  3297             switch (site.getTag()) {
  3298             case PACKAGE:
  3299                 return rs.accessBase(
  3300                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3301                     pos, location, site, name, true);
  3302             case ARRAY:
  3303             case CLASS:
  3304                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3305                     return rs.resolveQualifiedMethod(
  3306                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3307                 } else if (name == names._this || name == names._super) {
  3308                     return rs.resolveSelf(pos, env, site.tsym, name);
  3309                 } else if (name == names._class) {
  3310                     // In this case, we have already made sure in
  3311                     // visitSelect that qualifier expression is a type.
  3312                     Type t = syms.classType;
  3313                     List<Type> typeargs = allowGenerics
  3314                         ? List.of(types.erasure(site))
  3315                         : List.<Type>nil();
  3316                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3317                     return new VarSymbol(
  3318                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3319                 } else {
  3320                     // We are seeing a plain identifier as selector.
  3321                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3322                     if ((resultInfo.pkind & ERRONEOUS) == 0)
  3323                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3324                     return sym;
  3326             case WILDCARD:
  3327                 throw new AssertionError(tree);
  3328             case TYPEVAR:
  3329                 // Normally, site.getUpperBound() shouldn't be null.
  3330                 // It should only happen during memberEnter/attribBase
  3331                 // when determining the super type which *must* beac
  3332                 // done before attributing the type variables.  In
  3333                 // other words, we are seeing this illegal program:
  3334                 // class B<T> extends A<T.foo> {}
  3335                 Symbol sym = (site.getUpperBound() != null)
  3336                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3337                     : null;
  3338                 if (sym == null) {
  3339                     log.error(pos, "type.var.cant.be.deref");
  3340                     return syms.errSymbol;
  3341                 } else {
  3342                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3343                         rs.new AccessError(env, site, sym) :
  3344                                 sym;
  3345                     rs.accessBase(sym2, pos, location, site, name, true);
  3346                     return sym;
  3348             case ERROR:
  3349                 // preserve identifier names through errors
  3350                 return types.createErrorType(name, site.tsym, site).tsym;
  3351             default:
  3352                 // The qualifier expression is of a primitive type -- only
  3353                 // .class is allowed for these.
  3354                 if (name == names._class) {
  3355                     // In this case, we have already made sure in Select that
  3356                     // qualifier expression is a type.
  3357                     Type t = syms.classType;
  3358                     Type arg = types.boxedClass(site).type;
  3359                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3360                     return new VarSymbol(
  3361                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3362                 } else {
  3363                     log.error(pos, "cant.deref", site);
  3364                     return syms.errSymbol;
  3369         /** Determine type of identifier or select expression and check that
  3370          *  (1) the referenced symbol is not deprecated
  3371          *  (2) the symbol's type is safe (@see checkSafe)
  3372          *  (3) if symbol is a variable, check that its type and kind are
  3373          *      compatible with the prototype and protokind.
  3374          *  (4) if symbol is an instance field of a raw type,
  3375          *      which is being assigned to, issue an unchecked warning if its
  3376          *      type changes under erasure.
  3377          *  (5) if symbol is an instance method of a raw type, issue an
  3378          *      unchecked warning if its argument types change under erasure.
  3379          *  If checks succeed:
  3380          *    If symbol is a constant, return its constant type
  3381          *    else if symbol is a method, return its result type
  3382          *    otherwise return its type.
  3383          *  Otherwise return errType.
  3385          *  @param tree       The syntax tree representing the identifier
  3386          *  @param site       If this is a select, the type of the selected
  3387          *                    expression, otherwise the type of the current class.
  3388          *  @param sym        The symbol representing the identifier.
  3389          *  @param env        The current environment.
  3390          *  @param resultInfo    The expected result
  3391          */
  3392         Type checkId(JCTree tree,
  3393                      Type site,
  3394                      Symbol sym,
  3395                      Env<AttrContext> env,
  3396                      ResultInfo resultInfo) {
  3397             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3398                     checkMethodId(tree, site, sym, env, resultInfo) :
  3399                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3402         Type checkMethodId(JCTree tree,
  3403                      Type site,
  3404                      Symbol sym,
  3405                      Env<AttrContext> env,
  3406                      ResultInfo resultInfo) {
  3407             boolean isPolymorhicSignature =
  3408                 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
  3409             return isPolymorhicSignature ?
  3410                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3411                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3414         Type checkSigPolyMethodId(JCTree tree,
  3415                      Type site,
  3416                      Symbol sym,
  3417                      Env<AttrContext> env,
  3418                      ResultInfo resultInfo) {
  3419             //recover original symbol for signature polymorphic methods
  3420             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3421             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3422             return sym.type;
  3425         Type checkMethodIdInternal(JCTree tree,
  3426                      Type site,
  3427                      Symbol sym,
  3428                      Env<AttrContext> env,
  3429                      ResultInfo resultInfo) {
  3430             Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3431             Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3432             resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3433             return owntype;
  3436         Type checkIdInternal(JCTree tree,
  3437                      Type site,
  3438                      Symbol sym,
  3439                      Type pt,
  3440                      Env<AttrContext> env,
  3441                      ResultInfo resultInfo) {
  3442             if (pt.isErroneous()) {
  3443                 return types.createErrorType(site);
  3445             Type owntype; // The computed type of this identifier occurrence.
  3446             switch (sym.kind) {
  3447             case TYP:
  3448                 // For types, the computed type equals the symbol's type,
  3449                 // except for two situations:
  3450                 owntype = sym.type;
  3451                 if (owntype.hasTag(CLASS)) {
  3452                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3453                     Type ownOuter = owntype.getEnclosingType();
  3455                     // (a) If the symbol's type is parameterized, erase it
  3456                     // because no type parameters were given.
  3457                     // We recover generic outer type later in visitTypeApply.
  3458                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3459                         owntype = types.erasure(owntype);
  3462                     // (b) If the symbol's type is an inner class, then
  3463                     // we have to interpret its outer type as a superclass
  3464                     // of the site type. Example:
  3465                     //
  3466                     // class Tree<A> { class Visitor { ... } }
  3467                     // class PointTree extends Tree<Point> { ... }
  3468                     // ...PointTree.Visitor...
  3469                     //
  3470                     // Then the type of the last expression above is
  3471                     // Tree<Point>.Visitor.
  3472                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
  3473                         Type normOuter = site;
  3474                         if (normOuter.hasTag(CLASS)) {
  3475                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3476                             if (site.isAnnotated()) {
  3477                                 // Propagate any type annotations.
  3478                                 // TODO: should asEnclosingSuper do this?
  3479                                 // Note that the type annotations in site will be updated
  3480                                 // by annotateType. Therefore, modify site instead
  3481                                 // of creating a new AnnotatedType.
  3482                                 ((AnnotatedType)site).underlyingType = normOuter;
  3483                                 normOuter = site;
  3486                         if (normOuter == null) // perhaps from an import
  3487                             normOuter = types.erasure(ownOuter);
  3488                         if (normOuter != ownOuter)
  3489                             owntype = new ClassType(
  3490                                 normOuter, List.<Type>nil(), owntype.tsym);
  3493                 break;
  3494             case VAR:
  3495                 VarSymbol v = (VarSymbol)sym;
  3496                 // Test (4): if symbol is an instance field of a raw type,
  3497                 // which is being assigned to, issue an unchecked warning if
  3498                 // its type changes under erasure.
  3499                 if (allowGenerics &&
  3500                     resultInfo.pkind == VAR &&
  3501                     v.owner.kind == TYP &&
  3502                     (v.flags() & STATIC) == 0 &&
  3503                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3504                     Type s = types.asOuterSuper(site, v.owner);
  3505                     if (s != null &&
  3506                         s.isRaw() &&
  3507                         !types.isSameType(v.type, v.erasure(types))) {
  3508                         chk.warnUnchecked(tree.pos(),
  3509                                           "unchecked.assign.to.var",
  3510                                           v, s);
  3513                 // The computed type of a variable is the type of the
  3514                 // variable symbol, taken as a member of the site type.
  3515                 owntype = (sym.owner.kind == TYP &&
  3516                            sym.name != names._this && sym.name != names._super)
  3517                     ? types.memberType(site, sym)
  3518                     : sym.type;
  3520                 // If the variable is a constant, record constant value in
  3521                 // computed type.
  3522                 if (v.getConstValue() != null && isStaticReference(tree))
  3523                     owntype = owntype.constType(v.getConstValue());
  3525                 if (resultInfo.pkind == VAL) {
  3526                     owntype = capture(owntype); // capture "names as expressions"
  3528                 break;
  3529             case MTH: {
  3530                 owntype = checkMethod(site, sym,
  3531                         new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
  3532                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  3533                         resultInfo.pt.getTypeArguments());
  3534                 break;
  3536             case PCK: case ERR:
  3537                 owntype = sym.type;
  3538                 break;
  3539             default:
  3540                 throw new AssertionError("unexpected kind: " + sym.kind +
  3541                                          " in tree " + tree);
  3544             // Test (1): emit a `deprecation' warning if symbol is deprecated.
  3545             // (for constructors, the error was given when the constructor was
  3546             // resolved)
  3548             if (sym.name != names.init) {
  3549                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  3550                 chk.checkSunAPI(tree.pos(), sym);
  3551                 chk.checkProfile(tree.pos(), sym);
  3554             // Test (3): if symbol is a variable, check that its type and
  3555             // kind are compatible with the prototype and protokind.
  3556             return check(tree, owntype, sym.kind, resultInfo);
  3559         /** Check that variable is initialized and evaluate the variable's
  3560          *  initializer, if not yet done. Also check that variable is not
  3561          *  referenced before it is defined.
  3562          *  @param tree    The tree making up the variable reference.
  3563          *  @param env     The current environment.
  3564          *  @param v       The variable's symbol.
  3565          */
  3566         private void checkInit(JCTree tree,
  3567                                Env<AttrContext> env,
  3568                                VarSymbol v,
  3569                                boolean onlyWarning) {
  3570 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
  3571 //                             tree.pos + " " + v.pos + " " +
  3572 //                             Resolve.isStatic(env));//DEBUG
  3574             // A forward reference is diagnosed if the declaration position
  3575             // of the variable is greater than the current tree position
  3576             // and the tree and variable definition occur in the same class
  3577             // definition.  Note that writes don't count as references.
  3578             // This check applies only to class and instance
  3579             // variables.  Local variables follow different scope rules,
  3580             // and are subject to definite assignment checking.
  3581             if ((env.info.enclVar == v || v.pos > tree.pos) &&
  3582                 v.owner.kind == TYP &&
  3583                 canOwnInitializer(owner(env)) &&
  3584                 v.owner == env.info.scope.owner.enclClass() &&
  3585                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  3586                 (!env.tree.hasTag(ASSIGN) ||
  3587                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  3588                 String suffix = (env.info.enclVar == v) ?
  3589                                 "self.ref" : "forward.ref";
  3590                 if (!onlyWarning || isStaticEnumField(v)) {
  3591                     log.error(tree.pos(), "illegal." + suffix);
  3592                 } else if (useBeforeDeclarationWarning) {
  3593                     log.warning(tree.pos(), suffix, v);
  3597             v.getConstValue(); // ensure initializer is evaluated
  3599             checkEnumInitializer(tree, env, v);
  3602         /**
  3603          * Check for illegal references to static members of enum.  In
  3604          * an enum type, constructors and initializers may not
  3605          * reference its static members unless they are constant.
  3607          * @param tree    The tree making up the variable reference.
  3608          * @param env     The current environment.
  3609          * @param v       The variable's symbol.
  3610          * @jls  section 8.9 Enums
  3611          */
  3612         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  3613             // JLS:
  3614             //
  3615             // "It is a compile-time error to reference a static field
  3616             // of an enum type that is not a compile-time constant
  3617             // (15.28) from constructors, instance initializer blocks,
  3618             // or instance variable initializer expressions of that
  3619             // type. It is a compile-time error for the constructors,
  3620             // instance initializer blocks, or instance variable
  3621             // initializer expressions of an enum constant e to refer
  3622             // to itself or to an enum constant of the same type that
  3623             // is declared to the right of e."
  3624             if (isStaticEnumField(v)) {
  3625                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  3627                 if (enclClass == null || enclClass.owner == null)
  3628                     return;
  3630                 // See if the enclosing class is the enum (or a
  3631                 // subclass thereof) declaring v.  If not, this
  3632                 // reference is OK.
  3633                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  3634                     return;
  3636                 // If the reference isn't from an initializer, then
  3637                 // the reference is OK.
  3638                 if (!Resolve.isInitializer(env))
  3639                     return;
  3641                 log.error(tree.pos(), "illegal.enum.static.ref");
  3645         /** Is the given symbol a static, non-constant field of an Enum?
  3646          *  Note: enum literals should not be regarded as such
  3647          */
  3648         private boolean isStaticEnumField(VarSymbol v) {
  3649             return Flags.isEnum(v.owner) &&
  3650                    Flags.isStatic(v) &&
  3651                    !Flags.isConstant(v) &&
  3652                    v.name != names._class;
  3655         /** Can the given symbol be the owner of code which forms part
  3656          *  if class initialization? This is the case if the symbol is
  3657          *  a type or field, or if the symbol is the synthetic method.
  3658          *  owning a block.
  3659          */
  3660         private boolean canOwnInitializer(Symbol sym) {
  3661             return
  3662                 (sym.kind & (VAR | TYP)) != 0 ||
  3663                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
  3666     Warner noteWarner = new Warner();
  3668     /**
  3669      * Check that method arguments conform to its instantiation.
  3670      **/
  3671     public Type checkMethod(Type site,
  3672                             Symbol sym,
  3673                             ResultInfo resultInfo,
  3674                             Env<AttrContext> env,
  3675                             final List<JCExpression> argtrees,
  3676                             List<Type> argtypes,
  3677                             List<Type> typeargtypes) {
  3678         // Test (5): if symbol is an instance method of a raw type, issue
  3679         // an unchecked warning if its argument types change under erasure.
  3680         if (allowGenerics &&
  3681             (sym.flags() & STATIC) == 0 &&
  3682             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3683             Type s = types.asOuterSuper(site, sym.owner);
  3684             if (s != null && s.isRaw() &&
  3685                 !types.isSameTypes(sym.type.getParameterTypes(),
  3686                                    sym.erasure(types).getParameterTypes())) {
  3687                 chk.warnUnchecked(env.tree.pos(),
  3688                                   "unchecked.call.mbr.of.raw.type",
  3689                                   sym, s);
  3693         if (env.info.defaultSuperCallSite != null) {
  3694             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
  3695                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  3696                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  3697                 List<MethodSymbol> icand_sup =
  3698                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  3699                 if (icand_sup.nonEmpty() &&
  3700                         icand_sup.head != sym &&
  3701                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  3702                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  3703                         diags.fragment("overridden.default", sym, sup));
  3704                     break;
  3707             env.info.defaultSuperCallSite = null;
  3710         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  3711             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  3712             if (app.meth.hasTag(SELECT) &&
  3713                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  3714                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  3718         // Compute the identifier's instantiated type.
  3719         // For methods, we need to compute the instance type by
  3720         // Resolve.instantiate from the symbol's type as well as
  3721         // any type arguments and value arguments.
  3722         noteWarner.clear();
  3723         try {
  3724             Type owntype = rs.checkMethod(
  3725                     env,
  3726                     site,
  3727                     sym,
  3728                     resultInfo,
  3729                     argtypes,
  3730                     typeargtypes,
  3731                     noteWarner);
  3733             DeferredAttr.DeferredTypeMap checkDeferredMap =
  3734                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  3736             argtypes = Type.map(argtypes, checkDeferredMap);
  3738             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  3739                 chk.warnUnchecked(env.tree.pos(),
  3740                         "unchecked.meth.invocation.applied",
  3741                         kindName(sym),
  3742                         sym.name,
  3743                         rs.methodArguments(sym.type.getParameterTypes()),
  3744                         rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
  3745                         kindName(sym.location()),
  3746                         sym.location());
  3747                owntype = new MethodType(owntype.getParameterTypes(),
  3748                        types.erasure(owntype.getReturnType()),
  3749                        types.erasure(owntype.getThrownTypes()),
  3750                        syms.methodClass);
  3753             return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  3754                     resultInfo.checkContext.inferenceContext());
  3755         } catch (Infer.InferenceException ex) {
  3756             //invalid target type - propagate exception outwards or report error
  3757             //depending on the current check context
  3758             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  3759             return types.createErrorType(site);
  3760         } catch (Resolve.InapplicableMethodException ex) {
  3761             Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
  3762             return null;
  3766     public void visitLiteral(JCLiteral tree) {
  3767         result = check(
  3768             tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
  3770     //where
  3771     /** Return the type of a literal with given type tag.
  3772      */
  3773     Type litType(TypeTag tag) {
  3774         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  3777     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  3778         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
  3781     public void visitTypeArray(JCArrayTypeTree tree) {
  3782         Type etype = attribType(tree.elemtype, env);
  3783         Type type = new ArrayType(etype, syms.arrayClass);
  3784         result = check(tree, type, TYP, resultInfo);
  3787     /** Visitor method for parameterized types.
  3788      *  Bound checking is left until later, since types are attributed
  3789      *  before supertype structure is completely known
  3790      */
  3791     public void visitTypeApply(JCTypeApply tree) {
  3792         Type owntype = types.createErrorType(tree.type);
  3794         // Attribute functor part of application and make sure it's a class.
  3795         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  3797         // Attribute type parameters
  3798         List<Type> actuals = attribTypes(tree.arguments, env);
  3800         if (clazztype.hasTag(CLASS)) {
  3801             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  3802             if (actuals.isEmpty()) //diamond
  3803                 actuals = formals;
  3805             if (actuals.length() == formals.length()) {
  3806                 List<Type> a = actuals;
  3807                 List<Type> f = formals;
  3808                 while (a.nonEmpty()) {
  3809                     a.head = a.head.withTypeVar(f.head);
  3810                     a = a.tail;
  3811                     f = f.tail;
  3813                 // Compute the proper generic outer
  3814                 Type clazzOuter = clazztype.getEnclosingType();
  3815                 if (clazzOuter.hasTag(CLASS)) {
  3816                     Type site;
  3817                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  3818                     if (clazz.hasTag(IDENT)) {
  3819                         site = env.enclClass.sym.type;
  3820                     } else if (clazz.hasTag(SELECT)) {
  3821                         site = ((JCFieldAccess) clazz).selected.type;
  3822                     } else throw new AssertionError(""+tree);
  3823                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  3824                         if (site.hasTag(CLASS))
  3825                             site = types.asOuterSuper(site, clazzOuter.tsym);
  3826                         if (site == null)
  3827                             site = types.erasure(clazzOuter);
  3828                         clazzOuter = site;
  3831                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
  3832                 if (clazztype.isAnnotated()) {
  3833                     // Use the same AnnotatedType, because it will have
  3834                     // its annotations set later.
  3835                     ((AnnotatedType)clazztype).underlyingType = owntype;
  3836                     owntype = clazztype;
  3838             } else {
  3839                 if (formals.length() != 0) {
  3840                     log.error(tree.pos(), "wrong.number.type.args",
  3841                               Integer.toString(formals.length()));
  3842                 } else {
  3843                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  3845                 owntype = types.createErrorType(tree.type);
  3848         result = check(tree, owntype, TYP, resultInfo);
  3851     public void visitTypeUnion(JCTypeUnion tree) {
  3852         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
  3853         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  3854         for (JCExpression typeTree : tree.alternatives) {
  3855             Type ctype = attribType(typeTree, env);
  3856             ctype = chk.checkType(typeTree.pos(),
  3857                           chk.checkClassType(typeTree.pos(), ctype),
  3858                           syms.throwableType);
  3859             if (!ctype.isErroneous()) {
  3860                 //check that alternatives of a union type are pairwise
  3861                 //unrelated w.r.t. subtyping
  3862                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  3863                     for (Type t : multicatchTypes) {
  3864                         boolean sub = types.isSubtype(ctype, t);
  3865                         boolean sup = types.isSubtype(t, ctype);
  3866                         if (sub || sup) {
  3867                             //assume 'a' <: 'b'
  3868                             Type a = sub ? ctype : t;
  3869                             Type b = sub ? t : ctype;
  3870                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  3874                 multicatchTypes.append(ctype);
  3875                 if (all_multicatchTypes != null)
  3876                     all_multicatchTypes.append(ctype);
  3877             } else {
  3878                 if (all_multicatchTypes == null) {
  3879                     all_multicatchTypes = ListBuffer.lb();
  3880                     all_multicatchTypes.appendList(multicatchTypes);
  3882                 all_multicatchTypes.append(ctype);
  3885         Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
  3886         if (t.hasTag(CLASS)) {
  3887             List<Type> alternatives =
  3888                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  3889             t = new UnionClassType((ClassType) t, alternatives);
  3891         tree.type = result = t;
  3894     public void visitTypeIntersection(JCTypeIntersection tree) {
  3895         attribTypes(tree.bounds, env);
  3896         tree.type = result = checkIntersection(tree, tree.bounds);
  3899     public void visitTypeParameter(JCTypeParameter tree) {
  3900         TypeVar typeVar = (TypeVar) tree.type;
  3902         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  3903             AnnotatedType antype = new AnnotatedType(typeVar);
  3904             annotateType(antype, tree.annotations);
  3905             tree.type = antype;
  3908         if (!typeVar.bound.isErroneous()) {
  3909             //fixup type-parameter bound computed in 'attribTypeVariables'
  3910             typeVar.bound = checkIntersection(tree, tree.bounds);
  3914     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  3915         Set<Type> boundSet = new HashSet<Type>();
  3916         if (bounds.nonEmpty()) {
  3917             // accept class or interface or typevar as first bound.
  3918             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  3919             boundSet.add(types.erasure(bounds.head.type));
  3920             if (bounds.head.type.isErroneous()) {
  3921                 return bounds.head.type;
  3923             else if (bounds.head.type.hasTag(TYPEVAR)) {
  3924                 // if first bound was a typevar, do not accept further bounds.
  3925                 if (bounds.tail.nonEmpty()) {
  3926                     log.error(bounds.tail.head.pos(),
  3927                               "type.var.may.not.be.followed.by.other.bounds");
  3928                     return bounds.head.type;
  3930             } else {
  3931                 // if first bound was a class or interface, accept only interfaces
  3932                 // as further bounds.
  3933                 for (JCExpression bound : bounds.tail) {
  3934                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  3935                     if (bound.type.isErroneous()) {
  3936                         bounds = List.of(bound);
  3938                     else if (bound.type.hasTag(CLASS)) {
  3939                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  3945         if (bounds.length() == 0) {
  3946             return syms.objectType;
  3947         } else if (bounds.length() == 1) {
  3948             return bounds.head.type;
  3949         } else {
  3950             Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
  3951             if (tree.hasTag(TYPEINTERSECTION)) {
  3952                 ((IntersectionClassType)owntype).intersectionKind =
  3953                         IntersectionClassType.IntersectionKind.EXPLICIT;
  3955             // ... the variable's bound is a class type flagged COMPOUND
  3956             // (see comment for TypeVar.bound).
  3957             // In this case, generate a class tree that represents the
  3958             // bound class, ...
  3959             JCExpression extending;
  3960             List<JCExpression> implementing;
  3961             if (!bounds.head.type.isInterface()) {
  3962                 extending = bounds.head;
  3963                 implementing = bounds.tail;
  3964             } else {
  3965                 extending = null;
  3966                 implementing = bounds;
  3968             JCClassDecl cd = make.at(tree).ClassDef(
  3969                 make.Modifiers(PUBLIC | ABSTRACT),
  3970                 names.empty, List.<JCTypeParameter>nil(),
  3971                 extending, implementing, List.<JCTree>nil());
  3973             ClassSymbol c = (ClassSymbol)owntype.tsym;
  3974             Assert.check((c.flags() & COMPOUND) != 0);
  3975             cd.sym = c;
  3976             c.sourcefile = env.toplevel.sourcefile;
  3978             // ... and attribute the bound class
  3979             c.flags_field |= UNATTRIBUTED;
  3980             Env<AttrContext> cenv = enter.classEnv(cd, env);
  3981             enter.typeEnvs.put(c, cenv);
  3982             attribClass(c);
  3983             return owntype;
  3987     public void visitWildcard(JCWildcard tree) {
  3988         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  3989         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  3990             ? syms.objectType
  3991             : attribType(tree.inner, env);
  3992         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  3993                                               tree.kind.kind,
  3994                                               syms.boundClass),
  3995                        TYP, resultInfo);
  3998     public void visitAnnotation(JCAnnotation tree) {
  3999         log.error(tree.pos(), "annotation.not.valid.for.type", pt());
  4000         result = tree.type = syms.errType;
  4003     public void visitAnnotatedType(JCAnnotatedType tree) {
  4004         Type underlyingType = attribType(tree.getUnderlyingType(), env);
  4005         this.attribAnnotationTypes(tree.annotations, env);
  4006         AnnotatedType antype = new AnnotatedType(underlyingType);
  4007         annotateType(antype, tree.annotations);
  4008         result = tree.type = antype;
  4011     /**
  4012      * Apply the annotations to the particular type.
  4013      */
  4014     public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
  4015         if (annotations.isEmpty())
  4016             return;
  4017         annotate.typeAnnotation(new Annotate.Annotator() {
  4018             @Override
  4019             public String toString() {
  4020                 return "annotate " + annotations + " onto " + type;
  4022             @Override
  4023             public void enterAnnotation() {
  4024                 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
  4025                 type.typeAnnotations = compounds;
  4027         });
  4030     private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
  4031         if (annotations.isEmpty())
  4032             return List.nil();
  4034         ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
  4035         for (JCAnnotation anno : annotations) {
  4036             if (anno.attribute != null) {
  4037                 // TODO: this null-check is only needed for an obscure
  4038                 // ordering issue, where annotate.flush is called when
  4039                 // the attribute is not set yet. For an example failure
  4040                 // try the referenceinfos/NestedTypes.java test.
  4041                 // Any better solutions?
  4042                 buf.append((Attribute.TypeCompound) anno.attribute);
  4045         return buf.toList();
  4048     public void visitErroneous(JCErroneous tree) {
  4049         if (tree.errs != null)
  4050             for (JCTree err : tree.errs)
  4051                 attribTree(err, env, new ResultInfo(ERR, pt()));
  4052         result = tree.type = syms.errType;
  4055     /** Default visitor method for all other trees.
  4056      */
  4057     public void visitTree(JCTree tree) {
  4058         throw new AssertionError();
  4061     /**
  4062      * Attribute an env for either a top level tree or class declaration.
  4063      */
  4064     public void attrib(Env<AttrContext> env) {
  4065         if (env.tree.hasTag(TOPLEVEL))
  4066             attribTopLevel(env);
  4067         else
  4068             attribClass(env.tree.pos(), env.enclClass.sym);
  4071     /**
  4072      * Attribute a top level tree. These trees are encountered when the
  4073      * package declaration has annotations.
  4074      */
  4075     public void attribTopLevel(Env<AttrContext> env) {
  4076         JCCompilationUnit toplevel = env.toplevel;
  4077         try {
  4078             annotate.flush();
  4079             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
  4080         } catch (CompletionFailure ex) {
  4081             chk.completionError(toplevel.pos(), ex);
  4085     /** Main method: attribute class definition associated with given class symbol.
  4086      *  reporting completion failures at the given position.
  4087      *  @param pos The source position at which completion errors are to be
  4088      *             reported.
  4089      *  @param c   The class symbol whose definition will be attributed.
  4090      */
  4091     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4092         try {
  4093             annotate.flush();
  4094             attribClass(c);
  4095         } catch (CompletionFailure ex) {
  4096             chk.completionError(pos, ex);
  4100     /** Attribute class definition associated with given class symbol.
  4101      *  @param c   The class symbol whose definition will be attributed.
  4102      */
  4103     void attribClass(ClassSymbol c) throws CompletionFailure {
  4104         if (c.type.hasTag(ERROR)) return;
  4106         // Check for cycles in the inheritance graph, which can arise from
  4107         // ill-formed class files.
  4108         chk.checkNonCyclic(null, c.type);
  4110         Type st = types.supertype(c.type);
  4111         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4112             // First, attribute superclass.
  4113             if (st.hasTag(CLASS))
  4114                 attribClass((ClassSymbol)st.tsym);
  4116             // Next attribute owner, if it is a class.
  4117             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4118                 attribClass((ClassSymbol)c.owner);
  4121         // The previous operations might have attributed the current class
  4122         // if there was a cycle. So we test first whether the class is still
  4123         // UNATTRIBUTED.
  4124         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4125             c.flags_field &= ~UNATTRIBUTED;
  4127             // Get environment current at the point of class definition.
  4128             Env<AttrContext> env = enter.typeEnvs.get(c);
  4130             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
  4131             // because the annotations were not available at the time the env was created. Therefore,
  4132             // we look up the environment chain for the first enclosing environment for which the
  4133             // lint value is set. Typically, this is the parent env, but might be further if there
  4134             // are any envs created as a result of TypeParameter nodes.
  4135             Env<AttrContext> lintEnv = env;
  4136             while (lintEnv.info.lint == null)
  4137                 lintEnv = lintEnv.next;
  4139             // Having found the enclosing lint value, we can initialize the lint value for this class
  4140             env.info.lint = lintEnv.info.lint.augment(c);
  4142             Lint prevLint = chk.setLint(env.info.lint);
  4143             JavaFileObject prev = log.useSource(c.sourcefile);
  4144             ResultInfo prevReturnRes = env.info.returnResult;
  4146             try {
  4147                 env.info.returnResult = null;
  4148                 // java.lang.Enum may not be subclassed by a non-enum
  4149                 if (st.tsym == syms.enumSym &&
  4150                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4151                     log.error(env.tree.pos(), "enum.no.subclassing");
  4153                 // Enums may not be extended by source-level classes
  4154                 if (st.tsym != null &&
  4155                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4156                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4157                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4159                 attribClassBody(env, c);
  4161                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4162                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4163             } finally {
  4164                 env.info.returnResult = prevReturnRes;
  4165                 log.useSource(prev);
  4166                 chk.setLint(prevLint);
  4172     public void visitImport(JCImport tree) {
  4173         // nothing to do
  4176     /** Finish the attribution of a class. */
  4177     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4178         JCClassDecl tree = (JCClassDecl)env.tree;
  4179         Assert.check(c == tree.sym);
  4181         // Validate annotations
  4182         chk.validateAnnotations(tree.mods.annotations, c);
  4184         // Validate type parameters, supertype and interfaces.
  4185         attribStats(tree.typarams, env);
  4186         if (!c.isAnonymous()) {
  4187             //already checked if anonymous
  4188             chk.validate(tree.typarams, env);
  4189             chk.validate(tree.extending, env);
  4190             chk.validate(tree.implementing, env);
  4193         // If this is a non-abstract class, check that it has no abstract
  4194         // methods or unimplemented methods of an implemented interface.
  4195         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4196             if (!relax)
  4197                 chk.checkAllDefined(tree.pos(), c);
  4200         if ((c.flags() & ANNOTATION) != 0) {
  4201             if (tree.implementing.nonEmpty())
  4202                 log.error(tree.implementing.head.pos(),
  4203                           "cant.extend.intf.annotation");
  4204             if (tree.typarams.nonEmpty())
  4205                 log.error(tree.typarams.head.pos(),
  4206                           "intf.annotation.cant.have.type.params");
  4208             // If this annotation has a @Repeatable, validate
  4209             Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
  4210             if (repeatable != null) {
  4211                 // get diagnostic position for error reporting
  4212                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4213                 Assert.checkNonNull(cbPos);
  4215                 chk.validateRepeatable(c, repeatable, cbPos);
  4217         } else {
  4218             // Check that all extended classes and interfaces
  4219             // are compatible (i.e. no two define methods with same arguments
  4220             // yet different return types).  (JLS 8.4.6.3)
  4221             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4222             if (allowDefaultMethods) {
  4223                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4227         // Check that class does not import the same parameterized interface
  4228         // with two different argument lists.
  4229         chk.checkClassBounds(tree.pos(), c.type);
  4231         tree.type = c.type;
  4233         for (List<JCTypeParameter> l = tree.typarams;
  4234              l.nonEmpty(); l = l.tail) {
  4235              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
  4238         // Check that a generic class doesn't extend Throwable
  4239         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4240             log.error(tree.extending.pos(), "generic.throwable");
  4242         // Check that all methods which implement some
  4243         // method conform to the method they implement.
  4244         chk.checkImplementations(tree);
  4246         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4247         checkAutoCloseable(tree.pos(), env, c.type);
  4249         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4250             // Attribute declaration
  4251             attribStat(l.head, env);
  4252             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4253             // Make an exception for static constants.
  4254             if (c.owner.kind != PCK &&
  4255                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4256                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4257                 Symbol sym = null;
  4258                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4259                 if (sym == null ||
  4260                     sym.kind != VAR ||
  4261                     ((VarSymbol) sym).getConstValue() == null)
  4262                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4266         // Check for cycles among non-initial constructors.
  4267         chk.checkCyclicConstructors(tree);
  4269         // Check for cycles among annotation elements.
  4270         chk.checkNonCyclicElements(tree);
  4272         // Check for proper use of serialVersionUID
  4273         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
  4274             isSerializable(c) &&
  4275             (c.flags() & Flags.ENUM) == 0 &&
  4276             (c.flags() & ABSTRACT) == 0) {
  4277             checkSerialVersionUID(tree, c);
  4280         // Correctly organize the postions of the type annotations
  4281         TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
  4283         // Check type annotations applicability rules
  4284         validateTypeAnnotations(tree);
  4286         // where
  4287         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4288         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4289             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4290                 if (types.isSameType(al.head.annotationType.type, t))
  4291                     return al.head.pos();
  4294             return null;
  4297         /** check if a class is a subtype of Serializable, if that is available. */
  4298         private boolean isSerializable(ClassSymbol c) {
  4299             try {
  4300                 syms.serializableType.complete();
  4302             catch (CompletionFailure e) {
  4303                 return false;
  4305             return types.isSubtype(c.type, syms.serializableType);
  4308         /** Check that an appropriate serialVersionUID member is defined. */
  4309         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4311             // check for presence of serialVersionUID
  4312             Scope.Entry e = c.members().lookup(names.serialVersionUID);
  4313             while (e.scope != null && e.sym.kind != VAR) e = e.next();
  4314             if (e.scope == null) {
  4315                 log.warning(LintCategory.SERIAL,
  4316                         tree.pos(), "missing.SVUID", c);
  4317                 return;
  4320             // check that it is static final
  4321             VarSymbol svuid = (VarSymbol)e.sym;
  4322             if ((svuid.flags() & (STATIC | FINAL)) !=
  4323                 (STATIC | FINAL))
  4324                 log.warning(LintCategory.SERIAL,
  4325                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4327             // check that it is long
  4328             else if (!svuid.type.hasTag(LONG))
  4329                 log.warning(LintCategory.SERIAL,
  4330                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4332             // check constant
  4333             else if (svuid.getConstValue() == null)
  4334                 log.warning(LintCategory.SERIAL,
  4335                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4338     private Type capture(Type type) {
  4339         //do not capture free types
  4340         return resultInfo.checkContext.inferenceContext().free(type) ?
  4341                 type : types.capture(type);
  4344     private void validateTypeAnnotations(JCTree tree) {
  4345         tree.accept(typeAnnotationsValidator);
  4347     //where
  4348     private final JCTree.Visitor typeAnnotationsValidator = new TreeScanner() {
  4350         private boolean checkAllAnnotations = false;
  4352         public void visitAnnotation(JCAnnotation tree) {
  4353             if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
  4354                 chk.validateTypeAnnotation(tree, false);
  4356             super.visitAnnotation(tree);
  4358         public void visitTypeParameter(JCTypeParameter tree) {
  4359             chk.validateTypeAnnotations(tree.annotations, true);
  4360             scan(tree.bounds);
  4361             // Don't call super.
  4362             // This is needed because above we call validateTypeAnnotation with
  4363             // false, which would forbid annotations on type parameters.
  4364             // super.visitTypeParameter(tree);
  4366         public void visitMethodDef(JCMethodDecl tree) {
  4367             if (tree.recvparam != null &&
  4368                     tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
  4369                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4370                         tree.recvparam.vartype.type.tsym);
  4372             if (tree.restype != null && tree.restype.type != null) {
  4373                 validateAnnotatedType(tree.restype, tree.restype.type);
  4375             super.visitMethodDef(tree);
  4377         public void visitVarDef(final JCVariableDecl tree) {
  4378             if (tree.sym != null && tree.sym.type != null)
  4379                 validateAnnotatedType(tree, tree.sym.type);
  4380             super.visitVarDef(tree);
  4382         public void visitTypeCast(JCTypeCast tree) {
  4383             if (tree.clazz != null && tree.clazz.type != null)
  4384                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4385             super.visitTypeCast(tree);
  4387         public void visitTypeTest(JCInstanceOf tree) {
  4388             if (tree.clazz != null && tree.clazz.type != null)
  4389                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4390             super.visitTypeTest(tree);
  4392         public void visitNewClass(JCNewClass tree) {
  4393             if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  4394                 boolean prevCheck = this.checkAllAnnotations;
  4395                 try {
  4396                     this.checkAllAnnotations = true;
  4397                     scan(((JCAnnotatedType)tree.clazz).annotations);
  4398                 } finally {
  4399                     this.checkAllAnnotations = prevCheck;
  4402             super.visitNewClass(tree);
  4404         public void visitNewArray(JCNewArray tree) {
  4405             if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  4406                 boolean prevCheck = this.checkAllAnnotations;
  4407                 try {
  4408                     this.checkAllAnnotations = true;
  4409                     scan(((JCAnnotatedType)tree.elemtype).annotations);
  4410                 } finally {
  4411                     this.checkAllAnnotations = prevCheck;
  4414             super.visitNewArray(tree);
  4417         /* I would want to model this after
  4418          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  4419          * and override visitSelect and visitTypeApply.
  4420          * However, we only set the annotated type in the top-level type
  4421          * of the symbol.
  4422          * Therefore, we need to override each individual location where a type
  4423          * can occur.
  4424          */
  4425         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  4426             if (type.getEnclosingType() != null &&
  4427                     type != type.getEnclosingType()) {
  4428                 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
  4430             for (Type targ : type.getTypeArguments()) {
  4431                 validateAnnotatedType(errtree, targ);
  4434         private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
  4435             validateAnnotatedType(errtree, type);
  4436             if (type.tsym != null &&
  4437                     type.tsym.isStatic() &&
  4438                     type.getAnnotationMirrors().nonEmpty()) {
  4439                     // Enclosing static classes cannot have type annotations.
  4440                 log.error(errtree.pos(), "cant.annotate.static.class");
  4443     };
  4445     // <editor-fold desc="post-attribution visitor">
  4447     /**
  4448      * Handle missing types/symbols in an AST. This routine is useful when
  4449      * the compiler has encountered some errors (which might have ended up
  4450      * terminating attribution abruptly); if the compiler is used in fail-over
  4451      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  4452      * prevents NPE to be progagated during subsequent compilation steps.
  4453      */
  4454     public void postAttr(JCTree tree) {
  4455         new PostAttrAnalyzer().scan(tree);
  4458     class PostAttrAnalyzer extends TreeScanner {
  4460         private void initTypeIfNeeded(JCTree that) {
  4461             if (that.type == null) {
  4462                 that.type = syms.unknownType;
  4466         @Override
  4467         public void scan(JCTree tree) {
  4468             if (tree == null) return;
  4469             if (tree instanceof JCExpression) {
  4470                 initTypeIfNeeded(tree);
  4472             super.scan(tree);
  4475         @Override
  4476         public void visitIdent(JCIdent that) {
  4477             if (that.sym == null) {
  4478                 that.sym = syms.unknownSymbol;
  4482         @Override
  4483         public void visitSelect(JCFieldAccess that) {
  4484             if (that.sym == null) {
  4485                 that.sym = syms.unknownSymbol;
  4487             super.visitSelect(that);
  4490         @Override
  4491         public void visitClassDef(JCClassDecl that) {
  4492             initTypeIfNeeded(that);
  4493             if (that.sym == null) {
  4494                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  4496             super.visitClassDef(that);
  4499         @Override
  4500         public void visitMethodDef(JCMethodDecl that) {
  4501             initTypeIfNeeded(that);
  4502             if (that.sym == null) {
  4503                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  4505             super.visitMethodDef(that);
  4508         @Override
  4509         public void visitVarDef(JCVariableDecl that) {
  4510             initTypeIfNeeded(that);
  4511             if (that.sym == null) {
  4512                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
  4513                 that.sym.adr = 0;
  4515             super.visitVarDef(that);
  4518         @Override
  4519         public void visitNewClass(JCNewClass that) {
  4520             if (that.constructor == null) {
  4521                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
  4523             if (that.constructorType == null) {
  4524                 that.constructorType = syms.unknownType;
  4526             super.visitNewClass(that);
  4529         @Override
  4530         public void visitAssignop(JCAssignOp that) {
  4531             if (that.operator == null)
  4532                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4533             super.visitAssignop(that);
  4536         @Override
  4537         public void visitBinary(JCBinary that) {
  4538             if (that.operator == null)
  4539                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4540             super.visitBinary(that);
  4543         @Override
  4544         public void visitUnary(JCUnary that) {
  4545             if (that.operator == null)
  4546                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
  4547             super.visitUnary(that);
  4550         @Override
  4551         public void visitLambda(JCLambda that) {
  4552             super.visitLambda(that);
  4553             if (that.descriptorType == null) {
  4554                 that.descriptorType = syms.unknownType;
  4556             if (that.targets == null) {
  4557                 that.targets = List.nil();
  4561         @Override
  4562         public void visitReference(JCMemberReference that) {
  4563             super.visitReference(that);
  4564             if (that.sym == null) {
  4565                 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
  4567             if (that.descriptorType == null) {
  4568                 that.descriptorType = syms.unknownType;
  4570             if (that.targets == null) {
  4571                 that.targets = List.nil();
  4575     // </editor-fold>

mercurial