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 kotlin.Pair;
022    import org.jetbrains.annotations.NotNull;
023    import org.jetbrains.annotations.Nullable;
024    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
025    import org.jetbrains.kotlin.descriptors.*;
026    import org.jetbrains.kotlin.diagnostics.Errors;
027    import org.jetbrains.kotlin.lexer.KtTokens;
028    import org.jetbrains.kotlin.name.Name;
029    import org.jetbrains.kotlin.psi.*;
030    import org.jetbrains.kotlin.resolve.BindingContext;
031    import org.jetbrains.kotlin.resolve.BindingContextUtils;
032    import org.jetbrains.kotlin.resolve.TemporaryBindingTrace;
033    import org.jetbrains.kotlin.resolve.calls.context.CallPosition;
034    import org.jetbrains.kotlin.resolve.calls.context.TemporaryTraceAndCache;
035    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
036    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults;
037    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsImpl;
038    import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsUtil;
039    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
040    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue;
041    import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory;
042    import org.jetbrains.kotlin.resolve.scopes.LexicalWritableScope;
043    import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
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 KotlinTypeInfo 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 KotlinTypeInfo visitProperty(@NotNull KtProperty property, ExpressionTypingContext typingContext) {
108            Pair<KotlinTypeInfo, VariableDescriptor> typeInfoAndVariableDescriptor = components.localVariableResolver.process(property, typingContext, scope, facade);
109            scope.addVariableDescriptor(typeInfoAndVariableDescriptor.getSecond());
110            return typeInfoAndVariableDescriptor.getFirst();
111        }
112    
113        @Override
114        public KotlinTypeInfo visitDestructuringDeclaration(@NotNull KtDestructuringDeclaration multiDeclaration, ExpressionTypingContext context) {
115            components.annotationResolver.resolveAnnotationsWithArguments(scope, multiDeclaration.getModifierList(), context.trace);
116    
117            KtExpression initializer = multiDeclaration.getInitializer();
118            if (initializer == null) {
119                context.trace.report(INITIALIZER_REQUIRED_FOR_DESTRUCTURING_DECLARATION.on(multiDeclaration));
120                return TypeInfoFactoryKt.noTypeInfo(context);
121            }
122            ExpressionReceiver expressionReceiver = ExpressionTypingUtils.getExpressionReceiver(
123                    facade, initializer, context.replaceExpectedType(NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT));
124            KotlinTypeInfo typeInfo = facade.getTypeInfo(initializer, context);
125            if (expressionReceiver == null) {
126                return TypeInfoFactoryKt.noTypeInfo(context);
127            }
128            components.destructuringDeclarationResolver
129                    .defineLocalVariablesFromMultiDeclaration(scope, multiDeclaration, expressionReceiver, initializer, context);
130            components.modifiersChecker.withTrace(context.trace).checkModifiersForDestructuringDeclaration(multiDeclaration);
131            components.identifierChecker.checkDeclaration(multiDeclaration, context.trace);
132            return typeInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(multiDeclaration, context));
133        }
134    
135        @Override
136        public KotlinTypeInfo visitNamedFunction(@NotNull KtNamedFunction function, ExpressionTypingContext context) {
137            return functions.visitNamedFunction(function, context, true, scope);
138        }
139    
140        @Override
141        public KotlinTypeInfo visitClass(@NotNull KtClass klass, ExpressionTypingContext context) {
142            components.localClassifierAnalyzer.processClassOrObject(
143                    scope, context.replaceScope(scope).replaceContextDependency(INDEPENDENT),
144                    scope.getOwnerDescriptor(),
145                    klass);
146            return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(klass, context), context);
147        }
148    
149        @Override
150        public KotlinTypeInfo visitDeclaration(@NotNull KtDeclaration dcl, ExpressionTypingContext context) {
151            return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(dcl, context), context);
152        }
153    
154        @Override
155        public KotlinTypeInfo visitBinaryExpression(@NotNull KtBinaryExpression expression, ExpressionTypingContext context) {
156            KtSimpleNameExpression operationSign = expression.getOperationReference();
157            IElementType operationType = operationSign.getReferencedNameElementType();
158            KotlinTypeInfo result;
159            if (operationType == KtTokens.EQ) {
160                result = visitAssignment(expression, context);
161            }
162            else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) {
163                result = visitAssignmentOperation(expression, context);
164            }
165            else {
166                return facade.getTypeInfo(expression, context);
167            }
168            return components.dataFlowAnalyzer.checkType(result, expression, context);
169        }
170    
171        @NotNull
172        protected KotlinTypeInfo visitAssignmentOperation(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
173            //There is a temporary binding trace for an opportunity to resolve set method for array if needed (the initial trace should be used there)
174            TemporaryTraceAndCache temporary = TemporaryTraceAndCache.create(
175                    contextWithExpectedType, "trace to resolve array set method for binary expression", expression);
176            ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE)
177                    .replaceTraceAndCache(temporary).replaceContextDependency(INDEPENDENT);
178    
179            KtSimpleNameExpression operationSign = expression.getOperationReference();
180            IElementType operationType = operationSign.getReferencedNameElementType();
181            KtExpression leftOperand = expression.getLeft();
182            KotlinTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(leftOperand, context, facade);
183            KotlinType leftType = leftInfo.getType();
184    
185            KtExpression right = expression.getRight();
186            KtExpression left = leftOperand == null ? null : deparenthesize(leftOperand);
187            if (right == null || left == null) {
188                temporary.commit();
189                return leftInfo.clearType();
190            }
191    
192            if (leftType == null) {
193                KotlinTypeInfo rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
194                context.trace.report(UNRESOLVED_REFERENCE.on(operationSign, operationSign));
195                temporary.commit();
196                return rightInfo.clearType();
197            }
198            ExpressionReceiver receiver = ExpressionReceiver.Companion.create(left, leftType, context.trace.getBindingContext());
199    
200            // We check that defined only one of '+=' and '+' operations, and call it (in the case '+' we then also assign)
201            // Check for '+='
202            Name name = OperatorConventions.ASSIGNMENT_OPERATIONS.get(operationType);
203            TemporaryTraceAndCache temporaryForAssignmentOperation = TemporaryTraceAndCache.create(
204                    context, "trace to check assignment operation like '+=' for", expression);
205            OverloadResolutionResults<FunctionDescriptor> assignmentOperationDescriptors =
206                    components.callResolver.resolveBinaryCall(
207                            context.replaceTraceAndCache(temporaryForAssignmentOperation).replaceScope(scope),
208                            receiver, expression, name
209                    );
210            KotlinType assignmentOperationType = OverloadResolutionResultsUtil.getResultingType(assignmentOperationDescriptors,
211                                                                                                context.contextDependency);
212    
213            OverloadResolutionResults<FunctionDescriptor> binaryOperationDescriptors;
214            KotlinType binaryOperationType;
215            TemporaryTraceAndCache temporaryForBinaryOperation = TemporaryTraceAndCache.create(
216                    context, "trace to check binary operation like '+' for", expression);
217            TemporaryBindingTrace ignoreReportsTrace = TemporaryBindingTrace.create(context.trace, "Trace for checking assignability");
218            boolean lhsAssignable = basic.checkLValue(ignoreReportsTrace, context, left, right);
219            if (assignmentOperationType == null || lhsAssignable) {
220                // Check for '+'
221                Name counterpartName = OperatorConventions.BINARY_OPERATION_NAMES.get(OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS.get(operationType));
222                binaryOperationDescriptors = components.callResolver.resolveBinaryCall(
223                        context.replaceTraceAndCache(temporaryForBinaryOperation).replaceScope(scope),
224                        receiver, expression, counterpartName
225                );
226                binaryOperationType = OverloadResolutionResultsUtil.getResultingType(binaryOperationDescriptors, context.contextDependency);
227            }
228            else {
229                binaryOperationDescriptors = OverloadResolutionResultsImpl.nameNotFound();
230                binaryOperationType = null;
231            }
232    
233            KotlinType type = assignmentOperationType != null ? assignmentOperationType : binaryOperationType;
234            KotlinTypeInfo rightInfo = leftInfo;
235            if (assignmentOperationDescriptors.isSuccess() && binaryOperationDescriptors.isSuccess()) {
236                // Both 'plus()' and 'plusAssign()' available => ambiguity
237                OverloadResolutionResults<FunctionDescriptor> ambiguityResolutionResults = OverloadResolutionResultsUtil.ambiguity(assignmentOperationDescriptors, binaryOperationDescriptors);
238                context.trace.report(ASSIGN_OPERATOR_AMBIGUITY.on(operationSign, ambiguityResolutionResults.getResultingCalls()));
239                Collection<DeclarationDescriptor> descriptors = Sets.newHashSet();
240                for (ResolvedCall<?> resolvedCall : ambiguityResolutionResults.getResultingCalls()) {
241                    descriptors.add(resolvedCall.getResultingDescriptor());
242                }
243                rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
244                context.trace.record(AMBIGUOUS_REFERENCE_TARGET, operationSign, descriptors);
245            }
246            else if (assignmentOperationType != null && (assignmentOperationDescriptors.isSuccess() || !binaryOperationDescriptors.isSuccess())) {
247                // There's 'plusAssign()', so we do a.plusAssign(b)
248                temporaryForAssignmentOperation.commit();
249                if (!KotlinTypeChecker.DEFAULT.equalTypes(components.builtIns.getUnitType(), assignmentOperationType)) {
250                    context.trace.report(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT.on(operationSign, assignmentOperationDescriptors.getResultingDescriptor(), operationSign));
251                }
252            }
253            else {
254                // There's only 'plus()', so we try 'a = a + b'
255                temporaryForBinaryOperation.commit();
256                context.trace.record(VARIABLE_REASSIGNMENT, expression);
257                if (left instanceof KtArrayAccessExpression) {
258                    ExpressionTypingContext contextForResolve = context.replaceScope(scope).replaceBindingTrace(TemporaryBindingTrace.create(
259                            context.trace, "trace to resolve array set method for assignment", expression));
260                    basic.resolveArrayAccessSetMethod((KtArrayAccessExpression) left, right, contextForResolve, context.trace);
261                }
262                rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
263    
264                KotlinType expectedType = refineTypeFromPropertySetterIfPossible(context.trace.getBindingContext(), leftOperand, leftType);
265    
266                components.dataFlowAnalyzer.checkType(binaryOperationType, expression, context.replaceExpectedType(expectedType)
267                        .replaceDataFlowInfo(rightInfo.getDataFlowInfo()).replaceCallPosition(new CallPosition.PropertyAssignment(left)));
268                basic.checkLValue(context.trace, context, leftOperand, right);
269            }
270            temporary.commit();
271            return rightInfo.replaceType(checkAssignmentType(type, expression, contextWithExpectedType));
272        }
273    
274        @Nullable
275        private static KotlinType refineTypeFromPropertySetterIfPossible(
276                @NotNull BindingContext bindingContext,
277                @Nullable KtElement leftOperand,
278                @Nullable KotlinType leftOperandType
279        ) {
280            VariableDescriptor descriptor = BindingContextUtils.extractVariableFromResolvedCall(bindingContext, leftOperand);
281    
282            if (descriptor instanceof PropertyDescriptor) {
283                PropertySetterDescriptor setter = ((PropertyDescriptor) descriptor).getSetter();
284                if (setter != null) return setter.getValueParameters().get(0).getType();
285            }
286    
287            return leftOperandType;
288        }
289    
290        @NotNull
291        protected KotlinTypeInfo visitAssignment(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
292            ExpressionTypingContext context =
293                    contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE).replaceScope(scope).replaceContextDependency(INDEPENDENT);
294            KtExpression leftOperand = expression.getLeft();
295            if (leftOperand instanceof KtAnnotatedExpression) {
296                // We will lose all annotations during deparenthesizing, so we have to resolve them right now
297                components.annotationResolver.resolveAnnotationsWithArguments(
298                        scope, ((KtAnnotatedExpression) leftOperand).getAnnotationEntries(), context.trace
299                );
300            }
301            KtExpression left = deparenthesize(leftOperand);
302            KtExpression right = expression.getRight();
303            if (left instanceof KtArrayAccessExpression) {
304                KtArrayAccessExpression arrayAccessExpression = (KtArrayAccessExpression) left;
305                if (right == null) return TypeInfoFactoryKt.noTypeInfo(context);
306                KotlinTypeInfo typeInfo = basic.resolveArrayAccessSetMethod(arrayAccessExpression, right, context, context.trace);
307                basic.checkLValue(context.trace, context, arrayAccessExpression, right);
308                return typeInfo.replaceType(checkAssignmentType(typeInfo.getType(), expression, contextWithExpectedType));
309            }
310            KotlinTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(left, context, facade);
311            KotlinType expectedType = refineTypeFromPropertySetterIfPossible(context.trace.getBindingContext(), leftOperand, leftInfo.getType());
312            DataFlowInfo dataFlowInfo = leftInfo.getDataFlowInfo();
313            KotlinTypeInfo resultInfo;
314            if (right != null) {
315                resultInfo = facade.getTypeInfo(
316                                right, context.replaceDataFlowInfo(dataFlowInfo).replaceExpectedType(expectedType).replaceCallPosition(
317                                        new CallPosition.PropertyAssignment(leftOperand)));
318    
319                dataFlowInfo = resultInfo.getDataFlowInfo();
320                KotlinType rightType = resultInfo.getType();
321                if (left != null && expectedType != null && rightType != null) {
322                    DataFlowValue leftValue = DataFlowValueFactory.createDataFlowValue(left, expectedType, context);
323                    DataFlowValue rightValue = DataFlowValueFactory.createDataFlowValue(right, rightType, context);
324                    // We cannot say here anything new about rightValue except it has the same value as leftValue
325                    resultInfo = resultInfo.replaceDataFlowInfo(dataFlowInfo.assign(leftValue, rightValue));
326                }
327            }
328            else {
329                resultInfo = leftInfo;
330            }
331            if (expectedType != null && leftOperand != null) { //if expectedType == null, some other error has been generated
332                basic.checkLValue(context.trace, context, leftOperand, right);
333            }
334            return resultInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(expression, contextWithExpectedType));
335        }
336    
337    
338        @Override
339        public KotlinTypeInfo visitExpression(@NotNull KtExpression expression, ExpressionTypingContext context) {
340            return facade.getTypeInfo(expression, context);
341        }
342    
343        @Override
344        public KotlinTypeInfo visitKtElement(@NotNull KtElement element, ExpressionTypingContext context) {
345            context.trace.report(UNSUPPORTED.on(element, "in a block"));
346            return TypeInfoFactoryKt.noTypeInfo(context);
347        }
348    
349        @Override
350        public KotlinTypeInfo visitWhileExpression(@NotNull KtWhileExpression expression, ExpressionTypingContext context) {
351            return controlStructures.visitWhileExpression(expression, context, true);
352        }
353    
354        @Override
355        public KotlinTypeInfo visitDoWhileExpression(@NotNull KtDoWhileExpression expression, ExpressionTypingContext context) {
356            return controlStructures.visitDoWhileExpression(expression, context, true);
357        }
358    
359        @Override
360        public KotlinTypeInfo visitForExpression(@NotNull KtForExpression expression, ExpressionTypingContext context) {
361            return controlStructures.visitForExpression(expression, context, true);
362        }
363    
364        @Override
365        public KotlinTypeInfo visitAnnotatedExpression(
366                @NotNull KtAnnotatedExpression expression, ExpressionTypingContext data
367        ) {
368            return basic.visitAnnotatedExpression(expression, data, true);
369        }
370    
371        @Override
372        public KotlinTypeInfo visitIfExpression(@NotNull KtIfExpression expression, ExpressionTypingContext context) {
373            return controlStructures.visitIfExpression(expression, context, true);
374        }
375    
376        @Override
377        public KotlinTypeInfo visitWhenExpression(@NotNull KtWhenExpression expression, ExpressionTypingContext context) {
378            return patterns.visitWhenExpression(expression, context, true);
379        }
380    
381        @Override
382        public KotlinTypeInfo visitBlockExpression(@NotNull KtBlockExpression expression, ExpressionTypingContext context) {
383            return components.expressionTypingServices.getBlockReturnedType(expression, context, true);
384        }
385    
386        @Override
387        public KotlinTypeInfo visitLabeledExpression(@NotNull KtLabeledExpression expression, ExpressionTypingContext context) {
388            return basic.visitLabeledExpression(expression, context, true);
389        }
390    }