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

Thu, 05 Jan 2017 18:58:06 +0000

author
mcimadamore
date
Thu, 05 Jan 2017 18:58:06 +0000
changeset 3361
3a62189765a8
parent 3348
dc80683c4dd9
child 3446
e468915bad3a
permissions
-rw-r--r--

8168774: Polymorhic signature method check crashes javac
Summary: Check for polysig method assumes arity is greater than zero
Reviewed-by: vromero

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

mercurial