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.expressions;
018    
019    import com.google.common.collect.Sets;
020    import com.intellij.openapi.util.Ref;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
024    import org.jetbrains.kotlin.cfg.WhenChecker;
025    import org.jetbrains.kotlin.descriptors.ClassDescriptor;
026    import org.jetbrains.kotlin.diagnostics.Errors;
027    import org.jetbrains.kotlin.psi.*;
028    import org.jetbrains.kotlin.resolve.*;
029    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
030    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue;
031    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory;
032    import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastResult;
033    import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
034    import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind;
035    import org.jetbrains.kotlin.resolve.scopes.LexicalWritableScope;
036    import org.jetbrains.kotlin.types.*;
037    import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
038    import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt;
039    
040    import java.util.Collections;
041    import java.util.Set;
042    
043    import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isBoolean;
044    import static org.jetbrains.kotlin.diagnostics.Errors.*;
045    import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
046    import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
047    import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.newWritableScopeImpl;
048    
049    public class PatternMatchingTypingVisitor extends ExpressionTypingVisitor {
050        protected PatternMatchingTypingVisitor(@NotNull ExpressionTypingInternals facade) {
051            super(facade);
052        }
053    
054        @Override
055        public KotlinTypeInfo visitIsExpression(@NotNull KtIsExpression expression, ExpressionTypingContext contextWithExpectedType) {
056            ExpressionTypingContext context = contextWithExpectedType
057                                                .replaceExpectedType(NO_EXPECTED_TYPE)
058                                                .replaceContextDependency(INDEPENDENT);
059            KtExpression leftHandSide = expression.getLeftHandSide();
060            KotlinTypeInfo typeInfo = facade.safeGetTypeInfo(leftHandSide, context.replaceScope(context.scope));
061            KotlinType knownType = typeInfo.getType();
062            if (expression.getTypeReference() != null) {
063                DataFlowValue dataFlowValue = DataFlowValueFactory.createDataFlowValue(leftHandSide, knownType, context);
064                DataFlowInfo conditionInfo = checkTypeForIs(context, knownType, expression.getTypeReference(), dataFlowValue).thenInfo;
065                DataFlowInfo newDataFlowInfo = conditionInfo.and(typeInfo.getDataFlowInfo());
066                context.trace.record(BindingContext.DATAFLOW_INFO_AFTER_CONDITION, expression, newDataFlowInfo);
067            }
068            return components.dataFlowAnalyzer.checkType(typeInfo.replaceType(components.builtIns.getBooleanType()), expression, contextWithExpectedType);
069        }
070    
071        @Override
072        public KotlinTypeInfo visitWhenExpression(@NotNull KtWhenExpression expression, ExpressionTypingContext context) {
073            return visitWhenExpression(expression, context, false);
074        }
075    
076        public KotlinTypeInfo visitWhenExpression(KtWhenExpression expression, ExpressionTypingContext contextWithExpectedType, boolean isStatement) {
077            WhenChecker.checkDeprecatedWhenSyntax(contextWithExpectedType.trace, expression);
078    
079            components.dataFlowAnalyzer.recordExpectedType(contextWithExpectedType.trace, expression, contextWithExpectedType.expectedType);
080    
081            ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT);
082            // TODO :change scope according to the bound value in the when header
083            KtExpression subjectExpression = expression.getSubjectExpression();
084    
085            KotlinType subjectType;
086            boolean loopBreakContinuePossible = false;
087            if (subjectExpression == null) {
088                subjectType = ErrorUtils.createErrorType("Unknown type");
089            }
090            else {
091                KotlinTypeInfo typeInfo = facade.safeGetTypeInfo(subjectExpression, context);
092                loopBreakContinuePossible = typeInfo.getJumpOutPossible();
093                subjectType = typeInfo.getType();
094                assert subjectType != null;
095                if (TypeUtils.isNullableType(subjectType) && !WhenChecker.containsNullCase(expression, context.trace)) {
096                    TemporaryBindingTrace trace = TemporaryBindingTrace.create(context.trace, "Temporary trace for when subject nullability");
097                    ExpressionTypingContext subjectContext =
098                            context.replaceExpectedType(TypeUtils.makeNotNullable(subjectType)).replaceBindingTrace(trace);
099                    SmartCastResult castResult = components.dataFlowAnalyzer.checkPossibleCast(
100                            subjectType, KtPsiUtil.safeDeparenthesize(subjectExpression), subjectContext
101                    );
102                    if (castResult != null && castResult.isCorrect()) {
103                        trace.commit();
104                    }
105                }
106                context = context.replaceDataFlowInfo(typeInfo.getDataFlowInfo());
107            }
108            DataFlowValue subjectDataFlowValue = subjectExpression != null
109                    ? DataFlowValueFactory.createDataFlowValue(subjectExpression, subjectType, context)
110                    : DataFlowValue.nullValue(components.builtIns);
111    
112            // TODO : exhaustive patterns
113    
114            Set<KotlinType> expressionTypes = Sets.newHashSet();
115            DataFlowInfo commonDataFlowInfo = null;
116            DataFlowInfo elseDataFlowInfo = context.dataFlowInfo;
117            for (KtWhenEntry whenEntry : expression.getEntries()) {
118                DataFlowInfos infosForCondition = getDataFlowInfosForEntryCondition(
119                        whenEntry, context.replaceDataFlowInfo(elseDataFlowInfo), subjectExpression, subjectType, subjectDataFlowValue);
120                elseDataFlowInfo = elseDataFlowInfo.and(infosForCondition.elseInfo);
121    
122                KtExpression bodyExpression = whenEntry.getExpression();
123                if (bodyExpression != null) {
124                    LexicalWritableScope scopeToExtend = newWritableScopeImpl(context, LexicalScopeKind.WHEN);
125                    ExpressionTypingContext newContext = contextWithExpectedType
126                            .replaceScope(scopeToExtend).replaceDataFlowInfo(infosForCondition.thenInfo).replaceContextDependency(INDEPENDENT);
127                    CoercionStrategy coercionStrategy = isStatement ? CoercionStrategy.COERCION_TO_UNIT : CoercionStrategy.NO_COERCION;
128                    KotlinTypeInfo typeInfo = components.expressionTypingServices.getBlockReturnedTypeWithWritableScope(
129                            scopeToExtend, Collections.singletonList(bodyExpression), coercionStrategy, newContext);
130                    loopBreakContinuePossible |= typeInfo.getJumpOutPossible();
131                    KotlinType type = typeInfo.getType();
132                    if (type != null) {
133                        expressionTypes.add(type);
134                    }
135                    if (commonDataFlowInfo == null) {
136                        commonDataFlowInfo = typeInfo.getDataFlowInfo();
137                    }
138                    else {
139                        commonDataFlowInfo = commonDataFlowInfo.or(typeInfo.getDataFlowInfo());
140                    }
141                }
142            }
143    
144            if (commonDataFlowInfo == null) {
145                commonDataFlowInfo = context.dataFlowInfo;
146            }
147            else if (expression.getElseExpression() == null && !WhenChecker.isWhenExhaustive(expression, context.trace)) {
148                // Without else expression in non-exhaustive when, we *must* take initial data flow info into account,
149                // because data flow can bypass all when branches in this case
150                commonDataFlowInfo = commonDataFlowInfo.or(context.dataFlowInfo);
151            }
152    
153            return TypeInfoFactoryKt.createTypeInfo(expressionTypes.isEmpty() ? null : components.dataFlowAnalyzer.checkType(
154                                                                 components.dataFlowAnalyzer.checkImplicitCast(
155                                                                         CommonSupertypes.commonSupertype(expressionTypes), expression,
156                                                                         contextWithExpectedType, isStatement),
157                                                                 expression, contextWithExpectedType),
158                                                    commonDataFlowInfo,
159                                                    loopBreakContinuePossible,
160                                                    contextWithExpectedType.dataFlowInfo);
161        }
162    
163        @NotNull
164        private DataFlowInfos getDataFlowInfosForEntryCondition(
165                @NotNull KtWhenEntry whenEntry,
166                @NotNull ExpressionTypingContext context,
167                @Nullable KtExpression subjectExpression,
168                @NotNull KotlinType subjectType,
169                @NotNull DataFlowValue subjectDataFlowValue
170        ) {
171            if (whenEntry.isElse()) {
172                return new DataFlowInfos(context.dataFlowInfo);
173            }
174    
175            DataFlowInfos infos = null;
176            ExpressionTypingContext contextForCondition = context;
177            for (KtWhenCondition condition : whenEntry.getConditions()) {
178                DataFlowInfos conditionInfos = checkWhenCondition(subjectExpression, subjectType, condition,
179                                                                  contextForCondition, subjectDataFlowValue);
180                if (infos != null) {
181                    infos = new DataFlowInfos(infos.thenInfo.or(conditionInfos.thenInfo), infos.elseInfo.and(conditionInfos.elseInfo));
182                }
183                else {
184                    infos = conditionInfos;
185                }
186                contextForCondition = contextForCondition.replaceDataFlowInfo(conditionInfos.elseInfo);
187            }
188            return infos != null ? infos : new DataFlowInfos(context.dataFlowInfo);
189        }
190    
191        private DataFlowInfos checkWhenCondition(
192                @Nullable final KtExpression subjectExpression,
193                final KotlinType subjectType,
194                KtWhenCondition condition,
195                final ExpressionTypingContext context,
196                final DataFlowValue subjectDataFlowValue
197        ) {
198            final Ref<DataFlowInfos> newDataFlowInfo = new Ref<DataFlowInfos>(noChange(context));
199            condition.accept(new KtVisitorVoid() {
200                @Override
201                public void visitWhenConditionInRange(@NotNull KtWhenConditionInRange condition) {
202                    KtExpression rangeExpression = condition.getRangeExpression();
203                    if (rangeExpression == null) return;
204                    if (subjectExpression == null) {
205                        context.trace.report(EXPECTED_CONDITION.on(condition));
206                        DataFlowInfo dataFlowInfo = facade.getTypeInfo(rangeExpression, context).getDataFlowInfo();
207                        newDataFlowInfo.set(new DataFlowInfos(dataFlowInfo, dataFlowInfo));
208                        return;
209                    }
210                    ValueArgument argumentForSubject = CallMaker.makeExternalValueArgument(subjectExpression);
211                    KotlinTypeInfo typeInfo = facade.checkInExpression(condition, condition.getOperationReference(),
212                                                                       argumentForSubject, rangeExpression, context);
213                    DataFlowInfo dataFlowInfo = typeInfo.getDataFlowInfo();
214                    newDataFlowInfo.set(new DataFlowInfos(dataFlowInfo, dataFlowInfo));
215                    KotlinType type = typeInfo.getType();
216                    if (type == null || !isBoolean(type)) {
217                        context.trace.report(TYPE_MISMATCH_IN_RANGE.on(condition));
218                    }
219                }
220    
221                @Override
222                public void visitWhenConditionIsPattern(@NotNull KtWhenConditionIsPattern condition) {
223                    if (subjectExpression == null) {
224                        context.trace.report(EXPECTED_CONDITION.on(condition));
225                    }
226                    if (condition.getTypeReference() != null) {
227                        DataFlowInfos result = checkTypeForIs(context, subjectType, condition.getTypeReference(), subjectDataFlowValue);
228                        if (condition.isNegated()) {
229                            newDataFlowInfo.set(new DataFlowInfos(result.elseInfo, result.thenInfo));
230                        }
231                        else {
232                            newDataFlowInfo.set(result);
233                        }
234                    }
235                }
236    
237                @Override
238                public void visitWhenConditionWithExpression(@NotNull KtWhenConditionWithExpression condition) {
239                    KtExpression expression = condition.getExpression();
240                    if (expression != null) {
241                        newDataFlowInfo.set(checkTypeForExpressionCondition(context, expression, subjectType, subjectExpression == null,
242                                                                            subjectDataFlowValue));
243                    }
244                }
245    
246                @Override
247                public void visitKtElement(@NotNull KtElement element) {
248                    context.trace.report(UNSUPPORTED.on(element, getClass().getCanonicalName()));
249                }
250            });
251            return newDataFlowInfo.get();
252        }
253    
254        private static class DataFlowInfos {
255            private final DataFlowInfo thenInfo;
256            private final DataFlowInfo elseInfo;
257    
258            private DataFlowInfos(DataFlowInfo thenInfo, DataFlowInfo elseInfo) {
259                this.thenInfo = thenInfo;
260                this.elseInfo = elseInfo;
261            }
262    
263            private DataFlowInfos(DataFlowInfo info) {
264                this(info, info);
265            }
266        }
267    
268        private DataFlowInfos checkTypeForExpressionCondition(
269                ExpressionTypingContext context,
270                KtExpression expression,
271                KotlinType subjectType,
272                boolean conditionExpected,
273                DataFlowValue subjectDataFlowValue
274        ) {
275            if (expression == null) {
276                return noChange(context);
277            }
278            KotlinTypeInfo typeInfo = facade.getTypeInfo(expression, context);
279            KotlinType type = typeInfo.getType();
280            if (type == null) {
281                return noChange(context);
282            }
283            context = context.replaceDataFlowInfo(typeInfo.getDataFlowInfo());
284            if (conditionExpected) {
285                KotlinType booleanType = components.builtIns.getBooleanType();
286                if (!KotlinTypeChecker.DEFAULT.equalTypes(booleanType, type)) {
287                    context.trace.report(TYPE_MISMATCH_IN_CONDITION.on(expression, type));
288                }
289                else {
290                    DataFlowInfo ifInfo = components.dataFlowAnalyzer.extractDataFlowInfoFromCondition(expression, true, context);
291                    DataFlowInfo elseInfo = components.dataFlowAnalyzer.extractDataFlowInfoFromCondition(expression, false, context);
292                    return new DataFlowInfos(ifInfo, elseInfo);
293                }
294                return noChange(context);
295            }
296            checkTypeCompatibility(context, type, subjectType, expression);
297            DataFlowValue expressionDataFlowValue =
298                    DataFlowValueFactory.createDataFlowValue(expression, type, context);
299            DataFlowInfos result = noChange(context);
300            result = new DataFlowInfos(
301                    result.thenInfo.equate(subjectDataFlowValue, expressionDataFlowValue),
302                    result.elseInfo.disequate(subjectDataFlowValue, expressionDataFlowValue)
303            );
304            return result;
305        }
306    
307        private DataFlowInfos checkTypeForIs(
308                ExpressionTypingContext context,
309                KotlinType subjectType,
310                KtTypeReference typeReferenceAfterIs,
311                DataFlowValue subjectDataFlowValue
312        ) {
313            if (typeReferenceAfterIs == null) {
314                return noChange(context);
315            }
316            TypeResolutionContext typeResolutionContext = new TypeResolutionContext(context.scope, context.trace, true, /*allowBareTypes=*/ true);
317            PossiblyBareType possiblyBareTarget = components.typeResolver.resolvePossiblyBareType(typeResolutionContext, typeReferenceAfterIs);
318            KotlinType targetType = TypeReconstructionUtil.reconstructBareType(typeReferenceAfterIs, possiblyBareTarget, subjectType, context.trace, components.builtIns);
319    
320            if (DynamicTypesKt.isDynamic(targetType)) {
321                context.trace.report(DYNAMIC_NOT_ALLOWED.on(typeReferenceAfterIs));
322            }
323            ClassDescriptor targetDescriptor = TypeUtils.getClassDescriptor(targetType);
324            if (targetDescriptor != null && DescriptorUtils.isEnumEntry(targetDescriptor)) {
325                context.trace.report(IS_ENUM_ENTRY.on(typeReferenceAfterIs));
326            }
327    
328            if (!subjectType.isMarkedNullable() && targetType.isMarkedNullable()) {
329                KtTypeElement element = typeReferenceAfterIs.getTypeElement();
330                assert element instanceof KtNullableType : "element must be instance of " + KtNullableType.class.getName();
331                KtNullableType nullableType = (KtNullableType) element;
332                context.trace.report(Errors.USELESS_NULLABLE_CHECK.on(nullableType));
333            }
334            checkTypeCompatibility(context, targetType, subjectType, typeReferenceAfterIs);
335            if (CastDiagnosticsUtil.isCastErased(subjectType, targetType, KotlinTypeChecker.DEFAULT)) {
336                context.trace.report(Errors.CANNOT_CHECK_FOR_ERASED.on(typeReferenceAfterIs, targetType));
337            }
338            return new DataFlowInfos(context.dataFlowInfo.establishSubtyping(subjectDataFlowValue, targetType), context.dataFlowInfo);
339        }
340    
341        private static DataFlowInfos noChange(ExpressionTypingContext context) {
342            return new DataFlowInfos(context.dataFlowInfo, context.dataFlowInfo);
343        }
344    
345        /*
346         * (a: SubjectType) is Type
347         */
348        private void checkTypeCompatibility(
349                @NotNull ExpressionTypingContext context,
350                @Nullable KotlinType type,
351                @NotNull KotlinType subjectType,
352                @NotNull KtElement reportErrorOn
353        ) {
354            // TODO : Take smart casts into account?
355            if (type == null) {
356                return;
357            }
358            if (TypeIntersector.isIntersectionEmpty(type, subjectType)) {
359                context.trace.report(INCOMPATIBLE_TYPES.on(reportErrorOn, type, subjectType));
360                return;
361            }
362    
363            // check if the pattern is essentially a 'null' expression
364            if (KotlinBuiltIns.isNullableNothing(type) && !TypeUtils.isNullableType(subjectType)) {
365                context.trace.report(SENSELESS_NULL_IN_WHEN.on(reportErrorOn));
366            }
367        }
368    }