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

Mon, 21 Jan 2013 20:13:56 +0000

author
mcimadamore
date
Mon, 21 Jan 2013 20:13:56 +0000
changeset 1510
7873d37f5b37
parent 1479
38d3d1027f5a
child 1519
97bd5e7151bc
permissions
-rw-r--r--

8005244: Implement overload resolution as per latest spec EDR
Summary: Add support for stuck expressions and provisional applicability
Reviewed-by: jjg

     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.code.*;
    29 import com.sun.tools.javac.code.Symbol.*;
    30 import com.sun.tools.javac.code.Type.*;
    31 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    32 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    33 import com.sun.tools.javac.comp.Resolve.InapplicableMethodException;
    34 import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
    35 import com.sun.tools.javac.tree.JCTree;
    36 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
    37 import com.sun.tools.javac.tree.TreeInfo;
    38 import com.sun.tools.javac.util.*;
    39 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    42 import java.util.HashMap;
    43 import java.util.Map;
    45 import static com.sun.tools.javac.code.TypeTag.*;
    47 /** Helper class for type parameter inference, used by the attribution phase.
    48  *
    49  *  <p><b>This is NOT part of any supported API.
    50  *  If you write code that depends on this, you do so at your own risk.
    51  *  This code and its internal interfaces are subject to change or
    52  *  deletion without notice.</b>
    53  */
    54 public class Infer {
    55     protected static final Context.Key<Infer> inferKey =
    56         new Context.Key<Infer>();
    58     /** A value for prototypes that admit any type, including polymorphic ones. */
    59     public static final Type anyPoly = new Type(NONE, null);
    61     Symtab syms;
    62     Types types;
    63     Check chk;
    64     Resolve rs;
    65     DeferredAttr deferredAttr;
    66     Log log;
    67     JCDiagnostic.Factory diags;
    69     /** Should we inject return-type constraints earlier? */
    70     boolean allowEarlyReturnConstraints;
    72     public static Infer instance(Context context) {
    73         Infer instance = context.get(inferKey);
    74         if (instance == null)
    75             instance = new Infer(context);
    76         return instance;
    77     }
    79     protected Infer(Context context) {
    80         context.put(inferKey, this);
    81         syms = Symtab.instance(context);
    82         types = Types.instance(context);
    83         rs = Resolve.instance(context);
    84         deferredAttr = DeferredAttr.instance(context);
    85         log = Log.instance(context);
    86         chk = Check.instance(context);
    87         diags = JCDiagnostic.Factory.instance(context);
    88         inferenceException = new InferenceException(diags);
    89         allowEarlyReturnConstraints = Source.instance(context).allowEarlyReturnConstraints();
    90     }
    92    /**
    93     * This exception class is design to store a list of diagnostics corresponding
    94     * to inference errors that can arise during a method applicability check.
    95     */
    96     public static class InferenceException extends InapplicableMethodException {
    97         private static final long serialVersionUID = 0;
    99         List<JCDiagnostic> messages = List.nil();
   101         InferenceException(JCDiagnostic.Factory diags) {
   102             super(diags);
   103         }
   105         @Override
   106         InapplicableMethodException setMessage(JCDiagnostic diag) {
   107             messages = messages.append(diag);
   108             return this;
   109         }
   111         @Override
   112         public JCDiagnostic getDiagnostic() {
   113             return messages.head;
   114         }
   116         void clear() {
   117             messages = List.nil();
   118         }
   119     }
   121     final InferenceException inferenceException;
   123 /***************************************************************************
   124  * Mini/Maximization of UndetVars
   125  ***************************************************************************/
   127     /** Instantiate undetermined type variable to its minimal upper bound.
   128      *  Throw a NoInstanceException if this not possible.
   129      */
   130    void maximizeInst(UndetVar that, Warner warn) throws InferenceException {
   131         List<Type> hibounds = Type.filter(that.getBounds(InferenceBound.UPPER), boundFilter);
   132         if (that.getBounds(InferenceBound.EQ).isEmpty()) {
   133             if (hibounds.isEmpty())
   134                 that.inst = syms.objectType;
   135             else if (hibounds.tail.isEmpty())
   136                 that.inst = hibounds.head;
   137             else
   138                 that.inst = types.glb(hibounds);
   139         } else {
   140             that.inst = that.getBounds(InferenceBound.EQ).head;
   141         }
   142         if (that.inst == null ||
   143             that.inst.isErroneous())
   144             throw inferenceException
   145                 .setMessage("no.unique.maximal.instance.exists",
   146                             that.qtype, hibounds);
   147     }
   149     private Filter<Type> boundFilter = new Filter<Type>() {
   150         @Override
   151         public boolean accepts(Type t) {
   152             return !t.isErroneous() && !t.hasTag(BOT);
   153         }
   154     };
   156     /** Instantiate undetermined type variable to the lub of all its lower bounds.
   157      *  Throw a NoInstanceException if this not possible.
   158      */
   159     void minimizeInst(UndetVar that, Warner warn) throws InferenceException {
   160         List<Type> lobounds = Type.filter(that.getBounds(InferenceBound.LOWER), boundFilter);
   161         if (that.getBounds(InferenceBound.EQ).isEmpty()) {
   162             if (lobounds.isEmpty()) {
   163                 //do nothing - the inference variable is under-constrained
   164                 return;
   165             } else if (lobounds.tail.isEmpty())
   166                 that.inst = lobounds.head.isPrimitive() ? syms.errType : lobounds.head;
   167             else {
   168                 that.inst = types.lub(lobounds);
   169             }
   170             if (that.inst == null || that.inst.hasTag(ERROR))
   171                     throw inferenceException
   172                         .setMessage("no.unique.minimal.instance.exists",
   173                                     that.qtype, lobounds);
   174         } else {
   175             that.inst = that.getBounds(InferenceBound.EQ).head;
   176         }
   177     }
   179 /***************************************************************************
   180  * Exported Methods
   181  ***************************************************************************/
   183     /**
   184      * Instantiate uninferred inference variables (JLS 15.12.2.8). First
   185      * if the method return type is non-void, we derive constraints from the
   186      * expected type - then we use declared bound well-formedness to derive additional
   187      * constraints. If no instantiation exists, or if several incomparable
   188      * best instantiations exist throw a NoInstanceException.
   189      */
   190     public void instantiateUninferred(DiagnosticPosition pos,
   191             InferenceContext inferenceContext,
   192             MethodType mtype,
   193             Attr.ResultInfo resultInfo,
   194             Warner warn) throws InferenceException {
   195         while (true) {
   196             boolean stuck = true;
   197             for (Type t : inferenceContext.undetvars) {
   198                 UndetVar uv = (UndetVar)t;
   199                 if (uv.inst == null && (uv.getBounds(InferenceBound.EQ).nonEmpty() ||
   200                         !inferenceContext.free(uv.getBounds(InferenceBound.UPPER)))) {
   201                     maximizeInst((UndetVar)t, warn);
   202                     stuck = false;
   203                 }
   204             }
   205             if (inferenceContext.restvars().isEmpty()) {
   206                 //all variables have been instantiated - exit
   207                 break;
   208             } else if (stuck) {
   209                 //some variables could not be instantiated because of cycles in
   210                 //upper bounds - provide a (possibly recursive) default instantiation
   211                 instantiateAsUninferredVars(inferenceContext);
   212                 break;
   213             } else {
   214                 //some variables have been instantiated - replace newly instantiated
   215                 //variables in remaining upper bounds and continue
   216                 for (Type t : inferenceContext.undetvars) {
   217                     UndetVar uv = (UndetVar)t;
   218                     uv.substBounds(inferenceContext.inferenceVars(), inferenceContext.instTypes(), types);
   219                 }
   220             }
   221         }
   222     }
   224     /**
   225      * Infer cyclic inference variables as described in 15.12.2.8.
   226      */
   227     private void instantiateAsUninferredVars(InferenceContext inferenceContext) {
   228         ListBuffer<Type> todo = ListBuffer.lb();
   229         //step 1 - create fresh tvars
   230         for (Type t : inferenceContext.undetvars) {
   231             UndetVar uv = (UndetVar)t;
   232             if (uv.inst == null) {
   233                 TypeSymbol fresh_tvar = new TypeSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner);
   234                 fresh_tvar.type = new TypeVar(fresh_tvar, types.makeCompoundType(uv.getBounds(InferenceBound.UPPER)), null);
   235                 todo.append(uv);
   236                 uv.inst = fresh_tvar.type;
   237             }
   238         }
   239         //step 2 - replace fresh tvars in their bounds
   240         List<Type> formals = inferenceContext.inferenceVars();
   241         for (Type t : todo) {
   242             UndetVar uv = (UndetVar)t;
   243             TypeVar ct = (TypeVar)uv.inst;
   244             ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct), types));
   245             if (ct.bound.isErroneous()) {
   246                 //report inference error if glb fails
   247                 reportBoundError(uv, BoundErrorKind.BAD_UPPER);
   248             }
   249             formals = formals.tail;
   250         }
   251     }
   253     /** Instantiate a generic method type by finding instantiations for all its
   254      * inference variables so that it can be applied to a given argument type list.
   255      */
   256     public Type instantiateMethod(Env<AttrContext> env,
   257                                   List<Type> tvars,
   258                                   MethodType mt,
   259                                   Attr.ResultInfo resultInfo,
   260                                   Symbol msym,
   261                                   List<Type> argtypes,
   262                                   boolean allowBoxing,
   263                                   boolean useVarargs,
   264                                   Resolve.MethodResolutionContext resolveContext,
   265                                   Resolve.MethodCheck methodCheck,
   266                                   Warner warn) throws InferenceException {
   267         //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
   268         final InferenceContext inferenceContext = new InferenceContext(tvars, this, true);
   269         inferenceException.clear();
   271         DeferredAttr.DeferredAttrContext deferredAttrContext =
   272                 resolveContext.deferredAttrContext(msym, inferenceContext);
   274         try {
   275             methodCheck.argumentsAcceptable(env, deferredAttrContext, argtypes, mt.getParameterTypes(), warn);
   277             if (resultInfo != null && allowEarlyReturnConstraints &&
   278                     !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
   279                 generateReturnConstraints(mt, inferenceContext, resultInfo);
   280             }
   282             deferredAttrContext.complete();
   284             // minimize as yet undetermined type variables
   285             for (Type t : inferenceContext.undetvars) {
   286                 minimizeInst((UndetVar)t, warn);
   287             }
   289             checkWithinBounds(inferenceContext, warn);
   291             mt = (MethodType)inferenceContext.asInstType(mt, types);
   293             List<Type> restvars = inferenceContext.restvars();
   295             if (!restvars.isEmpty()) {
   296                 if (resultInfo != null && !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
   297                     if (!allowEarlyReturnConstraints) {
   298                         generateReturnConstraints(mt, inferenceContext, resultInfo);
   299                     }
   300                     instantiateUninferred(env.tree.pos(), inferenceContext, mt, resultInfo, warn);
   301                     checkWithinBounds(inferenceContext, warn);
   302                     mt = (MethodType)inferenceContext.asInstType(mt, types);
   303                     if (rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
   304                         log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt);
   305                     }
   306                 }
   307             }
   309             // return instantiated version of method type
   310             return mt;
   311         } finally {
   312             inferenceContext.notifyChange(types);
   313         }
   314     }
   315     //where
   316         void generateReturnConstraints(Type mt, InferenceContext inferenceContext, Attr.ResultInfo resultInfo) {
   317             if (resultInfo != null) {
   318                 Type to = resultInfo.pt;
   319                 if (to.hasTag(NONE) || resultInfo.checkContext.inferenceContext().free(resultInfo.pt)) {
   320                     to = mt.getReturnType().isPrimitiveOrVoid() ?
   321                             mt.getReturnType() : syms.objectType;
   322                 }
   323                 Type qtype1 = inferenceContext.asFree(mt.getReturnType(), types);
   324                 if (!types.isSubtype(qtype1,
   325                         qtype1.hasTag(UNDETVAR) ? types.boxedTypeOrType(to) : to)) {
   326                     throw inferenceException
   327                             .setMessage("infer.no.conforming.instance.exists",
   328                             inferenceContext.restvars(), mt.getReturnType(), to);
   329                 }
   330             }
   331         }
   333     /** check that type parameters are within their bounds.
   334      */
   335     void checkWithinBounds(InferenceContext inferenceContext,
   336                            Warner warn) throws InferenceException {
   337         //step 1 - check compatibility of instantiated type w.r.t. initial bounds
   338         for (Type t : inferenceContext.undetvars) {
   339             UndetVar uv = (UndetVar)t;
   340             uv.substBounds(inferenceContext.inferenceVars(), inferenceContext.instTypes(), types);
   341             checkCompatibleUpperBounds(uv, inferenceContext.inferenceVars());
   342             if (!inferenceContext.restvars().contains(uv.qtype)) {
   343                 Type inst = inferenceContext.asInstType(t, types);
   344                 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
   345                     if (!types.isSubtypeUnchecked(inst, inferenceContext.asFree(u, types), warn)) {
   346                         reportBoundError(uv, BoundErrorKind.UPPER);
   347                     }
   348                 }
   349                 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
   350                     Assert.check(!inferenceContext.free(l));
   351                     if (!types.isSubtypeUnchecked(l, inst, warn)) {
   352                         reportBoundError(uv, BoundErrorKind.LOWER);
   353                     }
   354                 }
   355                 for (Type e : uv.getBounds(InferenceBound.EQ)) {
   356                     Assert.check(!inferenceContext.free(e));
   357                     if (!types.isSameType(inst, e)) {
   358                         reportBoundError(uv, BoundErrorKind.EQ);
   359                     }
   360                 }
   361             }
   362         }
   364         //step 2 - check that eq bounds are consistent w.r.t. eq/lower bounds
   365         for (Type t : inferenceContext.undetvars) {
   366             UndetVar uv = (UndetVar)t;
   367             //check eq bounds consistency
   368             Type eq = null;
   369             for (Type e : uv.getBounds(InferenceBound.EQ)) {
   370                 Assert.check(!inferenceContext.free(e));
   371                 if (eq != null && !types.isSameType(e, eq)) {
   372                     reportBoundError(uv, BoundErrorKind.EQ);
   373                 }
   374                 eq = e;
   375                 for (Type l : uv.getBounds(InferenceBound.LOWER)) {
   376                     Assert.check(!inferenceContext.free(l));
   377                     if (!types.isSubtypeUnchecked(l, e, warn)) {
   378                         reportBoundError(uv, BoundErrorKind.BAD_EQ_LOWER);
   379                     }
   380                 }
   381                 for (Type u : uv.getBounds(InferenceBound.UPPER)) {
   382                     if (inferenceContext.free(u)) continue;
   383                     if (!types.isSubtypeUnchecked(e, u, warn)) {
   384                         reportBoundError(uv, BoundErrorKind.BAD_EQ_UPPER);
   385                     }
   386                 }
   387             }
   388         }
   389     }
   391     void checkCompatibleUpperBounds(UndetVar uv, List<Type> tvars) {
   392         // VGJ: sort of inlined maximizeInst() below.  Adding
   393         // bounds can cause lobounds that are above hibounds.
   394         ListBuffer<Type> hiboundsNoVars = ListBuffer.lb();
   395         for (Type t : Type.filter(uv.getBounds(InferenceBound.UPPER), boundFilter)) {
   396             if (!t.containsAny(tvars)) {
   397                 hiboundsNoVars.append(t);
   398             }
   399         }
   400         List<Type> hibounds = hiboundsNoVars.toList();
   401         Type hb = null;
   402         if (hibounds.isEmpty())
   403             hb = syms.objectType;
   404         else if (hibounds.tail.isEmpty())
   405             hb = hibounds.head;
   406         else
   407             hb = types.glb(hibounds);
   408         if (hb == null || hb.isErroneous())
   409             reportBoundError(uv, BoundErrorKind.BAD_UPPER);
   410     }
   412     enum BoundErrorKind {
   413         BAD_UPPER() {
   414             @Override
   415             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   416                 return ex.setMessage("incompatible.upper.bounds", uv.qtype,
   417                         uv.getBounds(InferenceBound.UPPER));
   418             }
   419         },
   420         BAD_EQ_UPPER() {
   421             @Override
   422             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   423                 return ex.setMessage("incompatible.eq.upper.bounds", uv.qtype,
   424                         uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.UPPER));
   425             }
   426         },
   427         BAD_EQ_LOWER() {
   428             @Override
   429             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   430                 return ex.setMessage("incompatible.eq.lower.bounds", uv.qtype,
   431                         uv.getBounds(InferenceBound.EQ), uv.getBounds(InferenceBound.LOWER));
   432             }
   433         },
   434         UPPER() {
   435             @Override
   436             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   437                 return ex.setMessage("inferred.do.not.conform.to.upper.bounds", uv.inst,
   438                         uv.getBounds(InferenceBound.UPPER));
   439             }
   440         },
   441         LOWER() {
   442             @Override
   443             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   444                 return ex.setMessage("inferred.do.not.conform.to.lower.bounds", uv.inst,
   445                         uv.getBounds(InferenceBound.LOWER));
   446             }
   447         },
   448         EQ() {
   449             @Override
   450             InapplicableMethodException setMessage(InferenceException ex, UndetVar uv) {
   451                 return ex.setMessage("inferred.do.not.conform.to.eq.bounds", uv.inst,
   452                         uv.getBounds(InferenceBound.EQ));
   453             }
   454         };
   456         abstract InapplicableMethodException setMessage(InferenceException ex, UndetVar uv);
   457     }
   458     //where
   459     void reportBoundError(UndetVar uv, BoundErrorKind bk) {
   460         throw bk.setMessage(inferenceException, uv);
   461     }
   463     // <editor-fold desc="functional interface instantiation">
   464     /**
   465      * This method is used to infer a suitable target functional interface in case
   466      * the original parameterized interface contains wildcards. An inference process
   467      * is applied so that wildcard bounds, as well as explicit lambda/method ref parameters
   468      * (where applicable) are used to constraint the solution.
   469      */
   470     public Type instantiateFunctionalInterface(DiagnosticPosition pos, Type funcInterface,
   471             List<Type> paramTypes, Check.CheckContext checkContext) {
   472         if (types.capture(funcInterface) == funcInterface) {
   473             //if capture doesn't change the type then return the target unchanged
   474             //(this means the target contains no wildcards!)
   475             return funcInterface;
   476         } else {
   477             Type formalInterface = funcInterface.tsym.type;
   478             InferenceContext funcInterfaceContext =
   479                     new InferenceContext(funcInterface.tsym.type.getTypeArguments(), this, false);
   480             Assert.check(paramTypes != null);
   481             //get constraints from explicit params (this is done by
   482             //checking that explicit param types are equal to the ones
   483             //in the functional interface descriptors)
   484             List<Type> descParameterTypes = types.findDescriptorType(formalInterface).getParameterTypes();
   485             if (descParameterTypes.size() != paramTypes.size()) {
   486                 checkContext.report(pos, diags.fragment("incompatible.arg.types.in.lambda"));
   487                 return types.createErrorType(funcInterface);
   488             }
   489             for (Type p : descParameterTypes) {
   490                 if (!types.isSameType(funcInterfaceContext.asFree(p, types), paramTypes.head)) {
   491                     checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
   492                     return types.createErrorType(funcInterface);
   493                 }
   494                 paramTypes = paramTypes.tail;
   495             }
   496             List<Type> actualTypeargs = funcInterface.getTypeArguments();
   497             for (Type t : funcInterfaceContext.undetvars) {
   498                 UndetVar uv = (UndetVar)t;
   499                 minimizeInst(uv, types.noWarnings);
   500                 if (uv.inst == null &&
   501                         Type.filter(uv.getBounds(InferenceBound.UPPER), boundFilter).nonEmpty()) {
   502                     maximizeInst(uv, types.noWarnings);
   503                 }
   504                 if (uv.inst == null) {
   505                     uv.inst = actualTypeargs.head;
   506                 }
   507                 actualTypeargs = actualTypeargs.tail;
   508             }
   509             Type owntype = funcInterfaceContext.asInstType(formalInterface, types);
   510             if (!chk.checkValidGenericType(owntype)) {
   511                 //if the inferred functional interface type is not well-formed,
   512                 //or if it's not a subtype of the original target, issue an error
   513                 checkContext.report(pos, diags.fragment("no.suitable.functional.intf.inst", funcInterface));
   514             }
   515             return owntype;
   516         }
   517     }
   518     // </editor-fold>
   520     /**
   521      * Compute a synthetic method type corresponding to the requested polymorphic
   522      * method signature. The target return type is computed from the immediately
   523      * enclosing scope surrounding the polymorphic-signature call.
   524      */
   525     Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
   526                                             MethodSymbol spMethod,  // sig. poly. method or null if none
   527                                             Resolve.MethodResolutionContext resolveContext,
   528                                             List<Type> argtypes) {
   529         final Type restype;
   531         //The return type for a polymorphic signature call is computed from
   532         //the enclosing tree E, as follows: if E is a cast, then use the
   533         //target type of the cast expression as a return type; if E is an
   534         //expression statement, the return type is 'void' - otherwise the
   535         //return type is simply 'Object'. A correctness check ensures that
   536         //env.next refers to the lexically enclosing environment in which
   537         //the polymorphic signature call environment is nested.
   539         switch (env.next.tree.getTag()) {
   540             case TYPECAST:
   541                 JCTypeCast castTree = (JCTypeCast)env.next.tree;
   542                 restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
   543                     castTree.clazz.type :
   544                     syms.objectType;
   545                 break;
   546             case EXEC:
   547                 JCTree.JCExpressionStatement execTree =
   548                         (JCTree.JCExpressionStatement)env.next.tree;
   549                 restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
   550                     syms.voidType :
   551                     syms.objectType;
   552                 break;
   553             default:
   554                 restype = syms.objectType;
   555         }
   557         List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
   558         List<Type> exType = spMethod != null ?
   559             spMethod.getThrownTypes() :
   560             List.of(syms.throwableType); // make it throw all exceptions
   562         MethodType mtype = new MethodType(paramtypes,
   563                                           restype,
   564                                           exType,
   565                                           syms.methodClass);
   566         return mtype;
   567     }
   568     //where
   569         class ImplicitArgType extends DeferredAttr.DeferredTypeMap {
   571             public ImplicitArgType(Symbol msym, Resolve.MethodResolutionPhase phase) {
   572                 deferredAttr.super(AttrMode.SPECULATIVE, msym, phase);
   573             }
   575             public Type apply(Type t) {
   576                 t = types.erasure(super.apply(t));
   577                 if (t.hasTag(BOT))
   578                     // nulls type as the marker type Null (which has no instances)
   579                     // infer as java.lang.Void for now
   580                     t = types.boxedClass(syms.voidType).type;
   581                 return t;
   582             }
   583         }
   585     /**
   586      * Mapping that turns inference variables into undet vars
   587      * (used by inference context)
   588      */
   589     class FromTypeVarFun extends Mapping {
   591         boolean includeBounds;
   593         FromTypeVarFun(boolean includeBounds) {
   594             super("fromTypeVarFunWithBounds");
   595             this.includeBounds = includeBounds;
   596         }
   598         public Type apply(Type t) {
   599             if (t.hasTag(TYPEVAR)) return new UndetVar((TypeVar)t, types, includeBounds);
   600             else return t.map(this);
   601         }
   602     };
   604     /**
   605      * An inference context keeps track of the set of variables that are free
   606      * in the current context. It provides utility methods for opening/closing
   607      * types to their corresponding free/closed forms. It also provide hooks for
   608      * attaching deferred post-inference action (see PendingCheck). Finally,
   609      * it can be used as an entry point for performing upper/lower bound inference
   610      * (see InferenceKind).
   611      */
   612     static class InferenceContext {
   614         /**
   615         * Single-method-interface for defining inference callbacks. Certain actions
   616         * (i.e. subtyping checks) might need to be redone after all inference variables
   617         * have been fixed.
   618         */
   619         interface FreeTypeListener {
   620             void typesInferred(InferenceContext inferenceContext);
   621         }
   623         /** list of inference vars as undet vars */
   624         List<Type> undetvars;
   626         /** list of inference vars in this context */
   627         List<Type> inferencevars;
   629         java.util.Map<FreeTypeListener, List<Type>> freeTypeListeners =
   630                 new java.util.HashMap<FreeTypeListener, List<Type>>();
   632         List<FreeTypeListener> freetypeListeners = List.nil();
   634         public InferenceContext(List<Type> inferencevars, Infer infer, boolean includeBounds) {
   635             this.undetvars = Type.map(inferencevars, infer.new FromTypeVarFun(includeBounds));
   636             this.inferencevars = inferencevars;
   637         }
   639         /**
   640          * returns the list of free variables (as type-variables) in this
   641          * inference context
   642          */
   643         List<Type> inferenceVars() {
   644             return inferencevars;
   645         }
   647         /**
   648          * returns the list of uninstantiated variables (as type-variables) in this
   649          * inference context (usually called after instantiate())
   650          */
   651         List<Type> restvars() {
   652             List<Type> undetvars = this.undetvars;
   653             ListBuffer<Type> restvars = ListBuffer.lb();
   654             for (Type t : instTypes()) {
   655                 UndetVar uv = (UndetVar)undetvars.head;
   656                 if (uv.qtype == t) {
   657                     restvars.append(t);
   658                 }
   659                 undetvars = undetvars.tail;
   660             }
   661             return restvars.toList();
   662         }
   664         /**
   665          * is this type free?
   666          */
   667         final boolean free(Type t) {
   668             return t.containsAny(inferencevars);
   669         }
   671         final boolean free(List<Type> ts) {
   672             for (Type t : ts) {
   673                 if (free(t)) return true;
   674             }
   675             return false;
   676         }
   678         /**
   679          * Returns a list of free variables in a given type
   680          */
   681         final List<Type> freeVarsIn(Type t) {
   682             ListBuffer<Type> buf = ListBuffer.lb();
   683             for (Type iv : inferenceVars()) {
   684                 if (t.contains(iv)) {
   685                     buf.add(iv);
   686                 }
   687             }
   688             return buf.toList();
   689         }
   691         final List<Type> freeVarsIn(List<Type> ts) {
   692             ListBuffer<Type> buf = ListBuffer.lb();
   693             for (Type t : ts) {
   694                 buf.appendList(freeVarsIn(t));
   695             }
   696             ListBuffer<Type> buf2 = ListBuffer.lb();
   697             for (Type t : buf) {
   698                 if (!buf2.contains(t)) {
   699                     buf2.add(t);
   700                 }
   701             }
   702             return buf2.toList();
   703         }
   705         /**
   706          * Replace all free variables in a given type with corresponding
   707          * undet vars (used ahead of subtyping/compatibility checks to allow propagation
   708          * of inference constraints).
   709          */
   710         final Type asFree(Type t, Types types) {
   711             return types.subst(t, inferencevars, undetvars);
   712         }
   714         final List<Type> asFree(List<Type> ts, Types types) {
   715             ListBuffer<Type> buf = ListBuffer.lb();
   716             for (Type t : ts) {
   717                 buf.append(asFree(t, types));
   718             }
   719             return buf.toList();
   720         }
   722         List<Type> instTypes() {
   723             ListBuffer<Type> buf = ListBuffer.lb();
   724             for (Type t : undetvars) {
   725                 UndetVar uv = (UndetVar)t;
   726                 buf.append(uv.inst != null ? uv.inst : uv.qtype);
   727             }
   728             return buf.toList();
   729         }
   731         /**
   732          * Replace all free variables in a given type with corresponding
   733          * instantiated types - if one or more free variable has not been
   734          * fully instantiated, it will still be available in the resulting type.
   735          */
   736         Type asInstType(Type t, Types types) {
   737             return types.subst(t, inferencevars, instTypes());
   738         }
   740         List<Type> asInstTypes(List<Type> ts, Types types) {
   741             ListBuffer<Type> buf = ListBuffer.lb();
   742             for (Type t : ts) {
   743                 buf.append(asInstType(t, types));
   744             }
   745             return buf.toList();
   746         }
   748         /**
   749          * Add custom hook for performing post-inference action
   750          */
   751         void addFreeTypeListener(List<Type> types, FreeTypeListener ftl) {
   752             freeTypeListeners.put(ftl, freeVarsIn(types));
   753         }
   755         /**
   756          * Mark the inference context as complete and trigger evaluation
   757          * of all deferred checks.
   758          */
   759         void notifyChange(Types types) {
   760             InferenceException thrownEx = null;
   761             for (Map.Entry<FreeTypeListener, List<Type>> entry :
   762                     new HashMap<FreeTypeListener, List<Type>>(freeTypeListeners).entrySet()) {
   763                 if (!Type.containsAny(entry.getValue(), restvars())) {
   764                     try {
   765                         entry.getKey().typesInferred(this);
   766                         freeTypeListeners.remove(entry.getKey());
   767                     } catch (InferenceException ex) {
   768                         if (thrownEx == null) {
   769                             thrownEx = ex;
   770                         }
   771                     }
   772                 }
   773             }
   774             //inference exception multiplexing - present any inference exception
   775             //thrown when processing listeners as a single one
   776             if (thrownEx != null) {
   777                 throw thrownEx;
   778             }
   779         }
   781         void solveAny(List<Type> varsToSolve, Types types, Infer infer) {
   782             boolean progress = false;
   783             for (Type t : varsToSolve) {
   784                 UndetVar uv = (UndetVar)asFree(t, types);
   785                 if (uv.inst == null) {
   786                     infer.minimizeInst(uv, types.noWarnings);
   787                     if (uv.inst != null) {
   788                         progress = true;
   789                     }
   790                 }
   791             }
   792             if (!progress) {
   793                 throw infer.inferenceException.setMessage("cyclic.inference", varsToSolve);
   794             }
   795         }
   796     }
   798     final InferenceContext emptyContext = new InferenceContext(List.<Type>nil(), this, false);
   799 }

mercurial