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.checker;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.annotations.Nullable;
021    import org.jetbrains.jet.lang.descriptors.TypeParameterDescriptor;
022    import org.jetbrains.jet.lang.types.*;
023    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
024    
025    import java.util.List;
026    
027    import static org.jetbrains.jet.lang.types.Variance.*;
028    
029    public class TypeCheckingProcedure {
030    
031        // This method returns the supertype of the first parameter that has the same constructor
032        // as the second parameter, applying the substitution of type arguments to it
033        @Nullable
034        public static JetType findCorrespondingSupertype(@NotNull JetType subtype, @NotNull JetType supertype) {
035            return findCorrespondingSupertype(subtype, supertype, new TypeCheckerTypingConstraints());
036        }
037    
038        // This method returns the supertype of the first parameter that has the same constructor
039        // as the second parameter, applying the substitution of type arguments to it
040        @Nullable
041        public static JetType findCorrespondingSupertype(@NotNull JetType subtype, @NotNull JetType supertype, @NotNull TypingConstraints typingConstraints) {
042            TypeConstructor constructor = subtype.getConstructor();
043            if (typingConstraints.assertEqualTypeConstructors(constructor, supertype.getConstructor())) {
044                return subtype;
045            }
046            for (JetType immediateSupertype : constructor.getSupertypes()) {
047                JetType correspondingSupertype = findCorrespondingSupertype(immediateSupertype, supertype, typingConstraints);
048                if (correspondingSupertype != null) {
049                    return TypeSubstitutor.create(subtype).safeSubstitute(correspondingSupertype, Variance.INVARIANT);
050                }
051            }
052            return null;
053        }
054    
055        public static JetType getOutType(TypeParameterDescriptor parameter, TypeProjection argument) {
056            boolean isOutProjected = argument.getProjectionKind() == IN_VARIANCE || parameter.getVariance() == IN_VARIANCE;
057            return isOutProjected ? parameter.getUpperBoundsAsType() : argument.getType();
058        }
059    
060        public static JetType getInType(TypeParameterDescriptor parameter, TypeProjection argument) {
061            boolean isOutProjected = argument.getProjectionKind() == OUT_VARIANCE || parameter.getVariance() == OUT_VARIANCE;
062            return isOutProjected ? KotlinBuiltIns.getInstance().getNothingType() : argument.getType();
063        }
064    
065        private final TypingConstraints constraints;
066    
067        public TypeCheckingProcedure(TypingConstraints constraints) {
068            this.constraints = constraints;
069        }
070    
071        public boolean equalTypes(@NotNull JetType type1, @NotNull JetType type2) {
072            if (TypesPackage.isFlexible(type1)) {
073                if (TypesPackage.isFlexible(type2)) {
074                    return !type1.isError() && !type2.isError() && isSubtypeOf(type1, type2) && isSubtypeOf(type2, type1);
075                }
076                return heterogeneousEquivalence(type2, type1);
077            }
078            else if (TypesPackage.isFlexible(type2)) {
079                return heterogeneousEquivalence(type1, type2);
080            }
081    
082            if (type1.isNullable() != type2.isNullable()) {
083                return false;
084            }
085    
086            if (type1.isNullable()) {
087                // Then type2 is nullable, too (see the previous condition
088                return constraints.assertEqualTypes(TypeUtils.makeNotNullable(type1), TypeUtils.makeNotNullable(type2), this);
089            }
090    
091            TypeConstructor constructor1 = type1.getConstructor();
092            TypeConstructor constructor2 = type2.getConstructor();
093    
094            if (!constraints.assertEqualTypeConstructors(constructor1, constructor2)) {
095                return false;
096            }
097    
098            List<TypeProjection> type1Arguments = type1.getArguments();
099            List<TypeProjection> type2Arguments = type2.getArguments();
100            if (type1Arguments.size() != type2Arguments.size()) {
101                return false;
102            }
103    
104            for (int i = 0; i < type1Arguments.size(); i++) {
105                TypeParameterDescriptor typeParameter1 = constructor1.getParameters().get(i);
106                TypeProjection typeProjection1 = type1Arguments.get(i);
107                TypeParameterDescriptor typeParameter2 = constructor2.getParameters().get(i);
108                TypeProjection typeProjection2 = type2Arguments.get(i);
109                if (getEffectiveProjectionKind(typeParameter1, typeProjection1) != getEffectiveProjectionKind(typeParameter2, typeProjection2)) {
110                    return false;
111                }
112    
113                if (!constraints.assertEqualTypes(typeProjection1.getType(), typeProjection2.getType(), this)) {
114                    return false;
115                }
116            }
117            return true;
118        }
119    
120        protected boolean heterogeneousEquivalence(JetType inflexibleType, JetType flexibleType) {
121            // This is to account for the case when we have Collection<X> vs (Mutable)Collection<X>! or K(java.util.Collection<? extends X>)
122            assert !TypesPackage.isFlexible(inflexibleType) : "Only inflexible types are allowed here: " + inflexibleType;
123            return isSubtypeOf(TypesPackage.flexibility(flexibleType).getLowerBound(), inflexibleType)
124                   && isSubtypeOf(inflexibleType, TypesPackage.flexibility(flexibleType).getUpperBound());
125        }
126    
127        public enum EnrichedProjectionKind {
128            IN, OUT, INV, STAR;
129    
130            @NotNull
131            public static EnrichedProjectionKind fromVariance(@NotNull Variance variance) {
132                switch (variance) {
133                    case INVARIANT:
134                        return INV;
135                    case IN_VARIANCE:
136                        return IN;
137                    case OUT_VARIANCE:
138                        return OUT;
139                }
140                throw new IllegalStateException("Unknown variance");
141            }
142        }
143    
144        // If class C<out T> then C<T> and C<out T> mean the same
145        // out * out = out
146        // out * in  = *
147        // out * inv = out
148        //
149        // in * out  = *
150        // in * in   = in
151        // in * inv  = in
152        //
153        // inv * out = out
154        // inv * in  = out
155        // inv * inv = inv
156        public static EnrichedProjectionKind getEffectiveProjectionKind(
157                @NotNull TypeParameterDescriptor typeParameter,
158                @NotNull TypeProjection typeArgument
159        ) {
160            Variance a = typeParameter.getVariance();
161            Variance b = typeArgument.getProjectionKind();
162    
163            // If they are not both invariant, let's make b not invariant for sure
164            if (b == INVARIANT) {
165                Variance t = a;
166                a = b;
167                b = t;
168            }
169    
170            // Opposites yield STAR
171            if (a == IN_VARIANCE && b == OUT_VARIANCE) {
172                return EnrichedProjectionKind.STAR;
173            }
174            if (a == OUT_VARIANCE && b == IN_VARIANCE) {
175                return EnrichedProjectionKind.STAR;
176            }
177    
178            // If they are not opposite, return b, because b is either equal to a or b is in/out and a is inv
179            return EnrichedProjectionKind.fromVariance(b);
180        }
181    
182        public boolean isSubtypeOf(@NotNull JetType subtype, @NotNull JetType supertype) {
183            if (TypesPackage.isFlexible(subtype)) {
184                return isSubtypeOf(TypesPackage.flexibility(subtype).getLowerBound(), supertype);
185            }
186            if (TypesPackage.isFlexible(supertype)) {
187                return isSubtypeOf(subtype, TypesPackage.flexibility(supertype).getUpperBound());
188            }
189            if (subtype.isError() || supertype.isError()) {
190                return true;
191            }
192            if (!supertype.isNullable() && subtype.isNullable()) {
193                return false;
194            }
195            subtype = TypeUtils.makeNotNullable(subtype);
196            supertype = TypeUtils.makeNotNullable(supertype);
197            if (KotlinBuiltIns.getInstance().isNothingOrNullableNothing(subtype)) {
198                return true;
199            }
200            @Nullable JetType closestSupertype = findCorrespondingSupertype(subtype, supertype, constraints);
201            if (closestSupertype == null) {
202                return constraints.noCorrespondingSupertype(subtype, supertype); // if this returns true, there still isn't any supertype to continue with
203            }
204    
205            return checkSubtypeForTheSameConstructor(closestSupertype, supertype);
206        }
207    
208        private boolean checkSubtypeForTheSameConstructor(@NotNull JetType subtype, @NotNull JetType supertype) {
209            TypeConstructor constructor = subtype.getConstructor();
210            assert constraints.assertEqualTypeConstructors(constructor, supertype.getConstructor()) : constructor + " is not " + supertype.getConstructor();
211    
212            List<TypeProjection> subArguments = subtype.getArguments();
213            List<TypeProjection> superArguments = supertype.getArguments();
214            if (subArguments.size() != superArguments.size()) return false;
215    
216            List<TypeParameterDescriptor> parameters = constructor.getParameters();
217            for (int i = 0; i < parameters.size(); i++) {
218                TypeParameterDescriptor parameter = parameters.get(i);
219    
220                TypeProjection subArgument = subArguments.get(i);
221                JetType subIn = getInType(parameter, subArgument);
222                JetType subOut = getOutType(parameter, subArgument);
223    
224                TypeProjection superArgument = superArguments.get(i);
225                JetType superIn = getInType(parameter, superArgument);
226                JetType superOut = getOutType(parameter, superArgument);
227    
228                boolean argumentIsErrorType = subArgument.getType().isError() || superArgument.getType().isError();
229                if (!argumentIsErrorType && parameter.getVariance() == INVARIANT
230                        && subArgument.getProjectionKind() == INVARIANT && superArgument.getProjectionKind() == INVARIANT) {
231                    if (!constraints.assertEqualTypes(subArgument.getType(), superArgument.getType(), this)) return false;
232                }
233                else {
234                    if (!constraints.assertSubtype(subOut, superOut, this)) return false;
235                    if (!constraints.assertSubtype(superIn, subIn, this)) return false;
236                }
237            }
238            return true;
239        }
240    }