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

Mon, 24 Oct 2011 13:00:30 +0100

author
mcimadamore
date
Mon, 24 Oct 2011 13:00:30 +0100
changeset 1114
05814303a056
parent 1087
3a2200681d69
child 1127
ca49d50318dc
permissions
-rw-r--r--

7098660: Write better overload resolution/inference tests
Summary: Add overload/inference debug diagnostics - added test harness using annotations to check outcome of overload resolution/inference
Reviewed-by: jjg

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

mercurial