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.DeclarationsCheckerKt;
032 import org.jetbrains.kotlin.resolve.DescriptorUtils;
033 import org.jetbrains.kotlin.resolve.TemporaryBindingTrace;
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 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 KotlinTypeInfo 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 ExpressionTypingUtils.checkVariableShadowing(context.scope, context.trace, propertyDescriptor);
157
158 scope.addVariableDescriptor(propertyDescriptor);
159 DeclarationsCheckerKt.checkTypeReferences(property, context.trace);
160 components.modifiersChecker.withTrace(context.trace).checkModifiersForLocalDeclaration(property, propertyDescriptor);
161 components.identifierChecker.checkDeclaration(property, context.trace);
162 return typeInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(property, context));
163 }
164
165 @Override
166 public KotlinTypeInfo visitMultiDeclaration(@NotNull KtMultiDeclaration multiDeclaration, ExpressionTypingContext context) {
167 components.annotationResolver.resolveAnnotationsWithArguments(scope, multiDeclaration.getModifierList(), context.trace);
168
169 KtExpression initializer = multiDeclaration.getInitializer();
170 if (initializer == null) {
171 context.trace.report(INITIALIZER_REQUIRED_FOR_DESTRUCTURING_DECLARATION.on(multiDeclaration));
172 return TypeInfoFactoryKt.noTypeInfo(context);
173 }
174 ExpressionReceiver expressionReceiver = ExpressionTypingUtils.getExpressionReceiver(
175 facade, initializer, context.replaceExpectedType(NO_EXPECTED_TYPE).replaceContextDependency(INDEPENDENT));
176 KotlinTypeInfo typeInfo = facade.getTypeInfo(initializer, context);
177 if (expressionReceiver == null) {
178 return TypeInfoFactoryKt.noTypeInfo(context);
179 }
180 components.multiDeclarationResolver.defineLocalVariablesFromMultiDeclaration(scope, multiDeclaration, expressionReceiver, initializer, context);
181 components.modifiersChecker.withTrace(context.trace).checkModifiersForMultiDeclaration(multiDeclaration);
182 components.identifierChecker.checkDeclaration(multiDeclaration, context.trace);
183 return typeInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(multiDeclaration, context));
184 }
185
186 @Override
187 public KotlinTypeInfo visitNamedFunction(@NotNull KtNamedFunction function, ExpressionTypingContext context) {
188 return functions.visitNamedFunction(function, context, true, scope);
189 }
190
191 @Override
192 public KotlinTypeInfo visitClass(@NotNull KtClass klass, ExpressionTypingContext context) {
193 components.localClassifierAnalyzer.processClassOrObject(
194 scope, context.replaceScope(scope).replaceContextDependency(INDEPENDENT),
195 scope.getOwnerDescriptor(),
196 klass);
197 return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(klass, context), context);
198 }
199
200 @Override
201 public KotlinTypeInfo visitTypedef(@NotNull KtTypedef typedef, ExpressionTypingContext context) {
202 context.trace.report(UNSUPPORTED.on(typedef, "Typedefs are not supported"));
203 return super.visitTypedef(typedef, context);
204 }
205
206 @Override
207 public KotlinTypeInfo visitDeclaration(@NotNull KtDeclaration dcl, ExpressionTypingContext context) {
208 return TypeInfoFactoryKt.createTypeInfo(components.dataFlowAnalyzer.checkStatementType(dcl, context), context);
209 }
210
211 @Override
212 public KotlinTypeInfo visitBinaryExpression(@NotNull KtBinaryExpression expression, ExpressionTypingContext context) {
213 KtSimpleNameExpression operationSign = expression.getOperationReference();
214 IElementType operationType = operationSign.getReferencedNameElementType();
215 KotlinTypeInfo result;
216 if (operationType == KtTokens.EQ) {
217 result = visitAssignment(expression, context);
218 }
219 else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) {
220 result = visitAssignmentOperation(expression, context);
221 }
222 else {
223 return facade.getTypeInfo(expression, context);
224 }
225 return components.dataFlowAnalyzer.checkType(result, expression, context);
226 }
227
228 @NotNull
229 protected KotlinTypeInfo visitAssignmentOperation(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
230 //There is a temporary binding trace for an opportunity to resolve set method for array if needed (the initial trace should be used there)
231 TemporaryTraceAndCache temporary = TemporaryTraceAndCache.create(
232 contextWithExpectedType, "trace to resolve array set method for binary expression", expression);
233 ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE)
234 .replaceTraceAndCache(temporary).replaceContextDependency(INDEPENDENT);
235
236 KtSimpleNameExpression operationSign = expression.getOperationReference();
237 IElementType operationType = operationSign.getReferencedNameElementType();
238 KtExpression leftOperand = expression.getLeft();
239 KotlinTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(leftOperand, context, facade);
240 KotlinType leftType = leftInfo.getType();
241
242 KtExpression right = expression.getRight();
243 KtExpression left = leftOperand == null ? null : deparenthesize(leftOperand);
244 if (right == null || left == null) {
245 temporary.commit();
246 return leftInfo.clearType();
247 }
248
249 if (leftType == null) {
250 KotlinTypeInfo rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
251 context.trace.report(UNRESOLVED_REFERENCE.on(operationSign, operationSign));
252 temporary.commit();
253 return rightInfo.clearType();
254 }
255 ExpressionReceiver receiver = ExpressionReceiver.Companion.create(left, leftType, context.trace.getBindingContext());
256
257 // We check that defined only one of '+=' and '+' operations, and call it (in the case '+' we then also assign)
258 // Check for '+='
259 Name name = OperatorConventions.ASSIGNMENT_OPERATIONS.get(operationType);
260 TemporaryTraceAndCache temporaryForAssignmentOperation = TemporaryTraceAndCache.create(
261 context, "trace to check assignment operation like '+=' for", expression);
262 OverloadResolutionResults<FunctionDescriptor> assignmentOperationDescriptors =
263 components.callResolver.resolveBinaryCall(
264 context.replaceTraceAndCache(temporaryForAssignmentOperation).replaceScope(scope),
265 receiver, expression, name
266 );
267 KotlinType assignmentOperationType = OverloadResolutionResultsUtil.getResultingType(assignmentOperationDescriptors,
268 context.contextDependency);
269
270 OverloadResolutionResults<FunctionDescriptor> binaryOperationDescriptors;
271 KotlinType binaryOperationType;
272 TemporaryTraceAndCache temporaryForBinaryOperation = TemporaryTraceAndCache.create(
273 context, "trace to check binary operation like '+' for", expression);
274 TemporaryBindingTrace ignoreReportsTrace = TemporaryBindingTrace.create(context.trace, "Trace for checking assignability");
275 boolean lhsAssignable = basic.checkLValue(ignoreReportsTrace, context, left, right);
276 if (assignmentOperationType == null || lhsAssignable) {
277 // Check for '+'
278 Name counterpartName = OperatorConventions.BINARY_OPERATION_NAMES.get(OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS.get(operationType));
279 binaryOperationDescriptors = components.callResolver.resolveBinaryCall(
280 context.replaceTraceAndCache(temporaryForBinaryOperation).replaceScope(scope),
281 receiver, expression, counterpartName
282 );
283 binaryOperationType = OverloadResolutionResultsUtil.getResultingType(binaryOperationDescriptors, context.contextDependency);
284 }
285 else {
286 binaryOperationDescriptors = OverloadResolutionResultsImpl.nameNotFound();
287 binaryOperationType = null;
288 }
289
290 KotlinType type = assignmentOperationType != null ? assignmentOperationType : binaryOperationType;
291 KotlinTypeInfo rightInfo = leftInfo;
292 if (assignmentOperationDescriptors.isSuccess() && binaryOperationDescriptors.isSuccess()) {
293 // Both 'plus()' and 'plusAssign()' available => ambiguity
294 OverloadResolutionResults<FunctionDescriptor> ambiguityResolutionResults = OverloadResolutionResultsUtil.ambiguity(assignmentOperationDescriptors, binaryOperationDescriptors);
295 context.trace.report(ASSIGN_OPERATOR_AMBIGUITY.on(operationSign, ambiguityResolutionResults.getResultingCalls()));
296 Collection<DeclarationDescriptor> descriptors = Sets.newHashSet();
297 for (ResolvedCall<?> resolvedCall : ambiguityResolutionResults.getResultingCalls()) {
298 descriptors.add(resolvedCall.getResultingDescriptor());
299 }
300 rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
301 context.trace.record(AMBIGUOUS_REFERENCE_TARGET, operationSign, descriptors);
302 }
303 else if (assignmentOperationType != null && (assignmentOperationDescriptors.isSuccess() || !binaryOperationDescriptors.isSuccess())) {
304 // There's 'plusAssign()', so we do a.plusAssign(b)
305 temporaryForAssignmentOperation.commit();
306 if (!KotlinTypeChecker.DEFAULT.equalTypes(components.builtIns.getUnitType(), assignmentOperationType)) {
307 context.trace.report(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT.on(operationSign, assignmentOperationDescriptors.getResultingDescriptor(), operationSign));
308 }
309 }
310 else {
311 // There's only 'plus()', so we try 'a = a + b'
312 temporaryForBinaryOperation.commit();
313 context.trace.record(VARIABLE_REASSIGNMENT, expression);
314 if (left instanceof KtArrayAccessExpression) {
315 ExpressionTypingContext contextForResolve = context.replaceScope(scope).replaceBindingTrace(TemporaryBindingTrace.create(
316 context.trace, "trace to resolve array set method for assignment", expression));
317 basic.resolveArrayAccessSetMethod((KtArrayAccessExpression) left, right, contextForResolve, context.trace);
318 }
319 rightInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(leftInfo.getDataFlowInfo()));
320 components.dataFlowAnalyzer.checkType(binaryOperationType, expression, context.replaceExpectedType(leftType).replaceDataFlowInfo(rightInfo.getDataFlowInfo()));
321 basic.checkLValue(context.trace, context, leftOperand, right);
322 }
323 temporary.commit();
324 return rightInfo.replaceType(checkAssignmentType(type, expression, contextWithExpectedType));
325 }
326
327 @NotNull
328 protected KotlinTypeInfo visitAssignment(KtBinaryExpression expression, ExpressionTypingContext contextWithExpectedType) {
329 final ExpressionTypingContext context =
330 contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE).replaceScope(scope).replaceContextDependency(INDEPENDENT);
331 KtExpression leftOperand = expression.getLeft();
332 if (leftOperand instanceof KtAnnotatedExpression) {
333 // We will lose all annotations during deparenthesizing, so we have to resolve them right now
334 components.annotationResolver.resolveAnnotationsWithArguments(
335 scope, ((KtAnnotatedExpression) leftOperand).getAnnotationEntries(), context.trace
336 );
337 }
338 KtExpression left = deparenthesize(leftOperand);
339 KtExpression right = expression.getRight();
340 if (left instanceof KtArrayAccessExpression) {
341 KtArrayAccessExpression arrayAccessExpression = (KtArrayAccessExpression) left;
342 if (right == null) return TypeInfoFactoryKt.noTypeInfo(context);
343 KotlinTypeInfo typeInfo = basic.resolveArrayAccessSetMethod(arrayAccessExpression, right, context, context.trace);
344 basic.checkLValue(context.trace, context, arrayAccessExpression, right);
345 return typeInfo.replaceType(checkAssignmentType(typeInfo.getType(), expression, contextWithExpectedType));
346 }
347 KotlinTypeInfo leftInfo = ExpressionTypingUtils.getTypeInfoOrNullType(left, context, facade);
348 KotlinType leftType = leftInfo.getType();
349 DataFlowInfo dataFlowInfo = leftInfo.getDataFlowInfo();
350 KotlinTypeInfo resultInfo;
351 if (right != null) {
352 resultInfo = facade.getTypeInfo(right, context.replaceDataFlowInfo(dataFlowInfo).replaceExpectedType(leftType));
353 dataFlowInfo = resultInfo.getDataFlowInfo();
354 KotlinType rightType = resultInfo.getType();
355 if (left != null && leftType != null && rightType != null) {
356 DataFlowValue leftValue = DataFlowValueFactory.createDataFlowValue(left, leftType, context);
357 DataFlowValue rightValue = DataFlowValueFactory.createDataFlowValue(right, rightType, context);
358 // We cannot say here anything new about rightValue except it has the same value as leftValue
359 resultInfo = resultInfo.replaceDataFlowInfo(dataFlowInfo.assign(leftValue, rightValue));
360 }
361 }
362 else {
363 resultInfo = leftInfo;
364 }
365 if (leftType != null && leftOperand != null) { //if leftType == null, some other error has been generated
366 basic.checkLValue(context.trace, context, leftOperand, right);
367 }
368 return resultInfo.replaceType(components.dataFlowAnalyzer.checkStatementType(expression, contextWithExpectedType));
369 }
370
371
372 @Override
373 public KotlinTypeInfo visitExpression(@NotNull KtExpression expression, ExpressionTypingContext context) {
374 return facade.getTypeInfo(expression, context);
375 }
376
377 @Override
378 public KotlinTypeInfo visitKtElement(@NotNull KtElement element, ExpressionTypingContext context) {
379 context.trace.report(UNSUPPORTED.on(element, "in a block"));
380 return TypeInfoFactoryKt.noTypeInfo(context);
381 }
382
383 @Override
384 public KotlinTypeInfo visitWhileExpression(@NotNull KtWhileExpression expression, ExpressionTypingContext context) {
385 return controlStructures.visitWhileExpression(expression, context, true);
386 }
387
388 @Override
389 public KotlinTypeInfo visitDoWhileExpression(@NotNull KtDoWhileExpression expression, ExpressionTypingContext context) {
390 return controlStructures.visitDoWhileExpression(expression, context, true);
391 }
392
393 @Override
394 public KotlinTypeInfo visitForExpression(@NotNull KtForExpression expression, ExpressionTypingContext context) {
395 return controlStructures.visitForExpression(expression, context, true);
396 }
397
398 @Override
399 public KotlinTypeInfo visitAnnotatedExpression(
400 @NotNull KtAnnotatedExpression expression, ExpressionTypingContext data
401 ) {
402 return basic.visitAnnotatedExpression(expression, data, true);
403 }
404
405 @Override
406 public KotlinTypeInfo visitIfExpression(@NotNull KtIfExpression expression, ExpressionTypingContext context) {
407 return controlStructures.visitIfExpression(expression, context, true);
408 }
409
410 @Override
411 public KotlinTypeInfo visitWhenExpression(@NotNull KtWhenExpression expression, ExpressionTypingContext context) {
412 return patterns.visitWhenExpression(expression, context, true);
413 }
414
415 @Override
416 public KotlinTypeInfo visitBlockExpression(@NotNull KtBlockExpression expression, ExpressionTypingContext context) {
417 return components.expressionTypingServices.getBlockReturnedType(expression, context, true);
418 }
419
420 @Override
421 public KotlinTypeInfo visitLabeledExpression(@NotNull KtLabeledExpression expression, ExpressionTypingContext context) {
422 return basic.visitLabeledExpression(expression, context, true);
423 }
424 }