1 /* 2 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.code; 27 28 import java.lang.ref.SoftReference; 29 import java.util.HashSet; 30 import java.util.HashMap; 31 import java.util.Locale; 32 import java.util.Map; 33 import java.util.Set; 34 import java.util.WeakHashMap; 35 36 import com.sun.tools.javac.code.Attribute.RetentionPolicy; 37 import com.sun.tools.javac.code.Lint.LintCategory; 38 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound; 39 import com.sun.tools.javac.comp.Check; 40 import com.sun.tools.javac.jvm.ClassReader; 41 import com.sun.tools.javac.util.*; 42 import static com.sun.tools.javac.code.BoundKind.*; 43 import static com.sun.tools.javac.code.Flags.*; 44 import static com.sun.tools.javac.code.Scope.*; 45 import static com.sun.tools.javac.code.Symbol.*; 46 import static com.sun.tools.javac.code.Type.*; 47 import static com.sun.tools.javac.code.TypeTag.*; 48 import static com.sun.tools.javac.jvm.ClassFile.externalize; 49 import static com.sun.tools.javac.util.ListBuffer.lb; 50 51 /** 52 * Utility class containing various operations on types. 53 * 54 * <p>Unless other names are more illustrative, the following naming 55 * conventions should be observed in this file: 56 * 57 * <dl> 58 * <dt>t</dt> 59 * <dd>If the first argument to an operation is a type, it should be named t.</dd> 60 * <dt>s</dt> 61 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd> 62 * <dt>ts</dt> 63 * <dd>If an operations takes a list of types, the first should be named ts.</dd> 64 * <dt>ss</dt> 65 * <dd>A second list of types should be named ss.</dd> 66 * </dl> 67 * 68 * <p><b>This is NOT part of any supported API. 69 * If you write code that depends on this, you do so at your own risk. 70 * This code and its internal interfaces are subject to change or 71 * deletion without notice.</b> 72 */ 73 public class Types { 74 protected static final Context.Key<Types> typesKey = 75 new Context.Key<Types>(); 76 77 final Symtab syms; 78 final JavacMessages messages; 79 final Names names; 80 final boolean allowBoxing; 81 final boolean allowCovariantReturns; 82 final boolean allowObjectToPrimitiveCast; 83 final boolean allowDefaultMethods; 84 final ClassReader reader; 85 final Check chk; 86 JCDiagnostic.Factory diags; 87 List<Warner> warnStack = List.nil(); 88 final Name capturedName; 89 private final FunctionDescriptorLookupError functionDescriptorLookupError; 90 91 public final Warner noWarnings; 92 93 // <editor-fold defaultstate="collapsed" desc="Instantiating"> 94 public static Types instance(Context context) { 95 Types instance = context.get(typesKey); 96 if (instance == null) 97 instance = new Types(context); 98 return instance; 99 } 100 101 protected Types(Context context) { 102 context.put(typesKey, this); 103 syms = Symtab.instance(context); 104 names = Names.instance(context); 105 Source source = Source.instance(context); 106 allowBoxing = source.allowBoxing(); 107 allowCovariantReturns = source.allowCovariantReturns(); 108 allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast(); 109 allowDefaultMethods = source.allowDefaultMethods(); 110 reader = ClassReader.instance(context); 111 chk = Check.instance(context); 112 capturedName = names.fromString("<captured wildcard>"); 113 messages = JavacMessages.instance(context); 114 diags = JCDiagnostic.Factory.instance(context); 115 functionDescriptorLookupError = new FunctionDescriptorLookupError(); 116 noWarnings = new Warner(null); 117 } 118 // </editor-fold> 119 120 // <editor-fold defaultstate="collapsed" desc="upperBound"> 121 /** 122 * The "rvalue conversion".<br> 123 * The upper bound of most types is the type 124 * itself. Wildcards, on the other hand have upper 125 * and lower bounds. 126 * @param t a type 127 * @return the upper bound of the given type 128 */ 129 public Type upperBound(Type t) { 130 return upperBound.visit(t); 131 } 132 // where 133 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() { 134 135 @Override 136 public Type visitWildcardType(WildcardType t, Void ignored) { 137 if (t.isSuperBound()) 138 return t.bound == null ? syms.objectType : t.bound.bound; 139 else 140 return visit(t.type); 141 } 142 143 @Override 144 public Type visitCapturedType(CapturedType t, Void ignored) { 145 return visit(t.bound); 146 } 147 }; 148 // </editor-fold> 149 150 // <editor-fold defaultstate="collapsed" desc="lowerBound"> 151 /** 152 * The "lvalue conversion".<br> 153 * The lower bound of most types is the type 154 * itself. Wildcards, on the other hand have upper 155 * and lower bounds. 156 * @param t a type 157 * @return the lower bound of the given type 158 */ 159 public Type lowerBound(Type t) { 160 return lowerBound.visit(t); 161 } 162 // where 163 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() { 164 165 @Override 166 public Type visitWildcardType(WildcardType t, Void ignored) { 167 return t.isExtendsBound() ? syms.botType : visit(t.type); 168 } 169 170 @Override 171 public Type visitCapturedType(CapturedType t, Void ignored) { 172 return visit(t.getLowerBound()); 173 } 174 }; 175 // </editor-fold> 176 177 // <editor-fold defaultstate="collapsed" desc="isUnbounded"> 178 /** 179 * Checks that all the arguments to a class are unbounded 180 * wildcards or something else that doesn't make any restrictions 181 * on the arguments. If a class isUnbounded, a raw super- or 182 * subclass can be cast to it without a warning. 183 * @param t a type 184 * @return true iff the given type is unbounded or raw 185 */ 186 public boolean isUnbounded(Type t) { 187 return isUnbounded.visit(t); 188 } 189 // where 190 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() { 191 192 public Boolean visitType(Type t, Void ignored) { 193 return true; 194 } 195 196 @Override 197 public Boolean visitClassType(ClassType t, Void ignored) { 198 List<Type> parms = t.tsym.type.allparams(); 199 List<Type> args = t.allparams(); 200 while (parms.nonEmpty()) { 201 WildcardType unb = new WildcardType(syms.objectType, 202 BoundKind.UNBOUND, 203 syms.boundClass, 204 (TypeVar)parms.head.unannotatedType()); 205 if (!containsType(args.head, unb)) 206 return false; 207 parms = parms.tail; 208 args = args.tail; 209 } 210 return true; 211 } 212 }; 213 // </editor-fold> 214 215 // <editor-fold defaultstate="collapsed" desc="asSub"> 216 /** 217 * Return the least specific subtype of t that starts with symbol 218 * sym. If none exists, return null. The least specific subtype 219 * is determined as follows: 220 * 221 * <p>If there is exactly one parameterized instance of sym that is a 222 * subtype of t, that parameterized instance is returned.<br> 223 * Otherwise, if the plain type or raw type `sym' is a subtype of 224 * type t, the type `sym' itself is returned. Otherwise, null is 225 * returned. 226 */ 227 public Type asSub(Type t, Symbol sym) { 228 return asSub.visit(t, sym); 229 } 230 // where 231 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() { 232 233 public Type visitType(Type t, Symbol sym) { 234 return null; 235 } 236 237 @Override 238 public Type visitClassType(ClassType t, Symbol sym) { 239 if (t.tsym == sym) 240 return t; 241 Type base = asSuper(sym.type, t.tsym); 242 if (base == null) 243 return null; 244 ListBuffer<Type> from = new ListBuffer<Type>(); 245 ListBuffer<Type> to = new ListBuffer<Type>(); 246 try { 247 adapt(base, t, from, to); 248 } catch (AdaptFailure ex) { 249 return null; 250 } 251 Type res = subst(sym.type, from.toList(), to.toList()); 252 if (!isSubtype(res, t)) 253 return null; 254 ListBuffer<Type> openVars = new ListBuffer<Type>(); 255 for (List<Type> l = sym.type.allparams(); 256 l.nonEmpty(); l = l.tail) 257 if (res.contains(l.head) && !t.contains(l.head)) 258 openVars.append(l.head); 259 if (openVars.nonEmpty()) { 260 if (t.isRaw()) { 261 // The subtype of a raw type is raw 262 res = erasure(res); 263 } else { 264 // Unbound type arguments default to ? 265 List<Type> opens = openVars.toList(); 266 ListBuffer<Type> qs = new ListBuffer<Type>(); 267 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) { 268 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType())); 269 } 270 res = subst(res, opens, qs.toList()); 271 } 272 } 273 return res; 274 } 275 276 @Override 277 public Type visitErrorType(ErrorType t, Symbol sym) { 278 return t; 279 } 280 }; 281 // </editor-fold> 282 283 // <editor-fold defaultstate="collapsed" desc="isConvertible"> 284 /** 285 * Is t a subtype of or convertible via boxing/unboxing 286 * conversion to s? 287 */ 288 public boolean isConvertible(Type t, Type s, Warner warn) { 289 if (t.tag == ERROR) 290 return true; 291 boolean tPrimitive = t.isPrimitive(); 292 boolean sPrimitive = s.isPrimitive(); 293 if (tPrimitive == sPrimitive) { 294 return isSubtypeUnchecked(t, s, warn); 295 } 296 if (!allowBoxing) return false; 297 return tPrimitive 298 ? isSubtype(boxedClass(t).type, s) 299 : isSubtype(unboxedType(t), s); 300 } 301 302 /** 303 * Is t a subtype of or convertiable via boxing/unboxing 304 * convertions to s? 305 */ 306 public boolean isConvertible(Type t, Type s) { 307 return isConvertible(t, s, noWarnings); 308 } 309 // </editor-fold> 310 311 // <editor-fold defaultstate="collapsed" desc="findSam"> 312 313 /** 314 * Exception used to report a function descriptor lookup failure. The exception 315 * wraps a diagnostic that can be used to generate more details error 316 * messages. 317 */ 318 public static class FunctionDescriptorLookupError extends RuntimeException { 319 private static final long serialVersionUID = 0; 320 321 JCDiagnostic diagnostic; 322 323 FunctionDescriptorLookupError() { 324 this.diagnostic = null; 325 } 326 327 FunctionDescriptorLookupError setMessage(JCDiagnostic diag) { 328 this.diagnostic = diag; 329 return this; 330 } 331 332 public JCDiagnostic getDiagnostic() { 333 return diagnostic; 334 } 335 } 336 337 /** 338 * A cache that keeps track of function descriptors associated with given 339 * functional interfaces. 340 */ 341 class DescriptorCache { 342 343 private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>(); 344 345 class FunctionDescriptor { 346 Symbol descSym; 347 348 FunctionDescriptor(Symbol descSym) { 349 this.descSym = descSym; 350 } 351 352 public Symbol getSymbol() { 353 return descSym; 354 } 355 356 public Type getType(Type site) { 357 site = removeWildcards(site); 358 if (!chk.checkValidGenericType(site)) { 359 //if the inferred functional interface type is not well-formed, 360 //or if it's not a subtype of the original target, issue an error 361 throw failure(diags.fragment("no.suitable.functional.intf.inst", site)); 362 } 363 return memberType(site, descSym); 364 } 365 } 366 367 class Entry { 368 final FunctionDescriptor cachedDescRes; 369 final int prevMark; 370 371 public Entry(FunctionDescriptor cachedDescRes, 372 int prevMark) { 373 this.cachedDescRes = cachedDescRes; 374 this.prevMark = prevMark; 375 } 376 377 boolean matches(int mark) { 378 return this.prevMark == mark; 379 } 380 } 381 382 FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError { 383 Entry e = _map.get(origin); 384 CompoundScope members = membersClosure(origin.type, false); 385 if (e == null || 386 !e.matches(members.getMark())) { 387 FunctionDescriptor descRes = findDescriptorInternal(origin, members); 388 _map.put(origin, new Entry(descRes, members.getMark())); 389 return descRes; 390 } 391 else { 392 return e.cachedDescRes; 393 } 394 } 395 396 /** 397 * Compute the function descriptor associated with a given functional interface 398 */ 399 public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError { 400 if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) { 401 //t must be an interface 402 throw failure("not.a.functional.intf", origin); 403 } 404 405 final ListBuffer<Symbol> abstracts = ListBuffer.lb(); 406 for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) { 407 Type mtype = memberType(origin.type, sym); 408 if (abstracts.isEmpty() || 409 (sym.name == abstracts.first().name && 410 overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) { 411 abstracts.append(sym); 412 } else { 413 //the target method(s) should be the only abstract members of t 414 throw failure("not.a.functional.intf.1", origin, 415 diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin)); 416 } 417 } 418 if (abstracts.isEmpty()) { 419 //t must define a suitable non-generic method 420 throw failure("not.a.functional.intf.1", origin, 421 diags.fragment("no.abstracts", Kinds.kindName(origin), origin)); 422 } else if (abstracts.size() == 1) { 423 return new FunctionDescriptor(abstracts.first()); 424 } else { // size > 1 425 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList()); 426 if (descRes == null) { 427 //we can get here if the functional interface is ill-formed 428 ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb(); 429 for (Symbol desc : abstracts) { 430 String key = desc.type.getThrownTypes().nonEmpty() ? 431 "descriptor.throws" : "descriptor"; 432 descriptors.append(diags.fragment(key, desc.name, 433 desc.type.getParameterTypes(), 434 desc.type.getReturnType(), 435 desc.type.getThrownTypes())); 436 } 437 JCDiagnostic.MultilineDiagnostic incompatibleDescriptors = 438 new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf", 439 Kinds.kindName(origin), origin), descriptors.toList()); 440 throw failure(incompatibleDescriptors); 441 } 442 return descRes; 443 } 444 } 445 446 /** 447 * Compute a synthetic type for the target descriptor given a list 448 * of override-equivalent methods in the functional interface type. 449 * The resulting method type is a method type that is override-equivalent 450 * and return-type substitutable with each method in the original list. 451 */ 452 private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) { 453 //pick argument types - simply take the signature that is a 454 //subsignature of all other signatures in the list (as per JLS 8.4.2) 455 List<Symbol> mostSpecific = List.nil(); 456 outer: for (Symbol msym1 : methodSyms) { 457 Type mt1 = memberType(origin.type, msym1); 458 for (Symbol msym2 : methodSyms) { 459 Type mt2 = memberType(origin.type, msym2); 460 if (!isSubSignature(mt1, mt2)) { 461 continue outer; 462 } 463 } 464 mostSpecific = mostSpecific.prepend(msym1); 465 } 466 if (mostSpecific.isEmpty()) { 467 return null; 468 } 469 470 471 //pick return types - this is done in two phases: (i) first, the most 472 //specific return type is chosen using strict subtyping; if this fails, 473 //a second attempt is made using return type substitutability (see JLS 8.4.5) 474 boolean phase2 = false; 475 Symbol bestSoFar = null; 476 while (bestSoFar == null) { 477 outer: for (Symbol msym1 : mostSpecific) { 478 Type mt1 = memberType(origin.type, msym1); 479 for (Symbol msym2 : methodSyms) { 480 Type mt2 = memberType(origin.type, msym2); 481 if (phase2 ? 482 !returnTypeSubstitutable(mt1, mt2) : 483 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) { 484 continue outer; 485 } 486 } 487 bestSoFar = msym1; 488 } 489 if (phase2) { 490 break; 491 } else { 492 phase2 = true; 493 } 494 } 495 if (bestSoFar == null) return null; 496 497 //merge thrown types - form the intersection of all the thrown types in 498 //all the signatures in the list 499 List<Type> thrown = null; 500 for (Symbol msym1 : methodSyms) { 501 Type mt1 = memberType(origin.type, msym1); 502 thrown = (thrown == null) ? 503 mt1.getThrownTypes() : 504 chk.intersect(mt1.getThrownTypes(), thrown); 505 } 506 507 final List<Type> thrown1 = thrown; 508 return new FunctionDescriptor(bestSoFar) { 509 @Override 510 public Type getType(Type origin) { 511 Type mt = memberType(origin, getSymbol()); 512 return createMethodTypeWithThrown(mt, thrown1); 513 } 514 }; 515 } 516 517 boolean isSubtypeInternal(Type s, Type t) { 518 return (s.isPrimitive() && t.isPrimitive()) ? 519 isSameType(t, s) : 520 isSubtype(s, t); 521 } 522 523 FunctionDescriptorLookupError failure(String msg, Object... args) { 524 return failure(diags.fragment(msg, args)); 525 } 526 527 FunctionDescriptorLookupError failure(JCDiagnostic diag) { 528 return functionDescriptorLookupError.setMessage(diag); 529 } 530 } 531 532 private DescriptorCache descCache = new DescriptorCache(); 533 534 /** 535 * Find the method descriptor associated to this class symbol - if the 536 * symbol 'origin' is not a functional interface, an exception is thrown. 537 */ 538 public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError { 539 return descCache.get(origin).getSymbol(); 540 } 541 542 /** 543 * Find the type of the method descriptor associated to this class symbol - 544 * if the symbol 'origin' is not a functional interface, an exception is thrown. 545 */ 546 public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError { 547 return descCache.get(origin.tsym).getType(origin); 548 } 549 550 /** 551 * Is given type a functional interface? 552 */ 553 public boolean isFunctionalInterface(TypeSymbol tsym) { 554 try { 555 findDescriptorSymbol(tsym); 556 return true; 557 } catch (FunctionDescriptorLookupError ex) { 558 return false; 559 } 560 } 561 562 public boolean isFunctionalInterface(Type site) { 563 try { 564 findDescriptorType(site); 565 return true; 566 } catch (FunctionDescriptorLookupError ex) { 567 return false; 568 } 569 } 570 571 public Type removeWildcards(Type site) { 572 Type capturedSite = capture(site); 573 if (capturedSite != site) { 574 Type formalInterface = site.tsym.type; 575 ListBuffer<Type> typeargs = ListBuffer.lb(); 576 List<Type> actualTypeargs = site.getTypeArguments(); 577 List<Type> capturedTypeargs = capturedSite.getTypeArguments(); 578 //simply replace the wildcards with its bound 579 for (Type t : formalInterface.getTypeArguments()) { 580 if (actualTypeargs.head.hasTag(WILDCARD)) { 581 WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType(); 582 Type bound; 583 switch (wt.kind) { 584 case EXTENDS: 585 case UNBOUND: 586 CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType(); 587 //use declared bound if it doesn't depend on formal type-args 588 bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ? 589 wt.type : capVar.bound; 590 break; 591 default: 592 bound = wt.type; 593 } 594 typeargs.append(bound); 595 } else { 596 typeargs.append(actualTypeargs.head); 597 } 598 actualTypeargs = actualTypeargs.tail; 599 capturedTypeargs = capturedTypeargs.tail; 600 } 601 return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList()); 602 } else { 603 return site; 604 } 605 } 606 // </editor-fold> 607 608 /** 609 * Scope filter used to skip methods that should be ignored (such as methods 610 * overridden by j.l.Object) during function interface conversion interface check 611 */ 612 class DescriptorFilter implements Filter<Symbol> { 613 614 TypeSymbol origin; 615 616 DescriptorFilter(TypeSymbol origin) { 617 this.origin = origin; 618 } 619 620 @Override 621 public boolean accepts(Symbol sym) { 622 return sym.kind == Kinds.MTH && 623 (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT && 624 !overridesObjectMethod(origin, sym) && 625 (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0; 626 } 627 }; 628 629 // <editor-fold defaultstate="collapsed" desc="isSubtype"> 630 /** 631 * Is t an unchecked subtype of s? 632 */ 633 public boolean isSubtypeUnchecked(Type t, Type s) { 634 return isSubtypeUnchecked(t, s, noWarnings); 635 } 636 /** 637 * Is t an unchecked subtype of s? 638 */ 639 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) { 640 boolean result = isSubtypeUncheckedInternal(t, s, warn); 641 if (result) { 642 checkUnsafeVarargsConversion(t, s, warn); 643 } 644 return result; 645 } 646 //where 647 private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) { 648 if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) { 649 t = t.unannotatedType(); 650 s = s.unannotatedType(); 651 if (((ArrayType)t).elemtype.isPrimitive()) { 652 return isSameType(elemtype(t), elemtype(s)); 653 } else { 654 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn); 655 } 656 } else if (isSubtype(t, s)) { 657 return true; 658 } 659 else if (t.tag == TYPEVAR) { 660 return isSubtypeUnchecked(t.getUpperBound(), s, warn); 661 } 662 else if (!s.isRaw()) { 663 Type t2 = asSuper(t, s.tsym); 664 if (t2 != null && t2.isRaw()) { 665 if (isReifiable(s)) 666 warn.silentWarn(LintCategory.UNCHECKED); 667 else 668 warn.warn(LintCategory.UNCHECKED); 669 return true; 670 } 671 } 672 return false; 673 } 674 675 private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) { 676 if (t.tag != ARRAY || isReifiable(t)) 677 return; 678 t = t.unannotatedType(); 679 s = s.unannotatedType(); 680 ArrayType from = (ArrayType)t; 681 boolean shouldWarn = false; 682 switch (s.tag) { 683 case ARRAY: 684 ArrayType to = (ArrayType)s; 685 shouldWarn = from.isVarargs() && 686 !to.isVarargs() && 687 !isReifiable(from); 688 break; 689 case CLASS: 690 shouldWarn = from.isVarargs(); 691 break; 692 } 693 if (shouldWarn) { 694 warn.warn(LintCategory.VARARGS); 695 } 696 } 697 698 /** 699 * Is t a subtype of s?<br> 700 * (not defined for Method and ForAll types) 701 */ 702 final public boolean isSubtype(Type t, Type s) { 703 return isSubtype(t, s, true); 704 } 705 final public boolean isSubtypeNoCapture(Type t, Type s) { 706 return isSubtype(t, s, false); 707 } 708 public boolean isSubtype(Type t, Type s, boolean capture) { 709 if (t == s) 710 return true; 711 712 t = t.unannotatedType(); 713 s = s.unannotatedType(); 714 715 if (t == s) 716 return true; 717 718 if (s.isPartial()) 719 return isSuperType(s, t); 720 721 if (s.isCompound()) { 722 for (Type s2 : interfaces(s).prepend(supertype(s))) { 723 if (!isSubtype(t, s2, capture)) 724 return false; 725 } 726 return true; 727 } 728 729 Type lower = lowerBound(s); 730 if (s != lower) 731 return isSubtype(capture ? capture(t) : t, lower, false); 732 733 return isSubtype.visit(capture ? capture(t) : t, s); 734 } 735 // where 736 private TypeRelation isSubtype = new TypeRelation() 737 { 738 public Boolean visitType(Type t, Type s) { 739 switch (t.tag) { 740 case BYTE: 741 return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag())); 742 case CHAR: 743 return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag())); 744 case SHORT: case INT: case LONG: 745 case FLOAT: case DOUBLE: 746 return t.getTag().isSubRangeOf(s.getTag()); 747 case BOOLEAN: case VOID: 748 return t.hasTag(s.getTag()); 749 case TYPEVAR: 750 return isSubtypeNoCapture(t.getUpperBound(), s); 751 case BOT: 752 return 753 s.hasTag(BOT) || s.hasTag(CLASS) || 754 s.hasTag(ARRAY) || s.hasTag(TYPEVAR); 755 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495) 756 case NONE: 757 return false; 758 default: 759 throw new AssertionError("isSubtype " + t.tag); 760 } 761 } 762 763 private Set<TypePair> cache = new HashSet<TypePair>(); 764 765 private boolean containsTypeRecursive(Type t, Type s) { 766 TypePair pair = new TypePair(t, s); 767 if (cache.add(pair)) { 768 try { 769 return containsType(t.getTypeArguments(), 770 s.getTypeArguments()); 771 } finally { 772 cache.remove(pair); 773 } 774 } else { 775 return containsType(t.getTypeArguments(), 776 rewriteSupers(s).getTypeArguments()); 777 } 778 } 779 780 private Type rewriteSupers(Type t) { 781 if (!t.isParameterized()) 782 return t; 783 ListBuffer<Type> from = lb(); 784 ListBuffer<Type> to = lb(); 785 adaptSelf(t, from, to); 786 if (from.isEmpty()) 787 return t; 788 ListBuffer<Type> rewrite = lb(); 789 boolean changed = false; 790 for (Type orig : to.toList()) { 791 Type s = rewriteSupers(orig); 792 if (s.isSuperBound() && !s.isExtendsBound()) { 793 s = new WildcardType(syms.objectType, 794 BoundKind.UNBOUND, 795 syms.boundClass); 796 changed = true; 797 } else if (s != orig) { 798 s = new WildcardType(upperBound(s), 799 BoundKind.EXTENDS, 800 syms.boundClass); 801 changed = true; 802 } 803 rewrite.append(s); 804 } 805 if (changed) 806 return subst(t.tsym.type, from.toList(), rewrite.toList()); 807 else 808 return t; 809 } 810 811 @Override 812 public Boolean visitClassType(ClassType t, Type s) { 813 Type sup = asSuper(t, s.tsym); 814 return sup != null 815 && sup.tsym == s.tsym 816 // You're not allowed to write 817 // Vector<Object> vec = new Vector<String>(); 818 // But with wildcards you can write 819 // Vector<? extends Object> vec = new Vector<String>(); 820 // which means that subtype checking must be done 821 // here instead of same-type checking (via containsType). 822 && (!s.isParameterized() || containsTypeRecursive(s, sup)) 823 && isSubtypeNoCapture(sup.getEnclosingType(), 824 s.getEnclosingType()); 825 } 826 827 @Override 828 public Boolean visitArrayType(ArrayType t, Type s) { 829 if (s.tag == ARRAY) { 830 if (t.elemtype.isPrimitive()) 831 return isSameType(t.elemtype, elemtype(s)); 832 else 833 return isSubtypeNoCapture(t.elemtype, elemtype(s)); 834 } 835 836 if (s.tag == CLASS) { 837 Name sname = s.tsym.getQualifiedName(); 838 return sname == names.java_lang_Object 839 || sname == names.java_lang_Cloneable 840 || sname == names.java_io_Serializable; 841 } 842 843 return false; 844 } 845 846 @Override 847 public Boolean visitUndetVar(UndetVar t, Type s) { 848 //todo: test against origin needed? or replace with substitution? 849 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) { 850 return true; 851 } else if (s.tag == BOT) { 852 //if 's' is 'null' there's no instantiated type U for which 853 //U <: s (but 'null' itself, which is not a valid type) 854 return false; 855 } 856 857 t.addBound(InferenceBound.UPPER, s, Types.this); 858 return true; 859 } 860 861 @Override 862 public Boolean visitErrorType(ErrorType t, Type s) { 863 return true; 864 } 865 }; 866 867 /** 868 * Is t a subtype of every type in given list `ts'?<br> 869 * (not defined for Method and ForAll types)<br> 870 * Allows unchecked conversions. 871 */ 872 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) { 873 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 874 if (!isSubtypeUnchecked(t, l.head, warn)) 875 return false; 876 return true; 877 } 878 879 /** 880 * Are corresponding elements of ts subtypes of ss? If lists are 881 * of different length, return false. 882 */ 883 public boolean isSubtypes(List<Type> ts, List<Type> ss) { 884 while (ts.tail != null && ss.tail != null 885 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 886 isSubtype(ts.head, ss.head)) { 887 ts = ts.tail; 888 ss = ss.tail; 889 } 890 return ts.tail == null && ss.tail == null; 891 /*inlined: ts.isEmpty() && ss.isEmpty();*/ 892 } 893 894 /** 895 * Are corresponding elements of ts subtypes of ss, allowing 896 * unchecked conversions? If lists are of different length, 897 * return false. 898 **/ 899 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) { 900 while (ts.tail != null && ss.tail != null 901 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 902 isSubtypeUnchecked(ts.head, ss.head, warn)) { 903 ts = ts.tail; 904 ss = ss.tail; 905 } 906 return ts.tail == null && ss.tail == null; 907 /*inlined: ts.isEmpty() && ss.isEmpty();*/ 908 } 909 // </editor-fold> 910 911 // <editor-fold defaultstate="collapsed" desc="isSuperType"> 912 /** 913 * Is t a supertype of s? 914 */ 915 public boolean isSuperType(Type t, Type s) { 916 switch (t.tag) { 917 case ERROR: 918 return true; 919 case UNDETVAR: { 920 UndetVar undet = (UndetVar)t; 921 if (t == s || 922 undet.qtype == s || 923 s.tag == ERROR || 924 s.tag == BOT) return true; 925 undet.addBound(InferenceBound.LOWER, s, this); 926 return true; 927 } 928 default: 929 return isSubtype(s, t); 930 } 931 } 932 // </editor-fold> 933 934 // <editor-fold defaultstate="collapsed" desc="isSameType"> 935 /** 936 * Are corresponding elements of the lists the same type? If 937 * lists are of different length, return false. 938 */ 939 public boolean isSameTypes(List<Type> ts, List<Type> ss) { 940 return isSameTypes(ts, ss, false); 941 } 942 public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) { 943 while (ts.tail != null && ss.tail != null 944 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && 945 isSameType(ts.head, ss.head, strict)) { 946 ts = ts.tail; 947 ss = ss.tail; 948 } 949 return ts.tail == null && ss.tail == null; 950 /*inlined: ts.isEmpty() && ss.isEmpty();*/ 951 } 952 953 /** 954 * Is t the same type as s? 955 */ 956 public boolean isSameType(Type t, Type s) { 957 return isSameType(t, s, false); 958 } 959 public boolean isSameType(Type t, Type s, boolean strict) { 960 return strict ? 961 isSameTypeStrict.visit(t, s) : 962 isSameTypeLoose.visit(t, s); 963 } 964 public boolean isSameAnnotatedType(Type t, Type s) { 965 return isSameAnnotatedType.visit(t, s); 966 } 967 // where 968 abstract class SameTypeVisitor extends TypeRelation { 969 970 public Boolean visitType(Type t, Type s) { 971 if (t == s) 972 return true; 973 974 if (s.isPartial()) 975 return visit(s, t); 976 977 switch (t.tag) { 978 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: 979 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE: 980 return t.tag == s.tag; 981 case TYPEVAR: { 982 if (s.tag == TYPEVAR) { 983 //type-substitution does not preserve type-var types 984 //check that type var symbols and bounds are indeed the same 985 return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType()); 986 } 987 else { 988 //special case for s == ? super X, where upper(s) = u 989 //check that u == t, where u has been set by Type.withTypeVar 990 return s.isSuperBound() && 991 !s.isExtendsBound() && 992 visit(t, upperBound(s)); 993 } 994 } 995 default: 996 throw new AssertionError("isSameType " + t.tag); 997 } 998 } 999 1000 abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2); 1001 1002 @Override 1003 public Boolean visitWildcardType(WildcardType t, Type s) { 1004 if (s.isPartial()) 1005 return visit(s, t); 1006 else 1007 return false; 1008 } 1009 1010 @Override 1011 public Boolean visitClassType(ClassType t, Type s) { 1012 if (t == s) 1013 return true; 1014 1015 if (s.isPartial()) 1016 return visit(s, t); 1017 1018 if (s.isSuperBound() && !s.isExtendsBound()) 1019 return visit(t, upperBound(s)) && visit(t, lowerBound(s)); 1020 1021 if (t.isCompound() && s.isCompound()) { 1022 if (!visit(supertype(t), supertype(s))) 1023 return false; 1024 1025 HashSet<UniqueType> set = new HashSet<UniqueType>(); 1026 for (Type x : interfaces(t)) 1027 set.add(new UniqueType(x, Types.this)); 1028 for (Type x : interfaces(s)) { 1029 if (!set.remove(new UniqueType(x, Types.this))) 1030 return false; 1031 } 1032 return (set.isEmpty()); 1033 } 1034 return t.tsym == s.tsym 1035 && visit(t.getEnclosingType(), s.getEnclosingType()) 1036 && containsTypes(t.getTypeArguments(), s.getTypeArguments()); 1037 } 1038 1039 abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2); 1040 1041 @Override 1042 public Boolean visitArrayType(ArrayType t, Type s) { 1043 if (t == s) 1044 return true; 1045 1046 if (s.isPartial()) 1047 return visit(s, t); 1048 1049 return s.hasTag(ARRAY) 1050 && containsTypeEquivalent(t.elemtype, elemtype(s)); 1051 } 1052 1053 @Override 1054 public Boolean visitMethodType(MethodType t, Type s) { 1055 // isSameType for methods does not take thrown 1056 // exceptions into account! 1057 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType()); 1058 } 1059 1060 @Override 1061 public Boolean visitPackageType(PackageType t, Type s) { 1062 return t == s; 1063 } 1064 1065 @Override 1066 public Boolean visitForAll(ForAll t, Type s) { 1067 if (s.tag != FORALL) 1068 return false; 1069 1070 ForAll forAll = (ForAll)s; 1071 return hasSameBounds(t, forAll) 1072 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); 1073 } 1074 1075 @Override 1076 public Boolean visitUndetVar(UndetVar t, Type s) { 1077 if (s.tag == WILDCARD) 1078 // FIXME, this might be leftovers from before capture conversion 1079 return false; 1080 1081 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) 1082 return true; 1083 1084 t.addBound(InferenceBound.EQ, s, Types.this); 1085 1086 return true; 1087 } 1088 1089 @Override 1090 public Boolean visitErrorType(ErrorType t, Type s) { 1091 return true; 1092 } 1093 } 1094 1095 /** 1096 * Standard type-equality relation - type variables are considered 1097 * equals if they share the same type symbol. 1098 */ 1099 TypeRelation isSameTypeLoose = new LooseSameTypeVisitor(); 1100 1101 private class LooseSameTypeVisitor extends SameTypeVisitor { 1102 @Override 1103 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) { 1104 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound()); 1105 } 1106 @Override 1107 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) { 1108 return containsTypeEquivalent(ts1, ts2); 1109 } 1110 }; 1111 1112 /** 1113 * Strict type-equality relation - type variables are considered 1114 * equals if they share the same object identity. 1115 */ 1116 TypeRelation isSameTypeStrict = new SameTypeVisitor() { 1117 @Override 1118 boolean sameTypeVars(TypeVar tv1, TypeVar tv2) { 1119 return tv1 == tv2; 1120 } 1121 @Override 1122 protected boolean containsTypes(List<Type> ts1, List<Type> ts2) { 1123 return isSameTypes(ts1, ts2, true); 1124 } 1125 1126 @Override 1127 public Boolean visitWildcardType(WildcardType t, Type s) { 1128 if (!s.hasTag(WILDCARD)) { 1129 return false; 1130 } else { 1131 WildcardType t2 = (WildcardType)s.unannotatedType(); 1132 return t.kind == t2.kind && 1133 isSameType(t.type, t2.type, true); 1134 } 1135 } 1136 }; 1137 1138 /** 1139 * A version of LooseSameTypeVisitor that takes AnnotatedTypes 1140 * into account. 1141 */ 1142 TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() { 1143 @Override 1144 public Boolean visitAnnotatedType(AnnotatedType t, Type s) { 1145 if (!s.isAnnotated()) 1146 return false; 1147 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors())) 1148 return false; 1149 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors())) 1150 return false; 1151 return visit(t.underlyingType, s); 1152 } 1153 }; 1154 // </editor-fold> 1155 1156 // <editor-fold defaultstate="collapsed" desc="Contains Type"> 1157 public boolean containedBy(Type t, Type s) { 1158 switch (t.tag) { 1159 case UNDETVAR: 1160 if (s.tag == WILDCARD) { 1161 UndetVar undetvar = (UndetVar)t; 1162 WildcardType wt = (WildcardType)s.unannotatedType(); 1163 switch(wt.kind) { 1164 case UNBOUND: //similar to ? extends Object 1165 case EXTENDS: { 1166 Type bound = upperBound(s); 1167 undetvar.addBound(InferenceBound.UPPER, bound, this); 1168 break; 1169 } 1170 case SUPER: { 1171 Type bound = lowerBound(s); 1172 undetvar.addBound(InferenceBound.LOWER, bound, this); 1173 break; 1174 } 1175 } 1176 return true; 1177 } else { 1178 return isSameType(t, s); 1179 } 1180 case ERROR: 1181 return true; 1182 default: 1183 return containsType(s, t); 1184 } 1185 } 1186 1187 boolean containsType(List<Type> ts, List<Type> ss) { 1188 while (ts.nonEmpty() && ss.nonEmpty() 1189 && containsType(ts.head, ss.head)) { 1190 ts = ts.tail; 1191 ss = ss.tail; 1192 } 1193 return ts.isEmpty() && ss.isEmpty(); 1194 } 1195 1196 /** 1197 * Check if t contains s. 1198 * 1199 * <p>T contains S if: 1200 * 1201 * <p>{@code L(T) <: L(S) && U(S) <: U(T)} 1202 * 1203 * <p>This relation is only used by ClassType.isSubtype(), that 1204 * is, 1205 * 1206 * <p>{@code C<S> <: C<T> if T contains S.} 1207 * 1208 * <p>Because of F-bounds, this relation can lead to infinite 1209 * recursion. Thus we must somehow break that recursion. Notice 1210 * that containsType() is only called from ClassType.isSubtype(). 1211 * Since the arguments have already been checked against their 1212 * bounds, we know: 1213 * 1214 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)} 1215 * 1216 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)} 1217 * 1218 * @param t a type 1219 * @param s a type 1220 */ 1221 public boolean containsType(Type t, Type s) { 1222 return containsType.visit(t, s); 1223 } 1224 // where 1225 private TypeRelation containsType = new TypeRelation() { 1226 1227 private Type U(Type t) { 1228 while (t.tag == WILDCARD) { 1229 WildcardType w = (WildcardType)t.unannotatedType(); 1230 if (w.isSuperBound()) 1231 return w.bound == null ? syms.objectType : w.bound.bound; 1232 else 1233 t = w.type; 1234 } 1235 return t; 1236 } 1237 1238 private Type L(Type t) { 1239 while (t.tag == WILDCARD) { 1240 WildcardType w = (WildcardType)t.unannotatedType(); 1241 if (w.isExtendsBound()) 1242 return syms.botType; 1243 else 1244 t = w.type; 1245 } 1246 return t; 1247 } 1248 1249 public Boolean visitType(Type t, Type s) { 1250 if (s.isPartial()) 1251 return containedBy(s, t); 1252 else 1253 return isSameType(t, s); 1254 } 1255 1256 // void debugContainsType(WildcardType t, Type s) { 1257 // System.err.println(); 1258 // System.err.format(" does %s contain %s?%n", t, s); 1259 // System.err.format(" %s U(%s) <: U(%s) %s = %s%n", 1260 // upperBound(s), s, t, U(t), 1261 // t.isSuperBound() 1262 // || isSubtypeNoCapture(upperBound(s), U(t))); 1263 // System.err.format(" %s L(%s) <: L(%s) %s = %s%n", 1264 // L(t), t, s, lowerBound(s), 1265 // t.isExtendsBound() 1266 // || isSubtypeNoCapture(L(t), lowerBound(s))); 1267 // System.err.println(); 1268 // } 1269 1270 @Override 1271 public Boolean visitWildcardType(WildcardType t, Type s) { 1272 if (s.isPartial()) 1273 return containedBy(s, t); 1274 else { 1275 // debugContainsType(t, s); 1276 return isSameWildcard(t, s) 1277 || isCaptureOf(s, t) 1278 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) && 1279 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t)))); 1280 } 1281 } 1282 1283 @Override 1284 public Boolean visitUndetVar(UndetVar t, Type s) { 1285 if (s.tag != WILDCARD) 1286 return isSameType(t, s); 1287 else 1288 return false; 1289 } 1290 1291 @Override 1292 public Boolean visitErrorType(ErrorType t, Type s) { 1293 return true; 1294 } 1295 }; 1296 1297 public boolean isCaptureOf(Type s, WildcardType t) { 1298 if (s.tag != TYPEVAR || !((TypeVar)s.unannotatedType()).isCaptured()) 1299 return false; 1300 return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard); 1301 } 1302 1303 public boolean isSameWildcard(WildcardType t, Type s) { 1304 if (s.tag != WILDCARD) 1305 return false; 1306 WildcardType w = (WildcardType)s.unannotatedType(); 1307 return w.kind == t.kind && w.type == t.type; 1308 } 1309 1310 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) { 1311 while (ts.nonEmpty() && ss.nonEmpty() 1312 && containsTypeEquivalent(ts.head, ss.head)) { 1313 ts = ts.tail; 1314 ss = ss.tail; 1315 } 1316 return ts.isEmpty() && ss.isEmpty(); 1317 } 1318 // </editor-fold> 1319 1320 /** 1321 * Can t and s be compared for equality? Any primitive == 1322 * primitive or primitive == object comparisons here are an error. 1323 * Unboxing and correct primitive == primitive comparisons are 1324 * already dealt with in Attr.visitBinary. 1325 * 1326 */ 1327 public boolean isEqualityComparable(Type s, Type t, Warner warn) { 1328 if (t.isNumeric() && s.isNumeric()) 1329 return true; 1330 1331 boolean tPrimitive = t.isPrimitive(); 1332 boolean sPrimitive = s.isPrimitive(); 1333 if (!tPrimitive && !sPrimitive) { 1334 return isCastable(s, t, warn) || isCastable(t, s, warn); 1335 } else { 1336 return false; 1337 } 1338 } 1339 1340 // <editor-fold defaultstate="collapsed" desc="isCastable"> 1341 public boolean isCastable(Type t, Type s) { 1342 return isCastable(t, s, noWarnings); 1343 } 1344 1345 /** 1346 * Is t is castable to s?<br> 1347 * s is assumed to be an erased type.<br> 1348 * (not defined for Method and ForAll types). 1349 */ 1350 public boolean isCastable(Type t, Type s, Warner warn) { 1351 if (t == s) 1352 return true; 1353 1354 if (t.isPrimitive() != s.isPrimitive()) 1355 return allowBoxing && ( 1356 isConvertible(t, s, warn) 1357 || (allowObjectToPrimitiveCast && 1358 s.isPrimitive() && 1359 isSubtype(boxedClass(s).type, t))); 1360 if (warn != warnStack.head) { 1361 try { 1362 warnStack = warnStack.prepend(warn); 1363 checkUnsafeVarargsConversion(t, s, warn); 1364 return isCastable.visit(t,s); 1365 } finally { 1366 warnStack = warnStack.tail; 1367 } 1368 } else { 1369 return isCastable.visit(t,s); 1370 } 1371 } 1372 // where 1373 private TypeRelation isCastable = new TypeRelation() { 1374 1375 public Boolean visitType(Type t, Type s) { 1376 if (s.tag == ERROR) 1377 return true; 1378 1379 switch (t.tag) { 1380 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: 1381 case DOUBLE: 1382 return s.isNumeric(); 1383 case BOOLEAN: 1384 return s.tag == BOOLEAN; 1385 case VOID: 1386 return false; 1387 case BOT: 1388 return isSubtype(t, s); 1389 default: 1390 throw new AssertionError(); 1391 } 1392 } 1393 1394 @Override 1395 public Boolean visitWildcardType(WildcardType t, Type s) { 1396 return isCastable(upperBound(t), s, warnStack.head); 1397 } 1398 1399 @Override 1400 public Boolean visitClassType(ClassType t, Type s) { 1401 if (s.tag == ERROR || s.tag == BOT) 1402 return true; 1403 1404 if (s.tag == TYPEVAR) { 1405 if (isCastable(t, s.getUpperBound(), noWarnings)) { 1406 warnStack.head.warn(LintCategory.UNCHECKED); 1407 return true; 1408 } else { 1409 return false; 1410 } 1411 } 1412 1413 if (t.isCompound() || s.isCompound()) { 1414 return !t.isCompound() ? 1415 visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) : 1416 visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false); 1417 } 1418 1419 if (s.tag == CLASS || s.tag == ARRAY) { 1420 boolean upcast; 1421 if ((upcast = isSubtype(erasure(t), erasure(s))) 1422 || isSubtype(erasure(s), erasure(t))) { 1423 if (!upcast && s.tag == ARRAY) { 1424 if (!isReifiable(s)) 1425 warnStack.head.warn(LintCategory.UNCHECKED); 1426 return true; 1427 } else if (s.isRaw()) { 1428 return true; 1429 } else if (t.isRaw()) { 1430 if (!isUnbounded(s)) 1431 warnStack.head.warn(LintCategory.UNCHECKED); 1432 return true; 1433 } 1434 // Assume |a| <: |b| 1435 final Type a = upcast ? t : s; 1436 final Type b = upcast ? s : t; 1437 final boolean HIGH = true; 1438 final boolean LOW = false; 1439 final boolean DONT_REWRITE_TYPEVARS = false; 1440 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS); 1441 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS); 1442 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS); 1443 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS); 1444 Type lowSub = asSub(bLow, aLow.tsym); 1445 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); 1446 if (highSub == null) { 1447 final boolean REWRITE_TYPEVARS = true; 1448 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS); 1449 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS); 1450 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS); 1451 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS); 1452 lowSub = asSub(bLow, aLow.tsym); 1453 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); 1454 } 1455 if (highSub != null) { 1456 if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) { 1457 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym); 1458 } 1459 if (!disjointTypes(aHigh.allparams(), highSub.allparams()) 1460 && !disjointTypes(aHigh.allparams(), lowSub.allparams()) 1461 && !disjointTypes(aLow.allparams(), highSub.allparams()) 1462 && !disjointTypes(aLow.allparams(), lowSub.allparams())) { 1463 if (upcast ? giveWarning(a, b) : 1464 giveWarning(b, a)) 1465 warnStack.head.warn(LintCategory.UNCHECKED); 1466 return true; 1467 } 1468 } 1469 if (isReifiable(s)) 1470 return isSubtypeUnchecked(a, b); 1471 else 1472 return isSubtypeUnchecked(a, b, warnStack.head); 1473 } 1474 1475 // Sidecast 1476 if (s.tag == CLASS) { 1477 if ((s.tsym.flags() & INTERFACE) != 0) { 1478 return ((t.tsym.flags() & FINAL) == 0) 1479 ? sideCast(t, s, warnStack.head) 1480 : sideCastFinal(t, s, warnStack.head); 1481 } else if ((t.tsym.flags() & INTERFACE) != 0) { 1482 return ((s.tsym.flags() & FINAL) == 0) 1483 ? sideCast(t, s, warnStack.head) 1484 : sideCastFinal(t, s, warnStack.head); 1485 } else { 1486 // unrelated class types 1487 return false; 1488 } 1489 } 1490 } 1491 return false; 1492 } 1493 1494 boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) { 1495 Warner warn = noWarnings; 1496 for (Type c : ict.getComponents()) { 1497 warn.clear(); 1498 if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn)) 1499 return false; 1500 } 1501 if (warn.hasLint(LintCategory.UNCHECKED)) 1502 warnStack.head.warn(LintCategory.UNCHECKED); 1503 return true; 1504 } 1505 1506 @Override 1507 public Boolean visitArrayType(ArrayType t, Type s) { 1508 switch (s.tag) { 1509 case ERROR: 1510 case BOT: 1511 return true; 1512 case TYPEVAR: 1513 if (isCastable(s, t, noWarnings)) { 1514 warnStack.head.warn(LintCategory.UNCHECKED); 1515 return true; 1516 } else { 1517 return false; 1518 } 1519 case CLASS: 1520 return isSubtype(t, s); 1521 case ARRAY: 1522 if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) { 1523 return elemtype(t).tag == elemtype(s).tag; 1524 } else { 1525 return visit(elemtype(t), elemtype(s)); 1526 } 1527 default: 1528 return false; 1529 } 1530 } 1531 1532 @Override 1533 public Boolean visitTypeVar(TypeVar t, Type s) { 1534 switch (s.tag) { 1535 case ERROR: 1536 case BOT: 1537 return true; 1538 case TYPEVAR: 1539 if (isSubtype(t, s)) { 1540 return true; 1541 } else if (isCastable(t.bound, s, noWarnings)) { 1542 warnStack.head.warn(LintCategory.UNCHECKED); 1543 return true; 1544 } else { 1545 return false; 1546 } 1547 default: 1548 return isCastable(t.bound, s, warnStack.head); 1549 } 1550 } 1551 1552 @Override 1553 public Boolean visitErrorType(ErrorType t, Type s) { 1554 return true; 1555 } 1556 }; 1557 // </editor-fold> 1558 1559 // <editor-fold defaultstate="collapsed" desc="disjointTypes"> 1560 public boolean disjointTypes(List<Type> ts, List<Type> ss) { 1561 while (ts.tail != null && ss.tail != null) { 1562 if (disjointType(ts.head, ss.head)) return true; 1563 ts = ts.tail; 1564 ss = ss.tail; 1565 } 1566 return false; 1567 } 1568 1569 /** 1570 * Two types or wildcards are considered disjoint if it can be 1571 * proven that no type can be contained in both. It is 1572 * conservative in that it is allowed to say that two types are 1573 * not disjoint, even though they actually are. 1574 * 1575 * The type {@code C<X>} is castable to {@code C<Y>} exactly if 1576 * {@code X} and {@code Y} are not disjoint. 1577 */ 1578 public boolean disjointType(Type t, Type s) { 1579 return disjointType.visit(t, s); 1580 } 1581 // where 1582 private TypeRelation disjointType = new TypeRelation() { 1583 1584 private Set<TypePair> cache = new HashSet<TypePair>(); 1585 1586 public Boolean visitType(Type t, Type s) { 1587 if (s.tag == WILDCARD) 1588 return visit(s, t); 1589 else 1590 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t); 1591 } 1592 1593 private boolean isCastableRecursive(Type t, Type s) { 1594 TypePair pair = new TypePair(t, s); 1595 if (cache.add(pair)) { 1596 try { 1597 return Types.this.isCastable(t, s); 1598 } finally { 1599 cache.remove(pair); 1600 } 1601 } else { 1602 return true; 1603 } 1604 } 1605 1606 private boolean notSoftSubtypeRecursive(Type t, Type s) { 1607 TypePair pair = new TypePair(t, s); 1608 if (cache.add(pair)) { 1609 try { 1610 return Types.this.notSoftSubtype(t, s); 1611 } finally { 1612 cache.remove(pair); 1613 } 1614 } else { 1615 return false; 1616 } 1617 } 1618 1619 @Override 1620 public Boolean visitWildcardType(WildcardType t, Type s) { 1621 if (t.isUnbound()) 1622 return false; 1623 1624 if (s.tag != WILDCARD) { 1625 if (t.isExtendsBound()) 1626 return notSoftSubtypeRecursive(s, t.type); 1627 else // isSuperBound() 1628 return notSoftSubtypeRecursive(t.type, s); 1629 } 1630 1631 if (s.isUnbound()) 1632 return false; 1633 1634 if (t.isExtendsBound()) { 1635 if (s.isExtendsBound()) 1636 return !isCastableRecursive(t.type, upperBound(s)); 1637 else if (s.isSuperBound()) 1638 return notSoftSubtypeRecursive(lowerBound(s), t.type); 1639 } else if (t.isSuperBound()) { 1640 if (s.isExtendsBound()) 1641 return notSoftSubtypeRecursive(t.type, upperBound(s)); 1642 } 1643 return false; 1644 } 1645 }; 1646 // </editor-fold> 1647 1648 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes"> 1649 /** 1650 * Returns the lower bounds of the formals of a method. 1651 */ 1652 public List<Type> lowerBoundArgtypes(Type t) { 1653 return lowerBounds(t.getParameterTypes()); 1654 } 1655 public List<Type> lowerBounds(List<Type> ts) { 1656 return map(ts, lowerBoundMapping); 1657 } 1658 private final Mapping lowerBoundMapping = new Mapping("lowerBound") { 1659 public Type apply(Type t) { 1660 return lowerBound(t); 1661 } 1662 }; 1663 // </editor-fold> 1664 1665 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype"> 1666 /** 1667 * This relation answers the question: is impossible that 1668 * something of type `t' can be a subtype of `s'? This is 1669 * different from the question "is `t' not a subtype of `s'?" 1670 * when type variables are involved: Integer is not a subtype of T 1671 * where {@code <T extends Number>} but it is not true that Integer cannot 1672 * possibly be a subtype of T. 1673 */ 1674 public boolean notSoftSubtype(Type t, Type s) { 1675 if (t == s) return false; 1676 if (t.tag == TYPEVAR) { 1677 TypeVar tv = (TypeVar) t; 1678 return !isCastable(tv.bound, 1679 relaxBound(s), 1680 noWarnings); 1681 } 1682 if (s.tag != WILDCARD) 1683 s = upperBound(s); 1684 1685 return !isSubtype(t, relaxBound(s)); 1686 } 1687 1688 private Type relaxBound(Type t) { 1689 if (t.tag == TYPEVAR) { 1690 while (t.tag == TYPEVAR) 1691 t = t.getUpperBound(); 1692 t = rewriteQuantifiers(t, true, true); 1693 } 1694 return t; 1695 } 1696 // </editor-fold> 1697 1698 // <editor-fold defaultstate="collapsed" desc="isReifiable"> 1699 public boolean isReifiable(Type t) { 1700 return isReifiable.visit(t); 1701 } 1702 // where 1703 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() { 1704 1705 public Boolean visitType(Type t, Void ignored) { 1706 return true; 1707 } 1708 1709 @Override 1710 public Boolean visitClassType(ClassType t, Void ignored) { 1711 if (t.isCompound()) 1712 return false; 1713 else { 1714 if (!t.isParameterized()) 1715 return true; 1716 1717 for (Type param : t.allparams()) { 1718 if (!param.isUnbound()) 1719 return false; 1720 } 1721 return true; 1722 } 1723 } 1724 1725 @Override 1726 public Boolean visitArrayType(ArrayType t, Void ignored) { 1727 return visit(t.elemtype); 1728 } 1729 1730 @Override 1731 public Boolean visitTypeVar(TypeVar t, Void ignored) { 1732 return false; 1733 } 1734 }; 1735 // </editor-fold> 1736 1737 // <editor-fold defaultstate="collapsed" desc="Array Utils"> 1738 public boolean isArray(Type t) { 1739 while (t.tag == WILDCARD) 1740 t = upperBound(t); 1741 return t.tag == ARRAY; 1742 } 1743 1744 /** 1745 * The element type of an array. 1746 */ 1747 public Type elemtype(Type t) { 1748 switch (t.tag) { 1749 case WILDCARD: 1750 return elemtype(upperBound(t)); 1751 case ARRAY: 1752 t = t.unannotatedType(); 1753 return ((ArrayType)t).elemtype; 1754 case FORALL: 1755 return elemtype(((ForAll)t).qtype); 1756 case ERROR: 1757 return t; 1758 default: 1759 return null; 1760 } 1761 } 1762 1763 public Type elemtypeOrType(Type t) { 1764 Type elemtype = elemtype(t); 1765 return elemtype != null ? 1766 elemtype : 1767 t; 1768 } 1769 1770 /** 1771 * Mapping to take element type of an arraytype 1772 */ 1773 private Mapping elemTypeFun = new Mapping ("elemTypeFun") { 1774 public Type apply(Type t) { return elemtype(t); } 1775 }; 1776 1777 /** 1778 * The number of dimensions of an array type. 1779 */ 1780 public int dimensions(Type t) { 1781 int result = 0; 1782 while (t.tag == ARRAY) { 1783 result++; 1784 t = elemtype(t); 1785 } 1786 return result; 1787 } 1788 1789 /** 1790 * Returns an ArrayType with the component type t 1791 * 1792 * @param t The component type of the ArrayType 1793 * @return the ArrayType for the given component 1794 */ 1795 public ArrayType makeArrayType(Type t) { 1796 if (t.tag == VOID || 1797 t.tag == PACKAGE) { 1798 Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString()); 1799 } 1800 return new ArrayType(t, syms.arrayClass); 1801 } 1802 // </editor-fold> 1803 1804 // <editor-fold defaultstate="collapsed" desc="asSuper"> 1805 /** 1806 * Return the (most specific) base type of t that starts with the 1807 * given symbol. If none exists, return null. 1808 * 1809 * @param t a type 1810 * @param sym a symbol 1811 */ 1812 public Type asSuper(Type t, Symbol sym) { 1813 return asSuper.visit(t, sym); 1814 } 1815 // where 1816 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() { 1817 1818 public Type visitType(Type t, Symbol sym) { 1819 return null; 1820 } 1821 1822 @Override 1823 public Type visitClassType(ClassType t, Symbol sym) { 1824 if (t.tsym == sym) 1825 return t; 1826 1827 Type st = supertype(t); 1828 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) { 1829 Type x = asSuper(st, sym); 1830 if (x != null) 1831 return x; 1832 } 1833 if ((sym.flags() & INTERFACE) != 0) { 1834 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { 1835 Type x = asSuper(l.head, sym); 1836 if (x != null) 1837 return x; 1838 } 1839 } 1840 return null; 1841 } 1842 1843 @Override 1844 public Type visitArrayType(ArrayType t, Symbol sym) { 1845 return isSubtype(t, sym.type) ? sym.type : null; 1846 } 1847 1848 @Override 1849 public Type visitTypeVar(TypeVar t, Symbol sym) { 1850 if (t.tsym == sym) 1851 return t; 1852 else 1853 return asSuper(t.bound, sym); 1854 } 1855 1856 @Override 1857 public Type visitErrorType(ErrorType t, Symbol sym) { 1858 return t; 1859 } 1860 }; 1861 1862 /** 1863 * Return the base type of t or any of its outer types that starts 1864 * with the given symbol. If none exists, return null. 1865 * 1866 * @param t a type 1867 * @param sym a symbol 1868 */ 1869 public Type asOuterSuper(Type t, Symbol sym) { 1870 switch (t.tag) { 1871 case CLASS: 1872 do { 1873 Type s = asSuper(t, sym); 1874 if (s != null) return s; 1875 t = t.getEnclosingType(); 1876 } while (t.tag == CLASS); 1877 return null; 1878 case ARRAY: 1879 return isSubtype(t, sym.type) ? sym.type : null; 1880 case TYPEVAR: 1881 return asSuper(t, sym); 1882 case ERROR: 1883 return t; 1884 default: 1885 return null; 1886 } 1887 } 1888 1889 /** 1890 * Return the base type of t or any of its enclosing types that 1891 * starts with the given symbol. If none exists, return null. 1892 * 1893 * @param t a type 1894 * @param sym a symbol 1895 */ 1896 public Type asEnclosingSuper(Type t, Symbol sym) { 1897 switch (t.tag) { 1898 case CLASS: 1899 do { 1900 Type s = asSuper(t, sym); 1901 if (s != null) return s; 1902 Type outer = t.getEnclosingType(); 1903 t = (outer.tag == CLASS) ? outer : 1904 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type : 1905 Type.noType; 1906 } while (t.tag == CLASS); 1907 return null; 1908 case ARRAY: 1909 return isSubtype(t, sym.type) ? sym.type : null; 1910 case TYPEVAR: 1911 return asSuper(t, sym); 1912 case ERROR: 1913 return t; 1914 default: 1915 return null; 1916 } 1917 } 1918 // </editor-fold> 1919 1920 // <editor-fold defaultstate="collapsed" desc="memberType"> 1921 /** 1922 * The type of given symbol, seen as a member of t. 1923 * 1924 * @param t a type 1925 * @param sym a symbol 1926 */ 1927 public Type memberType(Type t, Symbol sym) { 1928 return (sym.flags() & STATIC) != 0 1929 ? sym.type 1930 : memberType.visit(t, sym); 1931 } 1932 // where 1933 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() { 1934 1935 public Type visitType(Type t, Symbol sym) { 1936 return sym.type; 1937 } 1938 1939 @Override 1940 public Type visitWildcardType(WildcardType t, Symbol sym) { 1941 return memberType(upperBound(t), sym); 1942 } 1943 1944 @Override 1945 public Type visitClassType(ClassType t, Symbol sym) { 1946 Symbol owner = sym.owner; 1947 long flags = sym.flags(); 1948 if (((flags & STATIC) == 0) && owner.type.isParameterized()) { 1949 Type base = asOuterSuper(t, owner); 1950 //if t is an intersection type T = CT & I1 & I2 ... & In 1951 //its supertypes CT, I1, ... In might contain wildcards 1952 //so we need to go through capture conversion 1953 base = t.isCompound() ? capture(base) : base; 1954 if (base != null) { 1955 List<Type> ownerParams = owner.type.allparams(); 1956 List<Type> baseParams = base.allparams(); 1957 if (ownerParams.nonEmpty()) { 1958 if (baseParams.isEmpty()) { 1959 // then base is a raw type 1960 return erasure(sym.type); 1961 } else { 1962 return subst(sym.type, ownerParams, baseParams); 1963 } 1964 } 1965 } 1966 } 1967 return sym.type; 1968 } 1969 1970 @Override 1971 public Type visitTypeVar(TypeVar t, Symbol sym) { 1972 return memberType(t.bound, sym); 1973 } 1974 1975 @Override 1976 public Type visitErrorType(ErrorType t, Symbol sym) { 1977 return t; 1978 } 1979 }; 1980 // </editor-fold> 1981 1982 // <editor-fold defaultstate="collapsed" desc="isAssignable"> 1983 public boolean isAssignable(Type t, Type s) { 1984 return isAssignable(t, s, noWarnings); 1985 } 1986 1987 /** 1988 * Is t assignable to s?<br> 1989 * Equivalent to subtype except for constant values and raw 1990 * types.<br> 1991 * (not defined for Method and ForAll types) 1992 */ 1993 public boolean isAssignable(Type t, Type s, Warner warn) { 1994 if (t.tag == ERROR) 1995 return true; 1996 if (t.tag.isSubRangeOf(INT) && t.constValue() != null) { 1997 int value = ((Number)t.constValue()).intValue(); 1998 switch (s.tag) { 1999 case BYTE: 2000 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) 2001 return true; 2002 break; 2003 case CHAR: 2004 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE) 2005 return true; 2006 break; 2007 case SHORT: 2008 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) 2009 return true; 2010 break; 2011 case INT: 2012 return true; 2013 case CLASS: 2014 switch (unboxedType(s).tag) { 2015 case BYTE: 2016 case CHAR: 2017 case SHORT: 2018 return isAssignable(t, unboxedType(s), warn); 2019 } 2020 break; 2021 } 2022 } 2023 return isConvertible(t, s, warn); 2024 } 2025 // </editor-fold> 2026 2027 // <editor-fold defaultstate="collapsed" desc="erasure"> 2028 /** 2029 * The erasure of t {@code |t|} -- the type that results when all 2030 * type parameters in t are deleted. 2031 */ 2032 public Type erasure(Type t) { 2033 return eraseNotNeeded(t)? t : erasure(t, false); 2034 } 2035 //where 2036 private boolean eraseNotNeeded(Type t) { 2037 // We don't want to erase primitive types and String type as that 2038 // operation is idempotent. Also, erasing these could result in loss 2039 // of information such as constant values attached to such types. 2040 return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym); 2041 } 2042 2043 private Type erasure(Type t, boolean recurse) { 2044 if (t.isPrimitive()) 2045 return t; /* fast special case */ 2046 else 2047 return erasure.visit(t, recurse); 2048 } 2049 // where 2050 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() { 2051 public Type visitType(Type t, Boolean recurse) { 2052 if (t.isPrimitive()) 2053 return t; /*fast special case*/ 2054 else 2055 return t.map(recurse ? erasureRecFun : erasureFun); 2056 } 2057 2058 @Override 2059 public Type visitWildcardType(WildcardType t, Boolean recurse) { 2060 return erasure(upperBound(t), recurse); 2061 } 2062 2063 @Override 2064 public Type visitClassType(ClassType t, Boolean recurse) { 2065 Type erased = t.tsym.erasure(Types.this); 2066 if (recurse) { 2067 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym); 2068 } 2069 return erased; 2070 } 2071 2072 @Override 2073 public Type visitTypeVar(TypeVar t, Boolean recurse) { 2074 return erasure(t.bound, recurse); 2075 } 2076 2077 @Override 2078 public Type visitErrorType(ErrorType t, Boolean recurse) { 2079 return t; 2080 } 2081 2082 @Override 2083 public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) { 2084 Type erased = erasure(t.underlyingType, recurse); 2085 if (erased.isAnnotated()) { 2086 // This can only happen when the underlying type is a 2087 // type variable and the upper bound of it is annotated. 2088 // The annotation on the type variable overrides the one 2089 // on the bound. 2090 erased = ((AnnotatedType)erased).underlyingType; 2091 } 2092 return new AnnotatedType(t.typeAnnotations, erased); 2093 } 2094 }; 2095 2096 private Mapping erasureFun = new Mapping ("erasure") { 2097 public Type apply(Type t) { return erasure(t); } 2098 }; 2099 2100 private Mapping erasureRecFun = new Mapping ("erasureRecursive") { 2101 public Type apply(Type t) { return erasureRecursive(t); } 2102 }; 2103 2104 public List<Type> erasure(List<Type> ts) { 2105 return Type.map(ts, erasureFun); 2106 } 2107 2108 public Type erasureRecursive(Type t) { 2109 return erasure(t, true); 2110 } 2111 2112 public List<Type> erasureRecursive(List<Type> ts) { 2113 return Type.map(ts, erasureRecFun); 2114 } 2115 // </editor-fold> 2116 2117 // <editor-fold defaultstate="collapsed" desc="makeCompoundType"> 2118 /** 2119 * Make a compound type from non-empty list of types 2120 * 2121 * @param bounds the types from which the compound type is formed 2122 * @param supertype is objectType if all bounds are interfaces, 2123 * null otherwise. 2124 */ 2125 public Type makeCompoundType(List<Type> bounds) { 2126 return makeCompoundType(bounds, bounds.head.tsym.isInterface()); 2127 } 2128 public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) { 2129 Assert.check(bounds.nonEmpty()); 2130 Type firstExplicitBound = bounds.head; 2131 if (allInterfaces) { 2132 bounds = bounds.prepend(syms.objectType); 2133 } 2134 ClassSymbol bc = 2135 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC, 2136 Type.moreInfo 2137 ? names.fromString(bounds.toString()) 2138 : names.empty, 2139 null, 2140 syms.noSymbol); 2141 bc.type = new IntersectionClassType(bounds, bc, allInterfaces); 2142 bc.erasure_field = (bounds.head.tag == TYPEVAR) ? 2143 syms.objectType : // error condition, recover 2144 erasure(firstExplicitBound); 2145 bc.members_field = new Scope(bc); 2146 return bc.type; 2147 } 2148 2149 /** 2150 * A convenience wrapper for {@link #makeCompoundType(List)}; the 2151 * arguments are converted to a list and passed to the other 2152 * method. Note that this might cause a symbol completion. 2153 * Hence, this version of makeCompoundType may not be called 2154 * during a classfile read. 2155 */ 2156 public Type makeCompoundType(Type bound1, Type bound2) { 2157 return makeCompoundType(List.of(bound1, bound2)); 2158 } 2159 // </editor-fold> 2160 2161 // <editor-fold defaultstate="collapsed" desc="supertype"> 2162 public Type supertype(Type t) { 2163 return supertype.visit(t); 2164 } 2165 // where 2166 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() { 2167 2168 public Type visitType(Type t, Void ignored) { 2169 // A note on wildcards: there is no good way to 2170 // determine a supertype for a super bounded wildcard. 2171 return null; 2172 } 2173 2174 @Override 2175 public Type visitClassType(ClassType t, Void ignored) { 2176 if (t.supertype_field == null) { 2177 Type supertype = ((ClassSymbol)t.tsym).getSuperclass(); 2178 // An interface has no superclass; its supertype is Object. 2179 if (t.isInterface()) 2180 supertype = ((ClassType)t.tsym.type).supertype_field; 2181 if (t.supertype_field == null) { 2182 List<Type> actuals = classBound(t).allparams(); 2183 List<Type> formals = t.tsym.type.allparams(); 2184 if (t.hasErasedSupertypes()) { 2185 t.supertype_field = erasureRecursive(supertype); 2186 } else if (formals.nonEmpty()) { 2187 t.supertype_field = subst(supertype, formals, actuals); 2188 } 2189 else { 2190 t.supertype_field = supertype; 2191 } 2192 } 2193 } 2194 return t.supertype_field; 2195 } 2196 2197 /** 2198 * The supertype is always a class type. If the type 2199 * variable's bounds start with a class type, this is also 2200 * the supertype. Otherwise, the supertype is 2201 * java.lang.Object. 2202 */ 2203 @Override 2204 public Type visitTypeVar(TypeVar t, Void ignored) { 2205 if (t.bound.tag == TYPEVAR || 2206 (!t.bound.isCompound() && !t.bound.isInterface())) { 2207 return t.bound; 2208 } else { 2209 return supertype(t.bound); 2210 } 2211 } 2212 2213 @Override 2214 public Type visitArrayType(ArrayType t, Void ignored) { 2215 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType)) 2216 return arraySuperType(); 2217 else 2218 return new ArrayType(supertype(t.elemtype), t.tsym); 2219 } 2220 2221 @Override 2222 public Type visitErrorType(ErrorType t, Void ignored) { 2223 return t; 2224 } 2225 }; 2226 // </editor-fold> 2227 2228 // <editor-fold defaultstate="collapsed" desc="interfaces"> 2229 /** 2230 * Return the interfaces implemented by this class. 2231 */ 2232 public List<Type> interfaces(Type t) { 2233 return interfaces.visit(t); 2234 } 2235 // where 2236 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() { 2237 2238 public List<Type> visitType(Type t, Void ignored) { 2239 return List.nil(); 2240 } 2241 2242 @Override 2243 public List<Type> visitClassType(ClassType t, Void ignored) { 2244 if (t.interfaces_field == null) { 2245 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces(); 2246 if (t.interfaces_field == null) { 2247 // If t.interfaces_field is null, then t must 2248 // be a parameterized type (not to be confused 2249 // with a generic type declaration). 2250 // Terminology: 2251 // Parameterized type: List<String> 2252 // Generic type declaration: class List<E> { ... } 2253 // So t corresponds to List<String> and 2254 // t.tsym.type corresponds to List<E>. 2255 // The reason t must be parameterized type is 2256 // that completion will happen as a side 2257 // effect of calling 2258 // ClassSymbol.getInterfaces. Since 2259 // t.interfaces_field is null after 2260 // completion, we can assume that t is not the 2261 // type of a class/interface declaration. 2262 Assert.check(t != t.tsym.type, t); 2263 List<Type> actuals = t.allparams(); 2264 List<Type> formals = t.tsym.type.allparams(); 2265 if (t.hasErasedSupertypes()) { 2266 t.interfaces_field = erasureRecursive(interfaces); 2267 } else if (formals.nonEmpty()) { 2268 t.interfaces_field = 2269 upperBounds(subst(interfaces, formals, actuals)); 2270 } 2271 else { 2272 t.interfaces_field = interfaces; 2273 } 2274 } 2275 } 2276 return t.interfaces_field; 2277 } 2278 2279 @Override 2280 public List<Type> visitTypeVar(TypeVar t, Void ignored) { 2281 if (t.bound.isCompound()) 2282 return interfaces(t.bound); 2283 2284 if (t.bound.isInterface()) 2285 return List.of(t.bound); 2286 2287 return List.nil(); 2288 } 2289 }; 2290 2291 public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) { 2292 for (Type i2 : interfaces(origin.type)) { 2293 if (isym == i2.tsym) return true; 2294 } 2295 return false; 2296 } 2297 // </editor-fold> 2298 2299 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw"> 2300 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>(); 2301 2302 public boolean isDerivedRaw(Type t) { 2303 Boolean result = isDerivedRawCache.get(t); 2304 if (result == null) { 2305 result = isDerivedRawInternal(t); 2306 isDerivedRawCache.put(t, result); 2307 } 2308 return result; 2309 } 2310 2311 public boolean isDerivedRawInternal(Type t) { 2312 if (t.isErroneous()) 2313 return false; 2314 return 2315 t.isRaw() || 2316 supertype(t) != null && isDerivedRaw(supertype(t)) || 2317 isDerivedRaw(interfaces(t)); 2318 } 2319 2320 public boolean isDerivedRaw(List<Type> ts) { 2321 List<Type> l = ts; 2322 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail; 2323 return l.nonEmpty(); 2324 } 2325 // </editor-fold> 2326 2327 // <editor-fold defaultstate="collapsed" desc="setBounds"> 2328 /** 2329 * Set the bounds field of the given type variable to reflect a 2330 * (possibly multiple) list of bounds. 2331 * @param t a type variable 2332 * @param bounds the bounds, must be nonempty 2333 * @param supertype is objectType if all bounds are interfaces, 2334 * null otherwise. 2335 */ 2336 public void setBounds(TypeVar t, List<Type> bounds) { 2337 setBounds(t, bounds, bounds.head.tsym.isInterface()); 2338 } 2339 2340 /** 2341 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that 2342 * third parameter is computed directly, as follows: if all 2343 * all bounds are interface types, the computed supertype is Object, 2344 * otherwise the supertype is simply left null (in this case, the supertype 2345 * is assumed to be the head of the bound list passed as second argument). 2346 * Note that this check might cause a symbol completion. Hence, this version of 2347 * setBounds may not be called during a classfile read. 2348 */ 2349 public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) { 2350 t.bound = bounds.tail.isEmpty() ? 2351 bounds.head : 2352 makeCompoundType(bounds, allInterfaces); 2353 t.rank_field = -1; 2354 } 2355 // </editor-fold> 2356 2357 // <editor-fold defaultstate="collapsed" desc="getBounds"> 2358 /** 2359 * Return list of bounds of the given type variable. 2360 */ 2361 public List<Type> getBounds(TypeVar t) { 2362 if (t.bound.hasTag(NONE)) 2363 return List.nil(); 2364 else if (t.bound.isErroneous() || !t.bound.isCompound()) 2365 return List.of(t.bound); 2366 else if ((erasure(t).tsym.flags() & INTERFACE) == 0) 2367 return interfaces(t).prepend(supertype(t)); 2368 else 2369 // No superclass was given in bounds. 2370 // In this case, supertype is Object, erasure is first interface. 2371 return interfaces(t); 2372 } 2373 // </editor-fold> 2374 2375 // <editor-fold defaultstate="collapsed" desc="classBound"> 2376 /** 2377 * If the given type is a (possibly selected) type variable, 2378 * return the bounding class of this type, otherwise return the 2379 * type itself. 2380 */ 2381 public Type classBound(Type t) { 2382 return classBound.visit(t); 2383 } 2384 // where 2385 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() { 2386 2387 public Type visitType(Type t, Void ignored) { 2388 return t; 2389 } 2390 2391 @Override 2392 public Type visitClassType(ClassType t, Void ignored) { 2393 Type outer1 = classBound(t.getEnclosingType()); 2394 if (outer1 != t.getEnclosingType()) 2395 return new ClassType(outer1, t.getTypeArguments(), t.tsym); 2396 else 2397 return t; 2398 } 2399 2400 @Override 2401 public Type visitTypeVar(TypeVar t, Void ignored) { 2402 return classBound(supertype(t)); 2403 } 2404 2405 @Override 2406 public Type visitErrorType(ErrorType t, Void ignored) { 2407 return t; 2408 } 2409 }; 2410 // </editor-fold> 2411 2412 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence"> 2413 /** 2414 * Returns true iff the first signature is a <em>sub 2415 * signature</em> of the other. This is <b>not</b> an equivalence 2416 * relation. 2417 * 2418 * @jls section 8.4.2. 2419 * @see #overrideEquivalent(Type t, Type s) 2420 * @param t first signature (possibly raw). 2421 * @param s second signature (could be subjected to erasure). 2422 * @return true if t is a sub signature of s. 2423 */ 2424 public boolean isSubSignature(Type t, Type s) { 2425 return isSubSignature(t, s, true); 2426 } 2427 2428 public boolean isSubSignature(Type t, Type s, boolean strict) { 2429 return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict); 2430 } 2431 2432 /** 2433 * Returns true iff these signatures are related by <em>override 2434 * equivalence</em>. This is the natural extension of 2435 * isSubSignature to an equivalence relation. 2436 * 2437 * @jls section 8.4.2. 2438 * @see #isSubSignature(Type t, Type s) 2439 * @param t a signature (possible raw, could be subjected to 2440 * erasure). 2441 * @param s a signature (possible raw, could be subjected to 2442 * erasure). 2443 * @return true if either argument is a sub signature of the other. 2444 */ 2445 public boolean overrideEquivalent(Type t, Type s) { 2446 return hasSameArgs(t, s) || 2447 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s); 2448 } 2449 2450 public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) { 2451 for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) { 2452 if (msym.overrides(e.sym, origin, Types.this, true)) { 2453 return true; 2454 } 2455 } 2456 return false; 2457 } 2458 2459 // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site"> 2460 class ImplementationCache { 2461 2462 private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = 2463 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>(); 2464 2465 class Entry { 2466 final MethodSymbol cachedImpl; 2467 final Filter<Symbol> implFilter; 2468 final boolean checkResult; 2469 final int prevMark; 2470 2471 public Entry(MethodSymbol cachedImpl, 2472 Filter<Symbol> scopeFilter, 2473 boolean checkResult, 2474 int prevMark) { 2475 this.cachedImpl = cachedImpl; 2476 this.implFilter = scopeFilter; 2477 this.checkResult = checkResult; 2478 this.prevMark = prevMark; 2479 } 2480 2481 boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) { 2482 return this.implFilter == scopeFilter && 2483 this.checkResult == checkResult && 2484 this.prevMark == mark; 2485 } 2486 } 2487 2488 MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2489 SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms); 2490 Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null; 2491 if (cache == null) { 2492 cache = new HashMap<TypeSymbol, Entry>(); 2493 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache)); 2494 } 2495 Entry e = cache.get(origin); 2496 CompoundScope members = membersClosure(origin.type, true); 2497 if (e == null || 2498 !e.matches(implFilter, checkResult, members.getMark())) { 2499 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter); 2500 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark())); 2501 return impl; 2502 } 2503 else { 2504 return e.cachedImpl; 2505 } 2506 } 2507 2508 private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2509 for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) { 2510 while (t.tag == TYPEVAR) 2511 t = t.getUpperBound(); 2512 TypeSymbol c = t.tsym; 2513 for (Scope.Entry e = c.members().lookup(ms.name, implFilter); 2514 e.scope != null; 2515 e = e.next(implFilter)) { 2516 if (e.sym != null && 2517 e.sym.overrides(ms, origin, Types.this, checkResult)) 2518 return (MethodSymbol)e.sym; 2519 } 2520 } 2521 return null; 2522 } 2523 } 2524 2525 private ImplementationCache implCache = new ImplementationCache(); 2526 2527 public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { 2528 return implCache.get(ms, origin, checkResult, implFilter); 2529 } 2530 // </editor-fold> 2531 2532 // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site"> 2533 class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> { 2534 2535 private WeakHashMap<TypeSymbol, Entry> _map = 2536 new WeakHashMap<TypeSymbol, Entry>(); 2537 2538 class Entry { 2539 final boolean skipInterfaces; 2540 final CompoundScope compoundScope; 2541 2542 public Entry(boolean skipInterfaces, CompoundScope compoundScope) { 2543 this.skipInterfaces = skipInterfaces; 2544 this.compoundScope = compoundScope; 2545 } 2546 2547 boolean matches(boolean skipInterfaces) { 2548 return this.skipInterfaces == skipInterfaces; 2549 } 2550 } 2551 2552 List<TypeSymbol> seenTypes = List.nil(); 2553 2554 /** members closure visitor methods **/ 2555 2556 public CompoundScope visitType(Type t, Boolean skipInterface) { 2557 return null; 2558 } 2559 2560 @Override 2561 public CompoundScope visitClassType(ClassType t, Boolean skipInterface) { 2562 if (seenTypes.contains(t.tsym)) { 2563 //this is possible when an interface is implemented in multiple 2564 //superclasses, or when a classs hierarchy is circular - in such 2565 //cases we don't need to recurse (empty scope is returned) 2566 return new CompoundScope(t.tsym); 2567 } 2568 try { 2569 seenTypes = seenTypes.prepend(t.tsym); 2570 ClassSymbol csym = (ClassSymbol)t.tsym; 2571 Entry e = _map.get(csym); 2572 if (e == null || !e.matches(skipInterface)) { 2573 CompoundScope membersClosure = new CompoundScope(csym); 2574 if (!skipInterface) { 2575 for (Type i : interfaces(t)) { 2576 membersClosure.addSubScope(visit(i, skipInterface)); 2577 } 2578 } 2579 membersClosure.addSubScope(visit(supertype(t), skipInterface)); 2580 membersClosure.addSubScope(csym.members()); 2581 e = new Entry(skipInterface, membersClosure); 2582 _map.put(csym, e); 2583 } 2584 return e.compoundScope; 2585 } 2586 finally { 2587 seenTypes = seenTypes.tail; 2588 } 2589 } 2590 2591 @Override 2592 public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) { 2593 return visit(t.getUpperBound(), skipInterface); 2594 } 2595 } 2596 2597 private MembersClosureCache membersCache = new MembersClosureCache(); 2598 2599 public CompoundScope membersClosure(Type site, boolean skipInterface) { 2600 return membersCache.visit(site, skipInterface); 2601 } 2602 // </editor-fold> 2603 2604 2605 //where 2606 public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) { 2607 Filter<Symbol> filter = new MethodFilter(ms, site); 2608 List<MethodSymbol> candidates = List.nil(); 2609 for (Symbol s : membersClosure(site, false).getElements(filter)) { 2610 if (!site.tsym.isInterface() && !s.owner.isInterface()) { 2611 return List.of((MethodSymbol)s); 2612 } else if (!candidates.contains(s)) { 2613 candidates = candidates.prepend((MethodSymbol)s); 2614 } 2615 } 2616 return prune(candidates); 2617 } 2618 2619 public List<MethodSymbol> prune(List<MethodSymbol> methods) { 2620 ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb(); 2621 for (MethodSymbol m1 : methods) { 2622 boolean isMin_m1 = true; 2623 for (MethodSymbol m2 : methods) { 2624 if (m1 == m2) continue; 2625 if (m2.owner != m1.owner && 2626 asSuper(m2.owner.type, m1.owner) != null) { 2627 isMin_m1 = false; 2628 break; 2629 } 2630 } 2631 if (isMin_m1) 2632 methodsMin.append(m1); 2633 } 2634 return methodsMin.toList(); 2635 } 2636 // where 2637 private class MethodFilter implements Filter<Symbol> { 2638 2639 Symbol msym; 2640 Type site; 2641 2642 MethodFilter(Symbol msym, Type site) { 2643 this.msym = msym; 2644 this.site = site; 2645 } 2646 2647 public boolean accepts(Symbol s) { 2648 return s.kind == Kinds.MTH && 2649 s.name == msym.name && 2650 s.isInheritedIn(site.tsym, Types.this) && 2651 overrideEquivalent(memberType(site, s), memberType(site, msym)); 2652 } 2653 }; 2654 // </editor-fold> 2655 2656 /** 2657 * Does t have the same arguments as s? It is assumed that both 2658 * types are (possibly polymorphic) method types. Monomorphic 2659 * method types "have the same arguments", if their argument lists 2660 * are equal. Polymorphic method types "have the same arguments", 2661 * if they have the same arguments after renaming all type 2662 * variables of one to corresponding type variables in the other, 2663 * where correspondence is by position in the type parameter list. 2664 */ 2665 public boolean hasSameArgs(Type t, Type s) { 2666 return hasSameArgs(t, s, true); 2667 } 2668 2669 public boolean hasSameArgs(Type t, Type s, boolean strict) { 2670 return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict); 2671 } 2672 2673 private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) { 2674 return hasSameArgs.visit(t, s); 2675 } 2676 // where 2677 private class HasSameArgs extends TypeRelation { 2678 2679 boolean strict; 2680 2681 public HasSameArgs(boolean strict) { 2682 this.strict = strict; 2683 } 2684 2685 public Boolean visitType(Type t, Type s) { 2686 throw new AssertionError(); 2687 } 2688 2689 @Override 2690 public Boolean visitMethodType(MethodType t, Type s) { 2691 return s.tag == METHOD 2692 && containsTypeEquivalent(t.argtypes, s.getParameterTypes()); 2693 } 2694 2695 @Override 2696 public Boolean visitForAll(ForAll t, Type s) { 2697 if (s.tag != FORALL) 2698 return strict ? false : visitMethodType(t.asMethodType(), s); 2699 2700 ForAll forAll = (ForAll)s; 2701 return hasSameBounds(t, forAll) 2702 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); 2703 } 2704 2705 @Override 2706 public Boolean visitErrorType(ErrorType t, Type s) { 2707 return false; 2708 } 2709 }; 2710 2711 TypeRelation hasSameArgs_strict = new HasSameArgs(true); 2712 TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false); 2713 2714 // </editor-fold> 2715 2716 // <editor-fold defaultstate="collapsed" desc="subst"> 2717 public List<Type> subst(List<Type> ts, 2718 List<Type> from, 2719 List<Type> to) { 2720 return new Subst(from, to).subst(ts); 2721 } 2722 2723 /** 2724 * Substitute all occurrences of a type in `from' with the 2725 * corresponding type in `to' in 't'. Match lists `from' and `to' 2726 * from the right: If lists have different length, discard leading 2727 * elements of the longer list. 2728 */ 2729 public Type subst(Type t, List<Type> from, List<Type> to) { 2730 return new Subst(from, to).subst(t); 2731 } 2732 2733 private class Subst extends UnaryVisitor<Type> { 2734 List<Type> from; 2735 List<Type> to; 2736 2737 public Subst(List<Type> from, List<Type> to) { 2738 int fromLength = from.length(); 2739 int toLength = to.length(); 2740 while (fromLength > toLength) { 2741 fromLength--; 2742 from = from.tail; 2743 } 2744 while (fromLength < toLength) { 2745 toLength--; 2746 to = to.tail; 2747 } 2748 this.from = from; 2749 this.to = to; 2750 } 2751 2752 Type subst(Type t) { 2753 if (from.tail == null) 2754 return t; 2755 else 2756 return visit(t); 2757 } 2758 2759 List<Type> subst(List<Type> ts) { 2760 if (from.tail == null) 2761 return ts; 2762 boolean wild = false; 2763 if (ts.nonEmpty() && from.nonEmpty()) { 2764 Type head1 = subst(ts.head); 2765 List<Type> tail1 = subst(ts.tail); 2766 if (head1 != ts.head || tail1 != ts.tail) 2767 return tail1.prepend(head1); 2768 } 2769 return ts; 2770 } 2771 2772 public Type visitType(Type t, Void ignored) { 2773 return t; 2774 } 2775 2776 @Override 2777 public Type visitMethodType(MethodType t, Void ignored) { 2778 List<Type> argtypes = subst(t.argtypes); 2779 Type restype = subst(t.restype); 2780 List<Type> thrown = subst(t.thrown); 2781 if (argtypes == t.argtypes && 2782 restype == t.restype && 2783 thrown == t.thrown) 2784 return t; 2785 else 2786 return new MethodType(argtypes, restype, thrown, t.tsym); 2787 } 2788 2789 @Override 2790 public Type visitTypeVar(TypeVar t, Void ignored) { 2791 for (List<Type> from = this.from, to = this.to; 2792 from.nonEmpty(); 2793 from = from.tail, to = to.tail) { 2794 if (t == from.head) { 2795 return to.head.withTypeVar(t); 2796 } 2797 } 2798 return t; 2799 } 2800 2801 @Override 2802 public Type visitClassType(ClassType t, Void ignored) { 2803 if (!t.isCompound()) { 2804 List<Type> typarams = t.getTypeArguments(); 2805 List<Type> typarams1 = subst(typarams); 2806 Type outer = t.getEnclosingType(); 2807 Type outer1 = subst(outer); 2808 if (typarams1 == typarams && outer1 == outer) 2809 return t; 2810 else 2811 return new ClassType(outer1, typarams1, t.tsym); 2812 } else { 2813 Type st = subst(supertype(t)); 2814 List<Type> is = upperBounds(subst(interfaces(t))); 2815 if (st == supertype(t) && is == interfaces(t)) 2816 return t; 2817 else 2818 return makeCompoundType(is.prepend(st)); 2819 } 2820 } 2821 2822 @Override 2823 public Type visitWildcardType(WildcardType t, Void ignored) { 2824 Type bound = t.type; 2825 if (t.kind != BoundKind.UNBOUND) 2826 bound = subst(bound); 2827 if (bound == t.type) { 2828 return t; 2829 } else { 2830 if (t.isExtendsBound() && bound.isExtendsBound()) 2831 bound = upperBound(bound); 2832 return new WildcardType(bound, t.kind, syms.boundClass, t.bound); 2833 } 2834 } 2835 2836 @Override 2837 public Type visitArrayType(ArrayType t, Void ignored) { 2838 Type elemtype = subst(t.elemtype); 2839 if (elemtype == t.elemtype) 2840 return t; 2841 else 2842 return new ArrayType(upperBound(elemtype), t.tsym); 2843 } 2844 2845 @Override 2846 public Type visitForAll(ForAll t, Void ignored) { 2847 if (Type.containsAny(to, t.tvars)) { 2848 //perform alpha-renaming of free-variables in 't' 2849 //if 'to' types contain variables that are free in 't' 2850 List<Type> freevars = newInstances(t.tvars); 2851 t = new ForAll(freevars, 2852 Types.this.subst(t.qtype, t.tvars, freevars)); 2853 } 2854 List<Type> tvars1 = substBounds(t.tvars, from, to); 2855 Type qtype1 = subst(t.qtype); 2856 if (tvars1 == t.tvars && qtype1 == t.qtype) { 2857 return t; 2858 } else if (tvars1 == t.tvars) { 2859 return new ForAll(tvars1, qtype1); 2860 } else { 2861 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)); 2862 } 2863 } 2864 2865 @Override 2866 public Type visitErrorType(ErrorType t, Void ignored) { 2867 return t; 2868 } 2869 } 2870 2871 public List<Type> substBounds(List<Type> tvars, 2872 List<Type> from, 2873 List<Type> to) { 2874 if (tvars.isEmpty()) 2875 return tvars; 2876 ListBuffer<Type> newBoundsBuf = lb(); 2877 boolean changed = false; 2878 // calculate new bounds 2879 for (Type t : tvars) { 2880 TypeVar tv = (TypeVar) t; 2881 Type bound = subst(tv.bound, from, to); 2882 if (bound != tv.bound) 2883 changed = true; 2884 newBoundsBuf.append(bound); 2885 } 2886 if (!changed) 2887 return tvars; 2888 ListBuffer<Type> newTvars = lb(); 2889 // create new type variables without bounds 2890 for (Type t : tvars) { 2891 newTvars.append(new TypeVar(t.tsym, null, syms.botType)); 2892 } 2893 // the new bounds should use the new type variables in place 2894 // of the old 2895 List<Type> newBounds = newBoundsBuf.toList(); 2896 from = tvars; 2897 to = newTvars.toList(); 2898 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) { 2899 newBounds.head = subst(newBounds.head, from, to); 2900 } 2901 newBounds = newBoundsBuf.toList(); 2902 // set the bounds of new type variables to the new bounds 2903 for (Type t : newTvars.toList()) { 2904 TypeVar tv = (TypeVar) t; 2905 tv.bound = newBounds.head; 2906 newBounds = newBounds.tail; 2907 } 2908 return newTvars.toList(); 2909 } 2910 2911 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) { 2912 Type bound1 = subst(t.bound, from, to); 2913 if (bound1 == t.bound) 2914 return t; 2915 else { 2916 // create new type variable without bounds 2917 TypeVar tv = new TypeVar(t.tsym, null, syms.botType); 2918 // the new bound should use the new type variable in place 2919 // of the old 2920 tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv)); 2921 return tv; 2922 } 2923 } 2924 // </editor-fold> 2925 2926 // <editor-fold defaultstate="collapsed" desc="hasSameBounds"> 2927 /** 2928 * Does t have the same bounds for quantified variables as s? 2929 */ 2930 boolean hasSameBounds(ForAll t, ForAll s) { 2931 List<Type> l1 = t.tvars; 2932 List<Type> l2 = s.tvars; 2933 while (l1.nonEmpty() && l2.nonEmpty() && 2934 isSameType(l1.head.getUpperBound(), 2935 subst(l2.head.getUpperBound(), 2936 s.tvars, 2937 t.tvars))) { 2938 l1 = l1.tail; 2939 l2 = l2.tail; 2940 } 2941 return l1.isEmpty() && l2.isEmpty(); 2942 } 2943 // </editor-fold> 2944 2945 // <editor-fold defaultstate="collapsed" desc="newInstances"> 2946 /** Create new vector of type variables from list of variables 2947 * changing all recursive bounds from old to new list. 2948 */ 2949 public List<Type> newInstances(List<Type> tvars) { 2950 List<Type> tvars1 = Type.map(tvars, newInstanceFun); 2951 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) { 2952 TypeVar tv = (TypeVar) l.head; 2953 tv.bound = subst(tv.bound, tvars, tvars1); 2954 } 2955 return tvars1; 2956 } 2957 private static final Mapping newInstanceFun = new Mapping("newInstanceFun") { 2958 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); } 2959 }; 2960 // </editor-fold> 2961 2962 public Type createMethodTypeWithParameters(Type original, List<Type> newParams) { 2963 return original.accept(methodWithParameters, newParams); 2964 } 2965 // where 2966 private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() { 2967 public Type visitType(Type t, List<Type> newParams) { 2968 throw new IllegalArgumentException("Not a method type: " + t); 2969 } 2970 public Type visitMethodType(MethodType t, List<Type> newParams) { 2971 return new MethodType(newParams, t.restype, t.thrown, t.tsym); 2972 } 2973 public Type visitForAll(ForAll t, List<Type> newParams) { 2974 return new ForAll(t.tvars, t.qtype.accept(this, newParams)); 2975 } 2976 }; 2977 2978 public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) { 2979 return original.accept(methodWithThrown, newThrown); 2980 } 2981 // where 2982 private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() { 2983 public Type visitType(Type t, List<Type> newThrown) { 2984 throw new IllegalArgumentException("Not a method type: " + t); 2985 } 2986 public Type visitMethodType(MethodType t, List<Type> newThrown) { 2987 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym); 2988 } 2989 public Type visitForAll(ForAll t, List<Type> newThrown) { 2990 return new ForAll(t.tvars, t.qtype.accept(this, newThrown)); 2991 } 2992 }; 2993 2994 public Type createMethodTypeWithReturn(Type original, Type newReturn) { 2995 return original.accept(methodWithReturn, newReturn); 2996 } 2997 // where 2998 private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() { 2999 public Type visitType(Type t, Type newReturn) { 3000 throw new IllegalArgumentException("Not a method type: " + t); 3001 } 3002 public Type visitMethodType(MethodType t, Type newReturn) { 3003 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym); 3004 } 3005 public Type visitForAll(ForAll t, Type newReturn) { 3006 return new ForAll(t.tvars, t.qtype.accept(this, newReturn)); 3007 } 3008 }; 3009 3010 // <editor-fold defaultstate="collapsed" desc="createErrorType"> 3011 public Type createErrorType(Type originalType) { 3012 return new ErrorType(originalType, syms.errSymbol); 3013 } 3014 3015 public Type createErrorType(ClassSymbol c, Type originalType) { 3016 return new ErrorType(c, originalType); 3017 } 3018 3019 public Type createErrorType(Name name, TypeSymbol container, Type originalType) { 3020 return new ErrorType(name, container, originalType); 3021 } 3022 // </editor-fold> 3023 3024 // <editor-fold defaultstate="collapsed" desc="rank"> 3025 /** 3026 * The rank of a class is the length of the longest path between 3027 * the class and java.lang.Object in the class inheritance 3028 * graph. Undefined for all but reference types. 3029 */ 3030 public int rank(Type t) { 3031 t = t.unannotatedType(); 3032 switch(t.tag) { 3033 case CLASS: { 3034 ClassType cls = (ClassType)t; 3035 if (cls.rank_field < 0) { 3036 Name fullname = cls.tsym.getQualifiedName(); 3037 if (fullname == names.java_lang_Object) 3038 cls.rank_field = 0; 3039 else { 3040 int r = rank(supertype(cls)); 3041 for (List<Type> l = interfaces(cls); 3042 l.nonEmpty(); 3043 l = l.tail) { 3044 if (rank(l.head) > r) 3045 r = rank(l.head); 3046 } 3047 cls.rank_field = r + 1; 3048 } 3049 } 3050 return cls.rank_field; 3051 } 3052 case TYPEVAR: { 3053 TypeVar tvar = (TypeVar)t; 3054 if (tvar.rank_field < 0) { 3055 int r = rank(supertype(tvar)); 3056 for (List<Type> l = interfaces(tvar); 3057 l.nonEmpty(); 3058 l = l.tail) { 3059 if (rank(l.head) > r) r = rank(l.head); 3060 } 3061 tvar.rank_field = r + 1; 3062 } 3063 return tvar.rank_field; 3064 } 3065 case ERROR: 3066 return 0; 3067 default: 3068 throw new AssertionError(); 3069 } 3070 } 3071 // </editor-fold> 3072 3073 /** 3074 * Helper method for generating a string representation of a given type 3075 * accordingly to a given locale 3076 */ 3077 public String toString(Type t, Locale locale) { 3078 return Printer.createStandardPrinter(messages).visit(t, locale); 3079 } 3080 3081 /** 3082 * Helper method for generating a string representation of a given type 3083 * accordingly to a given locale 3084 */ 3085 public String toString(Symbol t, Locale locale) { 3086 return Printer.createStandardPrinter(messages).visit(t, locale); 3087 } 3088 3089 // <editor-fold defaultstate="collapsed" desc="toString"> 3090 /** 3091 * This toString is slightly more descriptive than the one on Type. 3092 * 3093 * @deprecated Types.toString(Type t, Locale l) provides better support 3094 * for localization 3095 */ 3096 @Deprecated 3097 public String toString(Type t) { 3098 if (t.tag == FORALL) { 3099 ForAll forAll = (ForAll)t; 3100 return typaramsString(forAll.tvars) + forAll.qtype; 3101 } 3102 return "" + t; 3103 } 3104 // where 3105 private String typaramsString(List<Type> tvars) { 3106 StringBuilder s = new StringBuilder(); 3107 s.append('<'); 3108 boolean first = true; 3109 for (Type t : tvars) { 3110 if (!first) s.append(", "); 3111 first = false; 3112 appendTyparamString(((TypeVar)t.unannotatedType()), s); 3113 } 3114 s.append('>'); 3115 return s.toString(); 3116 } 3117 private void appendTyparamString(TypeVar t, StringBuilder buf) { 3118 buf.append(t); 3119 if (t.bound == null || 3120 t.bound.tsym.getQualifiedName() == names.java_lang_Object) 3121 return; 3122 buf.append(" extends "); // Java syntax; no need for i18n 3123 Type bound = t.bound; 3124 if (!bound.isCompound()) { 3125 buf.append(bound); 3126 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) { 3127 buf.append(supertype(t)); 3128 for (Type intf : interfaces(t)) { 3129 buf.append('&'); 3130 buf.append(intf); 3131 } 3132 } else { 3133 // No superclass was given in bounds. 3134 // In this case, supertype is Object, erasure is first interface. 3135 boolean first = true; 3136 for (Type intf : interfaces(t)) { 3137 if (!first) buf.append('&'); 3138 first = false; 3139 buf.append(intf); 3140 } 3141 } 3142 } 3143 // </editor-fold> 3144 3145 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types"> 3146 /** 3147 * A cache for closures. 3148 * 3149 * <p>A closure is a list of all the supertypes and interfaces of 3150 * a class or interface type, ordered by ClassSymbol.precedes 3151 * (that is, subclasses come first, arbitrary but fixed 3152 * otherwise). 3153 */ 3154 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>(); 3155 3156 /** 3157 * Returns the closure of a class or interface type. 3158 */ 3159 public List<Type> closure(Type t) { 3160 List<Type> cl = closureCache.get(t); 3161 if (cl == null) { 3162 Type st = supertype(t); 3163 if (!t.isCompound()) { 3164 if (st.tag == CLASS) { 3165 cl = insert(closure(st), t); 3166 } else if (st.tag == TYPEVAR) { 3167 cl = closure(st).prepend(t); 3168 } else { 3169 cl = List.of(t); 3170 } 3171 } else { 3172 cl = closure(supertype(t)); 3173 } 3174 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) 3175 cl = union(cl, closure(l.head)); 3176 closureCache.put(t, cl); 3177 } 3178 return cl; 3179 } 3180 3181 /** 3182 * Insert a type in a closure 3183 */ 3184 public List<Type> insert(List<Type> cl, Type t) { 3185 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) { 3186 return cl.prepend(t); 3187 } else if (cl.head.tsym.precedes(t.tsym, this)) { 3188 return insert(cl.tail, t).prepend(cl.head); 3189 } else { 3190 return cl; 3191 } 3192 } 3193 3194 /** 3195 * Form the union of two closures 3196 */ 3197 public List<Type> union(List<Type> cl1, List<Type> cl2) { 3198 if (cl1.isEmpty()) { 3199 return cl2; 3200 } else if (cl2.isEmpty()) { 3201 return cl1; 3202 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) { 3203 return union(cl1.tail, cl2).prepend(cl1.head); 3204 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) { 3205 return union(cl1, cl2.tail).prepend(cl2.head); 3206 } else { 3207 return union(cl1.tail, cl2.tail).prepend(cl1.head); 3208 } 3209 } 3210 3211 /** 3212 * Intersect two closures 3213 */ 3214 public List<Type> intersect(List<Type> cl1, List<Type> cl2) { 3215 if (cl1 == cl2) 3216 return cl1; 3217 if (cl1.isEmpty() || cl2.isEmpty()) 3218 return List.nil(); 3219 if (cl1.head.tsym.precedes(cl2.head.tsym, this)) 3220 return intersect(cl1.tail, cl2); 3221 if (cl2.head.tsym.precedes(cl1.head.tsym, this)) 3222 return intersect(cl1, cl2.tail); 3223 if (isSameType(cl1.head, cl2.head)) 3224 return intersect(cl1.tail, cl2.tail).prepend(cl1.head); 3225 if (cl1.head.tsym == cl2.head.tsym && 3226 cl1.head.tag == CLASS && cl2.head.tag == CLASS) { 3227 if (cl1.head.isParameterized() && cl2.head.isParameterized()) { 3228 Type merge = merge(cl1.head,cl2.head); 3229 return intersect(cl1.tail, cl2.tail).prepend(merge); 3230 } 3231 if (cl1.head.isRaw() || cl2.head.isRaw()) 3232 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head)); 3233 } 3234 return intersect(cl1.tail, cl2.tail); 3235 } 3236 // where 3237 class TypePair { 3238 final Type t1; 3239 final Type t2; 3240 TypePair(Type t1, Type t2) { 3241 this.t1 = t1; 3242 this.t2 = t2; 3243 } 3244 @Override 3245 public int hashCode() { 3246 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2); 3247 } 3248 @Override 3249 public boolean equals(Object obj) { 3250 if (!(obj instanceof TypePair)) 3251 return false; 3252 TypePair typePair = (TypePair)obj; 3253 return isSameType(t1, typePair.t1) 3254 && isSameType(t2, typePair.t2); 3255 } 3256 } 3257 Set<TypePair> mergeCache = new HashSet<TypePair>(); 3258 private Type merge(Type c1, Type c2) { 3259 ClassType class1 = (ClassType) c1; 3260 List<Type> act1 = class1.getTypeArguments(); 3261 ClassType class2 = (ClassType) c2; 3262 List<Type> act2 = class2.getTypeArguments(); 3263 ListBuffer<Type> merged = new ListBuffer<Type>(); 3264 List<Type> typarams = class1.tsym.type.getTypeArguments(); 3265 3266 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) { 3267 if (containsType(act1.head, act2.head)) { 3268 merged.append(act1.head); 3269 } else if (containsType(act2.head, act1.head)) { 3270 merged.append(act2.head); 3271 } else { 3272 TypePair pair = new TypePair(c1, c2); 3273 Type m; 3274 if (mergeCache.add(pair)) { 3275 m = new WildcardType(lub(upperBound(act1.head), 3276 upperBound(act2.head)), 3277 BoundKind.EXTENDS, 3278 syms.boundClass); 3279 mergeCache.remove(pair); 3280 } else { 3281 m = new WildcardType(syms.objectType, 3282 BoundKind.UNBOUND, 3283 syms.boundClass); 3284 } 3285 merged.append(m.withTypeVar(typarams.head)); 3286 } 3287 act1 = act1.tail; 3288 act2 = act2.tail; 3289 typarams = typarams.tail; 3290 } 3291 Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty()); 3292 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym); 3293 } 3294 3295 /** 3296 * Return the minimum type of a closure, a compound type if no 3297 * unique minimum exists. 3298 */ 3299 private Type compoundMin(List<Type> cl) { 3300 if (cl.isEmpty()) return syms.objectType; 3301 List<Type> compound = closureMin(cl); 3302 if (compound.isEmpty()) 3303 return null; 3304 else if (compound.tail.isEmpty()) 3305 return compound.head; 3306 else 3307 return makeCompoundType(compound); 3308 } 3309 3310 /** 3311 * Return the minimum types of a closure, suitable for computing 3312 * compoundMin or glb. 3313 */ 3314 private List<Type> closureMin(List<Type> cl) { 3315 ListBuffer<Type> classes = lb(); 3316 ListBuffer<Type> interfaces = lb(); 3317 while (!cl.isEmpty()) { 3318 Type current = cl.head; 3319 if (current.isInterface()) 3320 interfaces.append(current); 3321 else 3322 classes.append(current); 3323 ListBuffer<Type> candidates = lb(); 3324 for (Type t : cl.tail) { 3325 if (!isSubtypeNoCapture(current, t)) 3326 candidates.append(t); 3327 } 3328 cl = candidates.toList(); 3329 } 3330 return classes.appendList(interfaces).toList(); 3331 } 3332 3333 /** 3334 * Return the least upper bound of pair of types. if the lub does 3335 * not exist return null. 3336 */ 3337 public Type lub(Type t1, Type t2) { 3338 return lub(List.of(t1, t2)); 3339 } 3340 3341 /** 3342 * Return the least upper bound (lub) of set of types. If the lub 3343 * does not exist return the type of null (bottom). 3344 */ 3345 public Type lub(List<Type> ts) { 3346 final int ARRAY_BOUND = 1; 3347 final int CLASS_BOUND = 2; 3348 int boundkind = 0; 3349 for (Type t : ts) { 3350 switch (t.tag) { 3351 case CLASS: 3352 boundkind |= CLASS_BOUND; 3353 break; 3354 case ARRAY: 3355 boundkind |= ARRAY_BOUND; 3356 break; 3357 case TYPEVAR: 3358 do { 3359 t = t.getUpperBound(); 3360 } while (t.tag == TYPEVAR); 3361 if (t.tag == ARRAY) { 3362 boundkind |= ARRAY_BOUND; 3363 } else { 3364 boundkind |= CLASS_BOUND; 3365 } 3366 break; 3367 default: 3368 if (t.isPrimitive()) 3369 return syms.errType; 3370 } 3371 } 3372 switch (boundkind) { 3373 case 0: 3374 return syms.botType; 3375 3376 case ARRAY_BOUND: 3377 // calculate lub(A[], B[]) 3378 List<Type> elements = Type.map(ts, elemTypeFun); 3379 for (Type t : elements) { 3380 if (t.isPrimitive()) { 3381 // if a primitive type is found, then return 3382 // arraySuperType unless all the types are the 3383 // same 3384 Type first = ts.head; 3385 for (Type s : ts.tail) { 3386 if (!isSameType(first, s)) { 3387 // lub(int[], B[]) is Cloneable & Serializable 3388 return arraySuperType(); 3389 } 3390 } 3391 // all the array types are the same, return one 3392 // lub(int[], int[]) is int[] 3393 return first; 3394 } 3395 } 3396 // lub(A[], B[]) is lub(A, B)[] 3397 return new ArrayType(lub(elements), syms.arrayClass); 3398 3399 case CLASS_BOUND: 3400 // calculate lub(A, B) 3401 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR) 3402 ts = ts.tail; 3403 Assert.check(!ts.isEmpty()); 3404 //step 1 - compute erased candidate set (EC) 3405 List<Type> cl = erasedSupertypes(ts.head); 3406 for (Type t : ts.tail) { 3407 if (t.tag == CLASS || t.tag == TYPEVAR) 3408 cl = intersect(cl, erasedSupertypes(t)); 3409 } 3410 //step 2 - compute minimal erased candidate set (MEC) 3411 List<Type> mec = closureMin(cl); 3412 //step 3 - for each element G in MEC, compute lci(Inv(G)) 3413 List<Type> candidates = List.nil(); 3414 for (Type erasedSupertype : mec) { 3415 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym)); 3416 for (Type t : ts) { 3417 lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym))); 3418 } 3419 candidates = candidates.appendList(lci); 3420 } 3421 //step 4 - let MEC be { G1, G2 ... Gn }, then we have that 3422 //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn)) 3423 return compoundMin(candidates); 3424 3425 default: 3426 // calculate lub(A, B[]) 3427 List<Type> classes = List.of(arraySuperType()); 3428 for (Type t : ts) { 3429 if (t.tag != ARRAY) // Filter out any arrays 3430 classes = classes.prepend(t); 3431 } 3432 // lub(A, B[]) is lub(A, arraySuperType) 3433 return lub(classes); 3434 } 3435 } 3436 // where 3437 List<Type> erasedSupertypes(Type t) { 3438 ListBuffer<Type> buf = lb(); 3439 for (Type sup : closure(t)) { 3440 if (sup.tag == TYPEVAR) { 3441 buf.append(sup); 3442 } else { 3443 buf.append(erasure(sup)); 3444 } 3445 } 3446 return buf.toList(); 3447 } 3448 3449 private Type arraySuperType = null; 3450 private Type arraySuperType() { 3451 // initialized lazily to avoid problems during compiler startup 3452 if (arraySuperType == null) { 3453 synchronized (this) { 3454 if (arraySuperType == null) { 3455 // JLS 10.8: all arrays implement Cloneable and Serializable. 3456 arraySuperType = makeCompoundType(List.of(syms.serializableType, 3457 syms.cloneableType), true); 3458 } 3459 } 3460 } 3461 return arraySuperType; 3462 } 3463 // </editor-fold> 3464 3465 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound"> 3466 public Type glb(List<Type> ts) { 3467 Type t1 = ts.head; 3468 for (Type t2 : ts.tail) { 3469 if (t1.isErroneous()) 3470 return t1; 3471 t1 = glb(t1, t2); 3472 } 3473 return t1; 3474 } 3475 //where 3476 public Type glb(Type t, Type s) { 3477 if (s == null) 3478 return t; 3479 else if (t.isPrimitive() || s.isPrimitive()) 3480 return syms.errType; 3481 else if (isSubtypeNoCapture(t, s)) 3482 return t; 3483 else if (isSubtypeNoCapture(s, t)) 3484 return s; 3485 3486 List<Type> closure = union(closure(t), closure(s)); 3487 List<Type> bounds = closureMin(closure); 3488 3489 if (bounds.isEmpty()) { // length == 0 3490 return syms.objectType; 3491 } else if (bounds.tail.isEmpty()) { // length == 1 3492 return bounds.head; 3493 } else { // length > 1 3494 int classCount = 0; 3495 for (Type bound : bounds) 3496 if (!bound.isInterface()) 3497 classCount++; 3498 if (classCount > 1) 3499 return createErrorType(t); 3500 } 3501 return makeCompoundType(bounds); 3502 } 3503 // </editor-fold> 3504 3505 // <editor-fold defaultstate="collapsed" desc="hashCode"> 3506 /** 3507 * Compute a hash code on a type. 3508 */ 3509 public int hashCode(Type t) { 3510 return hashCode.visit(t); 3511 } 3512 // where 3513 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() { 3514 3515 public Integer visitType(Type t, Void ignored) { 3516 return t.tag.ordinal(); 3517 } 3518 3519 @Override 3520 public Integer visitClassType(ClassType t, Void ignored) { 3521 int result = visit(t.getEnclosingType()); 3522 result *= 127; 3523 result += t.tsym.flatName().hashCode(); 3524 for (Type s : t.getTypeArguments()) { 3525 result *= 127; 3526 result += visit(s); 3527 } 3528 return result; 3529 } 3530 3531 @Override 3532 public Integer visitMethodType(MethodType t, Void ignored) { 3533 int h = METHOD.ordinal(); 3534 for (List<Type> thisargs = t.argtypes; 3535 thisargs.tail != null; 3536 thisargs = thisargs.tail) 3537 h = (h << 5) + visit(thisargs.head); 3538 return (h << 5) + visit(t.restype); 3539 } 3540 3541 @Override 3542 public Integer visitWildcardType(WildcardType t, Void ignored) { 3543 int result = t.kind.hashCode(); 3544 if (t.type != null) { 3545 result *= 127; 3546 result += visit(t.type); 3547 } 3548 return result; 3549 } 3550 3551 @Override 3552 public Integer visitArrayType(ArrayType t, Void ignored) { 3553 return visit(t.elemtype) + 12; 3554 } 3555 3556 @Override 3557 public Integer visitTypeVar(TypeVar t, Void ignored) { 3558 return System.identityHashCode(t.tsym); 3559 } 3560 3561 @Override 3562 public Integer visitUndetVar(UndetVar t, Void ignored) { 3563 return System.identityHashCode(t); 3564 } 3565 3566 @Override 3567 public Integer visitErrorType(ErrorType t, Void ignored) { 3568 return 0; 3569 } 3570 }; 3571 // </editor-fold> 3572 3573 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable"> 3574 /** 3575 * Does t have a result that is a subtype of the result type of s, 3576 * suitable for covariant returns? It is assumed that both types 3577 * are (possibly polymorphic) method types. Monomorphic method 3578 * types are handled in the obvious way. Polymorphic method types 3579 * require renaming all type variables of one to corresponding 3580 * type variables in the other, where correspondence is by 3581 * position in the type parameter list. */ 3582 public boolean resultSubtype(Type t, Type s, Warner warner) { 3583 List<Type> tvars = t.getTypeArguments(); 3584 List<Type> svars = s.getTypeArguments(); 3585 Type tres = t.getReturnType(); 3586 Type sres = subst(s.getReturnType(), svars, tvars); 3587 return covariantReturnType(tres, sres, warner); 3588 } 3589 3590 /** 3591 * Return-Type-Substitutable. 3592 * @jls section 8.4.5 3593 */ 3594 public boolean returnTypeSubstitutable(Type r1, Type r2) { 3595 if (hasSameArgs(r1, r2)) 3596 return resultSubtype(r1, r2, noWarnings); 3597 else 3598 return covariantReturnType(r1.getReturnType(), 3599 erasure(r2.getReturnType()), 3600 noWarnings); 3601 } 3602 3603 public boolean returnTypeSubstitutable(Type r1, 3604 Type r2, Type r2res, 3605 Warner warner) { 3606 if (isSameType(r1.getReturnType(), r2res)) 3607 return true; 3608 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive()) 3609 return false; 3610 3611 if (hasSameArgs(r1, r2)) 3612 return covariantReturnType(r1.getReturnType(), r2res, warner); 3613 if (!allowCovariantReturns) 3614 return false; 3615 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner)) 3616 return true; 3617 if (!isSubtype(r1.getReturnType(), erasure(r2res))) 3618 return false; 3619 warner.warn(LintCategory.UNCHECKED); 3620 return true; 3621 } 3622 3623 /** 3624 * Is t an appropriate return type in an overrider for a 3625 * method that returns s? 3626 */ 3627 public boolean covariantReturnType(Type t, Type s, Warner warner) { 3628 return 3629 isSameType(t, s) || 3630 allowCovariantReturns && 3631 !t.isPrimitive() && 3632 !s.isPrimitive() && 3633 isAssignable(t, s, warner); 3634 } 3635 // </editor-fold> 3636 3637 // <editor-fold defaultstate="collapsed" desc="Box/unbox support"> 3638 /** 3639 * Return the class that boxes the given primitive. 3640 */ 3641 public ClassSymbol boxedClass(Type t) { 3642 return reader.enterClass(syms.boxedName[t.tag.ordinal()]); 3643 } 3644 3645 /** 3646 * Return the boxed type if 't' is primitive, otherwise return 't' itself. 3647 */ 3648 public Type boxedTypeOrType(Type t) { 3649 return t.isPrimitive() ? 3650 boxedClass(t).type : 3651 t; 3652 } 3653 3654 /** 3655 * Return the primitive type corresponding to a boxed type. 3656 */ 3657 public Type unboxedType(Type t) { 3658 if (allowBoxing) { 3659 for (int i=0; i<syms.boxedName.length; i++) { 3660 Name box = syms.boxedName[i]; 3661 if (box != null && 3662 asSuper(t, reader.enterClass(box)) != null) 3663 return syms.typeOfTag[i]; 3664 } 3665 } 3666 return Type.noType; 3667 } 3668 3669 /** 3670 * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself. 3671 */ 3672 public Type unboxedTypeOrType(Type t) { 3673 Type unboxedType = unboxedType(t); 3674 return unboxedType.tag == NONE ? t : unboxedType; 3675 } 3676 // </editor-fold> 3677 3678 // <editor-fold defaultstate="collapsed" desc="Capture conversion"> 3679 /* 3680 * JLS 5.1.10 Capture Conversion: 3681 * 3682 * Let G name a generic type declaration with n formal type 3683 * parameters A1 ... An with corresponding bounds U1 ... Un. There 3684 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>, 3685 * where, for 1 <= i <= n: 3686 * 3687 * + If Ti is a wildcard type argument (4.5.1) of the form ? then 3688 * Si is a fresh type variable whose upper bound is 3689 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null 3690 * type. 3691 * 3692 * + If Ti is a wildcard type argument of the form ? extends Bi, 3693 * then Si is a fresh type variable whose upper bound is 3694 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is 3695 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is 3696 * a compile-time error if for any two classes (not interfaces) 3697 * Vi and Vj,Vi is not a subclass of Vj or vice versa. 3698 * 3699 * + If Ti is a wildcard type argument of the form ? super Bi, 3700 * then Si is a fresh type variable whose upper bound is 3701 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi. 3702 * 3703 * + Otherwise, Si = Ti. 3704 * 3705 * Capture conversion on any type other than a parameterized type 3706 * (4.5) acts as an identity conversion (5.1.1). Capture 3707 * conversions never require a special action at run time and 3708 * therefore never throw an exception at run time. 3709 * 3710 * Capture conversion is not applied recursively. 3711 */ 3712 /** 3713 * Capture conversion as specified by the JLS. 3714 */ 3715 3716 public List<Type> capture(List<Type> ts) { 3717 List<Type> buf = List.nil(); 3718 for (Type t : ts) { 3719 buf = buf.prepend(capture(t)); 3720 } 3721 return buf.reverse(); 3722 } 3723 public Type capture(Type t) { 3724 if (t.tag != CLASS) 3725 return t; 3726 if (t.getEnclosingType() != Type.noType) { 3727 Type capturedEncl = capture(t.getEnclosingType()); 3728 if (capturedEncl != t.getEnclosingType()) { 3729 Type type1 = memberType(capturedEncl, t.tsym); 3730 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments()); 3731 } 3732 } 3733 t = t.unannotatedType(); 3734 ClassType cls = (ClassType)t; 3735 if (cls.isRaw() || !cls.isParameterized()) 3736 return cls; 3737 3738 ClassType G = (ClassType)cls.asElement().asType(); 3739 List<Type> A = G.getTypeArguments(); 3740 List<Type> T = cls.getTypeArguments(); 3741 List<Type> S = freshTypeVariables(T); 3742 3743 List<Type> currentA = A; 3744 List<Type> currentT = T; 3745 List<Type> currentS = S; 3746 boolean captured = false; 3747 while (!currentA.isEmpty() && 3748 !currentT.isEmpty() && 3749 !currentS.isEmpty()) { 3750 if (currentS.head != currentT.head) { 3751 captured = true; 3752 WildcardType Ti = (WildcardType)currentT.head.unannotatedType(); 3753 Type Ui = currentA.head.getUpperBound(); 3754 CapturedType Si = (CapturedType)currentS.head.unannotatedType(); 3755 if (Ui == null) 3756 Ui = syms.objectType; 3757 switch (Ti.kind) { 3758 case UNBOUND: 3759 Si.bound = subst(Ui, A, S); 3760 Si.lower = syms.botType; 3761 break; 3762 case EXTENDS: 3763 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S)); 3764 Si.lower = syms.botType; 3765 break; 3766 case SUPER: 3767 Si.bound = subst(Ui, A, S); 3768 Si.lower = Ti.getSuperBound(); 3769 break; 3770 } 3771 if (Si.bound == Si.lower) 3772 currentS.head = Si.bound; 3773 } 3774 currentA = currentA.tail; 3775 currentT = currentT.tail; 3776 currentS = currentS.tail; 3777 } 3778 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty()) 3779 return erasure(t); // some "rare" type involved 3780 3781 if (captured) 3782 return new ClassType(cls.getEnclosingType(), S, cls.tsym); 3783 else 3784 return t; 3785 } 3786 // where 3787 public List<Type> freshTypeVariables(List<Type> types) { 3788 ListBuffer<Type> result = lb(); 3789 for (Type t : types) { 3790 if (t.tag == WILDCARD) { 3791 t = t.unannotatedType(); 3792 Type bound = ((WildcardType)t).getExtendsBound(); 3793 if (bound == null) 3794 bound = syms.objectType; 3795 result.append(new CapturedType(capturedName, 3796 syms.noSymbol, 3797 bound, 3798 syms.botType, 3799 (WildcardType)t)); 3800 } else { 3801 result.append(t); 3802 } 3803 } 3804 return result.toList(); 3805 } 3806 // </editor-fold> 3807 3808 // <editor-fold defaultstate="collapsed" desc="Internal utility methods"> 3809 private List<Type> upperBounds(List<Type> ss) { 3810 if (ss.isEmpty()) return ss; 3811 Type head = upperBound(ss.head); 3812 List<Type> tail = upperBounds(ss.tail); 3813 if (head != ss.head || tail != ss.tail) 3814 return tail.prepend(head); 3815 else 3816 return ss; 3817 } 3818 3819 private boolean sideCast(Type from, Type to, Warner warn) { 3820 // We are casting from type $from$ to type $to$, which are 3821 // non-final unrelated types. This method 3822 // tries to reject a cast by transferring type parameters 3823 // from $to$ to $from$ by common superinterfaces. 3824 boolean reverse = false; 3825 Type target = to; 3826 if ((to.tsym.flags() & INTERFACE) == 0) { 3827 Assert.check((from.tsym.flags() & INTERFACE) != 0); 3828 reverse = true; 3829 to = from; 3830 from = target; 3831 } 3832 List<Type> commonSupers = superClosure(to, erasure(from)); 3833 boolean giveWarning = commonSupers.isEmpty(); 3834 // The arguments to the supers could be unified here to 3835 // get a more accurate analysis 3836 while (commonSupers.nonEmpty()) { 3837 Type t1 = asSuper(from, commonSupers.head.tsym); 3838 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym); 3839 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) 3840 return false; 3841 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)); 3842 commonSupers = commonSupers.tail; 3843 } 3844 if (giveWarning && !isReifiable(reverse ? from : to)) 3845 warn.warn(LintCategory.UNCHECKED); 3846 if (!allowCovariantReturns) 3847 // reject if there is a common method signature with 3848 // incompatible return types. 3849 chk.checkCompatibleAbstracts(warn.pos(), from, to); 3850 return true; 3851 } 3852 3853 private boolean sideCastFinal(Type from, Type to, Warner warn) { 3854 // We are casting from type $from$ to type $to$, which are 3855 // unrelated types one of which is final and the other of 3856 // which is an interface. This method 3857 // tries to reject a cast by transferring type parameters 3858 // from the final class to the interface. 3859 boolean reverse = false; 3860 Type target = to; 3861 if ((to.tsym.flags() & INTERFACE) == 0) { 3862 Assert.check((from.tsym.flags() & INTERFACE) != 0); 3863 reverse = true; 3864 to = from; 3865 from = target; 3866 } 3867 Assert.check((from.tsym.flags() & FINAL) != 0); 3868 Type t1 = asSuper(from, to.tsym); 3869 if (t1 == null) return false; 3870 Type t2 = to; 3871 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) 3872 return false; 3873 if (!allowCovariantReturns) 3874 // reject if there is a common method signature with 3875 // incompatible return types. 3876 chk.checkCompatibleAbstracts(warn.pos(), from, to); 3877 if (!isReifiable(target) && 3878 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2))) 3879 warn.warn(LintCategory.UNCHECKED); 3880 return true; 3881 } 3882 3883 private boolean giveWarning(Type from, Type to) { 3884 List<Type> bounds = to.isCompound() ? 3885 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to); 3886 for (Type b : bounds) { 3887 Type subFrom = asSub(from, b.tsym); 3888 if (b.isParameterized() && 3889 (!(isUnbounded(b) || 3890 isSubtype(from, b) || 3891 ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) { 3892 return true; 3893 } 3894 } 3895 return false; 3896 } 3897 3898 private List<Type> superClosure(Type t, Type s) { 3899 List<Type> cl = List.nil(); 3900 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { 3901 if (isSubtype(s, erasure(l.head))) { 3902 cl = insert(cl, l.head); 3903 } else { 3904 cl = union(cl, superClosure(l.head, s)); 3905 } 3906 } 3907 return cl; 3908 } 3909 3910 private boolean containsTypeEquivalent(Type t, Type s) { 3911 return 3912 isSameType(t, s) || // shortcut 3913 containsType(t, s) && containsType(s, t); 3914 } 3915 3916 // <editor-fold defaultstate="collapsed" desc="adapt"> 3917 /** 3918 * Adapt a type by computing a substitution which maps a source 3919 * type to a target type. 3920 * 3921 * @param source the source type 3922 * @param target the target type 3923 * @param from the type variables of the computed substitution 3924 * @param to the types of the computed substitution. 3925 */ 3926 public void adapt(Type source, 3927 Type target, 3928 ListBuffer<Type> from, 3929 ListBuffer<Type> to) throws AdaptFailure { 3930 new Adapter(from, to).adapt(source, target); 3931 } 3932 3933 class Adapter extends SimpleVisitor<Void, Type> { 3934 3935 ListBuffer<Type> from; 3936 ListBuffer<Type> to; 3937 Map<Symbol,Type> mapping; 3938 3939 Adapter(ListBuffer<Type> from, ListBuffer<Type> to) { 3940 this.from = from; 3941 this.to = to; 3942 mapping = new HashMap<Symbol,Type>(); 3943 } 3944 3945 public void adapt(Type source, Type target) throws AdaptFailure { 3946 visit(source, target); 3947 List<Type> fromList = from.toList(); 3948 List<Type> toList = to.toList(); 3949 while (!fromList.isEmpty()) { 3950 Type val = mapping.get(fromList.head.tsym); 3951 if (toList.head != val) 3952 toList.head = val; 3953 fromList = fromList.tail; 3954 toList = toList.tail; 3955 } 3956 } 3957 3958 @Override 3959 public Void visitClassType(ClassType source, Type target) throws AdaptFailure { 3960 if (target.tag == CLASS) 3961 adaptRecursive(source.allparams(), target.allparams()); 3962 return null; 3963 } 3964 3965 @Override 3966 public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure { 3967 if (target.tag == ARRAY) 3968 adaptRecursive(elemtype(source), elemtype(target)); 3969 return null; 3970 } 3971 3972 @Override 3973 public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure { 3974 if (source.isExtendsBound()) 3975 adaptRecursive(upperBound(source), upperBound(target)); 3976 else if (source.isSuperBound()) 3977 adaptRecursive(lowerBound(source), lowerBound(target)); 3978 return null; 3979 } 3980 3981 @Override 3982 public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure { 3983 // Check to see if there is 3984 // already a mapping for $source$, in which case 3985 // the old mapping will be merged with the new 3986 Type val = mapping.get(source.tsym); 3987 if (val != null) { 3988 if (val.isSuperBound() && target.isSuperBound()) { 3989 val = isSubtype(lowerBound(val), lowerBound(target)) 3990 ? target : val; 3991 } else if (val.isExtendsBound() && target.isExtendsBound()) { 3992 val = isSubtype(upperBound(val), upperBound(target)) 3993 ? val : target; 3994 } else if (!isSameType(val, target)) { 3995 throw new AdaptFailure(); 3996 } 3997 } else { 3998 val = target; 3999 from.append(source); 4000 to.append(target); 4001 } 4002 mapping.put(source.tsym, val); 4003 return null; 4004 } 4005 4006 @Override 4007 public Void visitType(Type source, Type target) { 4008 return null; 4009 } 4010 4011 private Set<TypePair> cache = new HashSet<TypePair>(); 4012 4013 private void adaptRecursive(Type source, Type target) { 4014 TypePair pair = new TypePair(source, target); 4015 if (cache.add(pair)) { 4016 try { 4017 visit(source, target); 4018 } finally { 4019 cache.remove(pair); 4020 } 4021 } 4022 } 4023 4024 private void adaptRecursive(List<Type> source, List<Type> target) { 4025 if (source.length() == target.length()) { 4026 while (source.nonEmpty()) { 4027 adaptRecursive(source.head, target.head); 4028 source = source.tail; 4029 target = target.tail; 4030 } 4031 } 4032 } 4033 } 4034 4035 public static class AdaptFailure extends RuntimeException { 4036 static final long serialVersionUID = -7490231548272701566L; 4037 } 4038 4039 private void adaptSelf(Type t, 4040 ListBuffer<Type> from, 4041 ListBuffer<Type> to) { 4042 try { 4043 //if (t.tsym.type != t) 4044 adapt(t.tsym.type, t, from, to); 4045 } catch (AdaptFailure ex) { 4046 // Adapt should never fail calculating a mapping from 4047 // t.tsym.type to t as there can be no merge problem. 4048 throw new AssertionError(ex); 4049 } 4050 } 4051 // </editor-fold> 4052 4053 /** 4054 * Rewrite all type variables (universal quantifiers) in the given 4055 * type to wildcards (existential quantifiers). This is used to 4056 * determine if a cast is allowed. For example, if high is true 4057 * and {@code T <: Number}, then {@code List<T>} is rewritten to 4058 * {@code List<? extends Number>}. Since {@code List<Integer> <: 4059 * List<? extends Number>} a {@code List<T>} can be cast to {@code 4060 * List<Integer>} with a warning. 4061 * @param t a type 4062 * @param high if true return an upper bound; otherwise a lower 4063 * bound 4064 * @param rewriteTypeVars only rewrite captured wildcards if false; 4065 * otherwise rewrite all type variables 4066 * @return the type rewritten with wildcards (existential 4067 * quantifiers) only 4068 */ 4069 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) { 4070 return new Rewriter(high, rewriteTypeVars).visit(t); 4071 } 4072 4073 class Rewriter extends UnaryVisitor<Type> { 4074 4075 boolean high; 4076 boolean rewriteTypeVars; 4077 4078 Rewriter(boolean high, boolean rewriteTypeVars) { 4079 this.high = high; 4080 this.rewriteTypeVars = rewriteTypeVars; 4081 } 4082 4083 @Override 4084 public Type visitClassType(ClassType t, Void s) { 4085 ListBuffer<Type> rewritten = new ListBuffer<Type>(); 4086 boolean changed = false; 4087 for (Type arg : t.allparams()) { 4088 Type bound = visit(arg); 4089 if (arg != bound) { 4090 changed = true; 4091 } 4092 rewritten.append(bound); 4093 } 4094 if (changed) 4095 return subst(t.tsym.type, 4096 t.tsym.type.allparams(), 4097 rewritten.toList()); 4098 else 4099 return t; 4100 } 4101 4102 public Type visitType(Type t, Void s) { 4103 return high ? upperBound(t) : lowerBound(t); 4104 } 4105 4106 @Override 4107 public Type visitCapturedType(CapturedType t, Void s) { 4108 Type w_bound = t.wildcard.type; 4109 Type bound = w_bound.contains(t) ? 4110 erasure(w_bound) : 4111 visit(w_bound); 4112 return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind); 4113 } 4114 4115 @Override 4116 public Type visitTypeVar(TypeVar t, Void s) { 4117 if (rewriteTypeVars) { 4118 Type bound = t.bound.contains(t) ? 4119 erasure(t.bound) : 4120 visit(t.bound); 4121 return rewriteAsWildcardType(bound, t, EXTENDS); 4122 } else { 4123 return t; 4124 } 4125 } 4126 4127 @Override 4128 public Type visitWildcardType(WildcardType t, Void s) { 4129 Type bound2 = visit(t.type); 4130 return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind); 4131 } 4132 4133 private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) { 4134 switch (bk) { 4135 case EXTENDS: return high ? 4136 makeExtendsWildcard(B(bound), formal) : 4137 makeExtendsWildcard(syms.objectType, formal); 4138 case SUPER: return high ? 4139 makeSuperWildcard(syms.botType, formal) : 4140 makeSuperWildcard(B(bound), formal); 4141 case UNBOUND: return makeExtendsWildcard(syms.objectType, formal); 4142 default: 4143 Assert.error("Invalid bound kind " + bk); 4144 return null; 4145 } 4146 } 4147 4148 Type B(Type t) { 4149 while (t.tag == WILDCARD) { 4150 WildcardType w = (WildcardType)t.unannotatedType(); 4151 t = high ? 4152 w.getExtendsBound() : 4153 w.getSuperBound(); 4154 if (t == null) { 4155 t = high ? syms.objectType : syms.botType; 4156 } 4157 } 4158 return t; 4159 } 4160 } 4161 4162 4163 /** 4164 * Create a wildcard with the given upper (extends) bound; create 4165 * an unbounded wildcard if bound is Object. 4166 * 4167 * @param bound the upper bound 4168 * @param formal the formal type parameter that will be 4169 * substituted by the wildcard 4170 */ 4171 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) { 4172 if (bound == syms.objectType) { 4173 return new WildcardType(syms.objectType, 4174 BoundKind.UNBOUND, 4175 syms.boundClass, 4176 formal); 4177 } else { 4178 return new WildcardType(bound, 4179 BoundKind.EXTENDS, 4180 syms.boundClass, 4181 formal); 4182 } 4183 } 4184 4185 /** 4186 * Create a wildcard with the given lower (super) bound; create an 4187 * unbounded wildcard if bound is bottom (type of {@code null}). 4188 * 4189 * @param bound the lower bound 4190 * @param formal the formal type parameter that will be 4191 * substituted by the wildcard 4192 */ 4193 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) { 4194 if (bound.tag == BOT) { 4195 return new WildcardType(syms.objectType, 4196 BoundKind.UNBOUND, 4197 syms.boundClass, 4198 formal); 4199 } else { 4200 return new WildcardType(bound, 4201 BoundKind.SUPER, 4202 syms.boundClass, 4203 formal); 4204 } 4205 } 4206 4207 /** 4208 * A wrapper for a type that allows use in sets. 4209 */ 4210 public static class UniqueType { 4211 public final Type type; 4212 final Types types; 4213 4214 public UniqueType(Type type, Types types) { 4215 this.type = type; 4216 this.types = types; 4217 } 4218 4219 public int hashCode() { 4220 return types.hashCode(type); 4221 } 4222 4223 public boolean equals(Object obj) { 4224 return (obj instanceof UniqueType) && 4225 types.isSameAnnotatedType(type, ((UniqueType)obj).type); 4226 } 4227 4228 public String toString() { 4229 return type.toString(); 4230 } 4231 4232 } 4233 // </editor-fold> 4234 4235 // <editor-fold defaultstate="collapsed" desc="Visitors"> 4236 /** 4237 * A default visitor for types. All visitor methods except 4238 * visitType are implemented by delegating to visitType. Concrete 4239 * subclasses must provide an implementation of visitType and can 4240 * override other methods as needed. 4241 * 4242 * @param <R> the return type of the operation implemented by this 4243 * visitor; use Void if no return type is needed. 4244 * @param <S> the type of the second argument (the first being the 4245 * type itself) of the operation implemented by this visitor; use 4246 * Void if a second argument is not needed. 4247 */ 4248 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> { 4249 final public R visit(Type t, S s) { return t.accept(this, s); } 4250 public R visitClassType(ClassType t, S s) { return visitType(t, s); } 4251 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); } 4252 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); } 4253 public R visitMethodType(MethodType t, S s) { return visitType(t, s); } 4254 public R visitPackageType(PackageType t, S s) { return visitType(t, s); } 4255 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); } 4256 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); } 4257 public R visitForAll(ForAll t, S s) { return visitType(t, s); } 4258 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); } 4259 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); } 4260 // Pretend annotations don't exist 4261 public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); } 4262 } 4263 4264 /** 4265 * A default visitor for symbols. All visitor methods except 4266 * visitSymbol are implemented by delegating to visitSymbol. Concrete 4267 * subclasses must provide an implementation of visitSymbol and can 4268 * override other methods as needed. 4269 * 4270 * @param <R> the return type of the operation implemented by this 4271 * visitor; use Void if no return type is needed. 4272 * @param <S> the type of the second argument (the first being the 4273 * symbol itself) of the operation implemented by this visitor; use 4274 * Void if a second argument is not needed. 4275 */ 4276 public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> { 4277 final public R visit(Symbol s, S arg) { return s.accept(this, arg); } 4278 public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); } 4279 public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); } 4280 public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); } 4281 public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); } 4282 public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); } 4283 public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); } 4284 } 4285 4286 /** 4287 * A <em>simple</em> visitor for types. This visitor is simple as 4288 * captured wildcards, for-all types (generic methods), and 4289 * undetermined type variables (part of inference) are hidden. 4290 * Captured wildcards are hidden by treating them as type 4291 * variables and the rest are hidden by visiting their qtypes. 4292 * 4293 * @param <R> the return type of the operation implemented by this 4294 * visitor; use Void if no return type is needed. 4295 * @param <S> the type of the second argument (the first being the 4296 * type itself) of the operation implemented by this visitor; use 4297 * Void if a second argument is not needed. 4298 */ 4299 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> { 4300 @Override 4301 public R visitCapturedType(CapturedType t, S s) { 4302 return visitTypeVar(t, s); 4303 } 4304 @Override 4305 public R visitForAll(ForAll t, S s) { 4306 return visit(t.qtype, s); 4307 } 4308 @Override 4309 public R visitUndetVar(UndetVar t, S s) { 4310 return visit(t.qtype, s); 4311 } 4312 } 4313 4314 /** 4315 * A plain relation on types. That is a 2-ary function on the 4316 * form Type × Type → Boolean. 4317 * <!-- In plain text: Type x Type -> Boolean --> 4318 */ 4319 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {} 4320 4321 /** 4322 * A convenience visitor for implementing operations that only 4323 * require one argument (the type itself), that is, unary 4324 * operations. 4325 * 4326 * @param <R> the return type of the operation implemented by this 4327 * visitor; use Void if no return type is needed. 4328 */ 4329 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> { 4330 final public R visit(Type t) { return t.accept(this, null); } 4331 } 4332 4333 /** 4334 * A visitor for implementing a mapping from types to types. The 4335 * default behavior of this class is to implement the identity 4336 * mapping (mapping a type to itself). This can be overridden in 4337 * subclasses. 4338 * 4339 * @param <S> the type of the second argument (the first being the 4340 * type itself) of this mapping; use Void if a second argument is 4341 * not needed. 4342 */ 4343 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> { 4344 final public Type visit(Type t) { return t.accept(this, null); } 4345 public Type visitType(Type t, S s) { return t; } 4346 } 4347 // </editor-fold> 4348 4349 4350 // <editor-fold defaultstate="collapsed" desc="Annotation support"> 4351 4352 public RetentionPolicy getRetention(Attribute.Compound a) { 4353 return getRetention(a.type.tsym); 4354 } 4355 4356 public RetentionPolicy getRetention(Symbol sym) { 4357 RetentionPolicy vis = RetentionPolicy.CLASS; // the default 4358 Attribute.Compound c = sym.attribute(syms.retentionType.tsym); 4359 if (c != null) { 4360 Attribute value = c.member(names.value); 4361 if (value != null && value instanceof Attribute.Enum) { 4362 Name levelName = ((Attribute.Enum)value).value.name; 4363 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE; 4364 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS; 4365 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME; 4366 else ;// /* fail soft */ throw new AssertionError(levelName); 4367 } 4368 } 4369 return vis; 4370 } 4371 // </editor-fold> 4372 4373 // <editor-fold defaultstate="collapsed" desc="Signature Generation"> 4374 4375 public static abstract class SignatureGenerator { 4376 4377 private final Types types; 4378 4379 protected abstract void append(char ch); 4380 protected abstract void append(byte[] ba); 4381 protected abstract void append(Name name); 4382 protected void classReference(ClassSymbol c) { /* by default: no-op */ } 4383 4384 protected SignatureGenerator(Types types) { 4385 this.types = types; 4386 } 4387 4388 /** 4389 * Assemble signature of given type in string buffer. 4390 */ 4391 public void assembleSig(Type type) { 4392 type = type.unannotatedType(); 4393 switch (type.getTag()) { 4394 case BYTE: 4395 append('B'); 4396 break; 4397 case SHORT: 4398 append('S'); 4399 break; 4400 case CHAR: 4401 append('C'); 4402 break; 4403 case INT: 4404 append('I'); 4405 break; 4406 case LONG: 4407 append('J'); 4408 break; 4409 case FLOAT: 4410 append('F'); 4411 break; 4412 case DOUBLE: 4413 append('D'); 4414 break; 4415 case BOOLEAN: 4416 append('Z'); 4417 break; 4418 case VOID: 4419 append('V'); 4420 break; 4421 case CLASS: 4422 append('L'); 4423 assembleClassSig(type); 4424 append(';'); 4425 break; 4426 case ARRAY: 4427 ArrayType at = (ArrayType) type; 4428 append('['); 4429 assembleSig(at.elemtype); 4430 break; 4431 case METHOD: 4432 MethodType mt = (MethodType) type; 4433 append('('); 4434 assembleSig(mt.argtypes); 4435 append(')'); 4436 assembleSig(mt.restype); 4437 if (hasTypeVar(mt.thrown)) { 4438 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) { 4439 append('^'); 4440 assembleSig(l.head); 4441 } 4442 } 4443 break; 4444 case WILDCARD: { 4445 Type.WildcardType ta = (Type.WildcardType) type; 4446 switch (ta.kind) { 4447 case SUPER: 4448 append('-'); 4449 assembleSig(ta.type); 4450 break; 4451 case EXTENDS: 4452 append('+'); 4453 assembleSig(ta.type); 4454 break; 4455 case UNBOUND: 4456 append('*'); 4457 break; 4458 default: 4459 throw new AssertionError(ta.kind); 4460 } 4461 break; 4462 } 4463 case TYPEVAR: 4464 append('T'); 4465 append(type.tsym.name); 4466 append(';'); 4467 break; 4468 case FORALL: 4469 Type.ForAll ft = (Type.ForAll) type; 4470 assembleParamsSig(ft.tvars); 4471 assembleSig(ft.qtype); 4472 break; 4473 default: 4474 throw new AssertionError("typeSig " + type.getTag()); 4475 } 4476 } 4477 4478 public boolean hasTypeVar(List<Type> l) { 4479 while (l.nonEmpty()) { 4480 if (l.head.hasTag(TypeTag.TYPEVAR)) { 4481 return true; 4482 } 4483 l = l.tail; 4484 } 4485 return false; 4486 } 4487 4488 public void assembleClassSig(Type type) { 4489 type = type.unannotatedType(); 4490 ClassType ct = (ClassType) type; 4491 ClassSymbol c = (ClassSymbol) ct.tsym; 4492 classReference(c); 4493 Type outer = ct.getEnclosingType(); 4494 if (outer.allparams().nonEmpty()) { 4495 boolean rawOuter = 4496 c.owner.kind == Kinds.MTH || // either a local class 4497 c.name == types.names.empty; // or anonymous 4498 assembleClassSig(rawOuter 4499 ? types.erasure(outer) 4500 : outer); 4501 append('.'); 4502 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname)); 4503 append(rawOuter 4504 ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength()) 4505 : c.name); 4506 } else { 4507 append(externalize(c.flatname)); 4508 } 4509 if (ct.getTypeArguments().nonEmpty()) { 4510 append('<'); 4511 assembleSig(ct.getTypeArguments()); 4512 append('>'); 4513 } 4514 } 4515 4516 public void assembleParamsSig(List<Type> typarams) { 4517 append('<'); 4518 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) { 4519 Type.TypeVar tvar = (Type.TypeVar) ts.head; 4520 append(tvar.tsym.name); 4521 List<Type> bounds = types.getBounds(tvar); 4522 if ((bounds.head.tsym.flags() & INTERFACE) != 0) { 4523 append(':'); 4524 } 4525 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) { 4526 append(':'); 4527 assembleSig(l.head); 4528 } 4529 } 4530 append('>'); 4531 } 4532 4533 private void assembleSig(List<Type> types) { 4534 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) { 4535 assembleSig(ts.head); 4536 } 4537 } 4538 } 4539 // </editor-fold> 4540 }