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

Mon, 12 Aug 2013 17:25:07 +0100

author
mcimadamore
date
Mon, 12 Aug 2013 17:25:07 +0100
changeset 1945
f7f271bd74a2
parent 1919
3155e77d2676
child 1973
7a4717f3ea7b
permissions
-rw-r--r--

6537020: JCK tests: a compile-time error should be given in case of ambiguously imported fields (types, methods)
Summary: Hiding check does not support interface multiple inheritance
Reviewed-by: jjg

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

mercurial