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