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

Tue, 23 Jul 2013 20:42:54 -0400

author
emc
date
Tue, 23 Jul 2013 20:42:54 -0400
changeset 1916
558fe98d1ac0
parent 1907
e990e6bcecbe
child 1919
3155e77d2676
permissions
-rw-r--r--

8016880: 42 tests in annot102* fail with compile-time errors.
Summary: Fixes error in type equality when bounds of type variables have annotations.
Reviewed-by: jjg, mcimadamore

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

mercurial