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

Tue, 06 Mar 2012 13:28:05 +0000

author
mcimadamore
date
Tue, 06 Mar 2012 13:28:05 +0000
changeset 1219
48ee63caaa93
parent 1186
51fb17abfc32
child 1226
97bec6ab1227
permissions
-rw-r--r--

7144506: Attr.checkMethod should be called after inference variables have been fixed
Summary: Unify post-inference sanity check with Attr.checkMethod
Reviewed-by: jjg, dlsmith

     1 /*
     2  * Copyright (c) 1999, 2012, 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 com.sun.tools.javac.tree.JCTree;
    29 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
    30 import com.sun.tools.javac.tree.TreeInfo;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.List;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.code.Type.*;
    35 import com.sun.tools.javac.code.Type.ForAll.ConstraintKind;
    36 import com.sun.tools.javac.code.Symbol.*;
    37 import com.sun.tools.javac.comp.Resolve.InapplicableMethodException;
    38 import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
    39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    41 import static com.sun.tools.javac.code.TypeTags.*;
    43 /** Helper class for type parameter inference, used by the attribution phase.
    44  *
    45  *  <p><b>This is NOT part of any supported API.
    46  *  If you write code that depends on this, you do so at your own risk.
    47  *  This code and its internal interfaces are subject to change or
    48  *  deletion without notice.</b>
    49  */
    50 public class Infer {
    51     protected static final Context.Key<Infer> inferKey =
    52         new Context.Key<Infer>();
    54     /** A value for prototypes that admit any type, including polymorphic ones. */
    55     public static final Type anyPoly = new Type(NONE, null);
    57     Symtab syms;
    58     Types types;
    59     Check chk;
    60     Resolve rs;
    61     Log log;
    62     JCDiagnostic.Factory diags;
    64     public static Infer instance(Context context) {
    65         Infer instance = context.get(inferKey);
    66         if (instance == null)
    67             instance = new Infer(context);
    68         return instance;
    69     }
    71     protected Infer(Context context) {
    72         context.put(inferKey, this);
    73         syms = Symtab.instance(context);
    74         types = Types.instance(context);
    75         rs = Resolve.instance(context);
    76         log = Log.instance(context);
    77         chk = Check.instance(context);
    78         diags = JCDiagnostic.Factory.instance(context);
    79         ambiguousNoInstanceException =
    80             new NoInstanceException(true, diags);
    81         unambiguousNoInstanceException =
    82             new NoInstanceException(false, diags);
    83         invalidInstanceException =
    84             new InvalidInstanceException(diags);
    86     }
    88     public static class InferenceException extends InapplicableMethodException {
    89         private static final long serialVersionUID = 0;
    91         InferenceException(JCDiagnostic.Factory diags) {
    92             super(diags);
    93         }
    94     }
    96     public static class NoInstanceException extends InferenceException {
    97         private static final long serialVersionUID = 1;
    99         boolean isAmbiguous; // exist several incomparable best instances?
   101         NoInstanceException(boolean isAmbiguous, JCDiagnostic.Factory diags) {
   102             super(diags);
   103             this.isAmbiguous = isAmbiguous;
   104         }
   105     }
   107     public static class InvalidInstanceException extends InferenceException {
   108         private static final long serialVersionUID = 2;
   110         InvalidInstanceException(JCDiagnostic.Factory diags) {
   111             super(diags);
   112         }
   113     }
   115     private final NoInstanceException ambiguousNoInstanceException;
   116     private final NoInstanceException unambiguousNoInstanceException;
   117     private final InvalidInstanceException invalidInstanceException;
   119 /***************************************************************************
   120  * Auxiliary type values and classes
   121  ***************************************************************************/
   123     /** A mapping that turns type variables into undetermined type variables.
   124      */
   125     Mapping fromTypeVarFun = new Mapping("fromTypeVarFun") {
   126             public Type apply(Type t) {
   127                 if (t.tag == TYPEVAR) return new UndetVar(t);
   128                 else return t.map(this);
   129             }
   130         };
   132     /** A mapping that returns its type argument with every UndetVar replaced
   133      *  by its `inst' field. Throws a NoInstanceException
   134      *  if this not possible because an `inst' field is null.
   135      *  Note: mutually referring undertvars will be left uninstantiated
   136      *  (that is, they will be replaced by the underlying type-variable).
   137      */
   139     Mapping getInstFun = new Mapping("getInstFun") {
   140             public Type apply(Type t) {
   141                 switch (t.tag) {
   142                     case UNKNOWN:
   143                         throw ambiguousNoInstanceException
   144                             .setMessage("undetermined.type");
   145                     case UNDETVAR:
   146                         UndetVar that = (UndetVar) t;
   147                         if (that.inst == null)
   148                             throw ambiguousNoInstanceException
   149                                 .setMessage("type.variable.has.undetermined.type",
   150                                             that.qtype);
   151                         return isConstraintCyclic(that) ?
   152                             that.qtype :
   153                             apply(that.inst);
   154                         default:
   155                             return t.map(this);
   156                 }
   157             }
   159             private boolean isConstraintCyclic(UndetVar uv) {
   160                 Types.UnaryVisitor<Boolean> constraintScanner =
   161                         new Types.UnaryVisitor<Boolean>() {
   163                     List<Type> seen = List.nil();
   165                     Boolean visit(List<Type> ts) {
   166                         for (Type t : ts) {
   167                             if (visit(t)) return true;
   168                         }
   169                         return false;
   170                     }
   172                     public Boolean visitType(Type t, Void ignored) {
   173                         return false;
   174                     }
   176                     @Override
   177                     public Boolean visitClassType(ClassType t, Void ignored) {
   178                         if (t.isCompound()) {
   179                             return visit(types.supertype(t)) ||
   180                                     visit(types.interfaces(t));
   181                         } else {
   182                             return visit(t.getTypeArguments());
   183                         }
   184                     }
   185                     @Override
   186                     public Boolean visitWildcardType(WildcardType t, Void ignored) {
   187                         return visit(t.type);
   188                     }
   190                     @Override
   191                     public Boolean visitUndetVar(UndetVar t, Void ignored) {
   192                         if (seen.contains(t)) {
   193                             return true;
   194                         } else {
   195                             seen = seen.prepend(t);
   196                             return visit(t.inst);
   197                         }
   198                     }
   199                 };
   200                 return constraintScanner.visit(uv);
   201             }
   202         };
   204 /***************************************************************************
   205  * Mini/Maximization of UndetVars
   206  ***************************************************************************/
   208     /** Instantiate undetermined type variable to its minimal upper bound.
   209      *  Throw a NoInstanceException if this not possible.
   210      */
   211     void maximizeInst(UndetVar that, Warner warn) throws NoInstanceException {
   212         List<Type> hibounds = Type.filter(that.hibounds, errorFilter);
   213         if (that.inst == null) {
   214             if (hibounds.isEmpty())
   215                 that.inst = syms.objectType;
   216             else if (hibounds.tail.isEmpty())
   217                 that.inst = hibounds.head;
   218             else
   219                 that.inst = types.glb(hibounds);
   220         }
   221         if (that.inst == null ||
   222             that.inst.isErroneous())
   223             throw ambiguousNoInstanceException
   224                 .setMessage("no.unique.maximal.instance.exists",
   225                             that.qtype, hibounds);
   226     }
   227     //where
   228         private boolean isSubClass(Type t, final List<Type> ts) {
   229             t = t.baseType();
   230             if (t.tag == TYPEVAR) {
   231                 List<Type> bounds = types.getBounds((TypeVar)t);
   232                 for (Type s : ts) {
   233                     if (!types.isSameType(t, s.baseType())) {
   234                         for (Type bound : bounds) {
   235                             if (!isSubClass(bound, List.of(s.baseType())))
   236                                 return false;
   237                         }
   238                     }
   239                 }
   240             } else {
   241                 for (Type s : ts) {
   242                     if (!t.tsym.isSubClass(s.baseType().tsym, types))
   243                         return false;
   244                 }
   245             }
   246             return true;
   247         }
   249     private Filter<Type> errorFilter = new Filter<Type>() {
   250         @Override
   251         public boolean accepts(Type t) {
   252             return !t.isErroneous();
   253         }
   254     };
   256     /** Instantiate undetermined type variable to the lub of all its lower bounds.
   257      *  Throw a NoInstanceException if this not possible.
   258      */
   259     void minimizeInst(UndetVar that, Warner warn) throws NoInstanceException {
   260         List<Type> lobounds = Type.filter(that.lobounds, errorFilter);
   261         if (that.inst == null) {
   262             if (lobounds.isEmpty())
   263                 that.inst = syms.botType;
   264             else if (lobounds.tail.isEmpty())
   265                 that.inst = lobounds.head.isPrimitive() ? syms.errType : lobounds.head;
   266             else {
   267                 that.inst = types.lub(lobounds);
   268             }
   269             if (that.inst == null || that.inst.tag == ERROR)
   270                     throw ambiguousNoInstanceException
   271                         .setMessage("no.unique.minimal.instance.exists",
   272                                     that.qtype, lobounds);
   273             // VGJ: sort of inlined maximizeInst() below.  Adding
   274             // bounds can cause lobounds that are above hibounds.
   275             List<Type> hibounds = Type.filter(that.hibounds, errorFilter);
   276             Type hb = null;
   277             if (hibounds.isEmpty())
   278                 hb = syms.objectType;
   279             else if (hibounds.tail.isEmpty())
   280                 hb = hibounds.head;
   281             else
   282                 hb = types.glb(hibounds);
   283             if (hb == null ||
   284                 hb.isErroneous())
   285                 throw ambiguousNoInstanceException
   286                         .setMessage("incompatible.upper.bounds",
   287                                     that.qtype, hibounds);
   288         }
   289     }
   291     Type asUndetType(Type t, List<Type> undetvars) {
   292         return types.subst(t, inferenceVars(undetvars), undetvars);
   293     }
   295     List<Type> inferenceVars(List<Type> undetvars) {
   296         ListBuffer<Type> tvars = ListBuffer.lb();
   297         for (Type uv : undetvars) {
   298             tvars.append(((UndetVar)uv).qtype);
   299         }
   300         return tvars.toList();
   301     }
   303 /***************************************************************************
   304  * Exported Methods
   305  ***************************************************************************/
   307     /** Try to instantiate expression type `that' to given type `to'.
   308      *  If a maximal instantiation exists which makes this type
   309      *  a subtype of type `to', return the instantiated type.
   310      *  If no instantiation exists, or if several incomparable
   311      *  best instantiations exist throw a NoInstanceException.
   312      */
   313     public Type instantiateExpr(ForAll that,
   314                                 Type to,
   315                                 Warner warn) throws InferenceException {
   316         List<Type> undetvars = Type.map(that.tvars, fromTypeVarFun);
   317         for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail) {
   318             UndetVar uv = (UndetVar) l.head;
   319             TypeVar tv = (TypeVar)uv.qtype;
   320             ListBuffer<Type> hibounds = new ListBuffer<Type>();
   321             for (Type t : that.getConstraints(tv, ConstraintKind.EXTENDS)) {
   322                 hibounds.append(types.subst(t, that.tvars, undetvars));
   323             }
   325             List<Type> inst = that.getConstraints(tv, ConstraintKind.EQUAL);
   326             if (inst.nonEmpty() && inst.head.tag != BOT) {
   327                 uv.inst = inst.head;
   328             }
   329             uv.hibounds = hibounds.toList();
   330         }
   331         Type qtype1 = types.subst(that.qtype, that.tvars, undetvars);
   332         if (!types.isSubtype(qtype1,
   333                 qtype1.tag == UNDETVAR ? types.boxedTypeOrType(to) : to)) {
   334             throw unambiguousNoInstanceException
   335                 .setMessage("infer.no.conforming.instance.exists",
   336                             that.tvars, that.qtype, to);
   337         }
   338         for (List<Type> l = undetvars; l.nonEmpty(); l = l.tail)
   339             maximizeInst((UndetVar) l.head, warn);
   340         // System.out.println(" = " + qtype1.map(getInstFun));//DEBUG
   342         // check bounds
   343         List<Type> targs = Type.map(undetvars, getInstFun);
   344         if (Type.containsAny(targs, that.tvars)) {
   345             //replace uninferred type-vars
   346             targs = types.subst(targs,
   347                     that.tvars,
   348                     instantiateAsUninferredVars(undetvars, that.tvars));
   349         }
   350         return chk.checkType(warn.pos(), that.inst(targs, types), to);
   351     }
   352     //where
   353     private List<Type> instantiateAsUninferredVars(List<Type> undetvars, List<Type> tvars) {
   354         Assert.check(undetvars.length() == tvars.length());
   355         ListBuffer<Type> new_targs = ListBuffer.lb();
   356         //step 1 - create synthetic captured vars
   357         for (Type t : undetvars) {
   358             UndetVar uv = (UndetVar)t;
   359             Type newArg = new CapturedType(t.tsym.name, t.tsym, uv.inst, syms.botType, null);
   360             new_targs = new_targs.append(newArg);
   361         }
   362         //step 2 - replace synthetic vars in their bounds
   363         List<Type> formals = tvars;
   364         for (Type t : new_targs.toList()) {
   365             CapturedType ct = (CapturedType)t;
   366             ct.bound = types.subst(ct.bound, tvars, new_targs.toList());
   367             WildcardType wt = new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass);
   368             wt.bound = (TypeVar)formals.head;
   369             ct.wildcard = wt;
   370             formals = formals.tail;
   371         }
   372         return new_targs.toList();
   373     }
   375     /** Instantiate method type `mt' by finding instantiations of
   376      *  `tvars' so that method can be applied to `argtypes'.
   377      */
   378     public Type instantiateMethod(final Env<AttrContext> env,
   379                                   List<Type> tvars,
   380                                   MethodType mt,
   381                                   final Symbol msym,
   382                                   final List<Type> argtypes,
   383                                   final boolean allowBoxing,
   384                                   final boolean useVarargs,
   385                                   final Warner warn) throws InferenceException {
   386         //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
   387         List<Type> undetvars = Type.map(tvars, fromTypeVarFun);
   388         //final List<Type> capturedArgs = types.capture(argtypes);
   390         final List<Type> capturedArgs =
   391                 rs.checkRawArgumentsAcceptable(env, undetvars, argtypes, mt.getParameterTypes(),
   392                     allowBoxing, useVarargs, warn, new InferenceCheckHandler(undetvars));
   394         // minimize as yet undetermined type variables
   395         for (Type t : undetvars)
   396             minimizeInst((UndetVar) t, warn);
   398         /** Type variables instantiated to bottom */
   399         ListBuffer<Type> restvars = new ListBuffer<Type>();
   401         /** Undet vars instantiated to bottom */
   402         final ListBuffer<Type> restundet = new ListBuffer<Type>();
   404         /** Instantiated types or TypeVars if under-constrained */
   405         ListBuffer<Type> insttypes = new ListBuffer<Type>();
   407         /** Instantiated types or UndetVars if under-constrained */
   408         ListBuffer<Type> undettypes = new ListBuffer<Type>();
   410         for (Type t : undetvars) {
   411             UndetVar uv = (UndetVar)t;
   412             if (uv.inst.tag == BOT) {
   413                 restvars.append(uv.qtype);
   414                 restundet.append(uv);
   415                 insttypes.append(uv.qtype);
   416                 undettypes.append(uv);
   417                 uv.inst = null;
   418             } else {
   419                 insttypes.append(uv.inst);
   420                 undettypes.append(uv.inst);
   421             }
   422         }
   423         checkWithinBounds(tvars, undettypes.toList(), warn);
   425         mt = (MethodType)types.subst(mt, tvars, insttypes.toList());
   427         if (!restvars.isEmpty()) {
   428             // if there are uninstantiated variables,
   429             // quantify result type with them
   430             final List<Type> inferredTypes = insttypes.toList();
   431             final List<Type> all_tvars = tvars; //this is the wrong tvars
   432             return new UninferredMethodType(env.tree.pos(), msym, mt, restvars.toList()) {
   433                 @Override
   434                 List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
   435                     for (Type t : restundet.toList()) {
   436                         UndetVar uv = (UndetVar)t;
   437                         if (uv.qtype == tv) {
   438                             switch (ck) {
   439                                 case EXTENDS: return uv.hibounds.appendList(types.subst(types.getBounds(tv), all_tvars, inferredTypes));
   440                                 case SUPER: return uv.lobounds;
   441                                 case EQUAL: return uv.inst != null ? List.of(uv.inst) : List.<Type>nil();
   442                             }
   443                         }
   444                     }
   445                     return List.nil();
   446                 }
   447                 @Override
   448                 void instantiateReturnType(Type restype, List<Type> inferred, Types types) throws NoInstanceException {
   449                     Type owntype = new MethodType(types.subst(getParameterTypes(), tvars, inferred),
   450                                        restype,
   451                                        types.subst(getThrownTypes(), tvars, inferred),
   452                                        qtype.tsym);
   453                     // check that actuals conform to inferred formals
   454                     checkArgumentsAcceptable(env, capturedArgs, owntype.getParameterTypes(), allowBoxing, useVarargs, warn);
   455                     // check that inferred bounds conform to their bounds
   456                     checkWithinBounds(all_tvars,
   457                            types.subst(inferredTypes, tvars, inferred), warn);
   458                     qtype = chk.checkMethod(owntype, msym, env, TreeInfo.args(env.tree), capturedArgs, useVarargs);
   459                 }
   460             };
   461         }
   462         else {
   463             // check that actuals conform to inferred formals
   464             checkArgumentsAcceptable(env, capturedArgs, mt.getParameterTypes(), allowBoxing, useVarargs, warn);
   465             // return instantiated version of method type
   466             return mt;
   467         }
   468     }
   469     //where
   471         /** inference check handler **/
   472         class InferenceCheckHandler implements Resolve.MethodCheckHandler {
   474             List<Type> undetvars;
   476             public InferenceCheckHandler(List<Type> undetvars) {
   477                 this.undetvars = undetvars;
   478             }
   480             public InapplicableMethodException arityMismatch() {
   481                 return unambiguousNoInstanceException.setMessage("infer.arg.length.mismatch");
   482             }
   483             public InapplicableMethodException argumentMismatch(boolean varargs, Type found, Type expected) {
   484                 String key = varargs ?
   485                     "infer.varargs.argument.mismatch" :
   486                     "infer.no.conforming.assignment.exists";
   487                 return unambiguousNoInstanceException.setMessage(key,
   488                         inferenceVars(undetvars), found, expected);
   489             }
   490             public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
   491                 return unambiguousNoInstanceException.setMessage("inaccessible.varargs.type",
   492                         expected, Kinds.kindName(location), location);
   493             }
   494         }
   496         /**
   497          * A delegated type representing a partially uninferred method type.
   498          * The return type of a partially uninferred method type is a ForAll
   499          * type - when the return type is instantiated (see Infer.instantiateExpr)
   500          * the underlying method type is also updated.
   501          */
   502         abstract class UninferredMethodType extends DelegatedType {
   504             final List<Type> tvars;
   505             final Symbol msym;
   506             final DiagnosticPosition pos;
   508             public UninferredMethodType(DiagnosticPosition pos, Symbol msym, MethodType mtype, List<Type> tvars) {
   509                 super(METHOD, new MethodType(mtype.argtypes, null, mtype.thrown, mtype.tsym));
   510                 this.tvars = tvars;
   511                 this.msym = msym;
   512                 this.pos = pos;
   513                 asMethodType().restype = new UninferredReturnType(tvars, mtype.restype);
   514             }
   516             @Override
   517             public MethodType asMethodType() {
   518                 return qtype.asMethodType();
   519             }
   521             @Override
   522             public Type map(Mapping f) {
   523                 return qtype.map(f);
   524             }
   526             abstract void instantiateReturnType(Type restype, List<Type> inferred, Types types);
   528             abstract List<Type> getConstraints(TypeVar tv, ConstraintKind ck);
   530             class UninferredReturnType extends ForAll {
   531                 public UninferredReturnType(List<Type> tvars, Type restype) {
   532                     super(tvars, restype);
   533                 }
   534                 @Override
   535                 public Type inst(List<Type> actuals, Types types) {
   536                     Type newRestype = super.inst(actuals, types);
   537                     instantiateReturnType(newRestype, actuals, types);
   538                     if (rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
   539                         log.note(pos, "deferred.method.inst", msym, UninferredMethodType.this.qtype, newRestype);
   540                     }
   541                     return UninferredMethodType.this.qtype.getReturnType();
   542                 }
   543                 @Override
   544                 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
   545                     return UninferredMethodType.this.getConstraints(tv, ck);
   546                 }
   547             }
   548         }
   550         private void checkArgumentsAcceptable(Env<AttrContext> env, List<Type> actuals, List<Type> formals,
   551                 boolean allowBoxing, boolean useVarargs, Warner warn) {
   552             try {
   553                 rs.checkRawArgumentsAcceptable(env, actuals, formals,
   554                        allowBoxing, useVarargs, warn);
   555             }
   556             catch (InapplicableMethodException ex) {
   557                 // inferred method is not applicable
   558                 throw invalidInstanceException.setMessage(ex.getDiagnostic());
   559             }
   560         }
   562     /** Try to instantiate argument type `that' to given type `to'.
   563      *  If this fails, try to insantiate `that' to `to' where
   564      *  every occurrence of a type variable in `tvars' is replaced
   565      *  by an unknown type.
   566      */
   567     private Type instantiateArg(ForAll that,
   568                                 Type to,
   569                                 List<Type> tvars,
   570                                 Warner warn) throws InferenceException {
   571         List<Type> targs;
   572         try {
   573             return instantiateExpr(that, to, warn);
   574         } catch (NoInstanceException ex) {
   575             Type to1 = to;
   576             for (List<Type> l = tvars; l.nonEmpty(); l = l.tail)
   577                 to1 = types.subst(to1, List.of(l.head), List.of(syms.unknownType));
   578             return instantiateExpr(that, to1, warn);
   579         }
   580     }
   582     /** check that type parameters are within their bounds.
   583      */
   584     void checkWithinBounds(List<Type> tvars,
   585                                    List<Type> arguments,
   586                                    Warner warn)
   587         throws InvalidInstanceException {
   588         for (List<Type> tvs = tvars, args = arguments;
   589              tvs.nonEmpty();
   590              tvs = tvs.tail, args = args.tail) {
   591             if (args.head instanceof UndetVar ||
   592                     tvars.head.getUpperBound().isErroneous()) continue;
   593             List<Type> bounds = types.subst(types.getBounds((TypeVar)tvs.head), tvars, arguments);
   594             if (!types.isSubtypeUnchecked(args.head, bounds, warn))
   595                 throw invalidInstanceException
   596                     .setMessage("inferred.do.not.conform.to.bounds",
   597                                 args.head, bounds);
   598         }
   599     }
   601     /**
   602      * Compute a synthetic method type corresponding to the requested polymorphic
   603      * method signature. The target return type is computed from the immediately
   604      * enclosing scope surrounding the polymorphic-signature call.
   605      */
   606     Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env, Type site,
   607                                             Name name,
   608                                             MethodSymbol spMethod,  // sig. poly. method or null if none
   609                                             List<Type> argtypes) {
   610         final Type restype;
   612         //The return type for a polymorphic signature call is computed from
   613         //the enclosing tree E, as follows: if E is a cast, then use the
   614         //target type of the cast expression as a return type; if E is an
   615         //expression statement, the return type is 'void' - otherwise the
   616         //return type is simply 'Object'. A correctness check ensures that
   617         //env.next refers to the lexically enclosing environment in which
   618         //the polymorphic signature call environment is nested.
   620         switch (env.next.tree.getTag()) {
   621             case TYPECAST:
   622                 JCTypeCast castTree = (JCTypeCast)env.next.tree;
   623                 restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
   624                     castTree.clazz.type :
   625                     syms.objectType;
   626                 break;
   627             case EXEC:
   628                 JCTree.JCExpressionStatement execTree =
   629                         (JCTree.JCExpressionStatement)env.next.tree;
   630                 restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
   631                     syms.voidType :
   632                     syms.objectType;
   633                 break;
   634             default:
   635                 restype = syms.objectType;
   636         }
   638         List<Type> paramtypes = Type.map(argtypes, implicitArgType);
   639         List<Type> exType = spMethod != null ?
   640             spMethod.getThrownTypes() :
   641             List.of(syms.throwableType); // make it throw all exceptions
   643         MethodType mtype = new MethodType(paramtypes,
   644                                           restype,
   645                                           exType,
   646                                           syms.methodClass);
   647         return mtype;
   648     }
   649     //where
   650         Mapping implicitArgType = new Mapping ("implicitArgType") {
   651                 public Type apply(Type t) {
   652                     t = types.erasure(t);
   653                     if (t.tag == BOT)
   654                         // nulls type as the marker type Null (which has no instances)
   655                         // infer as java.lang.Void for now
   656                         t = types.boxedClass(syms.voidType).type;
   657                     return t;
   658                 }
   659         };
   660     }

mercurial