duke@1: /*
jjg@1521: * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@1: *
duke@1: * This code is free software; you can redistribute it and/or modify it
duke@1: * under the terms of the GNU General Public License version 2 only, as
ohair@554: * published by the Free Software Foundation. Oracle designates this
duke@1: * particular file as subject to the "Classpath" exception as provided
ohair@554: * by Oracle in the LICENSE file that accompanied this code.
duke@1: *
duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT
duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@1: * version 2 for more details (a copy is included in the LICENSE file that
duke@1: * accompanied this code).
duke@1: *
duke@1: * You should have received a copy of the GNU General Public License version
duke@1: * 2 along with this work; if not, write to the Free Software Foundation,
duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@1: *
ohair@554: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@554: * or visit www.oracle.com if you need additional information or have any
ohair@554: * questions.
duke@1: */
duke@1:
duke@1: package com.sun.tools.javac.code;
duke@1:
mcimadamore@341: import java.lang.ref.SoftReference;
jjg@1430: import java.util.Comparator;
jjg@1430: import java.util.HashSet;
jjg@1430: import java.util.HashMap;
jjg@1430: import java.util.Locale;
jjg@1430: import java.util.Map;
jjg@1430: import java.util.Set;
jjg@1430: import java.util.WeakHashMap;
duke@1:
jjg@1521: import javax.lang.model.type.TypeKind;
jjg@1521:
jjg@657: import com.sun.tools.javac.code.Attribute.RetentionPolicy;
mcimadamore@795: import com.sun.tools.javac.code.Lint.LintCategory;
mcimadamore@1338: import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
duke@1: import com.sun.tools.javac.comp.Check;
jjg@1357: import com.sun.tools.javac.jvm.ClassReader;
jjg@1357: import com.sun.tools.javac.util.*;
jjg@1357: import static com.sun.tools.javac.code.BoundKind.*;
jjg@1357: import static com.sun.tools.javac.code.Flags.*;
mcimadamore@858: import static com.sun.tools.javac.code.Scope.*;
jjg@1357: import static com.sun.tools.javac.code.Symbol.*;
duke@1: import static com.sun.tools.javac.code.Type.*;
jjg@1374: import static com.sun.tools.javac.code.TypeTag.*;
rfield@1587: import static com.sun.tools.javac.jvm.ClassFile.externalize;
duke@1: import static com.sun.tools.javac.util.ListBuffer.lb;
duke@1:
duke@1: /**
duke@1: * Utility class containing various operations on types.
duke@1: *
duke@1: *
Unless other names are more illustrative, the following naming
duke@1: * conventions should be observed in this file:
duke@1: *
duke@1: *
duke@1: *
t
duke@1: *
If the first argument to an operation is a type, it should be named t.
duke@1: *
s
duke@1: *
Similarly, if the second argument to an operation is a type, it should be named s.
duke@1: *
ts
duke@1: *
If an operations takes a list of types, the first should be named ts.
duke@1: *
ss
duke@1: *
A second list of types should be named ss.
duke@1: *
duke@1: *
jjg@581: *
This is NOT part of any supported API.
duke@1: * If you write code that depends on this, you do so at your own risk.
duke@1: * This code and its internal interfaces are subject to change or
duke@1: * deletion without notice.
duke@1: */
duke@1: public class Types {
duke@1: protected static final Context.Key typesKey =
duke@1: new Context.Key();
duke@1:
duke@1: final Symtab syms;
mcimadamore@136: final JavacMessages messages;
jjg@113: final Names names;
duke@1: final boolean allowBoxing;
jjg@984: final boolean allowCovariantReturns;
jjg@984: final boolean allowObjectToPrimitiveCast;
mcimadamore@1393: final boolean allowDefaultMethods;
duke@1: final ClassReader reader;
duke@1: final Check chk;
mcimadamore@1348: JCDiagnostic.Factory diags;
duke@1: List warnStack = List.nil();
duke@1: final Name capturedName;
mcimadamore@1348: private final FunctionDescriptorLookupError functionDescriptorLookupError;
duke@1:
mcimadamore@1415: public final Warner noWarnings;
mcimadamore@1415:
duke@1: //
duke@1: public static Types instance(Context context) {
duke@1: Types instance = context.get(typesKey);
duke@1: if (instance == null)
duke@1: instance = new Types(context);
duke@1: return instance;
duke@1: }
duke@1:
duke@1: protected Types(Context context) {
duke@1: context.put(typesKey, this);
duke@1: syms = Symtab.instance(context);
jjg@113: names = Names.instance(context);
jjg@984: Source source = Source.instance(context);
jjg@984: allowBoxing = source.allowBoxing();
jjg@984: allowCovariantReturns = source.allowCovariantReturns();
jjg@984: allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
mcimadamore@1393: allowDefaultMethods = source.allowDefaultMethods();
duke@1: reader = ClassReader.instance(context);
duke@1: chk = Check.instance(context);
duke@1: capturedName = names.fromString("");
mcimadamore@136: messages = JavacMessages.instance(context);
mcimadamore@1348: diags = JCDiagnostic.Factory.instance(context);
mcimadamore@1348: functionDescriptorLookupError = new FunctionDescriptorLookupError();
mcimadamore@1415: noWarnings = new Warner(null);
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * The "rvalue conversion".
duke@1: * The upper bound of most types is the type
duke@1: * itself. Wildcards, on the other hand have upper
duke@1: * and lower bounds.
duke@1: * @param t a type
duke@1: * @return the upper bound of the given type
duke@1: */
duke@1: public Type upperBound(Type t) {
duke@1: return upperBound.visit(t);
duke@1: }
duke@1: // where
duke@1: private final MapVisitor upperBound = new MapVisitor() {
duke@1:
duke@1: @Override
duke@1: public Type visitWildcardType(WildcardType t, Void ignored) {
duke@1: if (t.isSuperBound())
duke@1: return t.bound == null ? syms.objectType : t.bound.bound;
duke@1: else
duke@1: return visit(t.type);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitCapturedType(CapturedType t, Void ignored) {
duke@1: return visit(t.bound);
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * The "lvalue conversion".
duke@1: * The lower bound of most types is the type
duke@1: * itself. Wildcards, on the other hand have upper
duke@1: * and lower bounds.
duke@1: * @param t a type
duke@1: * @return the lower bound of the given type
duke@1: */
duke@1: public Type lowerBound(Type t) {
duke@1: return lowerBound.visit(t);
duke@1: }
duke@1: // where
duke@1: private final MapVisitor lowerBound = new MapVisitor() {
duke@1:
duke@1: @Override
duke@1: public Type visitWildcardType(WildcardType t, Void ignored) {
duke@1: return t.isExtendsBound() ? syms.botType : visit(t.type);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitCapturedType(CapturedType t, Void ignored) {
duke@1: return visit(t.getLowerBound());
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Checks that all the arguments to a class are unbounded
duke@1: * wildcards or something else that doesn't make any restrictions
duke@1: * on the arguments. If a class isUnbounded, a raw super- or
duke@1: * subclass can be cast to it without a warning.
duke@1: * @param t a type
duke@1: * @return true iff the given type is unbounded or raw
duke@1: */
duke@1: public boolean isUnbounded(Type t) {
duke@1: return isUnbounded.visit(t);
duke@1: }
duke@1: // where
duke@1: private final UnaryVisitor isUnbounded = new UnaryVisitor() {
duke@1:
duke@1: public Boolean visitType(Type t, Void ignored) {
duke@1: return true;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitClassType(ClassType t, Void ignored) {
duke@1: List parms = t.tsym.type.allparams();
duke@1: List args = t.allparams();
duke@1: while (parms.nonEmpty()) {
duke@1: WildcardType unb = new WildcardType(syms.objectType,
duke@1: BoundKind.UNBOUND,
duke@1: syms.boundClass,
duke@1: (TypeVar)parms.head);
duke@1: if (!containsType(args.head, unb))
duke@1: return false;
duke@1: parms = parms.tail;
duke@1: args = args.tail;
duke@1: }
duke@1: return true;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Return the least specific subtype of t that starts with symbol
duke@1: * sym. If none exists, return null. The least specific subtype
duke@1: * is determined as follows:
duke@1: *
duke@1: *
If there is exactly one parameterized instance of sym that is a
duke@1: * subtype of t, that parameterized instance is returned.
duke@1: * Otherwise, if the plain type or raw type `sym' is a subtype of
duke@1: * type t, the type `sym' itself is returned. Otherwise, null is
duke@1: * returned.
duke@1: */
duke@1: public Type asSub(Type t, Symbol sym) {
duke@1: return asSub.visit(t, sym);
duke@1: }
duke@1: // where
duke@1: private final SimpleVisitor asSub = new SimpleVisitor() {
duke@1:
duke@1: public Type visitType(Type t, Symbol sym) {
duke@1: return null;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Symbol sym) {
duke@1: if (t.tsym == sym)
duke@1: return t;
duke@1: Type base = asSuper(sym.type, t.tsym);
duke@1: if (base == null)
duke@1: return null;
duke@1: ListBuffer from = new ListBuffer();
duke@1: ListBuffer to = new ListBuffer();
duke@1: try {
duke@1: adapt(base, t, from, to);
duke@1: } catch (AdaptFailure ex) {
duke@1: return null;
duke@1: }
duke@1: Type res = subst(sym.type, from.toList(), to.toList());
duke@1: if (!isSubtype(res, t))
duke@1: return null;
duke@1: ListBuffer openVars = new ListBuffer();
duke@1: for (List l = sym.type.allparams();
duke@1: l.nonEmpty(); l = l.tail)
duke@1: if (res.contains(l.head) && !t.contains(l.head))
duke@1: openVars.append(l.head);
duke@1: if (openVars.nonEmpty()) {
duke@1: if (t.isRaw()) {
duke@1: // The subtype of a raw type is raw
duke@1: res = erasure(res);
duke@1: } else {
duke@1: // Unbound type arguments default to ?
duke@1: List opens = openVars.toList();
duke@1: ListBuffer qs = new ListBuffer();
duke@1: for (List iter = opens; iter.nonEmpty(); iter = iter.tail) {
duke@1: qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
duke@1: }
duke@1: res = subst(res, opens, qs.toList());
duke@1: }
duke@1: }
duke@1: return res;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Symbol sym) {
duke@1: return t;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
mcimadamore@1071: * Is t a subtype of or convertible via boxing/unboxing
mcimadamore@1071: * conversion to s?
duke@1: */
duke@1: public boolean isConvertible(Type t, Type s, Warner warn) {
mcimadamore@1071: if (t.tag == ERROR)
mcimadamore@1071: return true;
duke@1: boolean tPrimitive = t.isPrimitive();
duke@1: boolean sPrimitive = s.isPrimitive();
mcimadamore@795: if (tPrimitive == sPrimitive) {
duke@1: return isSubtypeUnchecked(t, s, warn);
mcimadamore@795: }
duke@1: if (!allowBoxing) return false;
duke@1: return tPrimitive
duke@1: ? isSubtype(boxedClass(t).type, s)
duke@1: : isSubtype(unboxedType(t), s);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Is t a subtype of or convertiable via boxing/unboxing
duke@1: * convertions to s?
duke@1: */
duke@1: public boolean isConvertible(Type t, Type s) {
mcimadamore@1415: return isConvertible(t, s, noWarnings);
duke@1: }
duke@1: //
duke@1:
mcimadamore@1348: //
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Exception used to report a function descriptor lookup failure. The exception
mcimadamore@1348: * wraps a diagnostic that can be used to generate more details error
mcimadamore@1348: * messages.
mcimadamore@1348: */
mcimadamore@1348: public static class FunctionDescriptorLookupError extends RuntimeException {
mcimadamore@1348: private static final long serialVersionUID = 0;
mcimadamore@1348:
mcimadamore@1348: JCDiagnostic diagnostic;
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptorLookupError() {
mcimadamore@1348: this.diagnostic = null;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
mcimadamore@1348: this.diagnostic = diag;
mcimadamore@1348: return this;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: public JCDiagnostic getDiagnostic() {
mcimadamore@1348: return diagnostic;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * A cache that keeps track of function descriptors associated with given
mcimadamore@1348: * functional interfaces.
mcimadamore@1348: */
mcimadamore@1348: class DescriptorCache {
mcimadamore@1348:
mcimadamore@1348: private WeakHashMap _map = new WeakHashMap();
mcimadamore@1348:
mcimadamore@1348: class FunctionDescriptor {
mcimadamore@1348: Symbol descSym;
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptor(Symbol descSym) {
mcimadamore@1348: this.descSym = descSym;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: public Symbol getSymbol() {
mcimadamore@1348: return descSym;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1510: public Type getType(Type site) {
mcimadamore@1579: site = removeWildcards(site);
mcimadamore@1579: if (!chk.checkValidGenericType(site)) {
mcimadamore@1579: //if the inferred functional interface type is not well-formed,
mcimadamore@1579: //or if it's not a subtype of the original target, issue an error
mcimadamore@1579: throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
mcimadamore@1510: }
mcimadamore@1510: return memberType(site, descSym);
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: class Entry {
mcimadamore@1348: final FunctionDescriptor cachedDescRes;
mcimadamore@1348: final int prevMark;
mcimadamore@1348:
mcimadamore@1348: public Entry(FunctionDescriptor cachedDescRes,
mcimadamore@1348: int prevMark) {
mcimadamore@1348: this.cachedDescRes = cachedDescRes;
mcimadamore@1348: this.prevMark = prevMark;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: boolean matches(int mark) {
mcimadamore@1348: return this.prevMark == mark;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
mcimadamore@1348: Entry e = _map.get(origin);
mcimadamore@1348: CompoundScope members = membersClosure(origin.type, false);
mcimadamore@1348: if (e == null ||
mcimadamore@1348: !e.matches(members.getMark())) {
mcimadamore@1348: FunctionDescriptor descRes = findDescriptorInternal(origin, members);
mcimadamore@1348: _map.put(origin, new Entry(descRes, members.getMark()));
mcimadamore@1348: return descRes;
mcimadamore@1348: }
mcimadamore@1348: else {
mcimadamore@1348: return e.cachedDescRes;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Compute the function descriptor associated with a given functional interface
mcimadamore@1348: */
mcimadamore@1348: public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
mcimadamore@1497: if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
mcimadamore@1348: //t must be an interface
mcimadamore@1497: throw failure("not.a.functional.intf", origin);
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: final ListBuffer abstracts = ListBuffer.lb();
mcimadamore@1348: for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
mcimadamore@1348: Type mtype = memberType(origin.type, sym);
mcimadamore@1348: if (abstracts.isEmpty() ||
mcimadamore@1348: (sym.name == abstracts.first().name &&
mcimadamore@1348: overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
mcimadamore@1348: abstracts.append(sym);
mcimadamore@1348: } else {
mcimadamore@1348: //the target method(s) should be the only abstract members of t
mcimadamore@1497: throw failure("not.a.functional.intf.1", origin,
mcimadamore@1348: diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348: if (abstracts.isEmpty()) {
mcimadamore@1348: //t must define a suitable non-generic method
mcimadamore@1497: throw failure("not.a.functional.intf.1", origin,
mcimadamore@1348: diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
mcimadamore@1348: } else if (abstracts.size() == 1) {
mcimadamore@1434: return new FunctionDescriptor(abstracts.first());
mcimadamore@1348: } else { // size > 1
mcimadamore@1348: FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
mcimadamore@1348: if (descRes == null) {
mcimadamore@1348: //we can get here if the functional interface is ill-formed
mcimadamore@1348: ListBuffer descriptors = ListBuffer.lb();
mcimadamore@1348: for (Symbol desc : abstracts) {
mcimadamore@1348: String key = desc.type.getThrownTypes().nonEmpty() ?
mcimadamore@1348: "descriptor.throws" : "descriptor";
mcimadamore@1348: descriptors.append(diags.fragment(key, desc.name,
mcimadamore@1348: desc.type.getParameterTypes(),
mcimadamore@1348: desc.type.getReturnType(),
mcimadamore@1348: desc.type.getThrownTypes()));
mcimadamore@1348: }
mcimadamore@1348: JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
mcimadamore@1348: new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
mcimadamore@1348: Kinds.kindName(origin), origin), descriptors.toList());
mcimadamore@1348: throw failure(incompatibleDescriptors);
mcimadamore@1348: }
mcimadamore@1348: return descRes;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Compute a synthetic type for the target descriptor given a list
mcimadamore@1348: * of override-equivalent methods in the functional interface type.
mcimadamore@1348: * The resulting method type is a method type that is override-equivalent
mcimadamore@1348: * and return-type substitutable with each method in the original list.
mcimadamore@1348: */
mcimadamore@1348: private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List methodSyms) {
mcimadamore@1348: //pick argument types - simply take the signature that is a
mcimadamore@1348: //subsignature of all other signatures in the list (as per JLS 8.4.2)
mcimadamore@1348: List mostSpecific = List.nil();
mcimadamore@1348: outer: for (Symbol msym1 : methodSyms) {
mcimadamore@1348: Type mt1 = memberType(origin.type, msym1);
mcimadamore@1348: for (Symbol msym2 : methodSyms) {
mcimadamore@1348: Type mt2 = memberType(origin.type, msym2);
mcimadamore@1348: if (!isSubSignature(mt1, mt2)) {
mcimadamore@1348: continue outer;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348: mostSpecific = mostSpecific.prepend(msym1);
mcimadamore@1348: }
mcimadamore@1348: if (mostSpecific.isEmpty()) {
mcimadamore@1348: return null;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348:
mcimadamore@1348: //pick return types - this is done in two phases: (i) first, the most
mcimadamore@1348: //specific return type is chosen using strict subtyping; if this fails,
mcimadamore@1348: //a second attempt is made using return type substitutability (see JLS 8.4.5)
mcimadamore@1348: boolean phase2 = false;
mcimadamore@1348: Symbol bestSoFar = null;
mcimadamore@1348: while (bestSoFar == null) {
mcimadamore@1348: outer: for (Symbol msym1 : mostSpecific) {
mcimadamore@1348: Type mt1 = memberType(origin.type, msym1);
mcimadamore@1348: for (Symbol msym2 : methodSyms) {
mcimadamore@1348: Type mt2 = memberType(origin.type, msym2);
mcimadamore@1348: if (phase2 ?
mcimadamore@1348: !returnTypeSubstitutable(mt1, mt2) :
mcimadamore@1348: !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
mcimadamore@1348: continue outer;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348: bestSoFar = msym1;
mcimadamore@1348: }
mcimadamore@1348: if (phase2) {
mcimadamore@1348: break;
mcimadamore@1348: } else {
mcimadamore@1348: phase2 = true;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348: if (bestSoFar == null) return null;
mcimadamore@1348:
mcimadamore@1348: //merge thrown types - form the intersection of all the thrown types in
mcimadamore@1348: //all the signatures in the list
mcimadamore@1348: List thrown = null;
mcimadamore@1348: for (Symbol msym1 : methodSyms) {
mcimadamore@1348: Type mt1 = memberType(origin.type, msym1);
mcimadamore@1348: thrown = (thrown == null) ?
mcimadamore@1348: mt1.getThrownTypes() :
mcimadamore@1348: chk.intersect(mt1.getThrownTypes(), thrown);
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: final List thrown1 = thrown;
mcimadamore@1348: return new FunctionDescriptor(bestSoFar) {
mcimadamore@1348: @Override
mcimadamore@1348: public Type getType(Type origin) {
mcimadamore@1348: Type mt = memberType(origin, getSymbol());
mcimadamore@1600: return createMethodTypeWithThrown(mt, thrown1);
mcimadamore@1348: }
mcimadamore@1348: };
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: boolean isSubtypeInternal(Type s, Type t) {
mcimadamore@1348: return (s.isPrimitive() && t.isPrimitive()) ?
mcimadamore@1348: isSameType(t, s) :
mcimadamore@1348: isSubtype(s, t);
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptorLookupError failure(String msg, Object... args) {
mcimadamore@1348: return failure(diags.fragment(msg, args));
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: FunctionDescriptorLookupError failure(JCDiagnostic diag) {
mcimadamore@1348: return functionDescriptorLookupError.setMessage(diag);
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: private DescriptorCache descCache = new DescriptorCache();
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Find the method descriptor associated to this class symbol - if the
mcimadamore@1348: * symbol 'origin' is not a functional interface, an exception is thrown.
mcimadamore@1348: */
mcimadamore@1348: public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
mcimadamore@1348: return descCache.get(origin).getSymbol();
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Find the type of the method descriptor associated to this class symbol -
mcimadamore@1348: * if the symbol 'origin' is not a functional interface, an exception is thrown.
mcimadamore@1348: */
mcimadamore@1348: public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
mcimadamore@1348: return descCache.get(origin.tsym).getType(origin);
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@1348: /**
mcimadamore@1348: * Is given type a functional interface?
mcimadamore@1348: */
mcimadamore@1348: public boolean isFunctionalInterface(TypeSymbol tsym) {
mcimadamore@1348: try {
mcimadamore@1348: findDescriptorSymbol(tsym);
mcimadamore@1348: return true;
mcimadamore@1348: } catch (FunctionDescriptorLookupError ex) {
mcimadamore@1348: return false;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1510:
mcimadamore@1510: public boolean isFunctionalInterface(Type site) {
mcimadamore@1510: try {
mcimadamore@1510: findDescriptorType(site);
mcimadamore@1510: return true;
mcimadamore@1510: } catch (FunctionDescriptorLookupError ex) {
mcimadamore@1510: return false;
mcimadamore@1510: }
mcimadamore@1510: }
mcimadamore@1579:
mcimadamore@1579: public Type removeWildcards(Type site) {
mcimadamore@1605: Type capturedSite = capture(site);
mcimadamore@1605: if (capturedSite != site) {
mcimadamore@1579: Type formalInterface = site.tsym.type;
mcimadamore@1579: ListBuffer typeargs = ListBuffer.lb();
mcimadamore@1579: List actualTypeargs = site.getTypeArguments();
mcimadamore@1605: List capturedTypeargs = capturedSite.getTypeArguments();
mcimadamore@1579: //simply replace the wildcards with its bound
mcimadamore@1579: for (Type t : formalInterface.getTypeArguments()) {
mcimadamore@1579: if (actualTypeargs.head.hasTag(WILDCARD)) {
mcimadamore@1579: WildcardType wt = (WildcardType)actualTypeargs.head;
mcimadamore@1598: Type bound;
mcimadamore@1598: switch (wt.kind) {
mcimadamore@1605: case EXTENDS:
mcimadamore@1598: case UNBOUND:
mcimadamore@1605: CapturedType capVar = (CapturedType)capturedTypeargs.head;
mcimadamore@1598: //use declared bound if it doesn't depend on formal type-args
mcimadamore@1605: bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
mcimadamore@1605: syms.objectType : capVar.bound;
mcimadamore@1598: break;
mcimadamore@1598: default:
mcimadamore@1598: bound = wt.type;
mcimadamore@1598: }
mcimadamore@1598: typeargs.append(bound);
mcimadamore@1579: } else {
mcimadamore@1579: typeargs.append(actualTypeargs.head);
mcimadamore@1579: }
mcimadamore@1579: actualTypeargs = actualTypeargs.tail;
mcimadamore@1605: capturedTypeargs = capturedTypeargs.tail;
mcimadamore@1579: }
mcimadamore@1579: return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
mcimadamore@1579: } else {
mcimadamore@1579: return site;
mcimadamore@1579: }
mcimadamore@1579: }
mcimadamore@1348: //
mcimadamore@1348:
mcimadamore@1436: /**
mcimadamore@1436: * Scope filter used to skip methods that should be ignored (such as methods
mcimadamore@1436: * overridden by j.l.Object) during function interface conversion/marker interface checks
mcimadamore@1436: */
mcimadamore@1436: class DescriptorFilter implements Filter {
mcimadamore@1436:
mcimadamore@1436: TypeSymbol origin;
mcimadamore@1436:
mcimadamore@1436: DescriptorFilter(TypeSymbol origin) {
mcimadamore@1436: this.origin = origin;
mcimadamore@1436: }
mcimadamore@1436:
mcimadamore@1436: @Override
mcimadamore@1436: public boolean accepts(Symbol sym) {
mcimadamore@1436: return sym.kind == Kinds.MTH &&
mcimadamore@1436: (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
mcimadamore@1436: !overridesObjectMethod(origin, sym) &&
mcimadamore@1436: (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
mcimadamore@1436: }
mcimadamore@1436: };
mcimadamore@1436:
mcimadamore@1436: //
mcimadamore@1436:
mcimadamore@1436: /**
mcimadamore@1436: * A cache that keeps track of marker interfaces
mcimadamore@1436: */
mcimadamore@1436: class MarkerCache {
mcimadamore@1436:
mcimadamore@1436: private WeakHashMap _map = new WeakHashMap();
mcimadamore@1436:
mcimadamore@1436: class Entry {
mcimadamore@1436: final boolean isMarkerIntf;
mcimadamore@1436: final int prevMark;
mcimadamore@1436:
mcimadamore@1436: public Entry(boolean isMarkerIntf,
mcimadamore@1436: int prevMark) {
mcimadamore@1436: this.isMarkerIntf = isMarkerIntf;
mcimadamore@1436: this.prevMark = prevMark;
mcimadamore@1436: }
mcimadamore@1436:
mcimadamore@1436: boolean matches(int mark) {
mcimadamore@1436: return this.prevMark == mark;
mcimadamore@1436: }
mcimadamore@1436: }
mcimadamore@1436:
mcimadamore@1436: boolean get(TypeSymbol origin) throws FunctionDescriptorLookupError {
mcimadamore@1436: Entry e = _map.get(origin);
mcimadamore@1436: CompoundScope members = membersClosure(origin.type, false);
mcimadamore@1436: if (e == null ||
mcimadamore@1436: !e.matches(members.getMark())) {
mcimadamore@1436: boolean isMarkerIntf = isMarkerInterfaceInternal(origin, members);
mcimadamore@1436: _map.put(origin, new Entry(isMarkerIntf, members.getMark()));
mcimadamore@1436: return isMarkerIntf;
mcimadamore@1436: }
mcimadamore@1436: else {
mcimadamore@1436: return e.isMarkerIntf;
mcimadamore@1436: }
mcimadamore@1436: }
mcimadamore@1436:
mcimadamore@1436: /**
mcimadamore@1436: * Is given symbol a marker interface
mcimadamore@1436: */
mcimadamore@1436: public boolean isMarkerInterfaceInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
mcimadamore@1436: return !origin.isInterface() ?
mcimadamore@1436: false :
mcimadamore@1436: !membersCache.getElements(new DescriptorFilter(origin)).iterator().hasNext();
mcimadamore@1436: }
mcimadamore@1436: }
mcimadamore@1436:
mcimadamore@1436: private MarkerCache markerCache = new MarkerCache();
mcimadamore@1436:
mcimadamore@1436: /**
mcimadamore@1436: * Is given type a marker interface?
mcimadamore@1436: */
mcimadamore@1436: public boolean isMarkerInterface(Type site) {
mcimadamore@1436: return markerCache.get(site.tsym);
mcimadamore@1436: }
mcimadamore@1436: //
mcimadamore@1436:
duke@1: //
duke@1: /**
duke@1: * Is t an unchecked subtype of s?
duke@1: */
duke@1: public boolean isSubtypeUnchecked(Type t, Type s) {
mcimadamore@1415: return isSubtypeUnchecked(t, s, noWarnings);
duke@1: }
duke@1: /**
duke@1: * Is t an unchecked subtype of s?
duke@1: */
duke@1: public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
mcimadamore@1108: boolean result = isSubtypeUncheckedInternal(t, s, warn);
mcimadamore@1108: if (result) {
mcimadamore@1108: checkUnsafeVarargsConversion(t, s, warn);
mcimadamore@1108: }
mcimadamore@1108: return result;
mcimadamore@1108: }
mcimadamore@1108: //where
mcimadamore@1108: private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
jjg@1374: if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
jjg@1521: t = t.unannotatedType();
jjg@1521: s = s.unannotatedType();
jjg@1374: if (((ArrayType)t).elemtype.isPrimitive()) {
mcimadamore@1108: return isSameType(elemtype(t), elemtype(s));
mcimadamore@1108: } else {
mcimadamore@1108: return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
mcimadamore@795: }
mcimadamore@1108: } else if (isSubtype(t, s)) {
duke@1: return true;
duke@1: }
mcimadamore@1108: else if (t.tag == TYPEVAR) {
mcimadamore@1108: return isSubtypeUnchecked(t.getUpperBound(), s, warn);
mcimadamore@1108: }
mcimadamore@1108: else if (!s.isRaw()) {
mcimadamore@1108: Type t2 = asSuper(t, s.tsym);
mcimadamore@1108: if (t2 != null && t2.isRaw()) {
mcimadamore@1108: if (isReifiable(s))
mcimadamore@1108: warn.silentWarn(LintCategory.UNCHECKED);
mcimadamore@1108: else
mcimadamore@1108: warn.warn(LintCategory.UNCHECKED);
mcimadamore@1108: return true;
mcimadamore@1108: }
mcimadamore@1108: }
mcimadamore@1108: return false;
duke@1: }
mcimadamore@1108:
mcimadamore@1108: private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
jjg@1521: if (t.tag != ARRAY || isReifiable(t))
jjg@1521: return;
jjg@1521: t = t.unannotatedType();
jjg@1521: s = s.unannotatedType();
mcimadamore@1108: ArrayType from = (ArrayType)t;
mcimadamore@1108: boolean shouldWarn = false;
mcimadamore@1108: switch (s.tag) {
mcimadamore@1108: case ARRAY:
mcimadamore@1108: ArrayType to = (ArrayType)s;
mcimadamore@1108: shouldWarn = from.isVarargs() &&
mcimadamore@1108: !to.isVarargs() &&
mcimadamore@1108: !isReifiable(from);
mcimadamore@1108: break;
mcimadamore@1108: case CLASS:
mcimadamore@1108: shouldWarn = from.isVarargs();
mcimadamore@1108: break;
mcimadamore@1108: }
mcimadamore@1108: if (shouldWarn) {
mcimadamore@1108: warn.warn(LintCategory.VARARGS);
mcimadamore@1108: }
mcimadamore@1108: }
duke@1:
duke@1: /**
duke@1: * Is t a subtype of s?
duke@1: * (not defined for Method and ForAll types)
duke@1: */
duke@1: final public boolean isSubtype(Type t, Type s) {
duke@1: return isSubtype(t, s, true);
duke@1: }
duke@1: final public boolean isSubtypeNoCapture(Type t, Type s) {
duke@1: return isSubtype(t, s, false);
duke@1: }
duke@1: public boolean isSubtype(Type t, Type s, boolean capture) {
duke@1: if (t == s)
duke@1: return true;
duke@1:
jjg@1521: t = t.unannotatedType();
jjg@1521: s = s.unannotatedType();
jjg@1521:
jjg@1521: if (t == s)
jjg@1521: return true;
jjg@1521:
jjg@1374: if (s.isPartial())
duke@1: return isSuperType(s, t);
duke@1:
mcimadamore@299: if (s.isCompound()) {
mcimadamore@299: for (Type s2 : interfaces(s).prepend(supertype(s))) {
mcimadamore@299: if (!isSubtype(t, s2, capture))
mcimadamore@299: return false;
mcimadamore@299: }
mcimadamore@299: return true;
mcimadamore@299: }
mcimadamore@299:
duke@1: Type lower = lowerBound(s);
duke@1: if (s != lower)
duke@1: return isSubtype(capture ? capture(t) : t, lower, false);
duke@1:
duke@1: return isSubtype.visit(capture ? capture(t) : t, s);
duke@1: }
duke@1: // where
duke@1: private TypeRelation isSubtype = new TypeRelation()
duke@1: {
duke@1: public Boolean visitType(Type t, Type s) {
duke@1: switch (t.tag) {
jjg@1374: case BYTE:
jjg@1374: return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
jjg@1374: case CHAR:
jjg@1374: return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
jjg@1374: case SHORT: case INT: case LONG:
jjg@1374: case FLOAT: case DOUBLE:
jjg@1374: return t.getTag().isSubRangeOf(s.getTag());
jjg@1374: case BOOLEAN: case VOID:
jjg@1374: return t.hasTag(s.getTag());
jjg@1374: case TYPEVAR:
jjg@1374: return isSubtypeNoCapture(t.getUpperBound(), s);
jjg@1374: case BOT:
jjg@1374: return
jjg@1374: s.hasTag(BOT) || s.hasTag(CLASS) ||
jjg@1374: s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
jjg@1374: case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
jjg@1374: case NONE:
jjg@1374: return false;
jjg@1374: default:
jjg@1374: throw new AssertionError("isSubtype " + t.tag);
jjg@1374: }
duke@1: }
duke@1:
duke@1: private Set cache = new HashSet();
duke@1:
duke@1: private boolean containsTypeRecursive(Type t, Type s) {
duke@1: TypePair pair = new TypePair(t, s);
duke@1: if (cache.add(pair)) {
duke@1: try {
duke@1: return containsType(t.getTypeArguments(),
duke@1: s.getTypeArguments());
duke@1: } finally {
duke@1: cache.remove(pair);
duke@1: }
duke@1: } else {
duke@1: return containsType(t.getTypeArguments(),
duke@1: rewriteSupers(s).getTypeArguments());
duke@1: }
duke@1: }
duke@1:
duke@1: private Type rewriteSupers(Type t) {
duke@1: if (!t.isParameterized())
duke@1: return t;
duke@1: ListBuffer from = lb();
duke@1: ListBuffer to = lb();
duke@1: adaptSelf(t, from, to);
duke@1: if (from.isEmpty())
duke@1: return t;
duke@1: ListBuffer rewrite = lb();
duke@1: boolean changed = false;
duke@1: for (Type orig : to.toList()) {
duke@1: Type s = rewriteSupers(orig);
duke@1: if (s.isSuperBound() && !s.isExtendsBound()) {
duke@1: s = new WildcardType(syms.objectType,
duke@1: BoundKind.UNBOUND,
duke@1: syms.boundClass);
duke@1: changed = true;
duke@1: } else if (s != orig) {
duke@1: s = new WildcardType(upperBound(s),
duke@1: BoundKind.EXTENDS,
duke@1: syms.boundClass);
duke@1: changed = true;
duke@1: }
duke@1: rewrite.append(s);
duke@1: }
duke@1: if (changed)
duke@1: return subst(t.tsym.type, from.toList(), rewrite.toList());
duke@1: else
duke@1: return t;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitClassType(ClassType t, Type s) {
duke@1: Type sup = asSuper(t, s.tsym);
duke@1: return sup != null
duke@1: && sup.tsym == s.tsym
duke@1: // You're not allowed to write
duke@1: // Vector
duke@1:
duke@1: //
duke@1: /**
duke@1: * Is t a supertype of s?
duke@1: */
duke@1: public boolean isSuperType(Type t, Type s) {
duke@1: switch (t.tag) {
duke@1: case ERROR:
duke@1: return true;
duke@1: case UNDETVAR: {
duke@1: UndetVar undet = (UndetVar)t;
duke@1: if (t == s ||
duke@1: undet.qtype == s ||
duke@1: s.tag == ERROR ||
duke@1: s.tag == BOT) return true;
mcimadamore@1338: undet.addBound(InferenceBound.LOWER, s, this);
duke@1: return true;
duke@1: }
duke@1: default:
duke@1: return isSubtype(s, t);
duke@1: }
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Are corresponding elements of the lists the same type? If
duke@1: * lists are of different length, return false.
duke@1: */
duke@1: public boolean isSameTypes(List ts, List ss) {
mcimadamore@1550: return isSameTypes(ts, ss, false);
mcimadamore@1550: }
mcimadamore@1550: public boolean isSameTypes(List ts, List ss, boolean strict) {
duke@1: while (ts.tail != null && ss.tail != null
duke@1: /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
mcimadamore@1550: isSameType(ts.head, ss.head, strict)) {
duke@1: ts = ts.tail;
duke@1: ss = ss.tail;
duke@1: }
duke@1: return ts.tail == null && ss.tail == null;
duke@1: /*inlined: ts.isEmpty() && ss.isEmpty();*/
duke@1: }
duke@1:
duke@1: /**
duke@1: * Is t the same type as s?
duke@1: */
duke@1: public boolean isSameType(Type t, Type s) {
mcimadamore@1550: return isSameType(t, s, false);
mcimadamore@1550: }
mcimadamore@1550: public boolean isSameType(Type t, Type s, boolean strict) {
mcimadamore@1550: return strict ?
mcimadamore@1550: isSameTypeStrict.visit(t, s) :
mcimadamore@1550: isSameTypeLoose.visit(t, s);
duke@1: }
duke@1: // where
mcimadamore@1550: abstract class SameTypeVisitor extends TypeRelation {
duke@1:
duke@1: public Boolean visitType(Type t, Type s) {
duke@1: if (t == s)
duke@1: return true;
duke@1:
jjg@1374: if (s.isPartial())
duke@1: return visit(s, t);
duke@1:
duke@1: switch (t.tag) {
duke@1: case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
duke@1: case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
duke@1: return t.tag == s.tag;
mcimadamore@561: case TYPEVAR: {
mcimadamore@561: if (s.tag == TYPEVAR) {
mcimadamore@561: //type-substitution does not preserve type-var types
mcimadamore@561: //check that type var symbols and bounds are indeed the same
mcimadamore@1550: return sameTypeVars((TypeVar)t, (TypeVar)s);
mcimadamore@561: }
mcimadamore@561: else {
mcimadamore@561: //special case for s == ? super X, where upper(s) = u
mcimadamore@561: //check that u == t, where u has been set by Type.withTypeVar
mcimadamore@561: return s.isSuperBound() &&
mcimadamore@561: !s.isExtendsBound() &&
mcimadamore@561: visit(t, upperBound(s));
mcimadamore@561: }
mcimadamore@561: }
duke@1: default:
duke@1: throw new AssertionError("isSameType " + t.tag);
duke@1: }
duke@1: }
duke@1:
mcimadamore@1550: abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
mcimadamore@1550:
duke@1: @Override
duke@1: public Boolean visitWildcardType(WildcardType t, Type s) {
jjg@1374: if (s.isPartial())
duke@1: return visit(s, t);
duke@1: else
duke@1: return false;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitClassType(ClassType t, Type s) {
duke@1: if (t == s)
duke@1: return true;
duke@1:
jjg@1374: if (s.isPartial())
duke@1: return visit(s, t);
duke@1:
duke@1: if (s.isSuperBound() && !s.isExtendsBound())
duke@1: return visit(t, upperBound(s)) && visit(t, lowerBound(s));
duke@1:
duke@1: if (t.isCompound() && s.isCompound()) {
duke@1: if (!visit(supertype(t), supertype(s)))
duke@1: return false;
duke@1:
vromero@1452: HashSet set = new HashSet();
duke@1: for (Type x : interfaces(t))
vromero@1452: set.add(new UniqueType(x, Types.this));
duke@1: for (Type x : interfaces(s)) {
vromero@1452: if (!set.remove(new UniqueType(x, Types.this)))
duke@1: return false;
duke@1: }
jjg@789: return (set.isEmpty());
duke@1: }
duke@1: return t.tsym == s.tsym
duke@1: && visit(t.getEnclosingType(), s.getEnclosingType())
mcimadamore@1550: && containsTypes(t.getTypeArguments(), s.getTypeArguments());
duke@1: }
duke@1:
mcimadamore@1550: abstract protected boolean containsTypes(List ts1, List ts2);
mcimadamore@1550:
duke@1: @Override
duke@1: public Boolean visitArrayType(ArrayType t, Type s) {
duke@1: if (t == s)
duke@1: return true;
duke@1:
jjg@1374: if (s.isPartial())
duke@1: return visit(s, t);
duke@1:
jjg@1374: return s.hasTag(ARRAY)
duke@1: && containsTypeEquivalent(t.elemtype, elemtype(s));
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitMethodType(MethodType t, Type s) {
duke@1: // isSameType for methods does not take thrown
duke@1: // exceptions into account!
duke@1: return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitPackageType(PackageType t, Type s) {
duke@1: return t == s;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitForAll(ForAll t, Type s) {
duke@1: if (s.tag != FORALL)
duke@1: return false;
duke@1:
duke@1: ForAll forAll = (ForAll)s;
duke@1: return hasSameBounds(t, forAll)
duke@1: && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitUndetVar(UndetVar t, Type s) {
duke@1: if (s.tag == WILDCARD)
duke@1: // FIXME, this might be leftovers from before capture conversion
duke@1: return false;
duke@1:
duke@1: if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
duke@1: return true;
duke@1:
mcimadamore@1338: t.addBound(InferenceBound.EQ, s, Types.this);
mcimadamore@1251:
duke@1: return true;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitErrorType(ErrorType t, Type s) {
duke@1: return true;
duke@1: }
mcimadamore@1550: }
mcimadamore@1550:
mcimadamore@1550: /**
mcimadamore@1550: * Standard type-equality relation - type variables are considered
mcimadamore@1550: * equals if they share the same type symbol.
mcimadamore@1550: */
mcimadamore@1550: TypeRelation isSameTypeLoose = new SameTypeVisitor() {
mcimadamore@1550: @Override
mcimadamore@1550: boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
mcimadamore@1550: return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
mcimadamore@1550: }
mcimadamore@1550: @Override
mcimadamore@1550: protected boolean containsTypes(List ts1, List ts2) {
mcimadamore@1550: return containsTypeEquivalent(ts1, ts2);
mcimadamore@1550: }
mcimadamore@1550: };
mcimadamore@1550:
mcimadamore@1550: /**
mcimadamore@1550: * Strict type-equality relation - type variables are considered
mcimadamore@1550: * equals if they share the same object identity.
mcimadamore@1550: */
mcimadamore@1550: TypeRelation isSameTypeStrict = new SameTypeVisitor() {
mcimadamore@1550: @Override
mcimadamore@1550: boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
mcimadamore@1550: return tv1 == tv2;
mcimadamore@1550: }
mcimadamore@1550: @Override
mcimadamore@1550: protected boolean containsTypes(List ts1, List ts2) {
mcimadamore@1550: return isSameTypes(ts1, ts2, true);
mcimadamore@1550: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean containedBy(Type t, Type s) {
duke@1: switch (t.tag) {
duke@1: case UNDETVAR:
duke@1: if (s.tag == WILDCARD) {
duke@1: UndetVar undetvar = (UndetVar)t;
mcimadamore@210: WildcardType wt = (WildcardType)s;
mcimadamore@210: switch(wt.kind) {
mcimadamore@210: case UNBOUND: //similar to ? extends Object
mcimadamore@210: case EXTENDS: {
mcimadamore@210: Type bound = upperBound(s);
mcimadamore@1338: undetvar.addBound(InferenceBound.UPPER, bound, this);
mcimadamore@210: break;
mcimadamore@210: }
mcimadamore@210: case SUPER: {
mcimadamore@210: Type bound = lowerBound(s);
mcimadamore@1338: undetvar.addBound(InferenceBound.LOWER, bound, this);
mcimadamore@210: break;
mcimadamore@210: }
mcimadamore@162: }
duke@1: return true;
duke@1: } else {
duke@1: return isSameType(t, s);
duke@1: }
duke@1: case ERROR:
duke@1: return true;
duke@1: default:
duke@1: return containsType(s, t);
duke@1: }
duke@1: }
duke@1:
duke@1: boolean containsType(List ts, List ss) {
duke@1: while (ts.nonEmpty() && ss.nonEmpty()
duke@1: && containsType(ts.head, ss.head)) {
duke@1: ts = ts.tail;
duke@1: ss = ss.tail;
duke@1: }
duke@1: return ts.isEmpty() && ss.isEmpty();
duke@1: }
duke@1:
duke@1: /**
duke@1: * Check if t contains s.
duke@1: *
duke@1: *
This relation is only used by ClassType.isSubtype(), that
duke@1: * is,
duke@1: *
duke@1: *
{@code C <: C if T contains S.}
duke@1: *
duke@1: *
Because of F-bounds, this relation can lead to infinite
duke@1: * recursion. Thus we must somehow break that recursion. Notice
duke@1: * that containsType() is only called from ClassType.isSubtype().
duke@1: * Since the arguments have already been checked against their
duke@1: * bounds, we know:
duke@1: *
duke@1: *
{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
duke@1: *
duke@1: *
{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
duke@1: *
duke@1: * @param t a type
duke@1: * @param s a type
duke@1: */
duke@1: public boolean containsType(Type t, Type s) {
duke@1: return containsType.visit(t, s);
duke@1: }
duke@1: // where
duke@1: private TypeRelation containsType = new TypeRelation() {
duke@1:
duke@1: private Type U(Type t) {
duke@1: while (t.tag == WILDCARD) {
duke@1: WildcardType w = (WildcardType)t;
duke@1: if (w.isSuperBound())
duke@1: return w.bound == null ? syms.objectType : w.bound.bound;
duke@1: else
duke@1: t = w.type;
duke@1: }
duke@1: return t;
duke@1: }
duke@1:
duke@1: private Type L(Type t) {
duke@1: while (t.tag == WILDCARD) {
duke@1: WildcardType w = (WildcardType)t;
duke@1: if (w.isExtendsBound())
duke@1: return syms.botType;
duke@1: else
duke@1: t = w.type;
duke@1: }
duke@1: return t;
duke@1: }
duke@1:
duke@1: public Boolean visitType(Type t, Type s) {
jjg@1374: if (s.isPartial())
duke@1: return containedBy(s, t);
duke@1: else
duke@1: return isSameType(t, s);
duke@1: }
duke@1:
jjg@789: // void debugContainsType(WildcardType t, Type s) {
jjg@789: // System.err.println();
jjg@789: // System.err.format(" does %s contain %s?%n", t, s);
jjg@789: // System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
jjg@789: // upperBound(s), s, t, U(t),
jjg@789: // t.isSuperBound()
jjg@789: // || isSubtypeNoCapture(upperBound(s), U(t)));
jjg@789: // System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
jjg@789: // L(t), t, s, lowerBound(s),
jjg@789: // t.isExtendsBound()
jjg@789: // || isSubtypeNoCapture(L(t), lowerBound(s)));
jjg@789: // System.err.println();
jjg@789: // }
duke@1:
duke@1: @Override
duke@1: public Boolean visitWildcardType(WildcardType t, Type s) {
jjg@1374: if (s.isPartial())
duke@1: return containedBy(s, t);
duke@1: else {
jjg@789: // debugContainsType(t, s);
duke@1: return isSameWildcard(t, s)
duke@1: || isCaptureOf(s, t)
duke@1: || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
duke@1: (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitUndetVar(UndetVar t, Type s) {
duke@1: if (s.tag != WILDCARD)
duke@1: return isSameType(t, s);
duke@1: else
duke@1: return false;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitErrorType(ErrorType t, Type s) {
duke@1: return true;
duke@1: }
duke@1: };
duke@1:
duke@1: public boolean isCaptureOf(Type s, WildcardType t) {
mcimadamore@79: if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
duke@1: return false;
duke@1: return isSameWildcard(t, ((CapturedType)s).wildcard);
duke@1: }
duke@1:
duke@1: public boolean isSameWildcard(WildcardType t, Type s) {
duke@1: if (s.tag != WILDCARD)
duke@1: return false;
duke@1: WildcardType w = (WildcardType)s;
duke@1: return w.kind == t.kind && w.type == t.type;
duke@1: }
duke@1:
duke@1: public boolean containsTypeEquivalent(List ts, List ss) {
duke@1: while (ts.nonEmpty() && ss.nonEmpty()
duke@1: && containsTypeEquivalent(ts.head, ss.head)) {
duke@1: ts = ts.tail;
duke@1: ss = ss.tail;
duke@1: }
duke@1: return ts.isEmpty() && ss.isEmpty();
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean isCastable(Type t, Type s) {
mcimadamore@1415: return isCastable(t, s, noWarnings);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Is t is castable to s?
duke@1: * s is assumed to be an erased type.
duke@1: * (not defined for Method and ForAll types).
duke@1: */
duke@1: public boolean isCastable(Type t, Type s, Warner warn) {
duke@1: if (t == s)
duke@1: return true;
duke@1:
duke@1: if (t.isPrimitive() != s.isPrimitive())
jjg@984: return allowBoxing && (
jjg@984: isConvertible(t, s, warn)
mcimadamore@1007: || (allowObjectToPrimitiveCast &&
mcimadamore@1007: s.isPrimitive() &&
mcimadamore@1007: isSubtype(boxedClass(s).type, t)));
duke@1: if (warn != warnStack.head) {
duke@1: try {
duke@1: warnStack = warnStack.prepend(warn);
mcimadamore@795: checkUnsafeVarargsConversion(t, s, warn);
mcimadamore@185: return isCastable.visit(t,s);
duke@1: } finally {
duke@1: warnStack = warnStack.tail;
duke@1: }
duke@1: } else {
mcimadamore@185: return isCastable.visit(t,s);
duke@1: }
duke@1: }
duke@1: // where
duke@1: private TypeRelation isCastable = new TypeRelation() {
duke@1:
duke@1: public Boolean visitType(Type t, Type s) {
duke@1: if (s.tag == ERROR)
duke@1: return true;
duke@1:
duke@1: switch (t.tag) {
duke@1: case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
duke@1: case DOUBLE:
jjg@1374: return s.isNumeric();
duke@1: case BOOLEAN:
duke@1: return s.tag == BOOLEAN;
duke@1: case VOID:
duke@1: return false;
duke@1: case BOT:
duke@1: return isSubtype(t, s);
duke@1: default:
duke@1: throw new AssertionError();
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitWildcardType(WildcardType t, Type s) {
duke@1: return isCastable(upperBound(t), s, warnStack.head);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitClassType(ClassType t, Type s) {
duke@1: if (s.tag == ERROR || s.tag == BOT)
duke@1: return true;
duke@1:
duke@1: if (s.tag == TYPEVAR) {
mcimadamore@1415: if (isCastable(t, s.getUpperBound(), noWarnings)) {
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: } else {
duke@1: return false;
duke@1: }
duke@1: }
duke@1:
duke@1: if (t.isCompound()) {
mcimadamore@211: Warner oldWarner = warnStack.head;
mcimadamore@1415: warnStack.head = noWarnings;
duke@1: if (!visit(supertype(t), s))
duke@1: return false;
duke@1: for (Type intf : interfaces(t)) {
duke@1: if (!visit(intf, s))
duke@1: return false;
duke@1: }
mcimadamore@795: if (warnStack.head.hasLint(LintCategory.UNCHECKED))
mcimadamore@795: oldWarner.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: }
duke@1:
duke@1: if (s.isCompound()) {
duke@1: // call recursively to reuse the above code
duke@1: return visitClassType((ClassType)s, t);
duke@1: }
duke@1:
duke@1: if (s.tag == CLASS || s.tag == ARRAY) {
duke@1: boolean upcast;
duke@1: if ((upcast = isSubtype(erasure(t), erasure(s)))
duke@1: || isSubtype(erasure(s), erasure(t))) {
duke@1: if (!upcast && s.tag == ARRAY) {
duke@1: if (!isReifiable(s))
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: } else if (s.isRaw()) {
duke@1: return true;
duke@1: } else if (t.isRaw()) {
duke@1: if (!isUnbounded(s))
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: }
duke@1: // Assume |a| <: |b|
duke@1: final Type a = upcast ? t : s;
duke@1: final Type b = upcast ? s : t;
duke@1: final boolean HIGH = true;
duke@1: final boolean LOW = false;
duke@1: final boolean DONT_REWRITE_TYPEVARS = false;
duke@1: Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
duke@1: Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
duke@1: Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
duke@1: Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
duke@1: Type lowSub = asSub(bLow, aLow.tsym);
duke@1: Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
duke@1: if (highSub == null) {
duke@1: final boolean REWRITE_TYPEVARS = true;
duke@1: aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
duke@1: aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
duke@1: bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
duke@1: bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
duke@1: lowSub = asSub(bLow, aLow.tsym);
duke@1: highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
duke@1: }
duke@1: if (highSub != null) {
jjg@816: if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
jjg@816: Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
jjg@816: }
mcimadamore@185: if (!disjointTypes(aHigh.allparams(), highSub.allparams())
mcimadamore@185: && !disjointTypes(aHigh.allparams(), lowSub.allparams())
mcimadamore@185: && !disjointTypes(aLow.allparams(), highSub.allparams())
mcimadamore@185: && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
mcimadamore@779: if (upcast ? giveWarning(a, b) :
mcimadamore@235: giveWarning(b, a))
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: }
duke@1: }
duke@1: if (isReifiable(s))
duke@1: return isSubtypeUnchecked(a, b);
duke@1: else
duke@1: return isSubtypeUnchecked(a, b, warnStack.head);
duke@1: }
duke@1:
duke@1: // Sidecast
duke@1: if (s.tag == CLASS) {
duke@1: if ((s.tsym.flags() & INTERFACE) != 0) {
duke@1: return ((t.tsym.flags() & FINAL) == 0)
duke@1: ? sideCast(t, s, warnStack.head)
duke@1: : sideCastFinal(t, s, warnStack.head);
duke@1: } else if ((t.tsym.flags() & INTERFACE) != 0) {
duke@1: return ((s.tsym.flags() & FINAL) == 0)
duke@1: ? sideCast(t, s, warnStack.head)
duke@1: : sideCastFinal(t, s, warnStack.head);
duke@1: } else {
duke@1: // unrelated class types
duke@1: return false;
duke@1: }
duke@1: }
duke@1: }
duke@1: return false;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitArrayType(ArrayType t, Type s) {
duke@1: switch (s.tag) {
duke@1: case ERROR:
duke@1: case BOT:
duke@1: return true;
duke@1: case TYPEVAR:
mcimadamore@1415: if (isCastable(s, t, noWarnings)) {
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: } else {
duke@1: return false;
duke@1: }
duke@1: case CLASS:
duke@1: return isSubtype(t, s);
duke@1: case ARRAY:
jjg@1374: if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
duke@1: return elemtype(t).tag == elemtype(s).tag;
duke@1: } else {
duke@1: return visit(elemtype(t), elemtype(s));
duke@1: }
duke@1: default:
duke@1: return false;
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitTypeVar(TypeVar t, Type s) {
duke@1: switch (s.tag) {
duke@1: case ERROR:
duke@1: case BOT:
duke@1: return true;
duke@1: case TYPEVAR:
duke@1: if (isSubtype(t, s)) {
duke@1: return true;
mcimadamore@1415: } else if (isCastable(t.bound, s, noWarnings)) {
mcimadamore@795: warnStack.head.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: } else {
duke@1: return false;
duke@1: }
duke@1: default:
duke@1: return isCastable(t.bound, s, warnStack.head);
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitErrorType(ErrorType t, Type s) {
duke@1: return true;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean disjointTypes(List ts, List ss) {
duke@1: while (ts.tail != null && ss.tail != null) {
duke@1: if (disjointType(ts.head, ss.head)) return true;
duke@1: ts = ts.tail;
duke@1: ss = ss.tail;
duke@1: }
duke@1: return false;
duke@1: }
duke@1:
duke@1: /**
duke@1: * Two types or wildcards are considered disjoint if it can be
duke@1: * proven that no type can be contained in both. It is
duke@1: * conservative in that it is allowed to say that two types are
duke@1: * not disjoint, even though they actually are.
duke@1: *
jjg@1358: * The type {@code C} is castable to {@code C} exactly if
jjg@1358: * {@code X} and {@code Y} are not disjoint.
duke@1: */
duke@1: public boolean disjointType(Type t, Type s) {
duke@1: return disjointType.visit(t, s);
duke@1: }
duke@1: // where
duke@1: private TypeRelation disjointType = new TypeRelation() {
duke@1:
duke@1: private Set cache = new HashSet();
duke@1:
duke@1: public Boolean visitType(Type t, Type s) {
duke@1: if (s.tag == WILDCARD)
duke@1: return visit(s, t);
duke@1: else
duke@1: return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
duke@1: }
duke@1:
duke@1: private boolean isCastableRecursive(Type t, Type s) {
duke@1: TypePair pair = new TypePair(t, s);
duke@1: if (cache.add(pair)) {
duke@1: try {
duke@1: return Types.this.isCastable(t, s);
duke@1: } finally {
duke@1: cache.remove(pair);
duke@1: }
duke@1: } else {
duke@1: return true;
duke@1: }
duke@1: }
duke@1:
duke@1: private boolean notSoftSubtypeRecursive(Type t, Type s) {
duke@1: TypePair pair = new TypePair(t, s);
duke@1: if (cache.add(pair)) {
duke@1: try {
duke@1: return Types.this.notSoftSubtype(t, s);
duke@1: } finally {
duke@1: cache.remove(pair);
duke@1: }
duke@1: } else {
duke@1: return false;
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitWildcardType(WildcardType t, Type s) {
duke@1: if (t.isUnbound())
duke@1: return false;
duke@1:
duke@1: if (s.tag != WILDCARD) {
duke@1: if (t.isExtendsBound())
duke@1: return notSoftSubtypeRecursive(s, t.type);
duke@1: else // isSuperBound()
duke@1: return notSoftSubtypeRecursive(t.type, s);
duke@1: }
duke@1:
duke@1: if (s.isUnbound())
duke@1: return false;
duke@1:
duke@1: if (t.isExtendsBound()) {
duke@1: if (s.isExtendsBound())
duke@1: return !isCastableRecursive(t.type, upperBound(s));
duke@1: else if (s.isSuperBound())
duke@1: return notSoftSubtypeRecursive(lowerBound(s), t.type);
duke@1: } else if (t.isSuperBound()) {
duke@1: if (s.isExtendsBound())
duke@1: return notSoftSubtypeRecursive(t.type, upperBound(s));
duke@1: }
duke@1: return false;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Returns the lower bounds of the formals of a method.
duke@1: */
duke@1: public List lowerBoundArgtypes(Type t) {
mcimadamore@1348: return lowerBounds(t.getParameterTypes());
mcimadamore@1348: }
mcimadamore@1348: public List lowerBounds(List ts) {
mcimadamore@1348: return map(ts, lowerBoundMapping);
duke@1: }
duke@1: private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
duke@1: public Type apply(Type t) {
duke@1: return lowerBound(t);
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * This relation answers the question: is impossible that
duke@1: * something of type `t' can be a subtype of `s'? This is
duke@1: * different from the question "is `t' not a subtype of `s'?"
duke@1: * when type variables are involved: Integer is not a subtype of T
jjg@1358: * where {@code } but it is not true that Integer cannot
duke@1: * possibly be a subtype of T.
duke@1: */
duke@1: public boolean notSoftSubtype(Type t, Type s) {
duke@1: if (t == s) return false;
duke@1: if (t.tag == TYPEVAR) {
duke@1: TypeVar tv = (TypeVar) t;
duke@1: return !isCastable(tv.bound,
mcimadamore@640: relaxBound(s),
mcimadamore@1415: noWarnings);
duke@1: }
duke@1: if (s.tag != WILDCARD)
duke@1: s = upperBound(s);
mcimadamore@640:
mcimadamore@640: return !isSubtype(t, relaxBound(s));
mcimadamore@640: }
mcimadamore@640:
mcimadamore@640: private Type relaxBound(Type t) {
mcimadamore@640: if (t.tag == TYPEVAR) {
mcimadamore@640: while (t.tag == TYPEVAR)
mcimadamore@640: t = t.getUpperBound();
mcimadamore@640: t = rewriteQuantifiers(t, true, true);
mcimadamore@640: }
mcimadamore@640: return t;
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean isReifiable(Type t) {
duke@1: return isReifiable.visit(t);
duke@1: }
duke@1: // where
duke@1: private UnaryVisitor isReifiable = new UnaryVisitor() {
duke@1:
duke@1: public Boolean visitType(Type t, Void ignored) {
duke@1: return true;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitClassType(ClassType t, Void ignored) {
mcimadamore@356: if (t.isCompound())
mcimadamore@356: return false;
mcimadamore@356: else {
mcimadamore@356: if (!t.isParameterized())
mcimadamore@356: return true;
mcimadamore@356:
mcimadamore@356: for (Type param : t.allparams()) {
mcimadamore@356: if (!param.isUnbound())
mcimadamore@356: return false;
mcimadamore@356: }
duke@1: return true;
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitArrayType(ArrayType t, Void ignored) {
duke@1: return visit(t.elemtype);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitTypeVar(TypeVar t, Void ignored) {
duke@1: return false;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean isArray(Type t) {
duke@1: while (t.tag == WILDCARD)
duke@1: t = upperBound(t);
duke@1: return t.tag == ARRAY;
duke@1: }
duke@1:
duke@1: /**
duke@1: * The element type of an array.
duke@1: */
duke@1: public Type elemtype(Type t) {
duke@1: switch (t.tag) {
duke@1: case WILDCARD:
duke@1: return elemtype(upperBound(t));
duke@1: case ARRAY:
jjg@1521: t = t.unannotatedType();
duke@1: return ((ArrayType)t).elemtype;
duke@1: case FORALL:
duke@1: return elemtype(((ForAll)t).qtype);
duke@1: case ERROR:
duke@1: return t;
duke@1: default:
duke@1: return null;
duke@1: }
duke@1: }
duke@1:
mcimadamore@787: public Type elemtypeOrType(Type t) {
mcimadamore@787: Type elemtype = elemtype(t);
mcimadamore@787: return elemtype != null ?
mcimadamore@787: elemtype :
mcimadamore@787: t;
mcimadamore@787: }
mcimadamore@787:
duke@1: /**
duke@1: * Mapping to take element type of an arraytype
duke@1: */
duke@1: private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
duke@1: public Type apply(Type t) { return elemtype(t); }
duke@1: };
duke@1:
duke@1: /**
duke@1: * The number of dimensions of an array type.
duke@1: */
duke@1: public int dimensions(Type t) {
duke@1: int result = 0;
duke@1: while (t.tag == ARRAY) {
duke@1: result++;
duke@1: t = elemtype(t);
duke@1: }
duke@1: return result;
duke@1: }
jfranck@1313:
jfranck@1313: /**
jfranck@1313: * Returns an ArrayType with the component type t
jfranck@1313: *
jfranck@1313: * @param t The component type of the ArrayType
jfranck@1313: * @return the ArrayType for the given component
jfranck@1313: */
jfranck@1313: public ArrayType makeArrayType(Type t) {
jfranck@1313: if (t.tag == VOID ||
jjg@1374: t.tag == PACKAGE) {
jjg@1374: Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
jfranck@1313: }
jfranck@1313: return new ArrayType(t, syms.arrayClass);
jfranck@1313: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Return the (most specific) base type of t that starts with the
duke@1: * given symbol. If none exists, return null.
duke@1: *
duke@1: * @param t a type
duke@1: * @param sym a symbol
duke@1: */
duke@1: public Type asSuper(Type t, Symbol sym) {
duke@1: return asSuper.visit(t, sym);
duke@1: }
duke@1: // where
duke@1: private SimpleVisitor asSuper = new SimpleVisitor() {
duke@1:
duke@1: public Type visitType(Type t, Symbol sym) {
duke@1: return null;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Symbol sym) {
duke@1: if (t.tsym == sym)
duke@1: return t;
duke@1:
duke@1: Type st = supertype(t);
mcimadamore@19: if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
duke@1: Type x = asSuper(st, sym);
duke@1: if (x != null)
duke@1: return x;
duke@1: }
duke@1: if ((sym.flags() & INTERFACE) != 0) {
duke@1: for (List l = interfaces(t); l.nonEmpty(); l = l.tail) {
duke@1: Type x = asSuper(l.head, sym);
duke@1: if (x != null)
duke@1: return x;
duke@1: }
duke@1: }
duke@1: return null;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitArrayType(ArrayType t, Symbol sym) {
duke@1: return isSubtype(t, sym.type) ? sym.type : null;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitTypeVar(TypeVar t, Symbol sym) {
mcimadamore@19: if (t.tsym == sym)
mcimadamore@19: return t;
mcimadamore@19: else
mcimadamore@19: return asSuper(t.bound, sym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Symbol sym) {
duke@1: return t;
duke@1: }
duke@1: };
duke@1:
duke@1: /**
duke@1: * Return the base type of t or any of its outer types that starts
duke@1: * with the given symbol. If none exists, return null.
duke@1: *
duke@1: * @param t a type
duke@1: * @param sym a symbol
duke@1: */
duke@1: public Type asOuterSuper(Type t, Symbol sym) {
duke@1: switch (t.tag) {
duke@1: case CLASS:
duke@1: do {
duke@1: Type s = asSuper(t, sym);
duke@1: if (s != null) return s;
duke@1: t = t.getEnclosingType();
duke@1: } while (t.tag == CLASS);
duke@1: return null;
duke@1: case ARRAY:
duke@1: return isSubtype(t, sym.type) ? sym.type : null;
duke@1: case TYPEVAR:
duke@1: return asSuper(t, sym);
duke@1: case ERROR:
duke@1: return t;
duke@1: default:
duke@1: return null;
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return the base type of t or any of its enclosing types that
duke@1: * starts with the given symbol. If none exists, return null.
duke@1: *
duke@1: * @param t a type
duke@1: * @param sym a symbol
duke@1: */
duke@1: public Type asEnclosingSuper(Type t, Symbol sym) {
duke@1: switch (t.tag) {
duke@1: case CLASS:
duke@1: do {
duke@1: Type s = asSuper(t, sym);
duke@1: if (s != null) return s;
duke@1: Type outer = t.getEnclosingType();
duke@1: t = (outer.tag == CLASS) ? outer :
duke@1: (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
duke@1: Type.noType;
duke@1: } while (t.tag == CLASS);
duke@1: return null;
duke@1: case ARRAY:
duke@1: return isSubtype(t, sym.type) ? sym.type : null;
duke@1: case TYPEVAR:
duke@1: return asSuper(t, sym);
duke@1: case ERROR:
duke@1: return t;
duke@1: default:
duke@1: return null;
duke@1: }
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * The type of given symbol, seen as a member of t.
duke@1: *
duke@1: * @param t a type
duke@1: * @param sym a symbol
duke@1: */
duke@1: public Type memberType(Type t, Symbol sym) {
duke@1: return (sym.flags() & STATIC) != 0
duke@1: ? sym.type
duke@1: : memberType.visit(t, sym);
mcimadamore@341: }
duke@1: // where
duke@1: private SimpleVisitor memberType = new SimpleVisitor() {
duke@1:
duke@1: public Type visitType(Type t, Symbol sym) {
duke@1: return sym.type;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitWildcardType(WildcardType t, Symbol sym) {
duke@1: return memberType(upperBound(t), sym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Symbol sym) {
duke@1: Symbol owner = sym.owner;
duke@1: long flags = sym.flags();
duke@1: if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
duke@1: Type base = asOuterSuper(t, owner);
mcimadamore@134: //if t is an intersection type T = CT & I1 & I2 ... & In
mcimadamore@134: //its supertypes CT, I1, ... In might contain wildcards
mcimadamore@134: //so we need to go through capture conversion
mcimadamore@134: base = t.isCompound() ? capture(base) : base;
duke@1: if (base != null) {
duke@1: List ownerParams = owner.type.allparams();
duke@1: List baseParams = base.allparams();
duke@1: if (ownerParams.nonEmpty()) {
duke@1: if (baseParams.isEmpty()) {
duke@1: // then base is a raw type
duke@1: return erasure(sym.type);
duke@1: } else {
duke@1: return subst(sym.type, ownerParams, baseParams);
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1: return sym.type;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitTypeVar(TypeVar t, Symbol sym) {
duke@1: return memberType(t.bound, sym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Symbol sym) {
duke@1: return t;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: public boolean isAssignable(Type t, Type s) {
mcimadamore@1415: return isAssignable(t, s, noWarnings);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Is t assignable to s?
duke@1: * Equivalent to subtype except for constant values and raw
duke@1: * types.
duke@1: * (not defined for Method and ForAll types)
duke@1: */
duke@1: public boolean isAssignable(Type t, Type s, Warner warn) {
duke@1: if (t.tag == ERROR)
duke@1: return true;
jjg@1374: if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
duke@1: int value = ((Number)t.constValue()).intValue();
duke@1: switch (s.tag) {
duke@1: case BYTE:
duke@1: if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
duke@1: return true;
duke@1: break;
duke@1: case CHAR:
duke@1: if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
duke@1: return true;
duke@1: break;
duke@1: case SHORT:
duke@1: if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
duke@1: return true;
duke@1: break;
duke@1: case INT:
duke@1: return true;
duke@1: case CLASS:
duke@1: switch (unboxedType(s).tag) {
duke@1: case BYTE:
duke@1: case CHAR:
duke@1: case SHORT:
duke@1: return isAssignable(t, unboxedType(s), warn);
duke@1: }
duke@1: break;
duke@1: }
duke@1: }
duke@1: return isConvertible(t, s, warn);
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * The erasure of t {@code |t|} -- the type that results when all
duke@1: * type parameters in t are deleted.
duke@1: */
duke@1: public Type erasure(Type t) {
sundar@1307: return eraseNotNeeded(t)? t : erasure(t, false);
mcimadamore@30: }
mcimadamore@30: //where
sundar@1307: private boolean eraseNotNeeded(Type t) {
sundar@1307: // We don't want to erase primitive types and String type as that
sundar@1307: // operation is idempotent. Also, erasing these could result in loss
sundar@1307: // of information such as constant values attached to such types.
jjg@1374: return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
sundar@1307: }
sundar@1307:
mcimadamore@30: private Type erasure(Type t, boolean recurse) {
jjg@1374: if (t.isPrimitive())
duke@1: return t; /* fast special case */
duke@1: else
mcimadamore@30: return erasure.visit(t, recurse);
mcimadamore@341: }
duke@1: // where
mcimadamore@30: private SimpleVisitor erasure = new SimpleVisitor() {
mcimadamore@30: public Type visitType(Type t, Boolean recurse) {
jjg@1374: if (t.isPrimitive())
duke@1: return t; /*fast special case*/
duke@1: else
mcimadamore@30: return t.map(recurse ? erasureRecFun : erasureFun);
duke@1: }
duke@1:
duke@1: @Override
mcimadamore@30: public Type visitWildcardType(WildcardType t, Boolean recurse) {
mcimadamore@30: return erasure(upperBound(t), recurse);
duke@1: }
duke@1:
duke@1: @Override
mcimadamore@30: public Type visitClassType(ClassType t, Boolean recurse) {
mcimadamore@30: Type erased = t.tsym.erasure(Types.this);
mcimadamore@30: if (recurse) {
mcimadamore@30: erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
mcimadamore@30: }
mcimadamore@30: return erased;
duke@1: }
duke@1:
duke@1: @Override
mcimadamore@30: public Type visitTypeVar(TypeVar t, Boolean recurse) {
mcimadamore@30: return erasure(t.bound, recurse);
duke@1: }
duke@1:
duke@1: @Override
mcimadamore@30: public Type visitErrorType(ErrorType t, Boolean recurse) {
duke@1: return t;
duke@1: }
jjg@1521:
jjg@1521: @Override
jjg@1521: public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
jjg@1563: Type erased = erasure(t.underlyingType, recurse);
jjg@1563: if (erased.getKind() == TypeKind.ANNOTATED) {
jjg@1563: // This can only happen when the underlying type is a
jjg@1563: // type variable and the upper bound of it is annotated.
jjg@1563: // The annotation on the type variable overrides the one
jjg@1563: // on the bound.
jjg@1563: erased = ((AnnotatedType)erased).underlyingType;
jjg@1563: }
jjg@1563: return new AnnotatedType(t.typeAnnotations, erased);
jjg@1521: }
duke@1: };
mcimadamore@30:
duke@1: private Mapping erasureFun = new Mapping ("erasure") {
duke@1: public Type apply(Type t) { return erasure(t); }
duke@1: };
duke@1:
mcimadamore@30: private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
mcimadamore@30: public Type apply(Type t) { return erasureRecursive(t); }
mcimadamore@30: };
mcimadamore@30:
duke@1: public List erasure(List ts) {
duke@1: return Type.map(ts, erasureFun);
duke@1: }
mcimadamore@30:
mcimadamore@30: public Type erasureRecursive(Type t) {
mcimadamore@30: return erasure(t, true);
mcimadamore@30: }
mcimadamore@30:
mcimadamore@30: public List erasureRecursive(List ts) {
mcimadamore@30: return Type.map(ts, erasureRecFun);
mcimadamore@30: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Make a compound type from non-empty list of types
duke@1: *
duke@1: * @param bounds the types from which the compound type is formed
duke@1: * @param supertype is objectType if all bounds are interfaces,
duke@1: * null otherwise.
duke@1: */
mcimadamore@1436: public Type makeCompoundType(List bounds) {
mcimadamore@1436: return makeCompoundType(bounds, bounds.head.tsym.isInterface());
mcimadamore@1436: }
mcimadamore@1436: public Type makeCompoundType(List bounds, boolean allInterfaces) {
mcimadamore@1436: Assert.check(bounds.nonEmpty());
mcimadamore@1436: Type firstExplicitBound = bounds.head;
mcimadamore@1436: if (allInterfaces) {
mcimadamore@1436: bounds = bounds.prepend(syms.objectType);
mcimadamore@1436: }
duke@1: ClassSymbol bc =
duke@1: new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
duke@1: Type.moreInfo
duke@1: ? names.fromString(bounds.toString())
duke@1: : names.empty,
mcimadamore@1436: null,
duke@1: syms.noSymbol);
mcimadamore@1436: bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
mcimadamore@1436: bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
mcimadamore@1436: syms.objectType : // error condition, recover
mcimadamore@1436: erasure(firstExplicitBound);
mcimadamore@1436: bc.members_field = new Scope(bc);
mcimadamore@1436: return bc.type;
duke@1: }
duke@1:
duke@1: /**
duke@1: * A convenience wrapper for {@link #makeCompoundType(List)}; the
duke@1: * arguments are converted to a list and passed to the other
duke@1: * method. Note that this might cause a symbol completion.
duke@1: * Hence, this version of makeCompoundType may not be called
duke@1: * during a classfile read.
duke@1: */
duke@1: public Type makeCompoundType(Type bound1, Type bound2) {
duke@1: return makeCompoundType(List.of(bound1, bound2));
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: public Type supertype(Type t) {
duke@1: return supertype.visit(t);
duke@1: }
duke@1: // where
duke@1: private UnaryVisitor supertype = new UnaryVisitor() {
duke@1:
duke@1: public Type visitType(Type t, Void ignored) {
duke@1: // A note on wildcards: there is no good way to
duke@1: // determine a supertype for a super bounded wildcard.
duke@1: return null;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Void ignored) {
duke@1: if (t.supertype_field == null) {
duke@1: Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
duke@1: // An interface has no superclass; its supertype is Object.
duke@1: if (t.isInterface())
duke@1: supertype = ((ClassType)t.tsym.type).supertype_field;
duke@1: if (t.supertype_field == null) {
duke@1: List actuals = classBound(t).allparams();
duke@1: List formals = t.tsym.type.allparams();
mcimadamore@30: if (t.hasErasedSupertypes()) {
mcimadamore@30: t.supertype_field = erasureRecursive(supertype);
mcimadamore@30: } else if (formals.nonEmpty()) {
duke@1: t.supertype_field = subst(supertype, formals, actuals);
duke@1: }
mcimadamore@30: else {
mcimadamore@30: t.supertype_field = supertype;
mcimadamore@30: }
duke@1: }
duke@1: }
duke@1: return t.supertype_field;
duke@1: }
duke@1:
duke@1: /**
duke@1: * The supertype is always a class type. If the type
duke@1: * variable's bounds start with a class type, this is also
duke@1: * the supertype. Otherwise, the supertype is
duke@1: * java.lang.Object.
duke@1: */
duke@1: @Override
duke@1: public Type visitTypeVar(TypeVar t, Void ignored) {
duke@1: if (t.bound.tag == TYPEVAR ||
duke@1: (!t.bound.isCompound() && !t.bound.isInterface())) {
duke@1: return t.bound;
duke@1: } else {
duke@1: return supertype(t.bound);
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitArrayType(ArrayType t, Void ignored) {
duke@1: if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
duke@1: return arraySuperType();
duke@1: else
duke@1: return new ArrayType(supertype(t.elemtype), t.tsym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Void ignored) {
duke@1: return t;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Return the interfaces implemented by this class.
duke@1: */
duke@1: public List interfaces(Type t) {
duke@1: return interfaces.visit(t);
duke@1: }
duke@1: // where
duke@1: private UnaryVisitor> interfaces = new UnaryVisitor>() {
duke@1:
duke@1: public List visitType(Type t, Void ignored) {
duke@1: return List.nil();
duke@1: }
duke@1:
duke@1: @Override
duke@1: public List visitClassType(ClassType t, Void ignored) {
duke@1: if (t.interfaces_field == null) {
duke@1: List interfaces = ((ClassSymbol)t.tsym).getInterfaces();
duke@1: if (t.interfaces_field == null) {
duke@1: // If t.interfaces_field is null, then t must
duke@1: // be a parameterized type (not to be confused
duke@1: // with a generic type declaration).
duke@1: // Terminology:
duke@1: // Parameterized type: List
duke@1: // Generic type declaration: class List { ... }
duke@1: // So t corresponds to List and
duke@1: // t.tsym.type corresponds to List.
duke@1: // The reason t must be parameterized type is
duke@1: // that completion will happen as a side
duke@1: // effect of calling
duke@1: // ClassSymbol.getInterfaces. Since
duke@1: // t.interfaces_field is null after
duke@1: // completion, we can assume that t is not the
duke@1: // type of a class/interface declaration.
jjg@816: Assert.check(t != t.tsym.type, t);
duke@1: List actuals = t.allparams();
duke@1: List formals = t.tsym.type.allparams();
mcimadamore@30: if (t.hasErasedSupertypes()) {
mcimadamore@30: t.interfaces_field = erasureRecursive(interfaces);
mcimadamore@30: } else if (formals.nonEmpty()) {
duke@1: t.interfaces_field =
duke@1: upperBounds(subst(interfaces, formals, actuals));
duke@1: }
mcimadamore@30: else {
mcimadamore@30: t.interfaces_field = interfaces;
mcimadamore@30: }
duke@1: }
duke@1: }
duke@1: return t.interfaces_field;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public List visitTypeVar(TypeVar t, Void ignored) {
duke@1: if (t.bound.isCompound())
duke@1: return interfaces(t.bound);
duke@1:
duke@1: if (t.bound.isInterface())
duke@1: return List.of(t.bound);
duke@1:
duke@1: return List.nil();
duke@1: }
duke@1: };
mcimadamore@1393:
mcimadamore@1415: public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
mcimadamore@1415: for (Type i2 : interfaces(origin.type)) {
mcimadamore@1415: if (isym == i2.tsym) return true;
mcimadamore@1393: }
mcimadamore@1393: return false;
mcimadamore@1393: }
duke@1: //
duke@1:
duke@1: //
duke@1: Map isDerivedRawCache = new HashMap();
duke@1:
duke@1: public boolean isDerivedRaw(Type t) {
duke@1: Boolean result = isDerivedRawCache.get(t);
duke@1: if (result == null) {
duke@1: result = isDerivedRawInternal(t);
duke@1: isDerivedRawCache.put(t, result);
duke@1: }
duke@1: return result;
duke@1: }
duke@1:
duke@1: public boolean isDerivedRawInternal(Type t) {
duke@1: if (t.isErroneous())
duke@1: return false;
duke@1: return
duke@1: t.isRaw() ||
duke@1: supertype(t) != null && isDerivedRaw(supertype(t)) ||
duke@1: isDerivedRaw(interfaces(t));
duke@1: }
duke@1:
duke@1: public boolean isDerivedRaw(List ts) {
duke@1: List l = ts;
duke@1: while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
duke@1: return l.nonEmpty();
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Set the bounds field of the given type variable to reflect a
duke@1: * (possibly multiple) list of bounds.
duke@1: * @param t a type variable
duke@1: * @param bounds the bounds, must be nonempty
duke@1: * @param supertype is objectType if all bounds are interfaces,
duke@1: * null otherwise.
duke@1: */
mcimadamore@1436: public void setBounds(TypeVar t, List bounds) {
mcimadamore@1436: setBounds(t, bounds, bounds.head.tsym.isInterface());
duke@1: }
duke@1:
duke@1: /**
duke@1: * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
mcimadamore@563: * third parameter is computed directly, as follows: if all
mcimadamore@563: * all bounds are interface types, the computed supertype is Object,
mcimadamore@563: * otherwise the supertype is simply left null (in this case, the supertype
mcimadamore@563: * is assumed to be the head of the bound list passed as second argument).
mcimadamore@563: * Note that this check might cause a symbol completion. Hence, this version of
duke@1: * setBounds may not be called during a classfile read.
duke@1: */
mcimadamore@1436: public void setBounds(TypeVar t, List bounds, boolean allInterfaces) {
mcimadamore@1436: t.bound = bounds.tail.isEmpty() ?
mcimadamore@1436: bounds.head :
mcimadamore@1436: makeCompoundType(bounds, allInterfaces);
duke@1: t.rank_field = -1;
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Return list of bounds of the given type variable.
duke@1: */
duke@1: public List getBounds(TypeVar t) {
mcimadamore@1436: if (t.bound.hasTag(NONE))
mcimadamore@1415: return List.nil();
mcimadamore@1415: else if (t.bound.isErroneous() || !t.bound.isCompound())
duke@1: return List.of(t.bound);
duke@1: else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
duke@1: return interfaces(t).prepend(supertype(t));
duke@1: else
duke@1: // No superclass was given in bounds.
duke@1: // In this case, supertype is Object, erasure is first interface.
duke@1: return interfaces(t);
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * If the given type is a (possibly selected) type variable,
duke@1: * return the bounding class of this type, otherwise return the
duke@1: * type itself.
duke@1: */
duke@1: public Type classBound(Type t) {
duke@1: return classBound.visit(t);
duke@1: }
duke@1: // where
duke@1: private UnaryVisitor classBound = new UnaryVisitor() {
duke@1:
duke@1: public Type visitType(Type t, Void ignored) {
duke@1: return t;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Void ignored) {
duke@1: Type outer1 = classBound(t.getEnclosingType());
duke@1: if (outer1 != t.getEnclosingType())
duke@1: return new ClassType(outer1, t.getTypeArguments(), t.tsym);
duke@1: else
duke@1: return t;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitTypeVar(TypeVar t, Void ignored) {
duke@1: return classBound(supertype(t));
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Void ignored) {
duke@1: return t;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Returns true iff the first signature is a sub
duke@1: * signature of the other. This is not an equivalence
duke@1: * relation.
duke@1: *
jjh@972: * @jls section 8.4.2.
duke@1: * @see #overrideEquivalent(Type t, Type s)
duke@1: * @param t first signature (possibly raw).
duke@1: * @param s second signature (could be subjected to erasure).
duke@1: * @return true if t is a sub signature of s.
duke@1: */
duke@1: public boolean isSubSignature(Type t, Type s) {
mcimadamore@907: return isSubSignature(t, s, true);
mcimadamore@907: }
mcimadamore@907:
mcimadamore@907: public boolean isSubSignature(Type t, Type s, boolean strict) {
mcimadamore@907: return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Returns true iff these signatures are related by override
duke@1: * equivalence. This is the natural extension of
duke@1: * isSubSignature to an equivalence relation.
duke@1: *
jjh@972: * @jls section 8.4.2.
duke@1: * @see #isSubSignature(Type t, Type s)
duke@1: * @param t a signature (possible raw, could be subjected to
duke@1: * erasure).
duke@1: * @param s a signature (possible raw, could be subjected to
duke@1: * erasure).
duke@1: * @return true if either argument is a sub signature of the other.
duke@1: */
duke@1: public boolean overrideEquivalent(Type t, Type s) {
duke@1: return hasSameArgs(t, s) ||
duke@1: hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
duke@1: }
duke@1:
mcimadamore@1348: public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
mcimadamore@1348: for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
mcimadamore@1348: if (msym.overrides(e.sym, origin, Types.this, true)) {
mcimadamore@1348: return true;
mcimadamore@1348: }
mcimadamore@1348: }
mcimadamore@1348: return false;
mcimadamore@1348: }
mcimadamore@1348:
mcimadamore@673: //
mcimadamore@673: class ImplementationCache {
mcimadamore@673:
mcimadamore@673: private WeakHashMap>> _map =
mcimadamore@673: new WeakHashMap>>();
mcimadamore@673:
mcimadamore@673: class Entry {
mcimadamore@673: final MethodSymbol cachedImpl;
mcimadamore@673: final Filter implFilter;
mcimadamore@673: final boolean checkResult;
mcimadamore@877: final int prevMark;
mcimadamore@673:
mcimadamore@673: public Entry(MethodSymbol cachedImpl,
mcimadamore@673: Filter scopeFilter,
mcimadamore@877: boolean checkResult,
mcimadamore@877: int prevMark) {
mcimadamore@673: this.cachedImpl = cachedImpl;
mcimadamore@673: this.implFilter = scopeFilter;
mcimadamore@673: this.checkResult = checkResult;
mcimadamore@877: this.prevMark = prevMark;
mcimadamore@673: }
mcimadamore@673:
mcimadamore@877: boolean matches(Filter scopeFilter, boolean checkResult, int mark) {
mcimadamore@673: return this.implFilter == scopeFilter &&
mcimadamore@877: this.checkResult == checkResult &&
mcimadamore@877: this.prevMark == mark;
mcimadamore@673: }
mcimadamore@341: }
mcimadamore@673:
mcimadamore@858: MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter implFilter) {
mcimadamore@673: SoftReference
mcimadamore@673:
mcimadamore@858: //
mcimadamore@1015: class MembersClosureCache extends SimpleVisitor {
mcimadamore@1015:
mcimadamore@1015: private WeakHashMap _map =
mcimadamore@1015: new WeakHashMap();
mcimadamore@1015:
mcimadamore@1015: class Entry {
mcimadamore@1015: final boolean skipInterfaces;
mcimadamore@1015: final CompoundScope compoundScope;
mcimadamore@1015:
mcimadamore@1015: public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
mcimadamore@1015: this.skipInterfaces = skipInterfaces;
mcimadamore@1015: this.compoundScope = compoundScope;
mcimadamore@1015: }
mcimadamore@1015:
mcimadamore@1015: boolean matches(boolean skipInterfaces) {
mcimadamore@1015: return this.skipInterfaces == skipInterfaces;
mcimadamore@1015: }
mcimadamore@1015: }
mcimadamore@1015:
mcimadamore@1072: List seenTypes = List.nil();
mcimadamore@1072:
mcimadamore@1015: /** members closure visitor methods **/
mcimadamore@1015:
mcimadamore@1015: public CompoundScope visitType(Type t, Boolean skipInterface) {
mcimadamore@858: return null;
mcimadamore@858: }
mcimadamore@858:
mcimadamore@858: @Override
mcimadamore@1015: public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
mcimadamore@1072: if (seenTypes.contains(t.tsym)) {
mcimadamore@1072: //this is possible when an interface is implemented in multiple
mcimadamore@1072: //superclasses, or when a classs hierarchy is circular - in such
mcimadamore@1072: //cases we don't need to recurse (empty scope is returned)
mcimadamore@1072: return new CompoundScope(t.tsym);
mcimadamore@1072: }
mcimadamore@1072: try {
mcimadamore@1072: seenTypes = seenTypes.prepend(t.tsym);
mcimadamore@1072: ClassSymbol csym = (ClassSymbol)t.tsym;
mcimadamore@1072: Entry e = _map.get(csym);
mcimadamore@1072: if (e == null || !e.matches(skipInterface)) {
mcimadamore@1072: CompoundScope membersClosure = new CompoundScope(csym);
mcimadamore@1072: if (!skipInterface) {
mcimadamore@1072: for (Type i : interfaces(t)) {
mcimadamore@1072: membersClosure.addSubScope(visit(i, skipInterface));
mcimadamore@1072: }
mcimadamore@1015: }
mcimadamore@1072: membersClosure.addSubScope(visit(supertype(t), skipInterface));
mcimadamore@1072: membersClosure.addSubScope(csym.members());
mcimadamore@1072: e = new Entry(skipInterface, membersClosure);
mcimadamore@1072: _map.put(csym, e);
mcimadamore@858: }
mcimadamore@1072: return e.compoundScope;
mcimadamore@858: }
mcimadamore@1072: finally {
mcimadamore@1072: seenTypes = seenTypes.tail;
mcimadamore@1072: }
mcimadamore@858: }
mcimadamore@858:
mcimadamore@858: @Override
mcimadamore@1015: public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
mcimadamore@1015: return visit(t.getUpperBound(), skipInterface);
mcimadamore@858: }
mcimadamore@1015: }
mcimadamore@1015:
mcimadamore@1015: private MembersClosureCache membersCache = new MembersClosureCache();
mcimadamore@1015:
mcimadamore@1015: public CompoundScope membersClosure(Type site, boolean skipInterface) {
mcimadamore@1015: return membersCache.visit(site, skipInterface);
mcimadamore@1015: }
mcimadamore@858: //
mcimadamore@858:
mcimadamore@1393:
mcimadamore@1393: //where
mcimadamore@1393: public List interfaceCandidates(Type site, MethodSymbol ms) {
mcimadamore@1415: Filter filter = new MethodFilter(ms, site);
mcimadamore@1393: List candidates = List.nil();
mcimadamore@1393: for (Symbol s : membersClosure(site, false).getElements(filter)) {
mcimadamore@1393: if (!site.tsym.isInterface() && !s.owner.isInterface()) {
mcimadamore@1393: return List.of((MethodSymbol)s);
mcimadamore@1393: } else if (!candidates.contains(s)) {
mcimadamore@1393: candidates = candidates.prepend((MethodSymbol)s);
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1582: return prune(candidates);
mcimadamore@1393: }
mcimadamore@1393:
mcimadamore@1582: public List prune(List methods) {
mcimadamore@1393: ListBuffer methodsMin = ListBuffer.lb();
mcimadamore@1393: for (MethodSymbol m1 : methods) {
mcimadamore@1393: boolean isMin_m1 = true;
mcimadamore@1393: for (MethodSymbol m2 : methods) {
mcimadamore@1393: if (m1 == m2) continue;
mcimadamore@1582: if (m2.owner != m1.owner &&
mcimadamore@1582: asSuper(m2.owner.type, m1.owner) != null) {
mcimadamore@1393: isMin_m1 = false;
mcimadamore@1393: break;
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: if (isMin_m1)
mcimadamore@1393: methodsMin.append(m1);
mcimadamore@1393: }
mcimadamore@1393: return methodsMin.toList();
mcimadamore@1393: }
mcimadamore@1393: // where
mcimadamore@1393: private class MethodFilter implements Filter {
mcimadamore@1393:
mcimadamore@1393: Symbol msym;
mcimadamore@1393: Type site;
mcimadamore@1415:
mcimadamore@1415: MethodFilter(Symbol msym, Type site) {
mcimadamore@1393: this.msym = msym;
mcimadamore@1393: this.site = site;
mcimadamore@1393: }
mcimadamore@1393:
mcimadamore@1393: public boolean accepts(Symbol s) {
mcimadamore@1393: return s.kind == Kinds.MTH &&
mcimadamore@1393: s.name == msym.name &&
mcimadamore@1393: s.isInheritedIn(site.tsym, Types.this) &&
mcimadamore@1393: overrideEquivalent(memberType(site, s), memberType(site, msym));
mcimadamore@1393: }
mcimadamore@1393: };
mcimadamore@1393: //
mcimadamore@1393:
duke@1: /**
duke@1: * Does t have the same arguments as s? It is assumed that both
duke@1: * types are (possibly polymorphic) method types. Monomorphic
duke@1: * method types "have the same arguments", if their argument lists
duke@1: * are equal. Polymorphic method types "have the same arguments",
duke@1: * if they have the same arguments after renaming all type
duke@1: * variables of one to corresponding type variables in the other,
duke@1: * where correspondence is by position in the type parameter list.
duke@1: */
duke@1: public boolean hasSameArgs(Type t, Type s) {
mcimadamore@907: return hasSameArgs(t, s, true);
mcimadamore@907: }
mcimadamore@907:
mcimadamore@907: public boolean hasSameArgs(Type t, Type s, boolean strict) {
mcimadamore@907: return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
mcimadamore@907: }
mcimadamore@907:
mcimadamore@907: private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
duke@1: return hasSameArgs.visit(t, s);
duke@1: }
duke@1: // where
mcimadamore@907: private class HasSameArgs extends TypeRelation {
mcimadamore@907:
mcimadamore@907: boolean strict;
mcimadamore@907:
mcimadamore@907: public HasSameArgs(boolean strict) {
mcimadamore@907: this.strict = strict;
mcimadamore@907: }
duke@1:
duke@1: public Boolean visitType(Type t, Type s) {
duke@1: throw new AssertionError();
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitMethodType(MethodType t, Type s) {
duke@1: return s.tag == METHOD
duke@1: && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitForAll(ForAll t, Type s) {
duke@1: if (s.tag != FORALL)
mcimadamore@907: return strict ? false : visitMethodType(t.asMethodType(), s);
duke@1:
duke@1: ForAll forAll = (ForAll)s;
duke@1: return hasSameBounds(t, forAll)
duke@1: && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Boolean visitErrorType(ErrorType t, Type s) {
duke@1: return false;
duke@1: }
duke@1: };
mcimadamore@907:
mcimadamore@907: TypeRelation hasSameArgs_strict = new HasSameArgs(true);
mcimadamore@907: TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
mcimadamore@907:
duke@1: //
duke@1:
duke@1: //
duke@1: public List subst(List ts,
duke@1: List from,
duke@1: List to) {
duke@1: return new Subst(from, to).subst(ts);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Substitute all occurrences of a type in `from' with the
duke@1: * corresponding type in `to' in 't'. Match lists `from' and `to'
duke@1: * from the right: If lists have different length, discard leading
duke@1: * elements of the longer list.
duke@1: */
duke@1: public Type subst(Type t, List from, List to) {
duke@1: return new Subst(from, to).subst(t);
duke@1: }
duke@1:
duke@1: private class Subst extends UnaryVisitor {
duke@1: List from;
duke@1: List to;
duke@1:
duke@1: public Subst(List from, List to) {
duke@1: int fromLength = from.length();
duke@1: int toLength = to.length();
duke@1: while (fromLength > toLength) {
duke@1: fromLength--;
duke@1: from = from.tail;
duke@1: }
duke@1: while (fromLength < toLength) {
duke@1: toLength--;
duke@1: to = to.tail;
duke@1: }
duke@1: this.from = from;
duke@1: this.to = to;
duke@1: }
duke@1:
duke@1: Type subst(Type t) {
duke@1: if (from.tail == null)
duke@1: return t;
duke@1: else
duke@1: return visit(t);
mcimadamore@238: }
duke@1:
duke@1: List subst(List ts) {
duke@1: if (from.tail == null)
duke@1: return ts;
duke@1: boolean wild = false;
duke@1: if (ts.nonEmpty() && from.nonEmpty()) {
duke@1: Type head1 = subst(ts.head);
duke@1: List tail1 = subst(ts.tail);
duke@1: if (head1 != ts.head || tail1 != ts.tail)
duke@1: return tail1.prepend(head1);
duke@1: }
duke@1: return ts;
duke@1: }
duke@1:
duke@1: public Type visitType(Type t, Void ignored) {
duke@1: return t;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitMethodType(MethodType t, Void ignored) {
duke@1: List argtypes = subst(t.argtypes);
duke@1: Type restype = subst(t.restype);
duke@1: List thrown = subst(t.thrown);
duke@1: if (argtypes == t.argtypes &&
duke@1: restype == t.restype &&
duke@1: thrown == t.thrown)
duke@1: return t;
duke@1: else
duke@1: return new MethodType(argtypes, restype, thrown, t.tsym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitTypeVar(TypeVar t, Void ignored) {
duke@1: for (List from = this.from, to = this.to;
duke@1: from.nonEmpty();
duke@1: from = from.tail, to = to.tail) {
duke@1: if (t == from.head) {
duke@1: return to.head.withTypeVar(t);
duke@1: }
duke@1: }
duke@1: return t;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitClassType(ClassType t, Void ignored) {
duke@1: if (!t.isCompound()) {
duke@1: List typarams = t.getTypeArguments();
duke@1: List typarams1 = subst(typarams);
duke@1: Type outer = t.getEnclosingType();
duke@1: Type outer1 = subst(outer);
duke@1: if (typarams1 == typarams && outer1 == outer)
duke@1: return t;
duke@1: else
duke@1: return new ClassType(outer1, typarams1, t.tsym);
duke@1: } else {
duke@1: Type st = subst(supertype(t));
duke@1: List is = upperBounds(subst(interfaces(t)));
duke@1: if (st == supertype(t) && is == interfaces(t))
duke@1: return t;
duke@1: else
duke@1: return makeCompoundType(is.prepend(st));
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitWildcardType(WildcardType t, Void ignored) {
duke@1: Type bound = t.type;
duke@1: if (t.kind != BoundKind.UNBOUND)
duke@1: bound = subst(bound);
duke@1: if (bound == t.type) {
duke@1: return t;
duke@1: } else {
duke@1: if (t.isExtendsBound() && bound.isExtendsBound())
duke@1: bound = upperBound(bound);
duke@1: return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitArrayType(ArrayType t, Void ignored) {
duke@1: Type elemtype = subst(t.elemtype);
duke@1: if (elemtype == t.elemtype)
duke@1: return t;
duke@1: else
mcimadamore@996: return new ArrayType(upperBound(elemtype), t.tsym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitForAll(ForAll t, Void ignored) {
mcimadamore@846: if (Type.containsAny(to, t.tvars)) {
mcimadamore@846: //perform alpha-renaming of free-variables in 't'
mcimadamore@846: //if 'to' types contain variables that are free in 't'
mcimadamore@846: List freevars = newInstances(t.tvars);
mcimadamore@846: t = new ForAll(freevars,
mcimadamore@846: Types.this.subst(t.qtype, t.tvars, freevars));
mcimadamore@846: }
duke@1: List tvars1 = substBounds(t.tvars, from, to);
duke@1: Type qtype1 = subst(t.qtype);
duke@1: if (tvars1 == t.tvars && qtype1 == t.qtype) {
duke@1: return t;
duke@1: } else if (tvars1 == t.tvars) {
duke@1: return new ForAll(tvars1, qtype1);
duke@1: } else {
duke@1: return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
duke@1: }
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Type visitErrorType(ErrorType t, Void ignored) {
duke@1: return t;
duke@1: }
duke@1: }
duke@1:
duke@1: public List substBounds(List tvars,
duke@1: List from,
duke@1: List to) {
duke@1: if (tvars.isEmpty())
duke@1: return tvars;
duke@1: ListBuffer newBoundsBuf = lb();
duke@1: boolean changed = false;
duke@1: // calculate new bounds
duke@1: for (Type t : tvars) {
duke@1: TypeVar tv = (TypeVar) t;
duke@1: Type bound = subst(tv.bound, from, to);
duke@1: if (bound != tv.bound)
duke@1: changed = true;
duke@1: newBoundsBuf.append(bound);
duke@1: }
duke@1: if (!changed)
duke@1: return tvars;
duke@1: ListBuffer newTvars = lb();
duke@1: // create new type variables without bounds
duke@1: for (Type t : tvars) {
duke@1: newTvars.append(new TypeVar(t.tsym, null, syms.botType));
duke@1: }
duke@1: // the new bounds should use the new type variables in place
duke@1: // of the old
duke@1: List newBounds = newBoundsBuf.toList();
duke@1: from = tvars;
duke@1: to = newTvars.toList();
duke@1: for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
duke@1: newBounds.head = subst(newBounds.head, from, to);
duke@1: }
duke@1: newBounds = newBoundsBuf.toList();
duke@1: // set the bounds of new type variables to the new bounds
duke@1: for (Type t : newTvars.toList()) {
duke@1: TypeVar tv = (TypeVar) t;
duke@1: tv.bound = newBounds.head;
duke@1: newBounds = newBounds.tail;
duke@1: }
duke@1: return newTvars.toList();
duke@1: }
duke@1:
duke@1: public TypeVar substBound(TypeVar t, List from, List to) {
duke@1: Type bound1 = subst(t.bound, from, to);
duke@1: if (bound1 == t.bound)
duke@1: return t;
mcimadamore@212: else {
mcimadamore@212: // create new type variable without bounds
mcimadamore@212: TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
mcimadamore@212: // the new bound should use the new type variable in place
mcimadamore@212: // of the old
mcimadamore@212: tv.bound = subst(bound1, List.of(t), List.of(tv));
mcimadamore@212: return tv;
mcimadamore@212: }
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Does t have the same bounds for quantified variables as s?
duke@1: */
duke@1: boolean hasSameBounds(ForAll t, ForAll s) {
duke@1: List l1 = t.tvars;
duke@1: List l2 = s.tvars;
duke@1: while (l1.nonEmpty() && l2.nonEmpty() &&
duke@1: isSameType(l1.head.getUpperBound(),
duke@1: subst(l2.head.getUpperBound(),
duke@1: s.tvars,
duke@1: t.tvars))) {
duke@1: l1 = l1.tail;
duke@1: l2 = l2.tail;
duke@1: }
duke@1: return l1.isEmpty() && l2.isEmpty();
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /** Create new vector of type variables from list of variables
duke@1: * changing all recursive bounds from old to new list.
duke@1: */
duke@1: public List newInstances(List tvars) {
duke@1: List tvars1 = Type.map(tvars, newInstanceFun);
duke@1: for (List l = tvars1; l.nonEmpty(); l = l.tail) {
duke@1: TypeVar tv = (TypeVar) l.head;
duke@1: tv.bound = subst(tv.bound, tvars, tvars1);
duke@1: }
duke@1: return tvars1;
duke@1: }
vromero@1442: private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
duke@1: public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
duke@1: };
duke@1: //
duke@1:
dlsmith@880: public Type createMethodTypeWithParameters(Type original, List newParams) {
dlsmith@880: return original.accept(methodWithParameters, newParams);
dlsmith@880: }
dlsmith@880: // where
dlsmith@880: private final MapVisitor> methodWithParameters = new MapVisitor>() {
dlsmith@880: public Type visitType(Type t, List newParams) {
dlsmith@880: throw new IllegalArgumentException("Not a method type: " + t);
dlsmith@880: }
dlsmith@880: public Type visitMethodType(MethodType t, List newParams) {
dlsmith@880: return new MethodType(newParams, t.restype, t.thrown, t.tsym);
dlsmith@880: }
dlsmith@880: public Type visitForAll(ForAll t, List newParams) {
dlsmith@880: return new ForAll(t.tvars, t.qtype.accept(this, newParams));
dlsmith@880: }
dlsmith@880: };
dlsmith@880:
dlsmith@880: public Type createMethodTypeWithThrown(Type original, List newThrown) {
dlsmith@880: return original.accept(methodWithThrown, newThrown);
dlsmith@880: }
dlsmith@880: // where
dlsmith@880: private final MapVisitor> methodWithThrown = new MapVisitor>() {
dlsmith@880: public Type visitType(Type t, List newThrown) {
dlsmith@880: throw new IllegalArgumentException("Not a method type: " + t);
dlsmith@880: }
dlsmith@880: public Type visitMethodType(MethodType t, List newThrown) {
dlsmith@880: return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
dlsmith@880: }
dlsmith@880: public Type visitForAll(ForAll t, List newThrown) {
dlsmith@880: return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
dlsmith@880: }
dlsmith@880: };
dlsmith@880:
mcimadamore@950: public Type createMethodTypeWithReturn(Type original, Type newReturn) {
mcimadamore@950: return original.accept(methodWithReturn, newReturn);
mcimadamore@950: }
mcimadamore@950: // where
mcimadamore@950: private final MapVisitor methodWithReturn = new MapVisitor() {
mcimadamore@950: public Type visitType(Type t, Type newReturn) {
mcimadamore@950: throw new IllegalArgumentException("Not a method type: " + t);
mcimadamore@950: }
mcimadamore@950: public Type visitMethodType(MethodType t, Type newReturn) {
mcimadamore@950: return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
mcimadamore@950: }
mcimadamore@950: public Type visitForAll(ForAll t, Type newReturn) {
mcimadamore@950: return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
mcimadamore@950: }
mcimadamore@950: };
mcimadamore@950:
jjg@110: //
jjg@110: public Type createErrorType(Type originalType) {
jjg@110: return new ErrorType(originalType, syms.errSymbol);
jjg@110: }
jjg@110:
jjg@110: public Type createErrorType(ClassSymbol c, Type originalType) {
jjg@110: return new ErrorType(c, originalType);
jjg@110: }
jjg@110:
jjg@110: public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
jjg@110: return new ErrorType(name, container, originalType);
jjg@110: }
jjg@110: //
jjg@110:
duke@1: //
duke@1: /**
duke@1: * The rank of a class is the length of the longest path between
duke@1: * the class and java.lang.Object in the class inheritance
duke@1: * graph. Undefined for all but reference types.
duke@1: */
duke@1: public int rank(Type t) {
jjg@1521: t = t.unannotatedType();
duke@1: switch(t.tag) {
duke@1: case CLASS: {
duke@1: ClassType cls = (ClassType)t;
duke@1: if (cls.rank_field < 0) {
duke@1: Name fullname = cls.tsym.getQualifiedName();
jjg@113: if (fullname == names.java_lang_Object)
duke@1: cls.rank_field = 0;
duke@1: else {
duke@1: int r = rank(supertype(cls));
duke@1: for (List l = interfaces(cls);
duke@1: l.nonEmpty();
duke@1: l = l.tail) {
duke@1: if (rank(l.head) > r)
duke@1: r = rank(l.head);
duke@1: }
duke@1: cls.rank_field = r + 1;
duke@1: }
duke@1: }
duke@1: return cls.rank_field;
duke@1: }
duke@1: case TYPEVAR: {
duke@1: TypeVar tvar = (TypeVar)t;
duke@1: if (tvar.rank_field < 0) {
duke@1: int r = rank(supertype(tvar));
duke@1: for (List l = interfaces(tvar);
duke@1: l.nonEmpty();
duke@1: l = l.tail) {
duke@1: if (rank(l.head) > r) r = rank(l.head);
duke@1: }
duke@1: tvar.rank_field = r + 1;
duke@1: }
duke@1: return tvar.rank_field;
duke@1: }
duke@1: case ERROR:
duke@1: return 0;
duke@1: default:
duke@1: throw new AssertionError();
duke@1: }
duke@1: }
duke@1: //
duke@1:
mcimadamore@121: /**
mcimadamore@238: * Helper method for generating a string representation of a given type
mcimadamore@121: * accordingly to a given locale
mcimadamore@121: */
mcimadamore@121: public String toString(Type t, Locale locale) {
mcimadamore@238: return Printer.createStandardPrinter(messages).visit(t, locale);
mcimadamore@121: }
mcimadamore@121:
mcimadamore@121: /**
mcimadamore@238: * Helper method for generating a string representation of a given type
mcimadamore@121: * accordingly to a given locale
mcimadamore@121: */
mcimadamore@121: public String toString(Symbol t, Locale locale) {
mcimadamore@238: return Printer.createStandardPrinter(messages).visit(t, locale);
mcimadamore@121: }
mcimadamore@121:
duke@1: //
duke@1: /**
duke@1: * This toString is slightly more descriptive than the one on Type.
mcimadamore@121: *
mcimadamore@121: * @deprecated Types.toString(Type t, Locale l) provides better support
mcimadamore@121: * for localization
duke@1: */
mcimadamore@121: @Deprecated
duke@1: public String toString(Type t) {
duke@1: if (t.tag == FORALL) {
duke@1: ForAll forAll = (ForAll)t;
duke@1: return typaramsString(forAll.tvars) + forAll.qtype;
duke@1: }
duke@1: return "" + t;
duke@1: }
duke@1: // where
duke@1: private String typaramsString(List tvars) {
jjg@904: StringBuilder s = new StringBuilder();
duke@1: s.append('<');
duke@1: boolean first = true;
duke@1: for (Type t : tvars) {
duke@1: if (!first) s.append(", ");
duke@1: first = false;
duke@1: appendTyparamString(((TypeVar)t), s);
duke@1: }
duke@1: s.append('>');
duke@1: return s.toString();
duke@1: }
jjg@904: private void appendTyparamString(TypeVar t, StringBuilder buf) {
duke@1: buf.append(t);
duke@1: if (t.bound == null ||
duke@1: t.bound.tsym.getQualifiedName() == names.java_lang_Object)
duke@1: return;
duke@1: buf.append(" extends "); // Java syntax; no need for i18n
duke@1: Type bound = t.bound;
duke@1: if (!bound.isCompound()) {
duke@1: buf.append(bound);
duke@1: } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
duke@1: buf.append(supertype(t));
duke@1: for (Type intf : interfaces(t)) {
duke@1: buf.append('&');
duke@1: buf.append(intf);
duke@1: }
duke@1: } else {
duke@1: // No superclass was given in bounds.
duke@1: // In this case, supertype is Object, erasure is first interface.
duke@1: boolean first = true;
duke@1: for (Type intf : interfaces(t)) {
duke@1: if (!first) buf.append('&');
duke@1: first = false;
duke@1: buf.append(intf);
duke@1: }
duke@1: }
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * A cache for closures.
duke@1: *
duke@1: *
A closure is a list of all the supertypes and interfaces of
duke@1: * a class or interface type, ordered by ClassSymbol.precedes
duke@1: * (that is, subclasses come first, arbitrary but fixed
duke@1: * otherwise).
duke@1: */
duke@1: private Map> closureCache = new HashMap>();
duke@1:
duke@1: /**
duke@1: * Returns the closure of a class or interface type.
duke@1: */
duke@1: public List closure(Type t) {
duke@1: List cl = closureCache.get(t);
duke@1: if (cl == null) {
duke@1: Type st = supertype(t);
duke@1: if (!t.isCompound()) {
duke@1: if (st.tag == CLASS) {
duke@1: cl = insert(closure(st), t);
duke@1: } else if (st.tag == TYPEVAR) {
duke@1: cl = closure(st).prepend(t);
duke@1: } else {
duke@1: cl = List.of(t);
duke@1: }
duke@1: } else {
duke@1: cl = closure(supertype(t));
duke@1: }
duke@1: for (List l = interfaces(t); l.nonEmpty(); l = l.tail)
duke@1: cl = union(cl, closure(l.head));
duke@1: closureCache.put(t, cl);
duke@1: }
duke@1: return cl;
duke@1: }
duke@1:
duke@1: /**
duke@1: * Insert a type in a closure
duke@1: */
duke@1: public List insert(List cl, Type t) {
duke@1: if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
duke@1: return cl.prepend(t);
duke@1: } else if (cl.head.tsym.precedes(t.tsym, this)) {
duke@1: return insert(cl.tail, t).prepend(cl.head);
duke@1: } else {
duke@1: return cl;
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Form the union of two closures
duke@1: */
duke@1: public List union(List cl1, List cl2) {
duke@1: if (cl1.isEmpty()) {
duke@1: return cl2;
duke@1: } else if (cl2.isEmpty()) {
duke@1: return cl1;
duke@1: } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
duke@1: return union(cl1.tail, cl2).prepend(cl1.head);
duke@1: } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
duke@1: return union(cl1, cl2.tail).prepend(cl2.head);
duke@1: } else {
duke@1: return union(cl1.tail, cl2.tail).prepend(cl1.head);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Intersect two closures
duke@1: */
duke@1: public List intersect(List cl1, List cl2) {
duke@1: if (cl1 == cl2)
duke@1: return cl1;
duke@1: if (cl1.isEmpty() || cl2.isEmpty())
duke@1: return List.nil();
duke@1: if (cl1.head.tsym.precedes(cl2.head.tsym, this))
duke@1: return intersect(cl1.tail, cl2);
duke@1: if (cl2.head.tsym.precedes(cl1.head.tsym, this))
duke@1: return intersect(cl1, cl2.tail);
duke@1: if (isSameType(cl1.head, cl2.head))
duke@1: return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
duke@1: if (cl1.head.tsym == cl2.head.tsym &&
duke@1: cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
duke@1: if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
duke@1: Type merge = merge(cl1.head,cl2.head);
duke@1: return intersect(cl1.tail, cl2.tail).prepend(merge);
duke@1: }
duke@1: if (cl1.head.isRaw() || cl2.head.isRaw())
duke@1: return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
duke@1: }
duke@1: return intersect(cl1.tail, cl2.tail);
duke@1: }
duke@1: // where
duke@1: class TypePair {
duke@1: final Type t1;
duke@1: final Type t2;
duke@1: TypePair(Type t1, Type t2) {
duke@1: this.t1 = t1;
duke@1: this.t2 = t2;
duke@1: }
duke@1: @Override
duke@1: public int hashCode() {
vromero@1452: return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
duke@1: }
duke@1: @Override
duke@1: public boolean equals(Object obj) {
duke@1: if (!(obj instanceof TypePair))
duke@1: return false;
duke@1: TypePair typePair = (TypePair)obj;
duke@1: return isSameType(t1, typePair.t1)
duke@1: && isSameType(t2, typePair.t2);
duke@1: }
duke@1: }
duke@1: Set mergeCache = new HashSet();
duke@1: private Type merge(Type c1, Type c2) {
duke@1: ClassType class1 = (ClassType) c1;
duke@1: List act1 = class1.getTypeArguments();
duke@1: ClassType class2 = (ClassType) c2;
duke@1: List act2 = class2.getTypeArguments();
duke@1: ListBuffer merged = new ListBuffer();
duke@1: List typarams = class1.tsym.type.getTypeArguments();
duke@1:
duke@1: while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
duke@1: if (containsType(act1.head, act2.head)) {
duke@1: merged.append(act1.head);
duke@1: } else if (containsType(act2.head, act1.head)) {
duke@1: merged.append(act2.head);
duke@1: } else {
duke@1: TypePair pair = new TypePair(c1, c2);
duke@1: Type m;
duke@1: if (mergeCache.add(pair)) {
duke@1: m = new WildcardType(lub(upperBound(act1.head),
duke@1: upperBound(act2.head)),
duke@1: BoundKind.EXTENDS,
duke@1: syms.boundClass);
duke@1: mergeCache.remove(pair);
duke@1: } else {
duke@1: m = new WildcardType(syms.objectType,
duke@1: BoundKind.UNBOUND,
duke@1: syms.boundClass);
duke@1: }
duke@1: merged.append(m.withTypeVar(typarams.head));
duke@1: }
duke@1: act1 = act1.tail;
duke@1: act2 = act2.tail;
duke@1: typarams = typarams.tail;
duke@1: }
jjg@816: Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
duke@1: return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return the minimum type of a closure, a compound type if no
duke@1: * unique minimum exists.
duke@1: */
duke@1: private Type compoundMin(List cl) {
duke@1: if (cl.isEmpty()) return syms.objectType;
duke@1: List compound = closureMin(cl);
duke@1: if (compound.isEmpty())
duke@1: return null;
duke@1: else if (compound.tail.isEmpty())
duke@1: return compound.head;
duke@1: else
duke@1: return makeCompoundType(compound);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return the minimum types of a closure, suitable for computing
duke@1: * compoundMin or glb.
duke@1: */
duke@1: private List closureMin(List cl) {
duke@1: ListBuffer classes = lb();
duke@1: ListBuffer interfaces = lb();
duke@1: while (!cl.isEmpty()) {
duke@1: Type current = cl.head;
duke@1: if (current.isInterface())
duke@1: interfaces.append(current);
duke@1: else
duke@1: classes.append(current);
duke@1: ListBuffer candidates = lb();
duke@1: for (Type t : cl.tail) {
duke@1: if (!isSubtypeNoCapture(current, t))
duke@1: candidates.append(t);
duke@1: }
duke@1: cl = candidates.toList();
duke@1: }
duke@1: return classes.appendList(interfaces).toList();
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return the least upper bound of pair of types. if the lub does
duke@1: * not exist return null.
duke@1: */
duke@1: public Type lub(Type t1, Type t2) {
duke@1: return lub(List.of(t1, t2));
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return the least upper bound (lub) of set of types. If the lub
duke@1: * does not exist return the type of null (bottom).
duke@1: */
duke@1: public Type lub(List ts) {
duke@1: final int ARRAY_BOUND = 1;
duke@1: final int CLASS_BOUND = 2;
duke@1: int boundkind = 0;
duke@1: for (Type t : ts) {
duke@1: switch (t.tag) {
duke@1: case CLASS:
duke@1: boundkind |= CLASS_BOUND;
duke@1: break;
duke@1: case ARRAY:
duke@1: boundkind |= ARRAY_BOUND;
duke@1: break;
duke@1: case TYPEVAR:
duke@1: do {
duke@1: t = t.getUpperBound();
duke@1: } while (t.tag == TYPEVAR);
duke@1: if (t.tag == ARRAY) {
duke@1: boundkind |= ARRAY_BOUND;
duke@1: } else {
duke@1: boundkind |= CLASS_BOUND;
duke@1: }
duke@1: break;
duke@1: default:
duke@1: if (t.isPrimitive())
mcimadamore@5: return syms.errType;
duke@1: }
duke@1: }
duke@1: switch (boundkind) {
duke@1: case 0:
duke@1: return syms.botType;
duke@1:
duke@1: case ARRAY_BOUND:
duke@1: // calculate lub(A[], B[])
duke@1: List elements = Type.map(ts, elemTypeFun);
duke@1: for (Type t : elements) {
duke@1: if (t.isPrimitive()) {
duke@1: // if a primitive type is found, then return
duke@1: // arraySuperType unless all the types are the
duke@1: // same
duke@1: Type first = ts.head;
duke@1: for (Type s : ts.tail) {
duke@1: if (!isSameType(first, s)) {
duke@1: // lub(int[], B[]) is Cloneable & Serializable
duke@1: return arraySuperType();
duke@1: }
duke@1: }
duke@1: // all the array types are the same, return one
duke@1: // lub(int[], int[]) is int[]
duke@1: return first;
duke@1: }
duke@1: }
duke@1: // lub(A[], B[]) is lub(A, B)[]
duke@1: return new ArrayType(lub(elements), syms.arrayClass);
duke@1:
duke@1: case CLASS_BOUND:
duke@1: // calculate lub(A, B)
duke@1: while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
duke@1: ts = ts.tail;
jjg@816: Assert.check(!ts.isEmpty());
mcimadamore@896: //step 1 - compute erased candidate set (EC)
mcimadamore@896: List cl = erasedSupertypes(ts.head);
duke@1: for (Type t : ts.tail) {
duke@1: if (t.tag == CLASS || t.tag == TYPEVAR)
mcimadamore@896: cl = intersect(cl, erasedSupertypes(t));
duke@1: }
mcimadamore@896: //step 2 - compute minimal erased candidate set (MEC)
mcimadamore@896: List mec = closureMin(cl);
mcimadamore@896: //step 3 - for each element G in MEC, compute lci(Inv(G))
mcimadamore@896: List candidates = List.nil();
mcimadamore@896: for (Type erasedSupertype : mec) {
mcimadamore@896: List lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
mcimadamore@896: for (Type t : ts) {
mcimadamore@896: lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
mcimadamore@896: }
mcimadamore@896: candidates = candidates.appendList(lci);
mcimadamore@896: }
mcimadamore@896: //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
mcimadamore@896: //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
mcimadamore@896: return compoundMin(candidates);
duke@1:
duke@1: default:
duke@1: // calculate lub(A, B[])
duke@1: List classes = List.of(arraySuperType());
duke@1: for (Type t : ts) {
duke@1: if (t.tag != ARRAY) // Filter out any arrays
duke@1: classes = classes.prepend(t);
duke@1: }
duke@1: // lub(A, B[]) is lub(A, arraySuperType)
duke@1: return lub(classes);
duke@1: }
duke@1: }
duke@1: // where
mcimadamore@896: List erasedSupertypes(Type t) {
mcimadamore@896: ListBuffer buf = lb();
mcimadamore@896: for (Type sup : closure(t)) {
mcimadamore@896: if (sup.tag == TYPEVAR) {
mcimadamore@896: buf.append(sup);
mcimadamore@896: } else {
mcimadamore@896: buf.append(erasure(sup));
mcimadamore@896: }
mcimadamore@896: }
mcimadamore@896: return buf.toList();
mcimadamore@896: }
mcimadamore@896:
duke@1: private Type arraySuperType = null;
duke@1: private Type arraySuperType() {
duke@1: // initialized lazily to avoid problems during compiler startup
duke@1: if (arraySuperType == null) {
duke@1: synchronized (this) {
duke@1: if (arraySuperType == null) {
duke@1: // JLS 10.8: all arrays implement Cloneable and Serializable.
duke@1: arraySuperType = makeCompoundType(List.of(syms.serializableType,
mcimadamore@1436: syms.cloneableType), true);
duke@1: }
duke@1: }
duke@1: }
duke@1: return arraySuperType;
duke@1: }
duke@1: //
duke@1:
duke@1: //
mcimadamore@210: public Type glb(List ts) {
mcimadamore@210: Type t1 = ts.head;
mcimadamore@210: for (Type t2 : ts.tail) {
mcimadamore@210: if (t1.isErroneous())
mcimadamore@210: return t1;
mcimadamore@210: t1 = glb(t1, t2);
mcimadamore@210: }
mcimadamore@210: return t1;
mcimadamore@210: }
mcimadamore@210: //where
duke@1: public Type glb(Type t, Type s) {
duke@1: if (s == null)
duke@1: return t;
mcimadamore@753: else if (t.isPrimitive() || s.isPrimitive())
mcimadamore@753: return syms.errType;
duke@1: else if (isSubtypeNoCapture(t, s))
duke@1: return t;
duke@1: else if (isSubtypeNoCapture(s, t))
duke@1: return s;
duke@1:
duke@1: List closure = union(closure(t), closure(s));
duke@1: List bounds = closureMin(closure);
duke@1:
duke@1: if (bounds.isEmpty()) { // length == 0
duke@1: return syms.objectType;
duke@1: } else if (bounds.tail.isEmpty()) { // length == 1
duke@1: return bounds.head;
duke@1: } else { // length > 1
duke@1: int classCount = 0;
duke@1: for (Type bound : bounds)
duke@1: if (!bound.isInterface())
duke@1: classCount++;
duke@1: if (classCount > 1)
jjg@110: return createErrorType(t);
duke@1: }
duke@1: return makeCompoundType(bounds);
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Compute a hash code on a type.
duke@1: */
vromero@1452: public int hashCode(Type t) {
duke@1: return hashCode.visit(t);
duke@1: }
duke@1: // where
duke@1: private static final UnaryVisitor hashCode = new UnaryVisitor() {
duke@1:
duke@1: public Integer visitType(Type t, Void ignored) {
jjg@1374: return t.tag.ordinal();
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Integer visitClassType(ClassType t, Void ignored) {
duke@1: int result = visit(t.getEnclosingType());
duke@1: result *= 127;
duke@1: result += t.tsym.flatName().hashCode();
duke@1: for (Type s : t.getTypeArguments()) {
duke@1: result *= 127;
duke@1: result += visit(s);
duke@1: }
duke@1: return result;
duke@1: }
duke@1:
duke@1: @Override
vromero@1452: public Integer visitMethodType(MethodType t, Void ignored) {
vromero@1452: int h = METHOD.ordinal();
vromero@1452: for (List thisargs = t.argtypes;
vromero@1452: thisargs.tail != null;
vromero@1452: thisargs = thisargs.tail)
vromero@1452: h = (h << 5) + visit(thisargs.head);
vromero@1452: return (h << 5) + visit(t.restype);
vromero@1452: }
vromero@1452:
vromero@1452: @Override
duke@1: public Integer visitWildcardType(WildcardType t, Void ignored) {
duke@1: int result = t.kind.hashCode();
duke@1: if (t.type != null) {
duke@1: result *= 127;
duke@1: result += visit(t.type);
duke@1: }
duke@1: return result;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Integer visitArrayType(ArrayType t, Void ignored) {
duke@1: return visit(t.elemtype) + 12;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Integer visitTypeVar(TypeVar t, Void ignored) {
duke@1: return System.identityHashCode(t.tsym);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Integer visitUndetVar(UndetVar t, Void ignored) {
duke@1: return System.identityHashCode(t);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Integer visitErrorType(ErrorType t, Void ignored) {
duke@1: return 0;
duke@1: }
duke@1: };
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Does t have a result that is a subtype of the result type of s,
duke@1: * suitable for covariant returns? It is assumed that both types
duke@1: * are (possibly polymorphic) method types. Monomorphic method
duke@1: * types are handled in the obvious way. Polymorphic method types
duke@1: * require renaming all type variables of one to corresponding
duke@1: * type variables in the other, where correspondence is by
duke@1: * position in the type parameter list. */
duke@1: public boolean resultSubtype(Type t, Type s, Warner warner) {
duke@1: List tvars = t.getTypeArguments();
duke@1: List svars = s.getTypeArguments();
duke@1: Type tres = t.getReturnType();
duke@1: Type sres = subst(s.getReturnType(), svars, tvars);
duke@1: return covariantReturnType(tres, sres, warner);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Return-Type-Substitutable.
jjh@972: * @jls section 8.4.5
duke@1: */
duke@1: public boolean returnTypeSubstitutable(Type r1, Type r2) {
duke@1: if (hasSameArgs(r1, r2))
mcimadamore@1415: return resultSubtype(r1, r2, noWarnings);
duke@1: else
duke@1: return covariantReturnType(r1.getReturnType(),
tbell@202: erasure(r2.getReturnType()),
mcimadamore@1415: noWarnings);
tbell@202: }
tbell@202:
tbell@202: public boolean returnTypeSubstitutable(Type r1,
tbell@202: Type r2, Type r2res,
tbell@202: Warner warner) {
tbell@202: if (isSameType(r1.getReturnType(), r2res))
tbell@202: return true;
tbell@202: if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
tbell@202: return false;
tbell@202:
tbell@202: if (hasSameArgs(r1, r2))
tbell@202: return covariantReturnType(r1.getReturnType(), r2res, warner);
jjg@984: if (!allowCovariantReturns)
tbell@202: return false;
tbell@202: if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
tbell@202: return true;
tbell@202: if (!isSubtype(r1.getReturnType(), erasure(r2res)))
tbell@202: return false;
mcimadamore@795: warner.warn(LintCategory.UNCHECKED);
tbell@202: return true;
duke@1: }
duke@1:
duke@1: /**
duke@1: * Is t an appropriate return type in an overrider for a
duke@1: * method that returns s?
duke@1: */
duke@1: public boolean covariantReturnType(Type t, Type s, Warner warner) {
tbell@202: return
tbell@202: isSameType(t, s) ||
jjg@984: allowCovariantReturns &&
duke@1: !t.isPrimitive() &&
tbell@202: !s.isPrimitive() &&
tbell@202: isAssignable(t, s, warner);
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * Return the class that boxes the given primitive.
duke@1: */
duke@1: public ClassSymbol boxedClass(Type t) {
jjg@1374: return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
duke@1: }
duke@1:
duke@1: /**
mcimadamore@753: * Return the boxed type if 't' is primitive, otherwise return 't' itself.
mcimadamore@753: */
mcimadamore@753: public Type boxedTypeOrType(Type t) {
mcimadamore@753: return t.isPrimitive() ?
mcimadamore@753: boxedClass(t).type :
mcimadamore@753: t;
mcimadamore@753: }
mcimadamore@753:
mcimadamore@753: /**
duke@1: * Return the primitive type corresponding to a boxed type.
duke@1: */
duke@1: public Type unboxedType(Type t) {
duke@1: if (allowBoxing) {
duke@1: for (int i=0; i
duke@1:
duke@1: //
duke@1: /*
jjh@972: * JLS 5.1.10 Capture Conversion:
duke@1: *
duke@1: * Let G name a generic type declaration with n formal type
duke@1: * parameters A1 ... An with corresponding bounds U1 ... Un. There
duke@1: * exists a capture conversion from G to G,
duke@1: * where, for 1 <= i <= n:
duke@1: *
duke@1: * + If Ti is a wildcard type argument (4.5.1) of the form ? then
duke@1: * Si is a fresh type variable whose upper bound is
duke@1: * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
duke@1: * type.
duke@1: *
duke@1: * + If Ti is a wildcard type argument of the form ? extends Bi,
duke@1: * then Si is a fresh type variable whose upper bound is
duke@1: * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
duke@1: * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
duke@1: * a compile-time error if for any two classes (not interfaces)
duke@1: * Vi and Vj,Vi is not a subclass of Vj or vice versa.
duke@1: *
duke@1: * + If Ti is a wildcard type argument of the form ? super Bi,
duke@1: * then Si is a fresh type variable whose upper bound is
duke@1: * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
duke@1: *
duke@1: * + Otherwise, Si = Ti.
duke@1: *
duke@1: * Capture conversion on any type other than a parameterized type
duke@1: * (4.5) acts as an identity conversion (5.1.1). Capture
duke@1: * conversions never require a special action at run time and
duke@1: * therefore never throw an exception at run time.
duke@1: *
duke@1: * Capture conversion is not applied recursively.
duke@1: */
duke@1: /**
jjh@972: * Capture conversion as specified by the JLS.
duke@1: */
mcimadamore@299:
mcimadamore@299: public List capture(List ts) {
mcimadamore@299: List buf = List.nil();
mcimadamore@299: for (Type t : ts) {
mcimadamore@299: buf = buf.prepend(capture(t));
mcimadamore@299: }
mcimadamore@299: return buf.reverse();
mcimadamore@299: }
duke@1: public Type capture(Type t) {
duke@1: if (t.tag != CLASS)
duke@1: return t;
mcimadamore@637: if (t.getEnclosingType() != Type.noType) {
mcimadamore@637: Type capturedEncl = capture(t.getEnclosingType());
mcimadamore@637: if (capturedEncl != t.getEnclosingType()) {
mcimadamore@637: Type type1 = memberType(capturedEncl, t.tsym);
mcimadamore@637: t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
mcimadamore@637: }
mcimadamore@637: }
jjg@1521: t = t.unannotatedType();
duke@1: ClassType cls = (ClassType)t;
duke@1: if (cls.isRaw() || !cls.isParameterized())
duke@1: return cls;
duke@1:
duke@1: ClassType G = (ClassType)cls.asElement().asType();
duke@1: List A = G.getTypeArguments();
duke@1: List T = cls.getTypeArguments();
duke@1: List S = freshTypeVariables(T);
duke@1:
duke@1: List currentA = A;
duke@1: List currentT = T;
duke@1: List currentS = S;
duke@1: boolean captured = false;
duke@1: while (!currentA.isEmpty() &&
duke@1: !currentT.isEmpty() &&
duke@1: !currentS.isEmpty()) {
duke@1: if (currentS.head != currentT.head) {
duke@1: captured = true;
duke@1: WildcardType Ti = (WildcardType)currentT.head;
duke@1: Type Ui = currentA.head.getUpperBound();
duke@1: CapturedType Si = (CapturedType)currentS.head;
duke@1: if (Ui == null)
duke@1: Ui = syms.objectType;
duke@1: switch (Ti.kind) {
duke@1: case UNBOUND:
duke@1: Si.bound = subst(Ui, A, S);
duke@1: Si.lower = syms.botType;
duke@1: break;
duke@1: case EXTENDS:
duke@1: Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
duke@1: Si.lower = syms.botType;
duke@1: break;
duke@1: case SUPER:
duke@1: Si.bound = subst(Ui, A, S);
duke@1: Si.lower = Ti.getSuperBound();
duke@1: break;
duke@1: }
duke@1: if (Si.bound == Si.lower)
duke@1: currentS.head = Si.bound;
duke@1: }
duke@1: currentA = currentA.tail;
duke@1: currentT = currentT.tail;
duke@1: currentS = currentS.tail;
duke@1: }
duke@1: if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
duke@1: return erasure(t); // some "rare" type involved
duke@1:
duke@1: if (captured)
duke@1: return new ClassType(cls.getEnclosingType(), S, cls.tsym);
duke@1: else
duke@1: return t;
duke@1: }
duke@1: // where
mcimadamore@238: public List freshTypeVariables(List types) {
duke@1: ListBuffer result = lb();
duke@1: for (Type t : types) {
duke@1: if (t.tag == WILDCARD) {
duke@1: Type bound = ((WildcardType)t).getExtendsBound();
duke@1: if (bound == null)
duke@1: bound = syms.objectType;
duke@1: result.append(new CapturedType(capturedName,
duke@1: syms.noSymbol,
duke@1: bound,
duke@1: syms.botType,
duke@1: (WildcardType)t));
duke@1: } else {
duke@1: result.append(t);
duke@1: }
duke@1: }
duke@1: return result.toList();
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: private List upperBounds(List ss) {
duke@1: if (ss.isEmpty()) return ss;
duke@1: Type head = upperBound(ss.head);
duke@1: List tail = upperBounds(ss.tail);
duke@1: if (head != ss.head || tail != ss.tail)
duke@1: return tail.prepend(head);
duke@1: else
duke@1: return ss;
duke@1: }
duke@1:
duke@1: private boolean sideCast(Type from, Type to, Warner warn) {
duke@1: // We are casting from type $from$ to type $to$, which are
duke@1: // non-final unrelated types. This method
duke@1: // tries to reject a cast by transferring type parameters
duke@1: // from $to$ to $from$ by common superinterfaces.
duke@1: boolean reverse = false;
duke@1: Type target = to;
duke@1: if ((to.tsym.flags() & INTERFACE) == 0) {
jjg@816: Assert.check((from.tsym.flags() & INTERFACE) != 0);
duke@1: reverse = true;
duke@1: to = from;
duke@1: from = target;
duke@1: }
duke@1: List commonSupers = superClosure(to, erasure(from));
duke@1: boolean giveWarning = commonSupers.isEmpty();
duke@1: // The arguments to the supers could be unified here to
duke@1: // get a more accurate analysis
duke@1: while (commonSupers.nonEmpty()) {
duke@1: Type t1 = asSuper(from, commonSupers.head.tsym);
duke@1: Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
duke@1: if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
duke@1: return false;
duke@1: giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
duke@1: commonSupers = commonSupers.tail;
duke@1: }
mcimadamore@187: if (giveWarning && !isReifiable(reverse ? from : to))
mcimadamore@795: warn.warn(LintCategory.UNCHECKED);
jjg@984: if (!allowCovariantReturns)
duke@1: // reject if there is a common method signature with
duke@1: // incompatible return types.
duke@1: chk.checkCompatibleAbstracts(warn.pos(), from, to);
duke@1: return true;
duke@1: }
duke@1:
duke@1: private boolean sideCastFinal(Type from, Type to, Warner warn) {
duke@1: // We are casting from type $from$ to type $to$, which are
duke@1: // unrelated types one of which is final and the other of
duke@1: // which is an interface. This method
duke@1: // tries to reject a cast by transferring type parameters
duke@1: // from the final class to the interface.
duke@1: boolean reverse = false;
duke@1: Type target = to;
duke@1: if ((to.tsym.flags() & INTERFACE) == 0) {
jjg@816: Assert.check((from.tsym.flags() & INTERFACE) != 0);
duke@1: reverse = true;
duke@1: to = from;
duke@1: from = target;
duke@1: }
jjg@816: Assert.check((from.tsym.flags() & FINAL) != 0);
duke@1: Type t1 = asSuper(from, to.tsym);
duke@1: if (t1 == null) return false;
duke@1: Type t2 = to;
duke@1: if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
duke@1: return false;
jjg@984: if (!allowCovariantReturns)
duke@1: // reject if there is a common method signature with
duke@1: // incompatible return types.
duke@1: chk.checkCompatibleAbstracts(warn.pos(), from, to);
duke@1: if (!isReifiable(target) &&
duke@1: (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
mcimadamore@795: warn.warn(LintCategory.UNCHECKED);
duke@1: return true;
duke@1: }
duke@1:
duke@1: private boolean giveWarning(Type from, Type to) {
mcimadamore@235: Type subFrom = asSub(from, to.tsym);
mcimadamore@235: return to.isParameterized() &&
mcimadamore@235: (!(isUnbounded(to) ||
mcimadamore@235: isSubtype(from, to) ||
mcimadamore@736: ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
duke@1: }
duke@1:
duke@1: private List superClosure(Type t, Type s) {
duke@1: List cl = List.nil();
duke@1: for (List l = interfaces(t); l.nonEmpty(); l = l.tail) {
duke@1: if (isSubtype(s, erasure(l.head))) {
duke@1: cl = insert(cl, l.head);
duke@1: } else {
duke@1: cl = union(cl, superClosure(l.head, s));
duke@1: }
duke@1: }
duke@1: return cl;
duke@1: }
duke@1:
duke@1: private boolean containsTypeEquivalent(Type t, Type s) {
duke@1: return
duke@1: isSameType(t, s) || // shortcut
duke@1: containsType(t, s) && containsType(s, t);
duke@1: }
duke@1:
mcimadamore@138: //
duke@1: /**
duke@1: * Adapt a type by computing a substitution which maps a source
duke@1: * type to a target type.
duke@1: *
duke@1: * @param source the source type
duke@1: * @param target the target type
duke@1: * @param from the type variables of the computed substitution
duke@1: * @param to the types of the computed substitution.
duke@1: */
duke@1: public void adapt(Type source,
duke@1: Type target,
duke@1: ListBuffer from,
duke@1: ListBuffer to) throws AdaptFailure {
mcimadamore@138: new Adapter(from, to).adapt(source, target);
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: class Adapter extends SimpleVisitor {
mcimadamore@138:
mcimadamore@138: ListBuffer from;
mcimadamore@138: ListBuffer to;
mcimadamore@138: Map mapping;
mcimadamore@138:
mcimadamore@138: Adapter(ListBuffer from, ListBuffer to) {
mcimadamore@138: this.from = from;
mcimadamore@138: this.to = to;
mcimadamore@138: mapping = new HashMap();
duke@1: }
mcimadamore@138:
mcimadamore@138: public void adapt(Type source, Type target) throws AdaptFailure {
mcimadamore@138: visit(source, target);
mcimadamore@138: List fromList = from.toList();
mcimadamore@138: List toList = to.toList();
mcimadamore@138: while (!fromList.isEmpty()) {
mcimadamore@138: Type val = mapping.get(fromList.head.tsym);
mcimadamore@138: if (toList.head != val)
mcimadamore@138: toList.head = val;
mcimadamore@138: fromList = fromList.tail;
mcimadamore@138: toList = toList.tail;
mcimadamore@138: }
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: @Override
mcimadamore@138: public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
mcimadamore@138: if (target.tag == CLASS)
mcimadamore@138: adaptRecursive(source.allparams(), target.allparams());
mcimadamore@138: return null;
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: @Override
mcimadamore@138: public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
mcimadamore@138: if (target.tag == ARRAY)
mcimadamore@138: adaptRecursive(elemtype(source), elemtype(target));
mcimadamore@138: return null;
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: @Override
mcimadamore@138: public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
mcimadamore@138: if (source.isExtendsBound())
mcimadamore@138: adaptRecursive(upperBound(source), upperBound(target));
mcimadamore@138: else if (source.isSuperBound())
mcimadamore@138: adaptRecursive(lowerBound(source), lowerBound(target));
mcimadamore@138: return null;
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: @Override
mcimadamore@138: public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
mcimadamore@138: // Check to see if there is
mcimadamore@138: // already a mapping for $source$, in which case
mcimadamore@138: // the old mapping will be merged with the new
mcimadamore@138: Type val = mapping.get(source.tsym);
mcimadamore@138: if (val != null) {
mcimadamore@138: if (val.isSuperBound() && target.isSuperBound()) {
mcimadamore@138: val = isSubtype(lowerBound(val), lowerBound(target))
mcimadamore@138: ? target : val;
mcimadamore@138: } else if (val.isExtendsBound() && target.isExtendsBound()) {
mcimadamore@138: val = isSubtype(upperBound(val), upperBound(target))
mcimadamore@138: ? val : target;
mcimadamore@138: } else if (!isSameType(val, target)) {
mcimadamore@138: throw new AdaptFailure();
duke@1: }
mcimadamore@138: } else {
mcimadamore@138: val = target;
mcimadamore@138: from.append(source);
mcimadamore@138: to.append(target);
mcimadamore@138: }
mcimadamore@138: mapping.put(source.tsym, val);
mcimadamore@138: return null;
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: @Override
mcimadamore@138: public Void visitType(Type source, Type target) {
mcimadamore@138: return null;
mcimadamore@138: }
mcimadamore@138:
mcimadamore@138: private Set cache = new HashSet();
mcimadamore@138:
mcimadamore@138: private void adaptRecursive(Type source, Type target) {
mcimadamore@138: TypePair pair = new TypePair(source, target);
mcimadamore@138: if (cache.add(pair)) {
mcimadamore@138: try {
mcimadamore@138: visit(source, target);
mcimadamore@138: } finally {
mcimadamore@138: cache.remove(pair);
duke@1: }
duke@1: }
duke@1: }
mcimadamore@138:
mcimadamore@138: private void adaptRecursive(List source, List target) {
mcimadamore@138: if (source.length() == target.length()) {
mcimadamore@138: while (source.nonEmpty()) {
mcimadamore@138: adaptRecursive(source.head, target.head);
mcimadamore@138: source = source.tail;
mcimadamore@138: target = target.tail;
mcimadamore@138: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
mcimadamore@138: public static class AdaptFailure extends RuntimeException {
mcimadamore@138: static final long serialVersionUID = -7490231548272701566L;
mcimadamore@138: }
mcimadamore@138:
duke@1: private void adaptSelf(Type t,
duke@1: ListBuffer from,
duke@1: ListBuffer to) {
duke@1: try {
duke@1: //if (t.tsym.type != t)
duke@1: adapt(t.tsym.type, t, from, to);
duke@1: } catch (AdaptFailure ex) {
duke@1: // Adapt should never fail calculating a mapping from
duke@1: // t.tsym.type to t as there can be no merge problem.
duke@1: throw new AssertionError(ex);
duke@1: }
duke@1: }
mcimadamore@138: //
duke@1:
duke@1: /**
duke@1: * Rewrite all type variables (universal quantifiers) in the given
duke@1: * type to wildcards (existential quantifiers). This is used to
duke@1: * determine if a cast is allowed. For example, if high is true
duke@1: * and {@code T <: Number}, then {@code List} is rewritten to
duke@1: * {@code List extends Number>}. Since {@code List <:
duke@1: * List extends Number>} a {@code List} can be cast to {@code
duke@1: * List} with a warning.
duke@1: * @param t a type
duke@1: * @param high if true return an upper bound; otherwise a lower
duke@1: * bound
duke@1: * @param rewriteTypeVars only rewrite captured wildcards if false;
duke@1: * otherwise rewrite all type variables
duke@1: * @return the type rewritten with wildcards (existential
duke@1: * quantifiers) only
duke@1: */
duke@1: private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
mcimadamore@640: return new Rewriter(high, rewriteTypeVars).visit(t);
mcimadamore@157: }
mcimadamore@157:
mcimadamore@157: class Rewriter extends UnaryVisitor {
mcimadamore@157:
mcimadamore@157: boolean high;
mcimadamore@157: boolean rewriteTypeVars;
mcimadamore@157:
mcimadamore@157: Rewriter(boolean high, boolean rewriteTypeVars) {
mcimadamore@157: this.high = high;
mcimadamore@157: this.rewriteTypeVars = rewriteTypeVars;
mcimadamore@157: }
mcimadamore@157:
mcimadamore@640: @Override
mcimadamore@640: public Type visitClassType(ClassType t, Void s) {
mcimadamore@157: ListBuffer rewritten = new ListBuffer();
mcimadamore@157: boolean changed = false;
mcimadamore@640: for (Type arg : t.allparams()) {
mcimadamore@157: Type bound = visit(arg);
mcimadamore@157: if (arg != bound) {
mcimadamore@157: changed = true;
mcimadamore@157: }
mcimadamore@157: rewritten.append(bound);
duke@1: }
mcimadamore@157: if (changed)
mcimadamore@640: return subst(t.tsym.type,
mcimadamore@640: t.tsym.type.allparams(),
mcimadamore@640: rewritten.toList());
mcimadamore@157: else
mcimadamore@157: return t;
duke@1: }
mcimadamore@157:
mcimadamore@157: public Type visitType(Type t, Void s) {
mcimadamore@157: return high ? upperBound(t) : lowerBound(t);
mcimadamore@157: }
mcimadamore@157:
mcimadamore@157: @Override
mcimadamore@157: public Type visitCapturedType(CapturedType t, Void s) {
mcimadamore@1177: Type w_bound = t.wildcard.type;
mcimadamore@1177: Type bound = w_bound.contains(t) ?
mcimadamore@1177: erasure(w_bound) :
mcimadamore@1177: visit(w_bound);
mcimadamore@1177: return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
mcimadamore@157: }
mcimadamore@157:
mcimadamore@157: @Override
mcimadamore@157: public Type visitTypeVar(TypeVar t, Void s) {
mcimadamore@640: if (rewriteTypeVars) {
mcimadamore@1177: Type bound = t.bound.contains(t) ?
mcimadamore@779: erasure(t.bound) :
mcimadamore@1177: visit(t.bound);
mcimadamore@1177: return rewriteAsWildcardType(bound, t, EXTENDS);
mcimadamore@1177: } else {
mcimadamore@1177: return t;
mcimadamore@640: }
mcimadamore@157: }
mcimadamore@157:
mcimadamore@157: @Override
mcimadamore@157: public Type visitWildcardType(WildcardType t, Void s) {
mcimadamore@1177: Type bound2 = visit(t.type);
mcimadamore@1177: return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
mcimadamore@640: }
mcimadamore@640:
mcimadamore@1177: private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
mcimadamore@1177: switch (bk) {
mcimadamore@1177: case EXTENDS: return high ?
mcimadamore@1177: makeExtendsWildcard(B(bound), formal) :
mcimadamore@1177: makeExtendsWildcard(syms.objectType, formal);
mcimadamore@1177: case SUPER: return high ?
mcimadamore@1177: makeSuperWildcard(syms.botType, formal) :
mcimadamore@1177: makeSuperWildcard(B(bound), formal);
mcimadamore@1177: case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
mcimadamore@1177: default:
mcimadamore@1177: Assert.error("Invalid bound kind " + bk);
mcimadamore@1177: return null;
mcimadamore@1177: }
mcimadamore@640: }
mcimadamore@640:
mcimadamore@640: Type B(Type t) {
mcimadamore@640: while (t.tag == WILDCARD) {
mcimadamore@640: WildcardType w = (WildcardType)t;
mcimadamore@640: t = high ?
mcimadamore@640: w.getExtendsBound() :
mcimadamore@640: w.getSuperBound();
mcimadamore@640: if (t == null) {
mcimadamore@640: t = high ? syms.objectType : syms.botType;
mcimadamore@640: }
mcimadamore@640: }
mcimadamore@640: return t;
mcimadamore@157: }
duke@1: }
duke@1:
mcimadamore@640:
duke@1: /**
duke@1: * Create a wildcard with the given upper (extends) bound; create
duke@1: * an unbounded wildcard if bound is Object.
duke@1: *
duke@1: * @param bound the upper bound
duke@1: * @param formal the formal type parameter that will be
duke@1: * substituted by the wildcard
duke@1: */
duke@1: private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
duke@1: if (bound == syms.objectType) {
duke@1: return new WildcardType(syms.objectType,
duke@1: BoundKind.UNBOUND,
duke@1: syms.boundClass,
duke@1: formal);
duke@1: } else {
duke@1: return new WildcardType(bound,
duke@1: BoundKind.EXTENDS,
duke@1: syms.boundClass,
duke@1: formal);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Create a wildcard with the given lower (super) bound; create an
duke@1: * unbounded wildcard if bound is bottom (type of {@code null}).
duke@1: *
duke@1: * @param bound the lower bound
duke@1: * @param formal the formal type parameter that will be
duke@1: * substituted by the wildcard
duke@1: */
duke@1: private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
duke@1: if (bound.tag == BOT) {
duke@1: return new WildcardType(syms.objectType,
duke@1: BoundKind.UNBOUND,
duke@1: syms.boundClass,
duke@1: formal);
duke@1: } else {
duke@1: return new WildcardType(bound,
duke@1: BoundKind.SUPER,
duke@1: syms.boundClass,
duke@1: formal);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * A wrapper for a type that allows use in sets.
duke@1: */
vromero@1452: public static class UniqueType {
vromero@1452: public final Type type;
vromero@1452: final Types types;
vromero@1452:
vromero@1452: public UniqueType(Type type, Types types) {
vromero@1452: this.type = type;
vromero@1452: this.types = types;
duke@1: }
vromero@1452:
duke@1: public int hashCode() {
vromero@1452: return types.hashCode(type);
duke@1: }
vromero@1452:
duke@1: public boolean equals(Object obj) {
vromero@1452: return (obj instanceof UniqueType) &&
vromero@1452: types.isSameType(type, ((UniqueType)obj).type);
duke@1: }
vromero@1452:
duke@1: public String toString() {
vromero@1452: return type.toString();
duke@1: }
vromero@1452:
duke@1: }
duke@1: //
duke@1:
duke@1: //
duke@1: /**
duke@1: * A default visitor for types. All visitor methods except
duke@1: * visitType are implemented by delegating to visitType. Concrete
duke@1: * subclasses must provide an implementation of visitType and can
duke@1: * override other methods as needed.
duke@1: *
duke@1: * @param the return type of the operation implemented by this
duke@1: * visitor; use Void if no return type is needed.
duke@1: * @param the type of the second argument (the first being the
duke@1: * type itself) of the operation implemented by this visitor; use
duke@1: * Void if a second argument is not needed.
duke@1: */
duke@1: public static abstract class DefaultTypeVisitor implements Type.Visitor {
duke@1: final public R visit(Type t, S s) { return t.accept(this, s); }
duke@1: public R visitClassType(ClassType t, S s) { return visitType(t, s); }
duke@1: public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
duke@1: public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
duke@1: public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
duke@1: public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
duke@1: public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
duke@1: public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
duke@1: public R visitForAll(ForAll t, S s) { return visitType(t, s); }
duke@1: public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
duke@1: public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
jjg@1521: // Pretend annotations don't exist
jjg@1521: public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
duke@1: }
duke@1:
duke@1: /**
mcimadamore@121: * A default visitor for symbols. All visitor methods except
mcimadamore@121: * visitSymbol are implemented by delegating to visitSymbol. Concrete
mcimadamore@121: * subclasses must provide an implementation of visitSymbol and can
mcimadamore@121: * override other methods as needed.
mcimadamore@121: *
mcimadamore@121: * @param the return type of the operation implemented by this
mcimadamore@121: * visitor; use Void if no return type is needed.
mcimadamore@121: * @param the type of the second argument (the first being the
mcimadamore@121: * symbol itself) of the operation implemented by this visitor; use
mcimadamore@121: * Void if a second argument is not needed.
mcimadamore@121: */
mcimadamore@121: public static abstract class DefaultSymbolVisitor implements Symbol.Visitor {
mcimadamore@121: final public R visit(Symbol s, S arg) { return s.accept(this, arg); }
mcimadamore@121: public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); }
mcimadamore@121: }
mcimadamore@121:
mcimadamore@121: /**
duke@1: * A simple visitor for types. This visitor is simple as
duke@1: * captured wildcards, for-all types (generic methods), and
duke@1: * undetermined type variables (part of inference) are hidden.
duke@1: * Captured wildcards are hidden by treating them as type
duke@1: * variables and the rest are hidden by visiting their qtypes.
duke@1: *
duke@1: * @param the return type of the operation implemented by this
duke@1: * visitor; use Void if no return type is needed.
duke@1: * @param the type of the second argument (the first being the
duke@1: * type itself) of the operation implemented by this visitor; use
duke@1: * Void if a second argument is not needed.
duke@1: */
duke@1: public static abstract class SimpleVisitor extends DefaultTypeVisitor {
duke@1: @Override
duke@1: public R visitCapturedType(CapturedType t, S s) {
duke@1: return visitTypeVar(t, s);
duke@1: }
duke@1: @Override
duke@1: public R visitForAll(ForAll t, S s) {
duke@1: return visit(t.qtype, s);
duke@1: }
duke@1: @Override
duke@1: public R visitUndetVar(UndetVar t, S s) {
duke@1: return visit(t.qtype, s);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * A plain relation on types. That is a 2-ary function on the
duke@1: * form Type × Type → Boolean.
duke@1: *
duke@1: */
duke@1: public static abstract class TypeRelation extends SimpleVisitor {}
duke@1:
duke@1: /**
duke@1: * A convenience visitor for implementing operations that only
duke@1: * require one argument (the type itself), that is, unary
duke@1: * operations.
duke@1: *
duke@1: * @param the return type of the operation implemented by this
duke@1: * visitor; use Void if no return type is needed.
duke@1: */
duke@1: public static abstract class UnaryVisitor extends SimpleVisitor {
duke@1: final public R visit(Type t) { return t.accept(this, null); }
duke@1: }
duke@1:
duke@1: /**
duke@1: * A visitor for implementing a mapping from types to types. The
duke@1: * default behavior of this class is to implement the identity
duke@1: * mapping (mapping a type to itself). This can be overridden in
duke@1: * subclasses.
duke@1: *
duke@1: * @param the type of the second argument (the first being the
duke@1: * type itself) of this mapping; use Void if a second argument is
duke@1: * not needed.
duke@1: */
duke@1: public static class MapVisitor extends DefaultTypeVisitor {
duke@1: final public Type visit(Type t) { return t.accept(this, null); }
duke@1: public Type visitType(Type t, S s) { return t; }
duke@1: }
duke@1: //
jjg@657:
jjg@657:
jjg@657: //
jjg@657:
jjg@657: public RetentionPolicy getRetention(Attribute.Compound a) {
jfranck@1313: return getRetention(a.type.tsym);
jfranck@1313: }
jfranck@1313:
jfranck@1313: public RetentionPolicy getRetention(Symbol sym) {
jjg@657: RetentionPolicy vis = RetentionPolicy.CLASS; // the default
jfranck@1313: Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
jjg@657: if (c != null) {
jjg@657: Attribute value = c.member(names.value);
jjg@657: if (value != null && value instanceof Attribute.Enum) {
jjg@657: Name levelName = ((Attribute.Enum)value).value.name;
jjg@657: if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
jjg@657: else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
jjg@657: else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
jjg@657: else ;// /* fail soft */ throw new AssertionError(levelName);
jjg@657: }
jjg@657: }
jjg@657: return vis;
jjg@657: }
jjg@657: //
rfield@1587:
rfield@1587: //
rfield@1587:
rfield@1587: public static abstract class SignatureGenerator {
rfield@1587:
rfield@1587: private final Types types;
rfield@1587:
rfield@1587: protected abstract void append(char ch);
rfield@1587: protected abstract void append(byte[] ba);
rfield@1587: protected abstract void append(Name name);
rfield@1587: protected void classReference(ClassSymbol c) { /* by default: no-op */ }
rfield@1587:
rfield@1587: protected SignatureGenerator(Types types) {
rfield@1587: this.types = types;
rfield@1587: }
rfield@1587:
rfield@1587: /**
rfield@1587: * Assemble signature of given type in string buffer.
rfield@1587: */
rfield@1587: public void assembleSig(Type type) {
rfield@1587: type = type.unannotatedType();
rfield@1587: switch (type.getTag()) {
rfield@1587: case BYTE:
rfield@1587: append('B');
rfield@1587: break;
rfield@1587: case SHORT:
rfield@1587: append('S');
rfield@1587: break;
rfield@1587: case CHAR:
rfield@1587: append('C');
rfield@1587: break;
rfield@1587: case INT:
rfield@1587: append('I');
rfield@1587: break;
rfield@1587: case LONG:
rfield@1587: append('J');
rfield@1587: break;
rfield@1587: case FLOAT:
rfield@1587: append('F');
rfield@1587: break;
rfield@1587: case DOUBLE:
rfield@1587: append('D');
rfield@1587: break;
rfield@1587: case BOOLEAN:
rfield@1587: append('Z');
rfield@1587: break;
rfield@1587: case VOID:
rfield@1587: append('V');
rfield@1587: break;
rfield@1587: case CLASS:
rfield@1587: append('L');
rfield@1587: assembleClassSig(type);
rfield@1587: append(';');
rfield@1587: break;
rfield@1587: case ARRAY:
rfield@1587: ArrayType at = (ArrayType) type;
rfield@1587: append('[');
rfield@1587: assembleSig(at.elemtype);
rfield@1587: break;
rfield@1587: case METHOD:
rfield@1587: MethodType mt = (MethodType) type;
rfield@1587: append('(');
rfield@1587: assembleSig(mt.argtypes);
rfield@1587: append(')');
rfield@1587: assembleSig(mt.restype);
rfield@1587: if (hasTypeVar(mt.thrown)) {
rfield@1587: for (List l = mt.thrown; l.nonEmpty(); l = l.tail) {
rfield@1587: append('^');
rfield@1587: assembleSig(l.head);
rfield@1587: }
rfield@1587: }
rfield@1587: break;
rfield@1587: case WILDCARD: {
rfield@1587: Type.WildcardType ta = (Type.WildcardType) type;
rfield@1587: switch (ta.kind) {
rfield@1587: case SUPER:
rfield@1587: append('-');
rfield@1587: assembleSig(ta.type);
rfield@1587: break;
rfield@1587: case EXTENDS:
rfield@1587: append('+');
rfield@1587: assembleSig(ta.type);
rfield@1587: break;
rfield@1587: case UNBOUND:
rfield@1587: append('*');
rfield@1587: break;
rfield@1587: default:
rfield@1587: throw new AssertionError(ta.kind);
rfield@1587: }
rfield@1587: break;
rfield@1587: }
rfield@1587: case TYPEVAR:
rfield@1587: append('T');
rfield@1587: append(type.tsym.name);
rfield@1587: append(';');
rfield@1587: break;
rfield@1587: case FORALL:
rfield@1587: Type.ForAll ft = (Type.ForAll) type;
rfield@1587: assembleParamsSig(ft.tvars);
rfield@1587: assembleSig(ft.qtype);
rfield@1587: break;
rfield@1587: default:
rfield@1587: throw new AssertionError("typeSig " + type.getTag());
rfield@1587: }
rfield@1587: }
rfield@1587:
rfield@1587: public boolean hasTypeVar(List l) {
rfield@1587: while (l.nonEmpty()) {
rfield@1587: if (l.head.hasTag(TypeTag.TYPEVAR)) {
rfield@1587: return true;
rfield@1587: }
rfield@1587: l = l.tail;
rfield@1587: }
rfield@1587: return false;
rfield@1587: }
rfield@1587:
rfield@1587: public void assembleClassSig(Type type) {
rfield@1587: type = type.unannotatedType();
rfield@1587: ClassType ct = (ClassType) type;
rfield@1587: ClassSymbol c = (ClassSymbol) ct.tsym;
rfield@1587: classReference(c);
rfield@1587: Type outer = ct.getEnclosingType();
rfield@1587: if (outer.allparams().nonEmpty()) {
rfield@1587: boolean rawOuter =
rfield@1587: c.owner.kind == Kinds.MTH || // either a local class
rfield@1587: c.name == types.names.empty; // or anonymous
rfield@1587: assembleClassSig(rawOuter
rfield@1587: ? types.erasure(outer)
rfield@1587: : outer);
rfield@1587: append('.');
rfield@1587: Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
rfield@1587: append(rawOuter
rfield@1587: ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
rfield@1587: : c.name);
rfield@1587: } else {
rfield@1587: append(externalize(c.flatname));
rfield@1587: }
rfield@1587: if (ct.getTypeArguments().nonEmpty()) {
rfield@1587: append('<');
rfield@1587: assembleSig(ct.getTypeArguments());
rfield@1587: append('>');
rfield@1587: }
rfield@1587: }
rfield@1587:
rfield@1587: public void assembleParamsSig(List typarams) {
rfield@1587: append('<');
rfield@1587: for (List ts = typarams; ts.nonEmpty(); ts = ts.tail) {
rfield@1587: Type.TypeVar tvar = (Type.TypeVar) ts.head;
rfield@1587: append(tvar.tsym.name);
rfield@1587: List bounds = types.getBounds(tvar);
rfield@1587: if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
rfield@1587: append(':');
rfield@1587: }
rfield@1587: for (List l = bounds; l.nonEmpty(); l = l.tail) {
rfield@1587: append(':');
rfield@1587: assembleSig(l.head);
rfield@1587: }
rfield@1587: }
rfield@1587: append('>');
rfield@1587: }
rfield@1587:
rfield@1587: private void assembleSig(List types) {
rfield@1587: for (List ts = types; ts.nonEmpty(); ts = ts.tail) {
rfield@1587: assembleSig(ts.head);
rfield@1587: }
rfield@1587: }
rfield@1587: }
rfield@1587: //
duke@1: }