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                    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                if (bestRepresentative == null) {
121                    throw new AssertionError("Empty intersection for types " + types);
122                }
123                return TypeUtils.makeNullableAsSpecified(bestRepresentative, allNullable);
124            }
125    
126            if (resultingTypes.size() == 1) {
127                return TypeUtils.makeNullableAsSpecified(resultingTypes.get(0), allNullable);
128            }
129    
130            TypeConstructor constructor = new IntersectionTypeConstructor(Annotations.Companion.getEMPTY(), resultingTypes);
131    
132            return KotlinTypeImpl.create(
133                    Annotations.Companion.getEMPTY(),
134                    constructor,
135                    allNullable,
136                    Collections.<TypeProjection>emptyList(),
137                    TypeIntersectionScope.create("member scope for intersection type " + constructor, resultingTypes)
138            );
139        }
140    
141        /**
142         * Note: this method was used in overload and override bindings to approximate type parameters with several bounds,
143         * but as it turned out at some point, that logic was inconsistent with Java rules, so it was simplified.
144         * Most of the other usages of this method are left untouched but probably should be investigated closely if they're still valid.
145         */
146        @NotNull
147        public static KotlinType getUpperBoundsAsType(@NotNull TypeParameterDescriptor descriptor) {
148            List<KotlinType> upperBounds = descriptor.getUpperBounds();
149            assert !upperBounds.isEmpty() : "Upper bound list is empty: " + descriptor;
150            KotlinType upperBoundsAsType = intersectTypes(KotlinTypeChecker.DEFAULT, upperBounds);
151            return upperBoundsAsType != null ? upperBoundsAsType : getBuiltIns(descriptor).getNothingType();
152        }
153    
154        private static class TypeUnifier {
155            private static class TypeParameterUsage {
156                private final TypeParameterDescriptor typeParameterDescriptor;
157                private final Variance howTheTypeParameterIsUsed;
158    
159                public TypeParameterUsage(TypeParameterDescriptor typeParameterDescriptor, Variance howTheTypeParameterIsUsed) {
160                    this.typeParameterDescriptor = typeParameterDescriptor;
161                    this.howTheTypeParameterIsUsed = howTheTypeParameterIsUsed;
162                }
163            }
164    
165            public static boolean mayBeEqual(@NotNull KotlinType type, @NotNull KotlinType other) {
166                return unify(type, other);
167            }
168    
169            private static boolean unify(KotlinType withParameters, KotlinType expected) {
170                // T -> how T is used
171                final Map<TypeParameterDescriptor, Variance> parameters = new HashMap<TypeParameterDescriptor, Variance>();
172                Function1<TypeParameterUsage, Unit> processor = new Function1<TypeParameterUsage, Unit>() {
173                    @Override
174                    public Unit invoke(TypeParameterUsage parameterUsage) {
175                        Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
176                        if (howTheTypeIsUsedBefore == null) {
177                            howTheTypeIsUsedBefore = Variance.INVARIANT;
178                        }
179                        parameters.put(parameterUsage.typeParameterDescriptor,
180                                       parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
181                        return Unit.INSTANCE;
182                    }
183                };
184                processAllTypeParameters(withParameters, Variance.INVARIANT, processor);
185                processAllTypeParameters(expected, Variance.INVARIANT, processor);
186                ConstraintSystem.Builder constraintSystem = new ConstraintSystemBuilderImpl();
187                TypeSubstitutor substitutor = constraintSystem.registerTypeVariables(CallHandle.NONE.INSTANCE, parameters.keySet(), false);
188                constraintSystem.addSubtypeConstraint(withParameters, substitutor.substitute(expected, Variance.INVARIANT), SPECIAL.position());
189    
190                return constraintSystem.build().getStatus().isSuccessful();
191            }
192    
193            private static void processAllTypeParameters(KotlinType type, Variance howThisTypeIsUsed, Function1<TypeParameterUsage, Unit> result) {
194                ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
195                if (descriptor instanceof TypeParameterDescriptor) {
196                    result.invoke(new TypeParameterUsage((TypeParameterDescriptor) descriptor, howThisTypeIsUsed));
197                }
198                for (TypeProjection projection : type.getArguments()) {
199                    if (projection.isStarProjection()) continue;
200                    processAllTypeParameters(projection.getType(), projection.getProjectionKind(), result);
201                }
202            }
203        }
204    }