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