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.psi.tree.IElementType;
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.DeclarationDescriptor;
025    import org.jetbrains.kotlin.descriptors.FunctionDescriptor;
026    import org.jetbrains.kotlin.descriptors.VariableDescriptor;
027    import org.jetbrains.kotlin.diagnostics.Errors;
028    import org.jetbrains.kotlin.lexer.KtTokens;
029    import org.jetbrains.kotlin.name.Name;
030    import org.jetbrains.kotlin.psi.*;
031    import org.jetbrains.kotlin.resolve.DescriptorUtils;
032    import org.jetbrains.kotlin.resolve.TemporaryBindingTrace;
033    import org.jetbrains.kotlin.resolve.calls.context.TemporaryTraceAndCache;
034    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
035    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults;
036    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsImpl;
037    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsUtil;
038    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
039    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue;
040    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory;
041    import org.jetbrains.kotlin.resolve.scopes.LexicalWritableScope;
042    import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
043    import org.jetbrains.kotlin.resolve.scopes.utils.ScopeUtilsKt;
044    import org.jetbrains.kotlin.types.KotlinType;
045    import org.jetbrains.kotlin.types.TypeUtils;
046    import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
047    import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt;
048    
049    import java.util.Collection;
050    
051    import static org.jetbrains.kotlin.diagnostics.Errors.*;
052    import static org.jetbrains.kotlin.psi.KtPsiUtil.deparenthesize;
053    import static org.jetbrains.kotlin.resolve.BindingContext.AMBIGUOUS_REFERENCE_TARGET;
054    import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE_REASSIGNMENT;
055    import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
056    import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
057    import static org.jetbrains.kotlin.types.TypeUtils.noExpectedType;
058    
059    @SuppressWarnings("SuspiciousMethodCalls")
060    public class ExpressionTypingVisitorForStatements extends ExpressionTypingVisitor {
061        private final LexicalWritableScope scope;
062        private final BasicExpressionTypingVisitor basic;
063        private final ControlStructureTypingVisitor controlStructures;
064        private final PatternMatchingTypingVisitor patterns;
065        private final FunctionsTypingVisitor functions;
066    
067        public ExpressionTypingVisitorForStatements(
068                @NotNull ExpressionTypingInternals facade,
069                @NotNull LexicalWritableScope scope,
070                @NotNull BasicExpressionTypingVisitor basic,
071                @NotNull ControlStructureTypingVisitor controlStructures,
072                @NotNull PatternMatchingTypingVisitor patterns,
073                @NotNull FunctionsTypingVisitor functions
074        ) {
075            super(facade);
076            this.scope = scope;
077            this.basic = basic;
078            this.controlStructures = controlStructures;
079            this.patterns = patterns;
080            this.functions = functions;
081        }
082    
083        @Nullable
084        private KotlinType checkAssignmentType(
085                @Nullable KotlinType assignmentType,
086                @NotNull KtBinaryExpression expression,
087                @NotNull ExpressionTypingContext context
088        ) {
089            if (assignmentType != null && !KotlinBuiltIns.isUnit(assignmentType) && !noExpectedType(context.expectedType) &&
090                !context.expectedType.isError() && TypeUtils.equalTypes(context.expectedType, assignmentType)) {
091                context.trace.report(Errors.ASSIGNMENT_TYPE_MISMATCH.on(expression, context.expectedType));
092                return null;
093            }
094            return components.dataFlowAnalyzer.checkStatementType(expression, context);
095        }
096    
097        @Override
098        public JetTypeInfo visitObjectDeclaration(@NotNull KtObjectDeclaration declaration, ExpressionTypingContext context) {
099            components.localClassifierAnalyzer.processClassOrObject(
100                    scope, context.replaceScope(scope).replaceContextDependency(INDEPENDENT),
101                    scope.getOwnerDescriptor(),
102                    declaration);
103            return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(declaration, context), context);
104        }
105    
106        @Override
107        public JetTypeInfo visitProperty(@NotNull KtProperty property, ExpressionTypingContext typingContext) {
108            ExpressionTypingContext context = typingContext.replaceContextDependency(INDEPENDENT).replaceScope(scope);
109            KtTypeReference receiverTypeRef = property.getReceiverTypeReference();
110            if (receiverTypeRef != null) {
111                context.trace.report(LOCAL_EXTENSION_PROPERTY.on(receiverTypeRef));
112            }
113    
114            KtPropertyAccessor getter = property.getGetter();
115            if (getter != null) {
116                context.trace.report(LOCAL_VARIABLE_WITH_GETTER.on(getter));
117            }
118    
119            KtPropertyAccessor setter = property.getSetter();
120            if (setter != null) {
121                context.trace.report(LOCAL_VARIABLE_WITH_SETTER.on(setter));
122            }
123    
124            KtExpression delegateExpression = property.getDelegateExpression();
125            if (delegateExpression != null) {
126                components.expressionTypingServices.getTypeInfo(delegateExpression, context);
127                context.trace.report(LOCAL_VARIABLE_WITH_DELEGATE.on(property.getDelegate()));
128            }
129    
130            VariableDescriptor propertyDescriptor = components.descriptorResolver.
131                    resolveLocalVariableDescriptor(scope, property, context.dataFlowInfo, context.trace);
132            KtExpression initializer = property.getInitializer();
133            JetTypeInfo typeInfo;
134            if (initializer != null) {
135                KotlinType outType = propertyDescriptor.getType();
136                typeInfo = facade.getTypeInfo(initializer, context.replaceExpectedType(outType));
137                DataFlowInfo dataFlowInfo = typeInfo.getDataFlowInfo();
138                KotlinType type = typeInfo.getType();
139                // At this moment we do not take initializer value into account if type is given for a property
140                // We can comment first part of this condition to take them into account, like here: var s: String? = "xyz"
141                // In this case s will be not-nullable until it is changed
142                if (property.getTypeReference() == null && type != null) {
143                    DataFlowValue variableDataFlowValue = DataFlowValueFactory.createDataFlowValueForProperty(
144                            property, propertyDescriptor, context.trace.getBindingContext(),
145                            DescriptorUtils.getContainingModuleOrNull(scope.getOwnerDescriptor()));
146                    DataFlowValue initializerDataFlowValue = DataFlowValueFactory.createDataFlowValue(initializer, type, context);
147                    // We cannot say here anything new about initializerDataFlowValue
148                    // except it has the same value as variableDataFlowValue
149                    typeInfo = typeInfo.replaceDataFlowInfo(dataFlowInfo.assign(variableDataFlowValue, initializerDataFlowValue));
150                }
151            }
152            else {
153                typeInfo = TypeInfoFactoryKt.noTypeInfo(context);
154            }
155    
156            {
157                VariableDescriptor olderVariable = ScopeUtilsKt.getLocalVariable(scope, propertyDescriptor.getName());
158                ExpressionTypingUtils.checkVariableShadowing(context, propertyDescriptor, olderVariable);
159            }
160    
161            scope.addVariableDescriptor(propertyDescriptor);
162            components.modifiersChecker.withTrace(context.trace).checkModifiersForLocalDeclaration(property, propertyDescriptor);
163            components.identifierChecker.checkDeclaration(property, context.trace);
164            return typeInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(property, context));
165        }
166    
167        @Override
168        public JetTypeInfo visitMultiDeclaration(@NotNull KtMultiDeclaration multiDeclaration, ExpressionTypingContext context) {
169            components.annotationResolver.resolveAnnotationsWithArguments(scope, multiDeclaration.getModifierList(), context.trace);
170    
171            KtExpression initializer = multiDeclaration.getInitializer();
172            if (initializer == null) {
173                context.trace.report(INITIALIZER_REQUIRED_FOR_MULTIDECLARATION.on(multiDeclaration));
174                return TypeInfoFactoryKt.noTypeInfo(context);
175            }
176            ExpressionReceiver expressionReceiver = ExpressionTypingUtils.getExpressionReceiver(
177                    facade, initializer, context.replaceExpectedType(NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT));
178            JetTypeInfo typeInfo = facade.getTypeInfo(initializer, context);
179            if (expressionReceiver == null) {
180                return TypeInfoFactoryKt.noTypeInfo(context);
181            }
182            components.multiDeclarationResolver.defineLocalVariablesFromMultiDeclaration(scope, multiDeclaration, expressionReceiver, initializer, context);
183            components.modifiersChecker.withTrace(context.trace).checkModifiersForMultiDeclaration(multiDeclaration);
184            components.identifierChecker.checkDeclaration(multiDeclaration, context.trace);
185            return typeInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(multiDeclaration, context));
186        }
187    
188        @Override
189        public JetTypeInfo visitNamedFunction(@NotNull KtNamedFunction function, ExpressionTypingContext context) {
190            return functions.visitNamedFunction(function, context, true, scope);
191        }
192    
193        @Override
194        public JetTypeInfo visitClass(@NotNull KtClass klass, ExpressionTypingContext context) {
195            components.localClassifierAnalyzer.processClassOrObject(
196                    scope, context.replaceScope(scope).replaceContextDependency(INDEPENDENT),
197                    scope.getOwnerDescriptor(),
198                    klass);
199            return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(klass, context), context);
200        }
201    
202        @Override
203        public JetTypeInfo visitTypedef(@NotNull KtTypedef typedef, ExpressionTypingContext context) {
204            context.trace.report(UNSUPPORTED.on(typedef, "Typedefs are not supported"));
205            return super.visitTypedef(typedef, context);
206        }
207    
208        @Override
209        public JetTypeInfo visitDeclaration(@NotNull KtDeclaration dcl, ExpressionTypingContext context) {
210            return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(dcl, context), context);
211        }
212    
213        @Override
214        public JetTypeInfo visitBinaryExpression(@NotNull KtBinaryExpression expression, ExpressionTypingContext context) {
215            KtSimpleNameExpression operationSign = expression.getOperationReference();
216            IElementType operationType = operationSign.getReferencedNameElementType();
217            JetTypeInfo result;
218            if (operationType == KtTokens.EQ) {
219                result = visitAssignment(expression, context);
220            }
221            else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) {
222                result = visitAssignmentOperation(expression, context);
223            }
224            else {
225                return facade.getTypeInfo(expression, context);
226            }
227            return components.dataFlowAnalyzer.checkType(result, expression, context);
228        }
229    
230        @NotNull
231        protected JetTypeInfo visitAssignmentOperation(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
232            //There is a temporary binding trace for an opportunity to resolve set method for array if needed (the initial trace should be used there)
233            TemporaryTraceAndCache temporary = TemporaryTraceAndCache.create(
234                    contextWithExpectedType, "trace to resolve array set method for binary expression", expression);
235            ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE)
236                    .replaceTraceAndCache(temporary).replaceContextDependency(INDEPENDENT);
237    
238            KtSimpleNameExpression operationSign = expression.getOperationReference();
239            IElementType operationType = operationSign.getReferencedNameElementType();
240            KtExpression leftOperand = expression.getLeft();
241            JetTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(leftOperand, context, facade);
242            KotlinType leftType = leftInfo.getType();
243    
244            KtExpression right = expression.getRight();
245            KtExpression left = leftOperand == null ? null : deparenthesize(leftOperand);
246            if (right == null || left == null) {
247                temporary.commit();
248                return leftInfo.clearType();
249            }
250    
251            if (leftType == null) {
252                JetTypeInfo rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
253                context.trace.report(UNRESOLVED_REFERENCE.on(operationSign, operationSign));
254                temporary.commit();
255                return rightInfo.clearType();
256            }
257            ExpressionReceiver receiver = new ExpressionReceiver(left, leftType);
258    
259            // We check that defined only one of '+=' and '+' operations, and call it (in the case '+' we then also assign)
260            // Check for '+='
261            Name name = OperatorConventions.ASSIGNMENT_OPERATIONS.get(operationType);
262            TemporaryTraceAndCache temporaryForAssignmentOperation = TemporaryTraceAndCache.create(
263                    context, "trace to check assignment operation like '+=' for", expression);
264            OverloadResolutionResults<FunctionDescriptor> assignmentOperationDescriptors =
265                    components.callResolver.resolveBinaryCall(
266                            context.replaceTraceAndCache(temporaryForAssignmentOperation).replaceScope(scope),
267                            receiver, expression, name
268                    );
269            KotlinType assignmentOperationType = OverloadResolutionResultsUtil.getResultingType(assignmentOperationDescriptors,
270                                                                                                context.contextDependency);
271    
272            OverloadResolutionResults<FunctionDescriptor> binaryOperationDescriptors;
273            KotlinType binaryOperationType;
274            TemporaryTraceAndCache temporaryForBinaryOperation = TemporaryTraceAndCache.create(
275                    context, "trace to check binary operation like '+' for", expression);
276            TemporaryBindingTrace ignoreReportsTrace = TemporaryBindingTrace.create(context.trace, "Trace for checking assignability");
277            boolean lhsAssignable = basic.checkLValue(ignoreReportsTrace, context, left, right);
278            if (assignmentOperationType == null || lhsAssignable) {
279                // Check for '+'
280                Name counterpartName = OperatorConventions.BINARY_OPERATION_NAMES.get(OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS.get(operationType));
281                binaryOperationDescriptors = components.callResolver.resolveBinaryCall(
282                        context.replaceTraceAndCache(temporaryForBinaryOperation).replaceScope(scope),
283                        receiver, expression, counterpartName
284                );
285                binaryOperationType = OverloadResolutionResultsUtil.getResultingType(binaryOperationDescriptors, context.contextDependency);
286            }
287            else {
288                binaryOperationDescriptors = OverloadResolutionResultsImpl.nameNotFound();
289                binaryOperationType = null;
290            }
291    
292            KotlinType type = assignmentOperationType != null ? assignmentOperationType : binaryOperationType;
293            JetTypeInfo rightInfo = leftInfo;
294            if (assignmentOperationDescriptors.isSuccess() && binaryOperationDescriptors.isSuccess()) {
295                // Both 'plus()' and 'plusAssign()' available => ambiguity
296                OverloadResolutionResults<FunctionDescriptor> ambiguityResolutionResults = OverloadResolutionResultsUtil.ambiguity(assignmentOperationDescriptors, binaryOperationDescriptors);
297                context.trace.report(ASSIGN_OPERATOR_AMBIGUITY.on(operationSign, ambiguityResolutionResults.getResultingCalls()));
298                Collection<DeclarationDescriptor> descriptors = Sets.newHashSet();
299                for (ResolvedCall<?> resolvedCall : ambiguityResolutionResults.getResultingCalls()) {
300                    descriptors.add(resolvedCall.getResultingDescriptor());
301                }
302                rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
303                context.trace.record(AMBIGUOUS_REFERENCE_TARGET, operationSign, descriptors);
304            }
305            else if (assignmentOperationType != null && (assignmentOperationDescriptors.isSuccess() || !binaryOperationDescriptors.isSuccess())) {
306                // There's 'plusAssign()', so we do a.plusAssign(b)
307                temporaryForAssignmentOperation.commit();
308                if (!KotlinTypeChecker.DEFAULT.equalTypes(components.builtIns.getUnitType(), assignmentOperationType)) {
309                    context.trace.report(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT.on(operationSign, assignmentOperationDescriptors.getResultingDescriptor(), operationSign));
310                }
311            }
312            else {
313                // There's only 'plus()', so we try 'a = a + b'
314                temporaryForBinaryOperation.commit();
315                context.trace.record(VARIABLE_REASSIGNMENT, expression);
316                if (left instanceof KtArrayAccessExpression) {
317                    ExpressionTypingContext contextForResolve = context.replaceScope(scope).replaceBindingTrace(TemporaryBindingTrace.create(
318                            context.trace, "trace to resolve array set method for assignment", expression));
319                    basic.resolveArrayAccessSetMethod((KtArrayAccessExpression) left, right, contextForResolve, context.trace);
320                }
321                rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
322                components.dataFlowAnalyzer.checkType(binaryOperationType, expression, context.replaceExpectedType(leftType).replaceDataFlowInfo(rightInfo.getDataFlowInfo()));
323                basic.checkLValue(context.trace, context, leftOperand, right);
324            }
325            temporary.commit();
326            return rightInfo.replaceType(checkAssignmentType(type, expression, contextWithExpectedType));
327        }
328    
329        @NotNull
330        protected JetTypeInfo visitAssignment(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
331            final ExpressionTypingContext context =
332                    contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE).replaceScope(scope).replaceContextDependency(INDEPENDENT);
333            KtExpression leftOperand = expression.getLeft();
334            if (leftOperand instanceof KtAnnotatedExpression) {
335                // We will lose all annotations during deparenthesizing, so we have to resolve them right now
336                components.annotationResolver.resolveAnnotationsWithArguments(
337                        scope, ((KtAnnotatedExpression) leftOperand).getAnnotationEntries(), context.trace
338                );
339            }
340            KtExpression left = deparenthesize(leftOperand);
341            KtExpression right = expression.getRight();
342            if (left instanceof KtArrayAccessExpression) {
343                KtArrayAccessExpression arrayAccessExpression = (KtArrayAccessExpression) left;
344                if (right == null) return TypeInfoFactoryKt.noTypeInfo(context);
345                JetTypeInfo typeInfo = basic.resolveArrayAccessSetMethod(arrayAccessExpression, right, context, context.trace);
346                basic.checkLValue(context.trace, context, arrayAccessExpression, right);
347                return typeInfo.replaceType(checkAssignmentType(typeInfo.getType(), expression, contextWithExpectedType));
348            }
349            JetTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(left, context, facade);
350            KotlinType leftType = leftInfo.getType();
351            DataFlowInfo dataFlowInfo = leftInfo.getDataFlowInfo();
352            JetTypeInfo resultInfo;
353            if (right != null) {
354                resultInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo).replaceExpectedType(leftType));
355                dataFlowInfo = resultInfo.getDataFlowInfo();
356                KotlinType rightType = resultInfo.getType();
357                if (left != null && leftType != null && rightType != null) {
358                    DataFlowValue leftValue = DataFlowValueFactory.createDataFlowValue(left, leftType, context);
359                    DataFlowValue rightValue = DataFlowValueFactory.createDataFlowValue(right, rightType, context);
360                    // We cannot say here anything new about rightValue except it has the same value as leftValue
361                    resultInfo = resultInfo.replaceDataFlowInfo(dataFlowInfo.assign(leftValue, rightValue));
362                }
363            }
364            else {
365                resultInfo = leftInfo;
366            }
367            if (leftType != null && leftOperand != null) { //if leftType == null, some other error has been generated
368                basic.checkLValue(context.trace, context, leftOperand, right);
369            }
370            return resultInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(expression, contextWithExpectedType));
371        }
372    
373    
374        @Override
375        public JetTypeInfo visitExpression(@NotNull KtExpression expression, ExpressionTypingContext context) {
376            return facade.getTypeInfo(expression, context);
377        }
378    
379        @Override
380        public JetTypeInfo visitJetElement(@NotNull KtElement element, ExpressionTypingContext context) {
381            context.trace.report(UNSUPPORTED.on(element, "in a block"));
382            return TypeInfoFactoryKt.noTypeInfo(context);
383        }
384    
385        @Override
386        public JetTypeInfo visitWhileExpression(@NotNull KtWhileExpression expression, ExpressionTypingContext context) {
387            return controlStructures.visitWhileExpression(expression, context, true);
388        }
389    
390        @Override
391        public JetTypeInfo visitDoWhileExpression(@NotNull KtDoWhileExpression expression, ExpressionTypingContext context) {
392            return controlStructures.visitDoWhileExpression(expression, context, true);
393        }
394    
395        @Override
396        public JetTypeInfo visitForExpression(@NotNull KtForExpression expression, ExpressionTypingContext context) {
397            return controlStructures.visitForExpression(expression, context, true);
398        }
399    
400        @Override
401        public JetTypeInfo visitAnnotatedExpression(
402                @NotNull KtAnnotatedExpression expression, ExpressionTypingContext data
403        ) {
404            return basic.visitAnnotatedExpression(expression, data, true);
405        }
406    
407        @Override
408        public JetTypeInfo visitIfExpression(@NotNull KtIfExpression expression, ExpressionTypingContext context) {
409            return controlStructures.visitIfExpression(expression, context, true);
410        }
411    
412        @Override
413        public JetTypeInfo visitWhenExpression(@NotNull KtWhenExpression expression, ExpressionTypingContext context) {
414            return patterns.visitWhenExpression(expression, context, true);
415        }
416    
417        @Override
418        public JetTypeInfo visitBlockExpression(@NotNull KtBlockExpression expression, ExpressionTypingContext context) {
419            return components.expressionTypingServices.getBlockReturnedType(expression, context, true);
420        }
421    
422        @Override
423        public JetTypeInfo visitLabeledExpression(@NotNull KtLabeledExpression expression, ExpressionTypingContext context) {
424            return basic.visitLabeledExpression(expression, context, true);
425        }
426    }