src/share/classes/com/sun/tools/javac/code/Types.java

Fri, 05 Oct 2012 14:35:24 +0100

author
mcimadamore
date
Fri, 05 Oct 2012 14:35:24 +0100
changeset 1348
573ceb23beeb
parent 1347
1408af4cd8b0
child 1357
c75be5bc5283
permissions
-rw-r--r--

7177385: Add attribution support for lambda expressions
Summary: Add support for function descriptor lookup, functional interface inference and lambda expression type-checking
Reviewed-by: jjg, dlsmith

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

mercurial