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