001 /*
002 * Copyright 2010-2016 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.jetbrains.kotlin.types;
018
019 import kotlin.Unit;
020 import kotlin.jvm.functions.Function1;
021 import org.jetbrains.annotations.NotNull;
022 import org.jetbrains.annotations.Nullable;
023 import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
024 import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
025 import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
026 import org.jetbrains.kotlin.descriptors.annotations.Annotations;
027 import org.jetbrains.kotlin.resolve.calls.inference.CallHandle;
028 import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem;
029 import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl;
030 import org.jetbrains.kotlin.resolve.scopes.TypeIntersectionScope;
031 import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
032
033 import java.util.*;
034
035 import static org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPositionKind.SPECIAL;
036 import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt.getBuiltIns;
037
038 public class TypeIntersector {
039
040 public static boolean isIntersectionEmpty(@NotNull KotlinType typeA, @NotNull KotlinType typeB) {
041 return intersectTypes(KotlinTypeChecker.DEFAULT, new LinkedHashSet<KotlinType>(Arrays.asList(typeA, typeB))) == null;
042 }
043
044 @Nullable
045 public static KotlinType intersectTypes(@NotNull KotlinTypeChecker typeChecker, @NotNull Collection<KotlinType> types) {
046 assert !types.isEmpty() : "Attempting to intersect empty collection of types, this case should be dealt with on the call site.";
047
048 if (types.size() == 1) {
049 return types.iterator().next();
050 }
051
052 // Intersection of T1..Tn is an intersection of their non-null versions,
053 // made nullable is they all were nullable
054 KotlinType nothingOrNullableNothing = null;
055 boolean allNullable = true;
056 List<KotlinType> nullabilityStripped = new ArrayList<KotlinType>(types.size());
057 for (KotlinType type : types) {
058 if (type.isError()) continue;
059
060 if (KotlinBuiltIns.isNothingOrNullableNothing(type)) {
061 nothingOrNullableNothing = type;
062 }
063 allNullable &= type.isMarkedNullable();
064 nullabilityStripped.add(TypeUtils.makeNotNullable(type));
065 }
066
067 if (nothingOrNullableNothing != null) {
068 return TypeUtils.makeNullableAsSpecified(nothingOrNullableNothing, allNullable);
069 }
070
071 if (nullabilityStripped.isEmpty()) {
072 // All types were errors
073 return ErrorUtils.createErrorType("Intersection of error types: " + types);
074 }
075
076 // Now we remove types that have subtypes in the list
077 List<KotlinType> resultingTypes = new ArrayList<KotlinType>();
078 outer:
079 for (KotlinType type : nullabilityStripped) {
080 if (!TypeUtils.canHaveSubtypes(typeChecker, type)) {
081 boolean relativeToAll = true;
082 for (KotlinType other : nullabilityStripped) {
083 // It makes sense to check for subtyping (other <: type), despite that
084 // type is not supposed to be open, for there're enums
085 boolean mayBeEqual = TypeUnifier.mayBeEqual(type, other);
086 boolean relative = typeChecker.isSubtypeOf(type, other) || typeChecker.isSubtypeOf(other, type);
087 if (!mayBeEqual && !relative) {
088 return null;
089 }
090 else if (!relative) {
091 // To build T & (final A), instead of returning just A as intersection
092 relativeToAll = false;
093 break;
094 }
095 }
096 if (relativeToAll) return TypeUtils.makeNullableAsSpecified(type, allNullable);
097 }
098 for (KotlinType other : nullabilityStripped) {
099 if (!type.equals(other) && typeChecker.isSubtypeOf(other, type)) {
100 continue outer;
101 }
102 }
103
104 // Don't add type if it is already present, to avoid trivial type intersections in result
105 for (KotlinType other : resultingTypes) {
106 if (typeChecker.equalTypes(other, type)) {
107 continue outer;
108 }
109 }
110 resultingTypes.add(type);
111 }
112
113 if (resultingTypes.isEmpty()) {
114 // If we ended up here, it means that all types from `nullabilityStripped` were excluded by the code above
115 // most likely, this is because they are all semantically interchangeable (e.g. List<Foo>! and List<Foo>),
116 // in that case, we can safely select the best representative out of that set and return it
117 // TODO: maybe return the most specific among the types that are subtypes to all others in the `nullabilityStripped`?
118 // TODO: e.g. among {Int, Int?, Int!}, return `Int` (now it returns `Int!`).
119 KotlinType bestRepresentative = FlexibleTypesKt.singleBestRepresentative(nullabilityStripped);
120
121 if (bestRepresentative == null) {
122 bestRepresentative = UtilsKt.hackForTypeIntersector(nullabilityStripped);
123 }
124
125 if (bestRepresentative == null) {
126 throw new AssertionError("Empty intersection for types " + types);
127 }
128 return TypeUtils.makeNullableAsSpecified(bestRepresentative, allNullable);
129 }
130
131 if (resultingTypes.size() == 1) {
132 return TypeUtils.makeNullableAsSpecified(resultingTypes.get(0), allNullable);
133 }
134
135 IntersectionTypeConstructor constructor = new IntersectionTypeConstructor(resultingTypes);
136
137 return KotlinTypeFactory.simpleType(
138 Annotations.Companion.getEMPTY(),
139 constructor,
140 Collections.<TypeProjection>emptyList(),
141 allNullable,
142 constructor.createScopeForKotlinType()
143 );
144 }
145
146 /**
147 * Note: this method was used in overload and override bindings to approximate type parameters with several bounds,
148 * but as it turned out at some point, that logic was inconsistent with Java rules, so it was simplified.
149 * Most of the other usages of this method are left untouched but probably should be investigated closely if they're still valid.
150 */
151 @NotNull
152 public static KotlinType getUpperBoundsAsType(@NotNull TypeParameterDescriptor descriptor) {
153 List<KotlinType> upperBounds = descriptor.getUpperBounds();
154 assert !upperBounds.isEmpty() : "Upper bound list is empty: " + descriptor;
155 KotlinType upperBoundsAsType = intersectTypes(KotlinTypeChecker.DEFAULT, upperBounds);
156 return upperBoundsAsType != null ? upperBoundsAsType : getBuiltIns(descriptor).getNothingType();
157 }
158
159 private static class TypeUnifier {
160 private static class TypeParameterUsage {
161 private final TypeParameterDescriptor typeParameterDescriptor;
162 private final Variance howTheTypeParameterIsUsed;
163
164 public TypeParameterUsage(TypeParameterDescriptor typeParameterDescriptor, Variance howTheTypeParameterIsUsed) {
165 this.typeParameterDescriptor = typeParameterDescriptor;
166 this.howTheTypeParameterIsUsed = howTheTypeParameterIsUsed;
167 }
168 }
169
170 public static boolean mayBeEqual(@NotNull KotlinType type, @NotNull KotlinType other) {
171 return unify(type, other);
172 }
173
174 private static boolean unify(KotlinType withParameters, KotlinType expected) {
175 // T -> how T is used
176 final Map<TypeParameterDescriptor, Variance> parameters = new HashMap<TypeParameterDescriptor, Variance>();
177 Function1<TypeParameterUsage, Unit> processor = new Function1<TypeParameterUsage, Unit>() {
178 @Override
179 public Unit invoke(TypeParameterUsage parameterUsage) {
180 Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
181 if (howTheTypeIsUsedBefore == null) {
182 howTheTypeIsUsedBefore = Variance.INVARIANT;
183 }
184 parameters.put(parameterUsage.typeParameterDescriptor,
185 parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
186 return Unit.INSTANCE;
187 }
188 };
189 processAllTypeParameters(withParameters, Variance.INVARIANT, processor);
190 processAllTypeParameters(expected, Variance.INVARIANT, processor);
191 ConstraintSystem.Builder constraintSystem = new ConstraintSystemBuilderImpl();
192 TypeSubstitutor substitutor = constraintSystem.registerTypeVariables(CallHandle.NONE.INSTANCE, parameters.keySet(), false);
193 constraintSystem.addSubtypeConstraint(withParameters, substitutor.substitute(expected, Variance.INVARIANT), SPECIAL.position());
194
195 return constraintSystem.build().getStatus().isSuccessful();
196 }
197
198 private static void processAllTypeParameters(KotlinType type, Variance howThisTypeIsUsed, Function1<TypeParameterUsage, Unit> result) {
199 ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
200 if (descriptor instanceof TypeParameterDescriptor) {
201 result.invoke(new TypeParameterUsage((TypeParameterDescriptor) descriptor, howThisTypeIsUsed));
202 }
203 for (TypeProjection projection : type.getArguments()) {
204 if (projection.isStarProjection()) continue;
205 processAllTypeParameters(projection.getType(), projection.getProjectionKind(), result);
206 }
207 }
208 }
209 }