001    /*
002     * Copyright 2010-2015 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                    for (KotlinType other : nullabilityStripped) {
082                        // It makes sense to check for subtyping (other <: type), despite that
083                        // type is not supposed to be open, for there're enums
084                        if (!TypeUnifier.mayBeEqual(type, other) && !typeChecker.isSubtypeOf(type, other) && !typeChecker.isSubtypeOf(other, type)) {
085                            return null;
086                        }
087                    }
088                    return TypeUtils.makeNullableAsSpecified(type, allNullable);
089                }
090                else {
091                    for (KotlinType other : nullabilityStripped) {
092                        if (!type.equals(other) && typeChecker.isSubtypeOf(other, type)) {
093                            continue outer;
094                        }
095                    }
096                }
097    
098                // Don't add type if it is already present, to avoid trivial type intersections in result
099                for (KotlinType other : resultingTypes) {
100                    if (typeChecker.equalTypes(other, type)) {
101                        continue outer;
102                    }
103                }
104                resultingTypes.add(type);
105            }
106    
107            if (resultingTypes.isEmpty()) {
108                // If we ended up here, it means that all types from `nullabilityStripped` were excluded by the code above
109                // most likely, this is because they are all semantically interchangeable (e.g. List<Foo>! and List<Foo>),
110                // in that case, we can safely select the best representative out of that set and return it
111                // TODO: maybe return the most specific among the types that are subtypes to all others in the `nullabilityStripped`?
112                // TODO: e.g. among {Int, Int?, Int!}, return `Int` (now it returns `Int!`).
113                KotlinType bestRepresentative = FlexibleTypesKt.singleBestRepresentative(nullabilityStripped);
114                if (bestRepresentative == null) {
115                    throw new AssertionError("Empty intersection for types " + types);
116                }
117                return TypeUtils.makeNullableAsSpecified(bestRepresentative, allNullable);
118            }
119    
120            if (resultingTypes.size() == 1) {
121                return TypeUtils.makeNullableAsSpecified(resultingTypes.get(0), allNullable);
122            }
123    
124            TypeConstructor constructor = new IntersectionTypeConstructor(Annotations.Companion.getEMPTY(), resultingTypes);
125    
126            return KotlinTypeImpl.create(
127                    Annotations.Companion.getEMPTY(),
128                    constructor,
129                    allNullable,
130                    Collections.<TypeProjection>emptyList(),
131                    TypeIntersectionScope.create("member scope for intersection type " + constructor, resultingTypes)
132            );
133        }
134    
135        /**
136         * Note: this method was used in overload and override bindings to approximate type parameters with several bounds,
137         * but as it turned out at some point, that logic was inconsistent with Java rules, so it was simplified.
138         * Most of the other usages of this method are left untouched but probably should be investigated closely if they're still valid.
139         */
140        @NotNull
141        public static KotlinType getUpperBoundsAsType(@NotNull TypeParameterDescriptor descriptor) {
142            List<KotlinType> upperBounds = descriptor.getUpperBounds();
143            assert !upperBounds.isEmpty() : "Upper bound list is empty: " + descriptor;
144            KotlinType upperBoundsAsType = intersectTypes(KotlinTypeChecker.DEFAULT, upperBounds);
145            return upperBoundsAsType != null ? upperBoundsAsType : getBuiltIns(descriptor).getNothingType();
146        }
147    
148        private static class TypeUnifier {
149            private static class TypeParameterUsage {
150                private final TypeParameterDescriptor typeParameterDescriptor;
151                private final Variance howTheTypeParameterIsUsed;
152    
153                public TypeParameterUsage(TypeParameterDescriptor typeParameterDescriptor, Variance howTheTypeParameterIsUsed) {
154                    this.typeParameterDescriptor = typeParameterDescriptor;
155                    this.howTheTypeParameterIsUsed = howTheTypeParameterIsUsed;
156                }
157            }
158    
159            public static boolean mayBeEqual(@NotNull KotlinType type, @NotNull KotlinType other) {
160                return unify(type, other);
161            }
162    
163            private static boolean unify(KotlinType withParameters, KotlinType expected) {
164                // T -> how T is used
165                final Map<TypeParameterDescriptor, Variance> parameters = new HashMap<TypeParameterDescriptor, Variance>();
166                Function1<TypeParameterUsage, Unit> processor = new Function1<TypeParameterUsage, Unit>() {
167                    @Override
168                    public Unit invoke(TypeParameterUsage parameterUsage) {
169                        Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
170                        if (howTheTypeIsUsedBefore == null) {
171                            howTheTypeIsUsedBefore = Variance.INVARIANT;
172                        }
173                        parameters.put(parameterUsage.typeParameterDescriptor,
174                                       parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
175                        return Unit.INSTANCE;
176                    }
177                };
178                processAllTypeParameters(withParameters, Variance.INVARIANT, processor);
179                processAllTypeParameters(expected, Variance.INVARIANT, processor);
180                ConstraintSystem.Builder constraintSystem = new ConstraintSystemBuilderImpl();
181                TypeSubstitutor substitutor = constraintSystem.registerTypeVariables(CallHandle.NONE.INSTANCE, parameters.keySet(), false);
182                constraintSystem.addSubtypeConstraint(withParameters, substitutor.substitute(expected, Variance.INVARIANT), SPECIAL.position());
183    
184                return constraintSystem.build().getStatus().isSuccessful();
185            }
186    
187            private static void processAllTypeParameters(KotlinType type, Variance howThisTypeIsUsed, Function1<TypeParameterUsage, Unit> result) {
188                ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
189                if (descriptor instanceof TypeParameterDescriptor) {
190                    result.invoke(new TypeParameterUsage((TypeParameterDescriptor) descriptor, howThisTypeIsUsed));
191                }
192                for (TypeProjection projection : type.getArguments()) {
193                    if (projection.isStarProjection()) continue;
194                    processAllTypeParameters(projection.getType(), projection.getProjectionKind(), result);
195                }
196            }
197        }
198    }