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.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.jet.lang.descriptors.*;
024    import org.jetbrains.jet.lang.diagnostics.Errors;
025    import org.jetbrains.jet.lang.psi.*;
026    import org.jetbrains.jet.lang.resolve.*;
027    import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo;
028    import org.jetbrains.jet.lang.resolve.calls.context.TemporaryTraceAndCache;
029    import org.jetbrains.jet.lang.resolve.calls.model.ResolvedCall;
030    import org.jetbrains.jet.lang.resolve.calls.results.OverloadResolutionResults;
031    import org.jetbrains.jet.lang.resolve.calls.results.OverloadResolutionResultsUtil;
032    import org.jetbrains.jet.lang.resolve.name.Name;
033    import org.jetbrains.jet.lang.resolve.scopes.JetScope;
034    import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
035    import org.jetbrains.jet.lang.resolve.scopes.receivers.ExpressionReceiver;
036    import org.jetbrains.jet.lang.types.JetType;
037    import org.jetbrains.jet.lang.types.JetTypeInfo;
038    import org.jetbrains.jet.lang.types.TypeUtils;
039    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
040    import org.jetbrains.jet.lexer.JetTokens;
041    
042    import java.util.Collection;
043    
044    import static org.jetbrains.jet.lang.diagnostics.Errors.*;
045    import static org.jetbrains.jet.lang.resolve.BindingContext.AMBIGUOUS_REFERENCE_TARGET;
046    import static org.jetbrains.jet.lang.resolve.BindingContext.VARIABLE_REASSIGNMENT;
047    import static org.jetbrains.jet.lang.resolve.calls.context.ContextDependency.INDEPENDENT;
048    import static org.jetbrains.jet.lang.types.TypeUtils.NO_EXPECTED_TYPE;
049    import static org.jetbrains.jet.lang.types.TypeUtils.noExpectedType;
050    
051    @SuppressWarnings("SuspiciousMethodCalls")
052    public class ExpressionTypingVisitorForStatements extends ExpressionTypingVisitor {
053        private final WritableScope scope;
054        private final BasicExpressionTypingVisitor basic;
055        private final ControlStructureTypingVisitor controlStructures;
056        private final PatternMatchingTypingVisitor patterns;
057    
058        public ExpressionTypingVisitorForStatements(
059                @NotNull ExpressionTypingInternals facade,
060                @NotNull WritableScope scope,
061                BasicExpressionTypingVisitor basic,
062                @NotNull ControlStructureTypingVisitor controlStructures,
063                @NotNull PatternMatchingTypingVisitor patterns) {
064            super(facade);
065            this.scope = scope;
066            this.basic = basic;
067            this.controlStructures = controlStructures;
068            this.patterns = patterns;
069        }
070    
071        @Nullable
072        private static JetType checkAssignmentType(
073                @Nullable JetType assignmentType,
074                @NotNull JetBinaryExpression expression,
075                @NotNull ExpressionTypingContext context
076        ) {
077            if (assignmentType != null && !KotlinBuiltIns.getInstance().isUnit(assignmentType) && !noExpectedType(context.expectedType) &&
078                TypeUtils.equalTypes(context.expectedType, assignmentType)) {
079                context.trace.report(Errors.ASSIGNMENT_TYPE_MISMATCH.on(expression, context.expectedType));
080                return null;
081            }
082            return DataFlowUtils.checkStatementType(expression, context);
083        }
084    
085        @Override
086        public JetTypeInfo visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, ExpressionTypingContext context) {
087            TopDownAnalyzer.processClassOrObject(
088                    context.replaceScope(scope).replaceContextDependency(INDEPENDENT), scope.getContainingDeclaration(), declaration);
089            ClassDescriptor classDescriptor = context.trace.getBindingContext().get(BindingContext.CLASS, declaration);
090            if (classDescriptor != null) {
091                scope.addClassifierDescriptor(classDescriptor);
092            }
093            return DataFlowUtils.checkStatementType(declaration, context, context.dataFlowInfo);
094        }
095    
096        @Override
097        public JetTypeInfo visitProperty(@NotNull JetProperty property, ExpressionTypingContext typingContext) {
098            ExpressionTypingContext context = typingContext.replaceContextDependency(INDEPENDENT).replaceScope(scope);
099            JetTypeReference receiverTypeRef = property.getReceiverTypeRef();
100            if (receiverTypeRef != null) {
101                context.trace.report(LOCAL_EXTENSION_PROPERTY.on(receiverTypeRef));
102            }
103    
104            JetPropertyAccessor getter = property.getGetter();
105            if (getter != null) {
106                context.trace.report(LOCAL_VARIABLE_WITH_GETTER.on(getter));
107            }
108    
109            JetPropertyAccessor setter = property.getSetter();
110            if (setter != null) {
111                context.trace.report(LOCAL_VARIABLE_WITH_SETTER.on(setter));
112            }
113    
114            JetExpression delegateExpression = property.getDelegateExpression();
115            if (delegateExpression != null) {
116                context.expressionTypingServices.getTypeInfo(delegateExpression, context);
117                context.trace.report(LOCAL_VARIABLE_WITH_DELEGATE.on(property.getDelegate()));
118            }
119    
120            for (JetTypeParameter typeParameter : property.getTypeParameters()) {
121                AnnotationResolver.reportUnsupportedAnnotationForTypeParameter(typeParameter, context.trace);
122            }
123    
124            VariableDescriptor propertyDescriptor = context.expressionTypingServices.getDescriptorResolver().
125                    resolveLocalVariableDescriptor(scope, property, context.dataFlowInfo, context.trace);
126            JetExpression initializer = property.getInitializer();
127            DataFlowInfo dataFlowInfo = context.dataFlowInfo;
128            if (initializer != null) {
129                JetType outType = propertyDescriptor.getType();
130                JetTypeInfo typeInfo = facade.getTypeInfo(initializer, context.replaceExpectedType(outType));
131                dataFlowInfo = typeInfo.getDataFlowInfo();
132            }
133    
134            {
135                VariableDescriptor olderVariable = scope.getLocalVariable(propertyDescriptor.getName());
136                ExpressionTypingUtils.checkVariableShadowing(context, propertyDescriptor, olderVariable);
137            }
138    
139            scope.addVariableDescriptor(propertyDescriptor);
140            ModifiersChecker.create(context.trace).checkModifiersForLocalDeclaration(property);
141            return DataFlowUtils.checkStatementType(property, context, dataFlowInfo);
142        }
143    
144        @Override
145        public JetTypeInfo visitMultiDeclaration(@NotNull JetMultiDeclaration multiDeclaration, ExpressionTypingContext context) {
146            context.expressionTypingServices.getAnnotationResolver().resolveAnnotationsWithArguments(
147                    scope, multiDeclaration.getModifierList(), context.trace);
148    
149            JetExpression initializer = multiDeclaration.getInitializer();
150            if (initializer == null) {
151                context.trace.report(INITIALIZER_REQUIRED_FOR_MULTIDECLARATION.on(multiDeclaration));
152                return JetTypeInfo.create(null, context.dataFlowInfo);
153            }
154            ExpressionReceiver expressionReceiver = ExpressionTypingUtils.getExpressionReceiver(
155                    facade, initializer, context.replaceExpectedType(NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT));
156            DataFlowInfo dataFlowInfo = facade.getTypeInfo(initializer, context).getDataFlowInfo();
157            if (expressionReceiver == null) {
158                return JetTypeInfo.create(null, dataFlowInfo);
159            }
160            ExpressionTypingUtils.defineLocalVariablesFromMultiDeclaration(scope, multiDeclaration, expressionReceiver, initializer, context);
161            return DataFlowUtils.checkStatementType(multiDeclaration, context, dataFlowInfo);
162        }
163    
164        @Override
165        public JetTypeInfo visitNamedFunction(@NotNull JetNamedFunction function, ExpressionTypingContext context) {
166            SimpleFunctionDescriptor functionDescriptor = context.expressionTypingServices.getDescriptorResolver().
167                    resolveFunctionDescriptorWithAnnotationArguments(
168                            scope.getContainingDeclaration(), scope, function, context.trace, context.dataFlowInfo);
169    
170            scope.addFunctionDescriptor(functionDescriptor);
171            JetScope functionInnerScope = FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace);
172            context.expressionTypingServices.checkFunctionReturnType(functionInnerScope, function, functionDescriptor, context.dataFlowInfo, null, context.trace);
173    
174            context.expressionTypingServices.resolveValueParameters(
175                    function.getValueParameters(), functionDescriptor.getValueParameters(), scope, context.dataFlowInfo, context.trace);
176    
177            ModifiersChecker.create(context.trace).checkModifiersForLocalDeclaration(function);
178            return DataFlowUtils.checkStatementType(function, context, context.dataFlowInfo);
179        }
180    
181        @Override
182        public JetTypeInfo visitClass(@NotNull JetClass klass, ExpressionTypingContext context) {
183            TopDownAnalyzer.processClassOrObject(
184                    context.replaceScope(scope).replaceContextDependency(INDEPENDENT), scope.getContainingDeclaration(), klass);
185            ClassDescriptor classDescriptor = context.trace.getBindingContext().get(BindingContext.CLASS, klass);
186            if (classDescriptor != null) {
187                scope.addClassifierDescriptor(classDescriptor);
188            }
189            return DataFlowUtils.checkStatementType(klass, context, context.dataFlowInfo);
190        }
191    
192        @Override
193        public JetTypeInfo visitTypedef(@NotNull JetTypedef typedef, ExpressionTypingContext context) {
194            return super.visitTypedef(typedef, context); // TODO
195        }
196    
197        @Override
198        public JetTypeInfo visitDeclaration(@NotNull JetDeclaration dcl, ExpressionTypingContext context) {
199            return DataFlowUtils.checkStatementType(dcl, context, context.dataFlowInfo);
200        }
201    
202        @Override
203        public JetTypeInfo visitBinaryExpression(@NotNull JetBinaryExpression expression, ExpressionTypingContext context) {
204            JetSimpleNameExpression operationSign = expression.getOperationReference();
205            IElementType operationType = operationSign.getReferencedNameElementType();
206            JetTypeInfo result;
207            if (operationType == JetTokens.EQ) {
208                result = visitAssignment(expression, context);
209            }
210            else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) {
211                result = visitAssignmentOperation(expression, context);
212            }
213            else {
214                return facade.getTypeInfo(expression, context);
215            }
216            return DataFlowUtils.checkType(result.getType(), expression, context, result.getDataFlowInfo());
217        }
218    
219        @NotNull
220        protected JetTypeInfo visitAssignmentOperation(JetBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
221            //There is a temporary binding trace for an opportunity to resolve set method for array if needed (the initial trace should be used there)
222            TemporaryTraceAndCache temporary = TemporaryTraceAndCache.create(
223                    contextWithExpectedType, "trace to resolve array set method for binary expression", expression);
224            ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE)
225                    .replaceTraceAndCache(temporary).replaceContextDependency(INDEPENDENT);
226    
227            JetSimpleNameExpression operationSign = expression.getOperationReference();
228            IElementType operationType = operationSign.getReferencedNameElementType();
229            JetExpression leftOperand = expression.getLeft();
230            JetTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(leftOperand, context, facade);
231            JetType leftType = leftInfo.getType();
232            DataFlowInfo dataFlowInfo = leftInfo.getDataFlowInfo();
233    
234            JetExpression right = expression.getRight();
235            JetExpression left = leftOperand == null ? null : JetPsiUtil.deparenthesize(leftOperand);
236            if (right == null || left == null) {
237                temporary.commit();
238                return JetTypeInfo.create(null, dataFlowInfo);
239            }
240    
241            if (leftType == null) {
242                dataFlowInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo)).getDataFlowInfo();
243                context.trace.report(UNRESOLVED_REFERENCE.on(operationSign, operationSign));
244                temporary.commit();
245                return JetTypeInfo.create(null, dataFlowInfo);
246            }
247            ExpressionReceiver receiver = new ExpressionReceiver(left, leftType);
248    
249            // We check that defined only one of '+=' and '+' operations, and call it (in the case '+' we then also assign)
250            // Check for '+='
251            Name name = OperatorConventions.ASSIGNMENT_OPERATIONS.get(operationType);
252            TemporaryTraceAndCache temporaryForAssignmentOperation = TemporaryTraceAndCache.create(
253                    context, "trace to check assignment operation like '+=' for", expression);
254            OverloadResolutionResults<FunctionDescriptor> assignmentOperationDescriptors = BasicExpressionTypingVisitor.getResolutionResultsForBinaryCall(
255                    scope, name, context.replaceTraceAndCache(temporaryForAssignmentOperation), expression, receiver);
256            JetType assignmentOperationType = OverloadResolutionResultsUtil.getResultingType(assignmentOperationDescriptors,
257                                                                                             context.contextDependency);
258    
259            // Check for '+'
260            Name counterpartName = OperatorConventions.BINARY_OPERATION_NAMES.get(OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS.get(operationType));
261            TemporaryTraceAndCache temporaryForBinaryOperation = TemporaryTraceAndCache.create(
262                    context, "trace to check binary operation like '+' for", expression);
263            OverloadResolutionResults<FunctionDescriptor> binaryOperationDescriptors = BasicExpressionTypingVisitor.getResolutionResultsForBinaryCall(
264                    scope, counterpartName, context.replaceTraceAndCache(temporaryForBinaryOperation), expression, receiver);
265            JetType binaryOperationType = OverloadResolutionResultsUtil.getResultingType(binaryOperationDescriptors, context.contextDependency);
266    
267            JetType type = assignmentOperationType != null ? assignmentOperationType : binaryOperationType;
268            if (assignmentOperationDescriptors.isSuccess() && binaryOperationDescriptors.isSuccess()) {
269                // Both 'plus()' and 'plusAssign()' available => ambiguity
270                OverloadResolutionResults<FunctionDescriptor> ambiguityResolutionResults = OverloadResolutionResultsUtil.ambiguity(assignmentOperationDescriptors, binaryOperationDescriptors);
271                context.trace.report(ASSIGN_OPERATOR_AMBIGUITY.on(operationSign, ambiguityResolutionResults.getResultingCalls()));
272                Collection<DeclarationDescriptor> descriptors = Sets.newHashSet();
273                for (ResolvedCall<? extends FunctionDescriptor> call : ambiguityResolutionResults.getResultingCalls()) {
274                    descriptors.add(call.getResultingDescriptor());
275                }
276                dataFlowInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo)).getDataFlowInfo();
277                context.trace.record(AMBIGUOUS_REFERENCE_TARGET, operationSign, descriptors);
278            }
279            else if (assignmentOperationType != null && (assignmentOperationDescriptors.isSuccess() || !binaryOperationDescriptors.isSuccess())) {
280                // There's 'plusAssign()', so we do a.plusAssign(b)
281                temporaryForAssignmentOperation.commit();
282                if (!KotlinBuiltIns.getInstance().isUnit(assignmentOperationType)) {
283                    context.trace.report(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT.on(operationSign, assignmentOperationDescriptors.getResultingDescriptor(), operationSign));
284                }
285            }
286            else {
287                // There's only 'plus()', so we try 'a = a + b'
288                temporaryForBinaryOperation.commit();
289                context.trace.record(VARIABLE_REASSIGNMENT, expression);
290                if (left instanceof JetArrayAccessExpression) {
291                    ExpressionTypingContext contextForResolve = context.replaceScope(scope).replaceBindingTrace(TemporaryBindingTrace.create(
292                            context.trace, "trace to resolve array set method for assignment", expression));
293                    basic.resolveArrayAccessSetMethod((JetArrayAccessExpression) left, right, contextForResolve, context.trace);
294                }
295                dataFlowInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo)).getDataFlowInfo();
296                BasicExpressionTypingVisitor.checkLValue(context.trace, leftOperand);
297            }
298            temporary.commit();
299            return JetTypeInfo.create(checkAssignmentType(type, expression, contextWithExpectedType), dataFlowInfo);
300        }
301    
302        @NotNull
303        protected JetTypeInfo visitAssignment(JetBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
304            ExpressionTypingContext context =
305                    contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE).replaceScope(scope).replaceContextDependency(INDEPENDENT);
306            JetExpression leftOperand = expression.getLeft();
307            JetExpression left = context.expressionTypingServices.deparenthesizeWithTypeResolution(leftOperand, context);
308            JetExpression right = expression.getRight();
309            if (left instanceof JetArrayAccessExpression) {
310                JetArrayAccessExpression arrayAccessExpression = (JetArrayAccessExpression) left;
311                if (right == null) return JetTypeInfo.create(null, context.dataFlowInfo);
312                JetTypeInfo typeInfo = basic.resolveArrayAccessSetMethod(arrayAccessExpression, right, context, context.trace);
313                BasicExpressionTypingVisitor.checkLValue(context.trace, arrayAccessExpression);
314                return JetTypeInfo.create(checkAssignmentType(typeInfo.getType(), expression, contextWithExpectedType),
315                                          typeInfo.getDataFlowInfo());
316            }
317            JetTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(left, context, facade);
318            JetType leftType = leftInfo.getType();
319            DataFlowInfo dataFlowInfo = leftInfo.getDataFlowInfo();
320            if (right != null) {
321                JetTypeInfo rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo).replaceExpectedType(leftType));
322                dataFlowInfo = rightInfo.getDataFlowInfo();
323            }
324            if (leftType != null && leftOperand != null) { //if leftType == null, some other error has been generated
325                BasicExpressionTypingVisitor.checkLValue(context.trace, leftOperand);
326            }
327            return DataFlowUtils.checkStatementType(expression, contextWithExpectedType, dataFlowInfo);
328        }
329    
330    
331        @Override
332        public JetTypeInfo visitExpression(@NotNull JetExpression expression, ExpressionTypingContext context) {
333            return facade.getTypeInfo(expression, context);
334        }
335    
336        @Override
337        public JetTypeInfo visitJetElement(@NotNull JetElement element, ExpressionTypingContext context) {
338            context.trace.report(UNSUPPORTED.on(element, "in a block"));
339            return JetTypeInfo.create(null, context.dataFlowInfo);
340        }
341    
342        @Override
343        public JetTypeInfo visitWhileExpression(@NotNull JetWhileExpression expression, ExpressionTypingContext context) {
344            return controlStructures.visitWhileExpression(expression, context, true);
345        }
346    
347        @Override
348        public JetTypeInfo visitDoWhileExpression(@NotNull JetDoWhileExpression expression, ExpressionTypingContext context) {
349            return controlStructures.visitDoWhileExpression(expression, context, true);
350        }
351    
352        @Override
353        public JetTypeInfo visitForExpression(@NotNull JetForExpression expression, ExpressionTypingContext context) {
354            return controlStructures.visitForExpression(expression, context, true);
355        }
356    
357        @Override
358        public JetTypeInfo visitAnnotatedExpression(
359                @NotNull JetAnnotatedExpression expression, ExpressionTypingContext data
360        ) {
361            return basic.visitAnnotatedExpression(expression, data, true);
362        }
363    
364        @Override
365        public JetTypeInfo visitIfExpression(@NotNull JetIfExpression expression, ExpressionTypingContext context) {
366            return controlStructures.visitIfExpression(expression, context, true);
367        }
368    
369        @Override
370        public JetTypeInfo visitWhenExpression(@NotNull JetWhenExpression expression, ExpressionTypingContext context) {
371            return patterns.visitWhenExpression(expression, context, true);
372        }
373    
374        @Override
375        public JetTypeInfo visitBlockExpression(@NotNull JetBlockExpression expression, ExpressionTypingContext context) {
376            return BasicExpressionTypingVisitor.visitBlockExpression(expression, context, true);
377        }
378    
379        @Override
380        public JetTypeInfo visitParenthesizedExpression(@NotNull JetParenthesizedExpression expression, ExpressionTypingContext context) {
381            return basic.visitParenthesizedExpression(expression, context, true);
382        }
383    
384        @Override
385        public JetTypeInfo visitUnaryExpression(@NotNull JetUnaryExpression expression, ExpressionTypingContext context) {
386            return basic.visitUnaryExpression(expression, context, true);
387        }
388    }