001    /*
002     * Copyright 2010-2013 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.jet.lang.types;
018    
019    import com.google.common.base.Function;
020    import com.google.common.collect.Collections2;
021    import com.google.common.collect.Lists;
022    import com.google.common.collect.Maps;
023    import com.google.common.collect.Sets;
024    import com.intellij.openapi.util.Pair;
025    import com.intellij.util.Processor;
026    import com.intellij.util.containers.ContainerUtil;
027    import org.jetbrains.annotations.NotNull;
028    import org.jetbrains.annotations.Nullable;
029    import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
030    import org.jetbrains.jet.lang.descriptors.ClassifierDescriptor;
031    import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
032    import org.jetbrains.jet.lang.descriptors.TypeParameterDescriptor;
033    import org.jetbrains.jet.lang.descriptors.annotations.Annotations;
034    import org.jetbrains.jet.lang.resolve.calls.inference.ConstraintPosition;
035    import org.jetbrains.jet.lang.resolve.calls.inference.ConstraintSystemImpl;
036    import org.jetbrains.jet.lang.resolve.constants.IntegerValueTypeConstructor;
037    import org.jetbrains.jet.lang.resolve.scopes.ChainedScope;
038    import org.jetbrains.jet.lang.resolve.scopes.JetScope;
039    import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
040    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
041    import org.jetbrains.jet.utils.DFS;
042    
043    import java.util.*;
044    
045    public class TypeUtils {
046        public static final JetType DONT_CARE = ErrorUtils.createErrorTypeWithCustomDebugName("DONT_CARE");
047        public static final JetType CANT_INFER_TYPE_PARAMETER = ErrorUtils.createErrorTypeWithCustomDebugName("CANT_INFER_TYPE_PARAMETER");
048        public static final JetType PLACEHOLDER_FUNCTION_TYPE = ErrorUtils.createErrorTypeWithCustomDebugName("PLACEHOLDER_FUNCTION_TYPE");
049    
050        public static final JetType CANT_INFER_LAMBDA_PARAM_TYPE = ErrorUtils.createErrorType("Cannot be inferred");
051    
052        public static class SpecialType implements JetType {
053            private final String name;
054    
055            public SpecialType(String name) {
056                this.name = name;
057            }
058    
059            @NotNull
060            @Override
061            public TypeConstructor getConstructor() {
062                throw new IllegalStateException(name);
063            }
064    
065            @NotNull
066            @Override
067            public List<TypeProjection> getArguments() {
068                throw new IllegalStateException(name);
069            }
070    
071            @Override
072            public boolean isNullable() {
073                throw new IllegalStateException(name);
074            }
075    
076            @NotNull
077            @Override
078            public JetScope getMemberScope() {
079                throw new IllegalStateException(name);
080            }
081    
082            @Override
083            public boolean isError() {
084                return false;
085            }
086    
087            @NotNull
088            @Override
089            public Annotations getAnnotations() {
090                throw new IllegalStateException(name);
091            }
092    
093            @Override
094            public String toString() {
095                return name;
096            }
097        }
098    
099        public static final JetType NO_EXPECTED_TYPE = new SpecialType("NO_EXPECTED_TYPE");
100        
101        public static final JetType UNIT_EXPECTED_TYPE = new SpecialType("UNIT_EXPECTED_TYPE");
102    
103        public static boolean noExpectedType(@NotNull JetType type) {
104            return type == NO_EXPECTED_TYPE || type == UNIT_EXPECTED_TYPE;
105        }
106    
107        @NotNull
108        public static JetType makeNullable(@NotNull JetType type) {
109            return makeNullableAsSpecified(type, true);
110        }
111    
112        @NotNull
113        public static JetType makeNotNullable(@NotNull JetType type) {
114            return makeNullableAsSpecified(type, false);
115        }
116    
117        @NotNull
118        public static JetType makeNullableAsSpecified(@NotNull JetType type, boolean nullable) {
119            // Wrapping serves two purposes here
120            // 1. It's requires less memory than copying with a changed nullability flag: a copy has many fields, while a wrapper has only one
121            // 2. It preserves laziness of types
122    
123            // Unwrap to avoid long delegation call chains
124            if (type instanceof AbstractTypeWithKnownNullability) {
125                return makeNullableAsSpecified(((AbstractTypeWithKnownNullability) type).delegate, nullable);
126            }
127    
128            // checking to preserve laziness
129            if (!(type instanceof LazyType) && type.isNullable() == nullable) {
130                return type;
131            }
132    
133            return nullable ? new NullableType(type) : new NotNullType(type);
134        }
135    
136        public static boolean isIntersectionEmpty(@NotNull JetType typeA, @NotNull JetType typeB) {
137            return intersect(JetTypeChecker.INSTANCE, Sets.newLinkedHashSet(Lists.newArrayList(typeA, typeB))) == null;
138        }
139    
140        @Nullable
141        public static JetType intersect(@NotNull JetTypeChecker typeChecker, @NotNull Set<JetType> types) {
142            if (types.isEmpty()) {
143                return KotlinBuiltIns.getInstance().getNullableAnyType();
144            }
145    
146            if (types.size() == 1) {
147                return types.iterator().next();
148            }
149    
150            // Intersection of T1..Tn is an intersection of their non-null versions,
151            //   made nullable is they all were nullable
152            boolean allNullable = true;
153            boolean nothingTypePresent = false;
154            List<JetType> nullabilityStripped = Lists.newArrayList();
155            for (JetType type : types) {
156                nothingTypePresent |= KotlinBuiltIns.getInstance().isNothingOrNullableNothing(type);
157                allNullable &= type.isNullable();
158                nullabilityStripped.add(makeNotNullable(type));
159            }
160            
161            if (nothingTypePresent) {
162                return allNullable ? KotlinBuiltIns.getInstance().getNullableNothingType() : KotlinBuiltIns.getInstance().getNothingType();
163            }
164    
165            // Now we remove types that have subtypes in the list
166            List<JetType> resultingTypes = Lists.newArrayList();
167            outer:
168            for (JetType type : nullabilityStripped) {
169                if (!canHaveSubtypes(typeChecker, type)) {
170                    for (JetType other : nullabilityStripped) {
171                        // It makes sense to check for subtyping (other <: type), despite that
172                        // type is not supposed to be open, for there're enums
173                        if (!TypeUnifier.mayBeEqual(type, other) && !typeChecker.isSubtypeOf(type, other) && !typeChecker.isSubtypeOf(other, type)) {
174                            return null;
175                        }
176                    }
177                    return makeNullableAsSpecified(type, allNullable);
178                }
179                else {
180                    for (JetType other : nullabilityStripped) {
181                        if (!type.equals(other) && typeChecker.isSubtypeOf(other, type)) {
182                            continue outer;
183                        }
184    
185                    }
186                }
187    
188                // Don't add type if it is already present, to avoid trivial type intersections in result
189                for (JetType other : resultingTypes) {
190                    if (typeChecker.equalTypes(other, type)) {
191                        continue outer;
192                    }
193                }
194                resultingTypes.add(type);
195            }
196            
197            if (resultingTypes.size() == 1) {
198                return makeNullableAsSpecified(resultingTypes.get(0), allNullable);
199            }
200    
201    
202            TypeConstructor constructor = new IntersectionTypeConstructor(Annotations.EMPTY, resultingTypes);
203    
204            JetScope[] scopes = new JetScope[resultingTypes.size()];
205            int i = 0;
206            for (JetType type : resultingTypes) {
207                scopes[i] = type.getMemberScope();
208                i++;
209            }
210    
211            return new JetTypeImpl(
212                    Annotations.EMPTY,
213                    constructor,
214                    allNullable,
215                    Collections.<TypeProjection>emptyList(),
216                    new ChainedScope(null, "member scope for intersection type " + constructor, scopes)); // TODO : check intersectibility, don't use a chanied scope
217        }
218    
219        private static class TypeUnifier {
220            private static class TypeParameterUsage {
221                private final TypeParameterDescriptor typeParameterDescriptor;
222                private final Variance howTheTypeParameterIsUsed;
223    
224                public TypeParameterUsage(TypeParameterDescriptor typeParameterDescriptor, Variance howTheTypeParameterIsUsed) {
225                    this.typeParameterDescriptor = typeParameterDescriptor;
226                    this.howTheTypeParameterIsUsed = howTheTypeParameterIsUsed;
227                }
228            }
229    
230            public static boolean mayBeEqual(@NotNull JetType type, @NotNull JetType other) {
231                return unify(type, other);
232            }
233    
234            private static boolean unify(JetType withParameters, JetType expected) {
235                // T -> how T is used
236                final Map<TypeParameterDescriptor, Variance> parameters = Maps.newHashMap();
237                Processor<TypeParameterUsage> processor = new Processor<TypeParameterUsage>() {
238                    @Override
239                    public boolean process(TypeParameterUsage parameterUsage) {
240                        Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
241                        if (howTheTypeIsUsedBefore == null) {
242                            howTheTypeIsUsedBefore = Variance.INVARIANT;
243                        }
244                        parameters.put(parameterUsage.typeParameterDescriptor,
245                                       parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
246                        return true;
247                    }
248                };
249                processAllTypeParameters(withParameters, Variance.INVARIANT, processor);
250                processAllTypeParameters(expected, Variance.INVARIANT, processor);
251                ConstraintSystemImpl constraintSystem = new ConstraintSystemImpl();
252                constraintSystem.registerTypeVariables(parameters);
253                constraintSystem.addSubtypeConstraint(withParameters, expected, ConstraintPosition.SPECIAL);
254    
255                return constraintSystem.getStatus().isSuccessful();
256            }
257    
258            private static void processAllTypeParameters(JetType type, Variance howThiTypeIsUsed, Processor<TypeParameterUsage> result) {
259                ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
260                if (descriptor instanceof TypeParameterDescriptor) {
261                    result.process(new TypeParameterUsage((TypeParameterDescriptor)descriptor, howThiTypeIsUsed));
262                }
263                for (TypeProjection projection : type.getArguments()) {
264                    processAllTypeParameters(projection.getType(), projection.getProjectionKind(), result);
265                }
266            }
267        }
268    
269        public static boolean canHaveSubtypes(JetTypeChecker typeChecker, JetType type) {
270            if (type.isNullable()) {
271                return true;
272            }
273            if (!type.getConstructor().isFinal()) {
274                return true;
275            }
276    
277            List<TypeParameterDescriptor> parameters = type.getConstructor().getParameters();
278            List<TypeProjection> arguments = type.getArguments();
279            for (int i = 0, parametersSize = parameters.size(); i < parametersSize; i++) {
280                TypeParameterDescriptor parameterDescriptor = parameters.get(i);
281                TypeProjection typeProjection = arguments.get(i);
282                Variance projectionKind = typeProjection.getProjectionKind();
283                JetType argument = typeProjection.getType();
284    
285                switch (parameterDescriptor.getVariance()) {
286                    case INVARIANT:
287                        switch (projectionKind) {
288                            case INVARIANT:
289                                if (lowerThanBound(typeChecker, argument, parameterDescriptor) || canHaveSubtypes(typeChecker, argument)) {
290                                    return true;
291                                }
292                                break;
293                            case IN_VARIANCE:
294                                if (lowerThanBound(typeChecker, argument, parameterDescriptor)) {
295                                    return true;
296                                }
297                                break;
298                            case OUT_VARIANCE:
299                                if (canHaveSubtypes(typeChecker, argument)) {
300                                    return true;
301                                }
302                                break;
303                        }
304                        break;
305                    case IN_VARIANCE:
306                        if (projectionKind != Variance.OUT_VARIANCE) {
307                            if (lowerThanBound(typeChecker, argument, parameterDescriptor)) {
308                                return true;
309                            }
310                        }
311                        else {
312                            if (canHaveSubtypes(typeChecker, argument)) {
313                                return true;
314                            }
315                        }
316                        break;
317                    case OUT_VARIANCE:
318                        if (projectionKind != Variance.IN_VARIANCE) {
319                            if (canHaveSubtypes(typeChecker, argument)) {
320                                return true;
321                            }
322                        }
323                        else {
324                            if (lowerThanBound(typeChecker, argument, parameterDescriptor)) {
325                                return true;
326                            }
327                        }
328                        break;
329                }
330            }
331            return false;
332        }
333    
334        private static boolean lowerThanBound(JetTypeChecker typeChecker, JetType argument, TypeParameterDescriptor parameterDescriptor) {
335            for (JetType bound : parameterDescriptor.getUpperBounds()) {
336                if (typeChecker.isSubtypeOf(argument, bound)) {
337                    if (!argument.getConstructor().equals(bound.getConstructor())) {
338                        return true;
339                    }
340                }
341            }
342            return false;
343        }
344    
345        public static JetType makeNullableIfNeeded(JetType type, boolean nullable) {
346            if (nullable) {
347                return makeNullable(type);
348            }
349            return type;
350        }
351    
352        @NotNull
353        public static JetType makeUnsubstitutedType(ClassDescriptor classDescriptor, JetScope unsubstitutedMemberScope) {
354            if (ErrorUtils.isError(classDescriptor)) {
355                return ErrorUtils.createErrorType("Unsubstituted type for " + classDescriptor);
356            }
357            TypeConstructor typeConstructor = classDescriptor.getTypeConstructor();
358            List<TypeProjection> arguments = getDefaultTypeProjections(typeConstructor.getParameters());
359            return new JetTypeImpl(
360                    Annotations.EMPTY,
361                    typeConstructor,
362                    false,
363                    arguments,
364                    unsubstitutedMemberScope
365            );
366        }
367    
368        @NotNull
369        public static List<TypeProjection> getDefaultTypeProjections(List<TypeParameterDescriptor> parameters) {
370            List<TypeProjection> result = new ArrayList<TypeProjection>();
371            for (TypeParameterDescriptor parameterDescriptor : parameters) {
372                result.add(new TypeProjectionImpl(parameterDescriptor.getDefaultType()));
373            }
374            return result;
375        }
376    
377        @NotNull
378        public static List<JetType> getDefaultTypes(List<TypeParameterDescriptor> parameters) {
379            List<JetType> result = Lists.newArrayList();
380            for (TypeParameterDescriptor parameterDescriptor : parameters) {
381                result.add(parameterDescriptor.getDefaultType());
382            }
383            return result;
384        }
385    
386        private static void collectImmediateSupertypes(@NotNull JetType type, @NotNull Collection<JetType> result) {
387            TypeSubstitutor substitutor = TypeSubstitutor.create(type);
388            for (JetType supertype : type.getConstructor().getSupertypes()) {
389                result.add(substitutor.substitute(supertype, Variance.INVARIANT));
390            }
391        }
392    
393        @NotNull
394        public static List<JetType> getImmediateSupertypes(@NotNull JetType type) {
395            List<JetType> result = Lists.newArrayList();
396            collectImmediateSupertypes(type, result);
397            return result;
398        }
399    
400        private static void collectAllSupertypes(@NotNull JetType type, @NotNull Set<JetType> result) {
401            List<JetType> immediateSupertypes = getImmediateSupertypes(type);
402            result.addAll(immediateSupertypes);
403            for (JetType supertype : immediateSupertypes) {
404                collectAllSupertypes(supertype, result);
405            }
406        }
407    
408    
409        @NotNull
410        public static Set<JetType> getAllSupertypes(@NotNull JetType type) {
411            // 15 is obtained by experimentation: JDK classes like ArrayList tend to have so many supertypes,
412            // the average number is lower
413            Set<JetType> result = new LinkedHashSet<JetType>(15);
414            collectAllSupertypes(type, result);
415            return result;
416        }
417    
418        public static boolean hasNullableLowerBound(@NotNull TypeParameterDescriptor typeParameterDescriptor) {
419            for (JetType bound : typeParameterDescriptor.getLowerBounds()) {
420                if (bound.isNullable()) {
421                    return true;
422                }
423            }
424            return false;
425        }
426    
427        public static boolean hasNullableSuperType(@NotNull JetType type) {
428            if (type.getConstructor().getDeclarationDescriptor() instanceof ClassDescriptor) {
429                // A class/trait cannot have a nullable supertype
430                return false;
431            }
432    
433            for (JetType supertype : getImmediateSupertypes(type)) {
434                if (supertype.isNullable()) return true;
435                if (hasNullableSuperType(supertype)) return true;
436            }
437            
438            return false;
439        }
440    
441        public static boolean equalClasses(@NotNull JetType type1, @NotNull JetType type2) {
442            DeclarationDescriptor declarationDescriptor1 = type1.getConstructor().getDeclarationDescriptor();
443            if (declarationDescriptor1 == null) return false; // No class, classes are not equal
444            DeclarationDescriptor declarationDescriptor2 = type2.getConstructor().getDeclarationDescriptor();
445            if (declarationDescriptor2 == null) return false; // Class of type1 is not null
446            return declarationDescriptor1.getOriginal().equals(declarationDescriptor2.getOriginal());
447        }
448    
449        @Nullable
450        public static ClassDescriptor getClassDescriptor(@NotNull JetType type) {
451            DeclarationDescriptor declarationDescriptor = type.getConstructor().getDeclarationDescriptor();
452            if (declarationDescriptor instanceof ClassDescriptor) {
453                return (ClassDescriptor) declarationDescriptor;
454            }
455            return null;
456        }
457    
458        @NotNull
459        public static JetType substituteParameters(@NotNull ClassDescriptor clazz, @NotNull List<JetType> typeArguments) {
460            List<TypeProjection> projections = ContainerUtil.map(typeArguments, new com.intellij.util.Function<JetType, TypeProjection>() {
461                @Override
462                public TypeProjection fun(JetType type) {
463                    return new TypeProjectionImpl(type);
464                }
465            });
466    
467            return substituteProjectionsForParameters(clazz, projections);
468        }
469    
470        @NotNull
471        public static JetType substituteProjectionsForParameters(@NotNull ClassDescriptor clazz, @NotNull List<TypeProjection> projections) {
472            List<TypeParameterDescriptor> clazzTypeParameters = clazz.getTypeConstructor().getParameters();
473            if (clazzTypeParameters.size() != projections.size()) {
474                throw new IllegalArgumentException("type parameter counts do not match: " + clazz + ", " + projections);
475            }
476    
477            Map<TypeConstructor, TypeProjection> substitutions = Maps.newHashMap();
478    
479            for (int i = 0; i < clazzTypeParameters.size(); ++i) {
480                TypeConstructor typeConstructor = clazzTypeParameters.get(i).getTypeConstructor();
481                substitutions.put(typeConstructor, projections.get(i));
482            }
483    
484            return TypeSubstitutor.create(substitutions).substitute(clazz.getDefaultType(), Variance.INVARIANT);
485        }
486    
487        public static boolean equalTypes(@NotNull JetType a, @NotNull JetType b) {
488            return JetTypeChecker.INSTANCE.isSubtypeOf(a, b) && JetTypeChecker.INSTANCE.isSubtypeOf(b, a);
489        }
490    
491        public static boolean typeConstructorUsedInType(@NotNull TypeConstructor key, @NotNull JetType value) {
492            if (value.getConstructor() == key) return true;
493            for (TypeProjection projection : value.getArguments()) {
494                if (typeConstructorUsedInType(key, projection.getType())) {
495                    return true;
496                }
497            }
498            return false;
499        }
500    
501        public static boolean dependsOnTypeParameters(@NotNull JetType type, @NotNull Collection<TypeParameterDescriptor> typeParameters) {
502            return dependsOnTypeConstructors(type, Collections2
503                    .transform(typeParameters, new Function<TypeParameterDescriptor, TypeConstructor>() {
504                        @Override
505                        public TypeConstructor apply(@Nullable TypeParameterDescriptor typeParameterDescriptor) {
506                            assert typeParameterDescriptor != null;
507                            return typeParameterDescriptor.getTypeConstructor();
508                        }
509                    }));
510        }
511    
512        public static boolean dependsOnTypeConstructors(@NotNull JetType type, @NotNull Collection<TypeConstructor> typeParameterConstructors) {
513            if (typeParameterConstructors.contains(type.getConstructor())) return true;
514            for (TypeProjection typeProjection : type.getArguments()) {
515                if (dependsOnTypeConstructors(typeProjection.getType(), typeParameterConstructors)) {
516                    return true;
517                }
518            }
519            return false;
520        }
521    
522        public static boolean equalsOrContainsAsArgument(@Nullable JetType type, @NotNull JetType... possibleArgumentTypes) {
523            return equalsOrContainsAsArgument(type, Sets.newHashSet(possibleArgumentTypes));
524        }
525    
526        private static boolean equalsOrContainsAsArgument(@Nullable JetType type, @NotNull Set<JetType> possibleArgumentTypes) {
527            if (type == null) return false;
528            if (possibleArgumentTypes.contains(type)) return true;
529            if (type instanceof PackageType) return false;
530            for (TypeProjection projection : type.getArguments()) {
531                if (equalsOrContainsAsArgument(projection.getType(), possibleArgumentTypes)) return true;
532            }
533            return false;
534        }
535    
536        @NotNull
537        public static String getTypeNameAndStarProjectionsString(@NotNull String name, int size) {
538            StringBuilder builder = new StringBuilder(name);
539            builder.append("<");
540            for (int i = 0; i < size; i++) {
541                builder.append("*");
542                if (i == size - 1) break;
543                builder.append(", ");
544            }
545            builder.append(">");
546    
547            return builder.toString();
548        }
549    
550        @Nullable
551        public static JetType commonSupertypeForNumberTypes(@NotNull Collection<JetType> numberLowerBounds) {
552            if (numberLowerBounds.isEmpty()) return null;
553            assert !numberLowerBounds.isEmpty();
554            Set<JetType> intersectionOfSupertypes = getIntersectionOfSupertypes(numberLowerBounds);
555            JetType primitiveNumberType = getDefaultPrimitiveNumberType(intersectionOfSupertypes);
556            if (primitiveNumberType != null) {
557                return primitiveNumberType;
558            }
559            return CommonSupertypes.commonSupertype(numberLowerBounds);
560        }
561    
562        @NotNull
563        private static Set<JetType> getIntersectionOfSupertypes(@NotNull Collection<JetType> types) {
564            Set<JetType> upperBounds = Sets.newHashSet();
565            for (JetType type : types) {
566                Set<JetType> supertypes = Sets.newHashSet(type.getConstructor().getSupertypes());
567                if (upperBounds.isEmpty()) {
568                    upperBounds.addAll(supertypes);
569                }
570                else {
571                    upperBounds = Sets.intersection(upperBounds, supertypes);
572                }
573            }
574            return upperBounds;
575        }
576    
577        @NotNull
578        public static JetType getDefaultPrimitiveNumberType(@NotNull IntegerValueTypeConstructor numberValueTypeConstructor) {
579            JetType type = getDefaultPrimitiveNumberType(numberValueTypeConstructor.getSupertypes());
580            assert type != null : "Strange number value type constructor: " + numberValueTypeConstructor + ". " +
581                                  "Super types doesn't contain double, int or long: " + numberValueTypeConstructor.getSupertypes();
582            return type;
583        }
584    
585        @Nullable
586        private static JetType getDefaultPrimitiveNumberType(@NotNull Collection<JetType> supertypes) {
587            JetType doubleType = KotlinBuiltIns.getInstance().getDoubleType();
588            if (supertypes.contains(doubleType)) {
589                return doubleType;
590            }
591            JetType intType = KotlinBuiltIns.getInstance().getIntType();
592            if (supertypes.contains(intType)) {
593                return intType;
594            }
595            JetType longType = KotlinBuiltIns.getInstance().getLongType();
596            if (supertypes.contains(longType)) {
597                return longType;
598            }
599            return null;
600        }
601    
602        @NotNull
603        public static JetType getPrimitiveNumberType(
604                @NotNull IntegerValueTypeConstructor numberValueTypeConstructor,
605                @NotNull JetType expectedType
606        ) {
607            if (noExpectedType(expectedType) || expectedType.isError()) {
608                return getDefaultPrimitiveNumberType(numberValueTypeConstructor);
609            }
610            for (JetType primitiveNumberType : numberValueTypeConstructor.getSupertypes()) {
611                if (JetTypeChecker.INSTANCE.isSubtypeOf(primitiveNumberType, expectedType)) {
612                    return primitiveNumberType;
613                }
614            }
615            return getDefaultPrimitiveNumberType(numberValueTypeConstructor);
616        }
617    
618        @NotNull
619        public static Pair<Collection<JetType>, Collection<JetType>> filterNumberTypes(@NotNull Collection<JetType> types) {
620            Collection<JetType> numberTypes = Sets.newLinkedHashSet();
621            Collection<JetType> otherTypes = Sets.newLinkedHashSet();
622            for (JetType type : types) {
623                if (type.getConstructor() instanceof IntegerValueTypeConstructor) {
624                    numberTypes.add(type);
625                }
626                else {
627                    otherTypes.add(type);
628                }
629            }
630            return Pair.create(otherTypes, numberTypes);
631        }
632    
633        public static List<TypeConstructor> topologicallySortSuperclassesAndRecordAllInstances(
634                @NotNull JetType type,
635                @NotNull final Map<TypeConstructor, Set<JetType>> constructorToAllInstances,
636                @NotNull final Set<TypeConstructor> visited
637        ) {
638            return DFS.dfs(
639                    Collections.singletonList(type),
640                    new DFS.Neighbors<JetType>() {
641                        @NotNull
642                        @Override
643                        public Iterable<JetType> getNeighbors(JetType current) {
644                            TypeSubstitutor substitutor = TypeSubstitutor.create(current);
645                            List<JetType> result = Lists.newArrayList();
646                            for (JetType supertype : current.getConstructor().getSupertypes()) {
647                                if (visited.contains(supertype.getConstructor())) {
648                                    continue;
649                                }
650                                result.add(substitutor.safeSubstitute(supertype, Variance.INVARIANT));
651                            }
652                            return result;
653                        }
654                    },
655                    new DFS.Visited<JetType>() {
656                        @Override
657                        public boolean checkAndMarkVisited(JetType current) {
658                            return visited.add(current.getConstructor());
659                        }
660                    },
661                    new DFS.NodeHandlerWithListResult<JetType, TypeConstructor>() {
662                        @Override
663                        public void beforeChildren(JetType current) {
664                            TypeConstructor constructor = current.getConstructor();
665    
666                            Set<JetType> instances = constructorToAllInstances.get(constructor);
667                            if (instances == null) {
668                                instances = new HashSet<JetType>();
669                                constructorToAllInstances.put(constructor, instances);
670                            }
671                            instances.add(current);
672                        }
673    
674                        @Override
675                        public void afterChildren(JetType current) {
676                            result.addFirst(current.getConstructor());
677                        }
678                    }
679            );
680        }
681    
682        public static TypeSubstitutor makeConstantSubstitutor(Collection<TypeParameterDescriptor> typeParameterDescriptors, JetType type) {
683            final Set<TypeConstructor> constructors = Sets.newHashSet();
684            for (TypeParameterDescriptor typeParameterDescriptor : typeParameterDescriptors) {
685                constructors.add(typeParameterDescriptor.getTypeConstructor());
686            }
687            final TypeProjection projection = new TypeProjectionImpl(type);
688    
689            return TypeSubstitutor.create(new TypeSubstitution() {
690                @Override
691                public TypeProjection get(TypeConstructor key) {
692                    if (constructors.contains(key)) {
693                        return projection;
694                    }
695                    return null;
696                }
697    
698                @Override
699                public boolean isEmpty() {
700                    return false;
701                }
702            });
703        }
704    
705        public static TypeSubstitutor makeSubstitutorForTypeParametersMap(
706               @NotNull final Map<TypeParameterDescriptor, TypeProjection> substitutionContext
707        ) {
708            return TypeSubstitutor.create(new TypeSubstitution() {
709                @Nullable
710                @Override
711                public TypeProjection get(TypeConstructor key) {
712                    DeclarationDescriptor declarationDescriptor = key.getDeclarationDescriptor();
713                    if (declarationDescriptor instanceof TypeParameterDescriptor) {
714                        TypeParameterDescriptor descriptor = (TypeParameterDescriptor) declarationDescriptor;
715                        return substitutionContext.get(descriptor);
716                    }
717                    return null;
718                }
719    
720                @Override
721                public boolean isEmpty() {
722                    return substitutionContext.isEmpty();
723                }
724    
725                @Override
726                public String toString() {
727                    return substitutionContext.toString();
728                }
729            });
730        }
731    
732        private static abstract class AbstractTypeWithKnownNullability extends AbstractJetType {
733            private final JetType delegate;
734    
735            private AbstractTypeWithKnownNullability(@NotNull JetType delegate) {
736                this.delegate = delegate;
737            }
738    
739            @Override
740            @NotNull
741            public TypeConstructor getConstructor() {
742                return delegate.getConstructor();
743            }
744    
745            @Override
746            @NotNull
747            public List<TypeProjection> getArguments() {
748                return delegate.getArguments();
749            }
750    
751            @Override
752            public abstract boolean isNullable();
753    
754            @Override
755            @NotNull
756            public JetScope getMemberScope() {
757                return delegate.getMemberScope();
758            }
759    
760            @Override
761            public boolean isError() {
762                return delegate.isError();
763            }
764    
765            @Override
766            @NotNull
767            public Annotations getAnnotations() {
768                return delegate.getAnnotations();
769            }
770        }
771    
772        private static class NullableType extends AbstractTypeWithKnownNullability {
773    
774            private NullableType(@NotNull JetType delegate) {
775                super(delegate);
776            }
777    
778            @Override
779            public boolean isNullable() {
780                return true;
781            }
782        }
783    
784        private static class NotNullType extends AbstractTypeWithKnownNullability {
785    
786            private NotNullType(@NotNull JetType delegate) {
787                super(delegate);
788            }
789    
790            @Override
791            public boolean isNullable() {
792                return false;
793            }
794        }
795    
796    }