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.collections.CollectionsKt;
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.ClassDescriptor;
025    import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
026    import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
027    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
028    import org.jetbrains.kotlin.resolve.scopes.MemberScope;
029    import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
030    import org.jetbrains.kotlin.types.typeUtil.TypeUtilsKt;
031    import org.jetbrains.kotlin.utils.DFS;
032    
033    import java.util.*;
034    
035    import static org.jetbrains.kotlin.types.Variance.IN_VARIANCE;
036    import static org.jetbrains.kotlin.types.Variance.OUT_VARIANCE;
037    
038    public class CommonSupertypes {
039        @Nullable
040        public static KotlinType commonSupertypeForNonDenotableTypes(@NotNull Collection<KotlinType> types) {
041            if (types.isEmpty()) return null;
042            if (types.size() == 1) {
043                KotlinType type = types.iterator().next();
044                if (type.getConstructor() instanceof IntersectionTypeConstructor) {
045                    return commonSupertypeForNonDenotableTypes(type.getConstructor().getSupertypes());
046                }
047            }
048            return commonSupertype(types);
049        }
050    
051        @NotNull
052        public static KotlinType commonSupertype(@NotNull Collection<KotlinType> types) {
053            // Recursion should not be significantly deeper than the deepest type in question
054            // It can be slightly deeper, though: e.g. when initial types are simple, but their supertypes are complex
055            return findCommonSupertype(types, 0, maxDepth(types) + 3);
056        }
057    
058        private static int maxDepth(@NotNull Collection<KotlinType> types) {
059            int max = 0;
060            for (KotlinType type : types) {
061                int depth = depth(type);
062                if (max < depth) {
063                    max = depth;
064                }
065            }
066            return max;
067        }
068    
069        private static int depth(@NotNull final KotlinType type) {
070            return 1 + maxDepth(CollectionsKt.map(type.getArguments(), new Function1<TypeProjection, KotlinType>() {
071                @Override
072                public KotlinType invoke(TypeProjection projection) {
073                    if (projection.isStarProjection()) {
074                        // any type is good enough for depth here
075                        return type.getConstructor().getBuiltIns().getAnyType();
076                    }
077                    return projection.getType();
078                }
079            }));
080        }
081    
082        @NotNull
083        private static KotlinType findCommonSupertype(@NotNull Collection<KotlinType> types, int recursionDepth, int maxDepth) {
084            assert recursionDepth <= maxDepth : "Recursion depth exceeded: " + recursionDepth + " > " + maxDepth + " for types " + types;
085            boolean hasFlexible = false;
086            List<KotlinType> upper = new ArrayList<KotlinType>(types.size());
087            List<KotlinType> lower = new ArrayList<KotlinType>(types.size());
088            Set<FlexibleTypeFactory> factories = new LinkedHashSet<FlexibleTypeFactory>();
089            for (KotlinType type : types) {
090                if (FlexibleTypesKt.isFlexible(type)) {
091                    if (DynamicTypesKt.isDynamic(type)) {
092                        return type;
093                    }
094                    hasFlexible = true;
095                    Flexibility flexibility = FlexibleTypesKt.flexibility(type);
096                    upper.add(flexibility.getUpperBound());
097                    lower.add(flexibility.getLowerBound());
098                    factories.add(flexibility.getFactory());
099                }
100                else {
101                    upper.add(type);
102                    lower.add(type);
103                }
104            }
105    
106            if (!hasFlexible) return commonSuperTypeForInflexible(types, recursionDepth, maxDepth);
107            return CollectionsKt.single(factories).create( // mixing different factories is not supported
108                    commonSuperTypeForInflexible(lower, recursionDepth, maxDepth),
109                    commonSuperTypeForInflexible(upper, recursionDepth, maxDepth)
110            );
111        }
112    
113        @NotNull
114        private static KotlinType commonSuperTypeForInflexible(@NotNull Collection<KotlinType> types, int recursionDepth, int maxDepth) {
115            assert !types.isEmpty();
116            Collection<KotlinType> typeSet = new HashSet<KotlinType>(types);
117    
118            KotlinType bestFit = FlexibleTypesKt.singleBestRepresentative(typeSet);
119            if (bestFit != null) return bestFit;
120    
121            // If any of the types is nullable, the result must be nullable
122            // This also removed Nothing and Nothing? because they are subtypes of everything else
123            boolean nullable = false;
124            for (Iterator<KotlinType> iterator = typeSet.iterator(); iterator.hasNext();) {
125                KotlinType type = iterator.next();
126                assert type != null;
127                assert !FlexibleTypesKt.isFlexible(type) : "Flexible type " + type + " passed to commonSuperTypeForInflexible";
128                if (KotlinBuiltIns.isNothingOrNullableNothing(type)) {
129                    iterator.remove();
130                }
131                if (type.isError()) {
132                    return ErrorUtils.createErrorType("Supertype of error type " + type);
133                }
134                nullable |= type.isMarkedNullable();
135            }
136    
137            // Everything deleted => it's Nothing or Nothing?
138            if (typeSet.isEmpty()) {
139                // TODO : attributes
140                KotlinBuiltIns builtIns = types.iterator().next().getConstructor().getBuiltIns();
141                return nullable ? builtIns.getNullableNothingType() : builtIns.getNothingType();
142            }
143    
144            if (typeSet.size() == 1) {
145                return TypeUtils.makeNullableIfNeeded(typeSet.iterator().next(), nullable);
146            }
147    
148            // constructor of the supertype -> all of its instantiations occurring as supertypes
149            Map<TypeConstructor, Set<KotlinType>> commonSupertypes = computeCommonRawSupertypes(typeSet);
150            while (commonSupertypes.size() > 1) {
151                Set<KotlinType> merge = new HashSet<KotlinType>();
152                for (Set<KotlinType> supertypes : commonSupertypes.values()) {
153                    merge.addAll(supertypes);
154                }
155                commonSupertypes = computeCommonRawSupertypes(merge);
156            }
157            assert !commonSupertypes.isEmpty() : commonSupertypes + " <- " + types;
158    
159            // constructor of the supertype -> all of its instantiations occurring as supertypes
160            Map.Entry<TypeConstructor, Set<KotlinType>> entry = commonSupertypes.entrySet().iterator().next();
161    
162            // Reconstructing type arguments if possible
163            KotlinType result = computeSupertypeProjections(entry.getKey(), entry.getValue(), recursionDepth, maxDepth);
164            return TypeUtils.makeNullableIfNeeded(result, nullable);
165        }
166    
167        // Raw supertypes are superclasses w/o type arguments
168        // @return TypeConstructor -> all instantiations of this constructor occurring as supertypes
169        @NotNull
170        private static Map<TypeConstructor, Set<KotlinType>> computeCommonRawSupertypes(@NotNull Collection<KotlinType> types) {
171            assert !types.isEmpty();
172    
173            Map<TypeConstructor, Set<KotlinType>> constructorToAllInstances = new HashMap<TypeConstructor, Set<KotlinType>>();
174            Set<TypeConstructor> commonSuperclasses = null;
175    
176            List<TypeConstructor> order = null;
177            for (KotlinType type : types) {
178                Set<TypeConstructor> visited = new HashSet<TypeConstructor>();
179                order = topologicallySortSuperclassesAndRecordAllInstances(type, constructorToAllInstances, visited);
180    
181                if (commonSuperclasses == null) {
182                    commonSuperclasses = visited;
183                }
184                else {
185                    commonSuperclasses.retainAll(visited);
186                }
187            }
188            assert order != null;
189    
190            Set<TypeConstructor> notSource = new HashSet<TypeConstructor>();
191            Map<TypeConstructor, Set<KotlinType>> result = new HashMap<TypeConstructor, Set<KotlinType>>();
192            for (TypeConstructor superConstructor : order) {
193                if (!commonSuperclasses.contains(superConstructor)) {
194                    continue;
195                }
196    
197                if (!notSource.contains(superConstructor)) {
198                    result.put(superConstructor, constructorToAllInstances.get(superConstructor));
199                    markAll(superConstructor, notSource);
200                }
201            }
202    
203            return result;
204        }
205    
206        // constructor - type constructor of a supertype to be instantiated
207        // types - instantiations of constructor occurring as supertypes of classes we are trying to intersect
208        @NotNull
209        private static KotlinType computeSupertypeProjections(@NotNull TypeConstructor constructor, @NotNull Set<KotlinType> types, int recursionDepth, int maxDepth) {
210            // we assume that all the given types are applications of the same type constructor
211    
212            assert !types.isEmpty();
213    
214            if (types.size() == 1) {
215                return types.iterator().next();
216            }
217    
218            List<TypeParameterDescriptor> parameters = constructor.getParameters();
219            List<TypeProjection> newProjections = new ArrayList<TypeProjection>(parameters.size());
220            for (TypeParameterDescriptor parameterDescriptor : parameters) {
221                Set<TypeProjection> typeProjections = new HashSet<TypeProjection>();
222                for (KotlinType type : types) {
223                    typeProjections.add(type.getArguments().get(parameterDescriptor.getIndex()));
224                }
225                newProjections.add(computeSupertypeProjection(parameterDescriptor, typeProjections, recursionDepth, maxDepth));
226            }
227    
228            boolean nullable = false;
229            for (KotlinType type : types) {
230                nullable |= type.isMarkedNullable();
231            }
232    
233            ClassifierDescriptor classifier = constructor.getDeclarationDescriptor();
234            MemberScope newScope;
235            if (classifier instanceof ClassDescriptor) {
236                newScope = ((ClassDescriptor) classifier).getMemberScope(newProjections);
237            }
238            else if (classifier instanceof TypeParameterDescriptor) {
239                newScope = classifier.getDefaultType().getMemberScope();
240            }
241            else {
242                newScope = ErrorUtils.createErrorScope("A scope for common supertype which is not a normal classifier", true);
243            }
244            return KotlinTypeImpl.create(Annotations.Companion.getEMPTY(), constructor, nullable, newProjections, newScope);
245        }
246    
247        @NotNull
248        private static TypeProjection computeSupertypeProjection(
249                @NotNull TypeParameterDescriptor parameterDescriptor,
250                @NotNull Set<TypeProjection> typeProjections,
251                int recursionDepth, int maxDepth
252        ) {
253            TypeProjection singleBestProjection = FlexibleTypesKt.singleBestRepresentative(typeProjections);
254            if (singleBestProjection != null) {
255                return singleBestProjection;
256            }
257    
258            if (recursionDepth >= maxDepth) {
259                // If recursion is too deep, we cut it by taking <out Any?> as an ultimate supertype argument
260                // Example: class A : Base<A>; class B : Base<B>, commonSuperType(A, B) = Base<*>
261                return TypeUtils.makeStarProjection(parameterDescriptor);
262            }
263    
264            Set<KotlinType> ins = new HashSet<KotlinType>();
265            Set<KotlinType> outs = new HashSet<KotlinType>();
266    
267            Variance variance = parameterDescriptor.getVariance();
268            switch (variance) {
269                case INVARIANT:
270                    // Nothing
271                    break;
272                case IN_VARIANCE:
273                    outs = null;
274                    break;
275                case OUT_VARIANCE:
276                    ins = null;
277                    break;
278            }
279    
280            for (TypeProjection projection : typeProjections) {
281                Variance projectionKind = projection.getProjectionKind();
282                if (projectionKind.getAllowsInPosition()) {
283                    if (ins != null) {
284                        ins.add(projection.getType());
285                    }
286                }
287                else {
288                    ins = null;
289                }
290    
291                if (projectionKind.getAllowsOutPosition()) {
292                    if (outs != null) {
293                        outs.add(projection.getType());
294                    }
295                }
296                else {
297                    outs = null;
298                }
299            }
300    
301            if (outs != null) {
302                assert !outs.isEmpty() : "Out projections is empty for parameter " + parameterDescriptor + ", type projections " + typeProjections;
303                Variance projectionKind = variance == OUT_VARIANCE ? Variance.INVARIANT : OUT_VARIANCE;
304                KotlinType superType = findCommonSupertype(outs, recursionDepth + 1, maxDepth);
305                for (KotlinType upperBound: parameterDescriptor.getUpperBounds()) {
306                    if (!TypeUtilsKt.isSubtypeOf(superType, upperBound)) {
307                        return new StarProjectionImpl(parameterDescriptor);
308                    }
309                }
310                return new TypeProjectionImpl(projectionKind, superType);
311            }
312            if (ins != null) {
313                assert !ins.isEmpty() : "In projections is empty for parameter " + parameterDescriptor + ", type projections " + typeProjections;
314                KotlinType intersection = TypeIntersector.intersectTypes(KotlinTypeChecker.DEFAULT, ins);
315                if (intersection == null) {
316                    return TypeUtils.makeStarProjection(parameterDescriptor);
317                }
318                Variance projectionKind = variance == IN_VARIANCE ? Variance.INVARIANT : IN_VARIANCE;
319                return new TypeProjectionImpl(projectionKind, intersection);
320            }
321            else {
322                return TypeUtils.makeStarProjection(parameterDescriptor);
323            }
324        }
325    
326        private static void markAll(@NotNull TypeConstructor typeConstructor, @NotNull Set<TypeConstructor> markerSet) {
327            markerSet.add(typeConstructor);
328            for (KotlinType type : typeConstructor.getSupertypes()) {
329                markAll(type.getConstructor(), markerSet);
330            }
331        }
332    
333        @NotNull
334        public static List<TypeConstructor> topologicallySortSuperclassesAndRecordAllInstances(
335                @NotNull KotlinType type,
336                @NotNull final Map<TypeConstructor, Set<KotlinType>> constructorToAllInstances,
337                @NotNull final Set<TypeConstructor> visited
338        ) {
339            return DFS.dfs(
340                    Collections.singletonList(type),
341                    new DFS.Neighbors<KotlinType>() {
342                        @NotNull
343                        @Override
344                        public Iterable<KotlinType> getNeighbors(KotlinType current) {
345                            TypeSubstitutor substitutor = TypeSubstitutor.create(current);
346                            Collection<KotlinType> supertypes = current.getConstructor().getSupertypes();
347                            List<KotlinType> result = new ArrayList<KotlinType>(supertypes.size());
348                            for (KotlinType supertype : supertypes) {
349                                if (visited.contains(supertype.getConstructor())) {
350                                    continue;
351                                }
352                                result.add(substitutor.safeSubstitute(supertype, Variance.INVARIANT));
353                            }
354                            return result;
355                        }
356                    },
357                    new DFS.Visited<KotlinType>() {
358                        @Override
359                        public boolean checkAndMarkVisited(KotlinType current) {
360                            return visited.add(current.getConstructor());
361                        }
362                    },
363                    new DFS.NodeHandlerWithListResult<KotlinType, TypeConstructor>() {
364                        @Override
365                        public boolean beforeChildren(KotlinType current) {
366                            TypeConstructor constructor = current.getConstructor();
367    
368                            Set<KotlinType> instances = constructorToAllInstances.get(constructor);
369                            if (instances == null) {
370                                instances = new HashSet<KotlinType>();
371                                constructorToAllInstances.put(constructor, instances);
372                            }
373                            instances.add(current);
374    
375                            return true;
376                        }
377    
378                        @Override
379                        public void afterChildren(KotlinType current) {
380                            result.addFirst(current.getConstructor());
381                        }
382                    }
383            );
384        }
385    }