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 (type1.isNullable() != type2.isNullable()) {
073                return false;
074            }
075    
076            if (type1.isNullable()) {
077                // Then type2 is nullable, too (see the previous condition
078                return constraints.assertEqualTypes(TypeUtils.makeNotNullable(type1), TypeUtils.makeNotNullable(type2), this);
079            }
080    
081            TypeConstructor constructor1 = type1.getConstructor();
082            TypeConstructor constructor2 = type2.getConstructor();
083    
084            if (!constraints.assertEqualTypeConstructors(constructor1, constructor2)) {
085                return false;
086            }
087    
088            List<TypeProjection> type1Arguments = type1.getArguments();
089            List<TypeProjection> type2Arguments = type2.getArguments();
090            if (type1Arguments.size() != type2Arguments.size()) {
091                return false;
092            }
093    
094            for (int i = 0; i < type1Arguments.size(); i++) {
095                TypeParameterDescriptor typeParameter1 = constructor1.getParameters().get(i);
096                TypeProjection typeProjection1 = type1Arguments.get(i);
097                TypeParameterDescriptor typeParameter2 = constructor2.getParameters().get(i);
098                TypeProjection typeProjection2 = type2Arguments.get(i);
099                if (getEffectiveProjectionKind(typeParameter1, typeProjection1) != getEffectiveProjectionKind(typeParameter2, typeProjection2)) {
100                    return false;
101                }
102    
103                if (!constraints.assertEqualTypes(typeProjection1.getType(), typeProjection2.getType(), this)) {
104                    return false;
105                }
106            }
107            return true;
108        }
109    
110        public enum EnrichedProjectionKind {
111            IN, OUT, INV, STAR;
112    
113            @NotNull
114            public static EnrichedProjectionKind fromVariance(@NotNull Variance variance) {
115                switch (variance) {
116                    case INVARIANT:
117                        return INV;
118                    case IN_VARIANCE:
119                        return IN;
120                    case OUT_VARIANCE:
121                        return OUT;
122                }
123                throw new IllegalStateException("Unknown variance");
124            }
125        }
126    
127        // If class C<out T> then C<T> and C<out T> mean the same
128        // out * out = out
129        // out * in  = *
130        // out * inv = out
131        //
132        // in * out  = *
133        // in * in   = in
134        // in * inv  = in
135        //
136        // inv * out = out
137        // inv * in  = out
138        // inv * inv = inv
139        public static EnrichedProjectionKind getEffectiveProjectionKind(
140                @NotNull TypeParameterDescriptor typeParameter,
141                @NotNull TypeProjection typeArgument
142        ) {
143            Variance a = typeParameter.getVariance();
144            Variance b = typeArgument.getProjectionKind();
145    
146            // If they are not both invariant, let's make b not invariant for sure
147            if (b == INVARIANT) {
148                Variance t = a;
149                a = b;
150                b = t;
151            }
152    
153            // Opposites yield STAR
154            if (a == IN_VARIANCE && b == OUT_VARIANCE) {
155                return EnrichedProjectionKind.STAR;
156            }
157            if (a == OUT_VARIANCE && b == IN_VARIANCE) {
158                return EnrichedProjectionKind.STAR;
159            }
160    
161            // If they are not opposite, return b, because b is either equal to a or b is in/out and a is inv
162            return EnrichedProjectionKind.fromVariance(b);
163        }
164    
165        public boolean isSubtypeOf(@NotNull JetType subtype, @NotNull JetType supertype) {
166            if (subtype.isError() || supertype.isError()) {
167                return true;
168            }
169            if (!supertype.isNullable() && subtype.isNullable()) {
170                return false;
171            }
172            subtype = TypeUtils.makeNotNullable(subtype);
173            supertype = TypeUtils.makeNotNullable(supertype);
174            if (KotlinBuiltIns.getInstance().isNothingOrNullableNothing(subtype)) {
175                return true;
176            }
177            @Nullable JetType closestSupertype = findCorrespondingSupertype(subtype, supertype, constraints);
178            if (closestSupertype == null) {
179                return constraints.noCorrespondingSupertype(subtype, supertype); // if this returns true, there still isn't any supertype to continue with
180            }
181    
182            return checkSubtypeForTheSameConstructor(closestSupertype, supertype);
183        }
184    
185        private boolean checkSubtypeForTheSameConstructor(@NotNull JetType subtype, @NotNull JetType supertype) {
186            TypeConstructor constructor = subtype.getConstructor();
187            assert constraints.assertEqualTypeConstructors(constructor, supertype.getConstructor()) : constructor + " is not " + supertype.getConstructor();
188    
189            List<TypeProjection> subArguments = subtype.getArguments();
190            List<TypeProjection> superArguments = supertype.getArguments();
191            if (subArguments.size() != superArguments.size()) return false;
192    
193            List<TypeParameterDescriptor> parameters = constructor.getParameters();
194            for (int i = 0; i < parameters.size(); i++) {
195                TypeParameterDescriptor parameter = parameters.get(i);
196    
197                TypeProjection subArgument = subArguments.get(i);
198                JetType subIn = getInType(parameter, subArgument);
199                JetType subOut = getOutType(parameter, subArgument);
200    
201                TypeProjection superArgument = superArguments.get(i);
202                JetType superIn = getInType(parameter, superArgument);
203                JetType superOut = getOutType(parameter, superArgument);
204    
205                boolean argumentIsErrorType = subArgument.getType().isError() || superArgument.getType().isError();
206                if (!argumentIsErrorType && parameter.getVariance() == INVARIANT
207                        && subArgument.getProjectionKind() == INVARIANT && superArgument.getProjectionKind() == INVARIANT) {
208                    if (!constraints.assertEqualTypes(subArgument.getType(), superArgument.getType(), this)) return false;
209                }
210                else {
211                    if (!constraints.assertSubtype(subOut, superOut, this)) return false;
212                    if (!constraints.assertSubtype(superIn, subIn, this)) return false;
213                }
214            }
215            return true;
216        }
217    }