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

Tue, 24 Sep 2013 14:20:33 -0700

author
mfang
date
Tue, 24 Sep 2013 14:20:33 -0700
changeset 2057
1332a99572c5
parent 2000
4a6acc42c3a1
child 2047
5f915a0c9615
permissions
-rw-r--r--

8025215: jdk8 l10n resource file translation update 4
Reviewed-by: naoto, yhuang

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

mercurial