JetTypeInferrer.java 82.9 KB
Newer Older
1 2
package org.jetbrains.jet.lang.types;

D
Dmitry Jemerov 已提交
3
import com.google.common.collect.ImmutableMap;
4
import com.intellij.lang.ASTNode;
5
import com.intellij.psi.PsiElement;
6 7 8 9 10
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.JetNodeTypes;
import org.jetbrains.jet.lang.JetSemanticServices;
11
import org.jetbrains.jet.lang.cfg.JetFlowInformationProvider;
A
Andrey Breslav 已提交
12
import org.jetbrains.jet.lang.descriptors.*;
13 14 15
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.*;
import org.jetbrains.jet.lexer.JetTokens;
16
import org.jetbrains.jet.resolve.DescriptorUtil;
17 18 19 20 21 22 23 24

import java.util.*;

/**
 * @author abreslav
 */
public class JetTypeInferrer {

D
Dmitry Jemerov 已提交
25 26 27 28 29 30 31
    private static final Map<IElementType, String> unaryOperationNames = ImmutableMap.<IElementType, String>builder()
            .put(JetTokens.PLUSPLUS, "inc")
            .put(JetTokens.MINUSMINUS, "dec")
            .put(JetTokens.PLUS, "plus")
            .put(JetTokens.MINUS, "minus")
            .put(JetTokens.EXCL, "not")
            .build();
A
Andrey Breslav 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

    private static final Map<IElementType, String> binaryOperationNames = new HashMap<IElementType, String>();
    static {
        binaryOperationNames.put(JetTokens.MUL, "times");
        binaryOperationNames.put(JetTokens.PLUS, "plus");
        binaryOperationNames.put(JetTokens.MINUS, "minus");
        binaryOperationNames.put(JetTokens.DIV, "div");
        binaryOperationNames.put(JetTokens.PERC, "mod");
        binaryOperationNames.put(JetTokens.ARROW, "arrow");
        binaryOperationNames.put(JetTokens.RANGE, "rangeTo");
    }

    private static final Set<IElementType> comparisonOperations = new HashSet<IElementType>(Arrays.asList(JetTokens.LT, JetTokens.GT, JetTokens.LTEQ, JetTokens.GTEQ));
    private static final Set<IElementType> equalsOperations = new HashSet<IElementType>(Arrays.asList(JetTokens.EQEQ, JetTokens.EXCLEQ));
    private static final Set<IElementType> inOperations = new HashSet<IElementType>(Arrays.asList(JetTokens.IN_KEYWORD, JetTokens.NOT_IN));

A
Andrey Breslav 已提交
48
    public static final Map<IElementType, String> assignmentOperationNames = new HashMap<IElementType, String>();
A
Andrey Breslav 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    static {
        assignmentOperationNames.put(JetTokens.MULTEQ, "timesAssign");
        assignmentOperationNames.put(JetTokens.DIVEQ, "divAssign");
        assignmentOperationNames.put(JetTokens.PERCEQ, "modAssign");
        assignmentOperationNames.put(JetTokens.PLUSEQ, "plusAssign");
        assignmentOperationNames.put(JetTokens.MINUSEQ, "minusAssign");
    }

    private static final Map<IElementType, IElementType> assignmentOperationCounterparts = new HashMap<IElementType, IElementType>();
    static {
        assignmentOperationCounterparts.put(JetTokens.MULTEQ, JetTokens.MUL);
        assignmentOperationCounterparts.put(JetTokens.DIVEQ, JetTokens.DIV);
        assignmentOperationCounterparts.put(JetTokens.PERCEQ, JetTokens.PERC);
        assignmentOperationCounterparts.put(JetTokens.PLUSEQ, JetTokens.PLUS);
        assignmentOperationCounterparts.put(JetTokens.MINUSEQ, JetTokens.MINUS);
    }

66 67
    private final Map<JetExpression, JetType> typeCache = new HashMap<JetExpression, JetType>();

68 69
    private final BindingTrace trace;
    private final JetSemanticServices semanticServices;
A
Andrey Breslav 已提交
70 71
    private final TypeResolver typeResolver;
    private final ClassDescriptorResolver classDescriptorResolver;
72
    private final JetFlowInformationProvider flowInformationProvider;
73

74 75
    public JetTypeInferrer(@NotNull BindingTrace trace, @NotNull JetFlowInformationProvider flowInformationProvider, @NotNull JetSemanticServices semanticServices) {
        this.trace = new CachedBindingTrace(trace);
76
        this.semanticServices = semanticServices;
77
        this.typeResolver = new TypeResolver(semanticServices, trace, true);
78
        this.classDescriptorResolver = semanticServices.getClassDescriptorResolver(trace);
79
        this.flowInformationProvider = flowInformationProvider;
80 81
    }

82
    @NotNull
A
Andrey Breslav 已提交
83 84
    public JetType safeGetType(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
        JetType type = getType(scope, expression, preferBlock);
85 86 87
        if (type != null) {
            return type;
        }
A
rename  
Andrey Breslav 已提交
88
        return ErrorUtils.createErrorType("Type for " + expression.getText());
89
    }
90

91
    @Nullable
A
Andrey Breslav 已提交
92
    public JetType getType(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
93
        return new TypeInferrerVisitor(scope, preferBlock).getType(expression);
94 95
    }

96 97 98 99
    public JetType getTypeWithNamespaces(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
        return new TypeInferrerVisitorWithNamespaces(scope, preferBlock).getType(expression);
    }

100
    @Nullable
A
Andrey Breslav 已提交
101 102
    private List<JetType> getTypes(JetScope scope, List<JetExpression> indexExpressions) {
        List<JetType> argumentTypes = new ArrayList<JetType>();
103
        TypeInferrerVisitor typeInferrerVisitor = new TypeInferrerVisitor(scope, false);
104
        for (JetExpression indexExpression : indexExpressions) {
105
            JetType type = typeInferrerVisitor.getType(indexExpression);
106 107 108 109
            if (type == null) {
                return null;
            }
            argumentTypes.add(type);
110
            typeInferrerVisitor.resetResult(); // TODO : recreate?
111 112 113 114
        }
        return argumentTypes;
    }

115 116 117 118 119 120 121 122 123 124
    @Nullable
    private FunctionDescriptor lookupFunction(
            @NotNull JetScope scope,
            @NotNull JetReferenceExpression reference,
            @NotNull String name,
            @NotNull JetType receiverType,
            @NotNull List<JetType> argumentTypes,
            boolean reportUnresolved) {
        OverloadDomain overloadDomain = semanticServices.getOverloadResolver().getOverloadDomain(receiverType, scope, name);
        overloadDomain = wrapForTracing(overloadDomain, reference, null, reportUnresolved);
125 126
        OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(Collections.<JetType>emptyList(), argumentTypes);
        return resolutionResult.isSuccess() ? resolutionResult.getFunctionDescriptor() : null;
127 128 129 130 131 132 133
    }

    private OverloadDomain getOverloadDomain(
            @NotNull final JetScope scope,
            @NotNull JetExpression calleeExpression,
            @Nullable PsiElement argumentList
    ) {
134
        final OverloadDomain[] result = new OverloadDomain[1];
135
        final JetSimpleNameExpression[] reference = new JetSimpleNameExpression[1];
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        calleeExpression.accept(new JetVisitor() {

            @Override
            public void visitHashQualifiedExpression(JetHashQualifiedExpression expression) {
                // a#b -- create a domain for all overloads of b in a
                throw new UnsupportedOperationException(); // TODO
            }

            @Override
            public void visitPredicateExpression(JetPredicateExpression expression) {
                // overload lookup for checking, but the type is receiver's type + nullable
                throw new UnsupportedOperationException(); // TODO
            }

            @Override
            public void visitQualifiedExpression(JetQualifiedExpression expression) {
                // . or ?.
A
Andrey Breslav 已提交
153 154 155
                JetType receiverType = getType(scope, expression.getReceiverExpression(), false);
                checkNullSafety(receiverType, expression);

156
                JetExpression selectorExpression = expression.getSelectorExpression();
157 158
                if (selectorExpression instanceof JetSimpleNameExpression) {
                    JetSimpleNameExpression referenceExpression = (JetSimpleNameExpression) selectorExpression;
159
                    String referencedName = referenceExpression.getReferencedName();
160

161 162
                    if (receiverType != null && referencedName != null) {
                        result[0] = semanticServices.getOverloadResolver().getOverloadDomain(receiverType, scope, referencedName);
163 164
                        reference[0] = referenceExpression;
                    }
165 166 167 168 169 170
                } else {
                    throw new UnsupportedOperationException(); // TODO
                }
            }

            @Override
171
            public void visitSimpleNameExpression(JetSimpleNameExpression expression) {
172
                // a -- create a hierarchical lookup domain for this.a
173 174 175 176 177
                String referencedName = expression.getReferencedName();
                if (referencedName != null) {
                    result[0] = semanticServices.getOverloadResolver().getOverloadDomain(null, scope, referencedName);
                    reference[0] = expression;
                }
178 179 180 181 182
            }

            @Override
            public void visitExpression(JetExpression expression) {
                // <e> create a dummy domain for the type of e
183
                throw new UnsupportedOperationException(expression.getText()); // TODO
184 185 186 187
            }

            @Override
            public void visitJetElement(JetElement elem) {
188
                trace.getErrorHandler().genericError(elem.getNode(), "Unsupported in call element"); // TODO : Message
189 190
            }
        });
191
        return wrapForTracing(result[0], reference[0], argumentList, true);
192 193
    }

A
Andrey Breslav 已提交
194 195
    private void checkNullSafety(JetType receiverType, JetQualifiedExpression expression) {
        if (receiverType != null) {
196 197 198
            boolean namespaceType = receiverType instanceof NamespaceType;
            boolean nullable = !namespaceType && receiverType.isNullable();
            if (nullable && expression.getOperationSign() == JetTokens.DOT) {
199
                trace.getErrorHandler().genericError(expression.getOperationTokenNode(), "Only safe calls (?.) are allowed on a nullable receiver of type " + receiverType);
A
Andrey Breslav 已提交
200
            }
201 202
            else if (!nullable && expression.getOperationSign() == JetTokens.SAFE_ACCESS) {
                if (namespaceType) {
203
                    trace.getErrorHandler().genericError(expression.getOperationTokenNode(), "Safe calls are not allowed on namespaces");
204 205
                }
                else {
206
                    trace.getErrorHandler().genericWarning(expression.getOperationTokenNode(), "Unnecessary safe call on a non-null receiver of type  " + receiverType);
207
                }
A
Andrey Breslav 已提交
208 209 210 211
            }
        }
    }

212 213
    private OverloadDomain wrapForTracing(
            @Nullable final OverloadDomain overloadDomain,
214
            final JetReferenceExpression referenceExpression,
215
            @Nullable final PsiElement argumentList,
216
            final boolean reportErrors) {
217
        if (overloadDomain == null) return OverloadDomain.EMPTY;
218
        assert referenceExpression != null;
219
        return new OverloadDomain() {
220
            @NotNull
221
            @Override
222 223 224 225
            public OverloadResolutionResult getFunctionDescriptorForNamedArguments(@NotNull List<JetType> typeArguments, @NotNull Map<String, JetType> valueArgumentTypes, @Nullable JetType functionLiteralArgumentType) {
                OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForNamedArguments(typeArguments, valueArgumentTypes, functionLiteralArgumentType);
                report(resolutionResult);
                return resolutionResult;
226 227
            }

228
            @NotNull
229
            @Override
230 231 232 233 234 235 236 237 238 239 240 241 242
            public OverloadResolutionResult getFunctionDescriptorForPositionedArguments(@NotNull List<JetType> typeArguments, @NotNull List<JetType> positionedValueArgumentTypes) {
                OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(typeArguments, positionedValueArgumentTypes);
                report(resolutionResult);
                return resolutionResult;
            }

            private void report(OverloadResolutionResult resolutionResult) {
                if (resolutionResult.isSuccess() || resolutionResult.singleFunction()) {
                    trace.recordReferenceResolution(referenceExpression, resolutionResult.getFunctionDescriptor());
                }
                if (reportErrors) {
                    switch (resolutionResult.getResultCode()) {
                        case NAME_NOT_FOUND:
243
                            trace.getErrorHandler().unresolvedReference(referenceExpression);
244 245 246 247
                            break;
                        case SINGLE_FUNCTION_ARGUMENT_MISMATCH:
                            if (argumentList != null) {
                                // TODO : More helpful message. NOTE: there's a separate handling for this for constructors
248
                                trace.getErrorHandler().genericError(argumentList.getNode(), "Arguments do not match " + DescriptorUtil.renderPresentableText(resolutionResult.getFunctionDescriptor()));
249 250
                            }
                            else {
251
                                trace.getErrorHandler().unresolvedReference(referenceExpression);
252 253 254 255 256
                            }
                            break;
                        case AMBIGUITY:
                            if (argumentList != null) {
                                // TODO : More helpful message. NOTE: there's a separate handling for this for constructors
257
                                trace.getErrorHandler().genericError(argumentList.getNode(), "Overload ambiguity [TODO : more helpful message]");
258 259
                            }
                            else {
260
                                trace.getErrorHandler().unresolvedReference(referenceExpression);
261 262 263 264
                            }
                            break;
                        default:
                            // Not a success
265
                    }
A
Andrey Breslav 已提交
266
                }
267 268 269 270 271
            }

            @Override
            public boolean isEmpty() {
                return overloadDomain.isEmpty();
272 273 274 275
            }
        };
    }

276
    @NotNull
277
    public JetType getFunctionReturnType(@NotNull JetScope outerScope, JetDeclarationWithBody function, FunctionDescriptor functionDescriptor) {
278
        Map<JetElement, JetType> typeMap = collectReturnedExpressions(outerScope, function, functionDescriptor);
279 280 281 282 283 284 285 286 287
        Collection<JetType> types = typeMap.values();
        return types.isEmpty() ? JetStandardClasses.getNothingType() : semanticServices.getTypeChecker().commonSupertype(types);
    }

    private JetType getCachedType(@NotNull JetExpression expression) {
//        assert typeCache.containsKey(expression) : "No type cached for " + expression.getText();
        return typeCache.get(expression);
    }

288
    public void checkFunctionReturnType(@NotNull JetScope outerScope, @NotNull JetDeclarationWithBody function, @NotNull FunctionDescriptor functionDescriptor) {
289
        Map<JetElement, JetType> typeMap = collectReturnedExpressions(outerScope, function, functionDescriptor);
290 291 292 293 294 295 296
        if (typeMap.isEmpty()) {
            return; // The function returns Nothing
        }
        JetType expectedReturnType = functionDescriptor.getUnsubstitutedReturnType();
        for (Map.Entry<JetElement, JetType> entry : typeMap.entrySet()) {
            JetType actualType = entry.getValue();
            JetElement element = entry.getKey();
297 298 299
            JetTypeChecker typeChecker = semanticServices.getTypeChecker();
            if (!typeChecker.isSubtypeOf(actualType, expectedReturnType)) {
                if (typeChecker.isConvertibleBySpecialConversion(actualType, expectedReturnType)) {
300 301
                    if (expectedReturnType.getConstructor().equals(JetStandardClasses.getUnitType().getConstructor())
                        && element.getParent() instanceof JetReturnExpression) {
302
                        trace.getErrorHandler().genericError(element.getNode(), "This function must return a value of type Unit");
303
                    }
304 305
                }
                else {
A
Andrey Breslav 已提交
306 307 308
                    if (element == function) {
                        JetExpression bodyExpression = function.getBodyExpression();
                        assert bodyExpression != null;
309
                        trace.getErrorHandler().genericError(bodyExpression.getNode(), "This function must return a value of type " + expectedReturnType);
A
Andrey Breslav 已提交
310 311
                    }
                    else if (element instanceof JetExpression) {
312
                        JetExpression expression = (JetExpression) element;
313
                        trace.getErrorHandler().typeMismatch(expression, expectedReturnType, actualType);
314 315
                    }
                    else {
316
                        trace.getErrorHandler().genericError(element.getNode(), "This function must return a value of type " + expectedReturnType);
317
                    }
318 319 320 321 322
                }
            }
        }
    }

323
    private Map<JetElement, JetType> collectReturnedExpressions(JetScope outerScope, JetDeclarationWithBody function, FunctionDescriptor functionDescriptor) {
324 325
        JetExpression bodyExpression = function.getBodyExpression();
        assert bodyExpression != null;
326
        JetScope functionInnerScope = FunctionDescriptorUtil.getFunctionInnerScope(outerScope, functionDescriptor, trace);
327 328 329
        getType(functionInnerScope, bodyExpression, function.hasBlockBody());
        Collection<JetExpression> returnedExpressions = new ArrayList<JetExpression>();
        Collection<JetElement> elementsReturningUnit = new ArrayList<JetElement>();
330
        flowInformationProvider.collectReturnedInformation(function.asElement(), returnedExpressions, elementsReturningUnit);
331 332 333
        Map<JetElement,JetType> typeMap = new HashMap<JetElement, JetType>();
        for (JetExpression returnedExpression : returnedExpressions) {
            JetType cachedType = getCachedType(returnedExpression);
334
            trace.removeStatementRecord(returnedExpression);
335 336 337 338 339 340 341 342 343 344
            if (cachedType != null) {
                typeMap.put(returnedExpression, cachedType);
            }
        }
        for (JetElement jetElement : elementsReturningUnit) {
            typeMap.put(jetElement, JetStandardClasses.getUnitType());
        }
        return typeMap;
    }

345
    @Nullable
346
    private JetType getBlockReturnedType(@NotNull JetScope outerScope, @NotNull List<JetElement> block) {
347 348
        if (block.isEmpty()) {
            return JetStandardClasses.getUnitType();
A
Andrey Breslav 已提交
349
        }
A
Andrey Breslav 已提交
350 351

        DeclarationDescriptor containingDescriptor = outerScope.getContainingDeclaration();
352
        WritableScope scope = new WritableScopeImpl(outerScope, containingDescriptor, trace.getErrorHandler(), null);
353
        return getBlockReturnedTypeWithWritableScope(scope, block);
A
Andrey Breslav 已提交
354 355
    }

356
    private JetType getBlockReturnedTypeWithWritableScope(@NotNull WritableScope scope, @NotNull List<? extends JetElement> block) {
357 358 359
        if (block.isEmpty()) {
            return JetStandardClasses.getUnitType();
        }
A
Andrey Breslav 已提交
360

361
        TypeInferrerVisitorWithWritableScope blockLevelVisitor = new TypeInferrerVisitorWithWritableScope(scope, true);
A
Andrey Breslav 已提交
362

A
Andrey Breslav 已提交
363 364
        JetType result = null;
        for (JetElement statement : block) {
365 366 367
            trace.recordStatement(statement);
            JetExpression statementExpression = (JetExpression) statement;
            result = blockLevelVisitor.getType(statementExpression);
A
Andrey Breslav 已提交
368
            blockLevelVisitor.resetResult(); // TODO : maybe it's better to recreate the visitors with the same scope?
369
        }
A
Andrey Breslav 已提交
370
        return result;
371 372
    }

A
Andrey Breslav 已提交
373
    private void collectAllReturnTypes(JetWhenExpression whenExpression, JetScope scope, List<JetType> result) {
374 375 376 377 378 379 380 381 382 383 384 385 386
        for (JetWhenEntry entry : whenExpression.getEntries()) {
            JetWhenExpression subWhen = entry.getSubWhen();
            if (subWhen != null) {
                collectAllReturnTypes(subWhen, scope, result);
            } else {
                JetExpression resultExpression = entry.getExpression();
                if (resultExpression != null) {
                    result.add(getType(scope, resultExpression, true));
                }
            }
        }
    }

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    @Nullable
    private JetType resolveOverloads(JetScope scope, JetCallExpression expression, OverloadDomain overloadDomain) {
        List<JetTypeProjection> typeArguments = expression.getTypeArguments();
        List<JetArgument> valueArguments = expression.getValueArguments();
        List<JetExpression> functionLiteralArguments = expression.getFunctionLiteralArguments();
        return resolveOverloads(scope, overloadDomain, typeArguments, valueArguments, functionLiteralArguments);
    }

    @Nullable
    private JetType resolveOverloads(
            @NotNull JetScope scope,
            @NotNull OverloadDomain overloadDomain,
            @NotNull List<JetTypeProjection> typeArguments,
            @NotNull List<JetArgument> valueArguments,
            @NotNull List<JetExpression> functionLiteralArguments) {
        // 1) ends with a name -> (scope, name) to look up
        // 2) ends with something else -> just check types

        for (JetTypeProjection typeArgument : typeArguments) {
            if (typeArgument.getProjectionKind() != JetProjectionKind.NONE) {
407
                trace.getErrorHandler().genericError(typeArgument.getNode(), "Projections are not allowed on type parameters for methods"); // TODO : better positioning
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
            }
        }

        boolean someNamed = false;
        for (JetArgument argument : valueArguments) {
            if (argument.isNamed()) {
                someNamed = true;
                break;
            }
        }

//                JetExpression functionLiteralArgument = functionLiteralArguments.isEmpty() ? null : functionLiteralArguments.get(0);
        // TODO : must be a check
        assert functionLiteralArguments.size() <= 1;

        if (someNamed) {
            // TODO : check that all are named
            throw new UnsupportedOperationException(); // TODO

//                    result = overloadDomain.getFunctionDescriptorForNamedArguments(typeArguments, valueArguments, functionLiteralArgument);
        } else {
            List<JetType> types = new ArrayList<JetType>();
            for (JetTypeProjection projection : typeArguments) {
                // TODO : check that there's no projection
                JetTypeReference typeReference = projection.getTypeReference();
                if (typeReference != null) {
                    types.add(typeResolver.resolveType(scope, typeReference));
                }
            }

            List<JetExpression> positionedValueArguments = new ArrayList<JetExpression>();
            for (JetArgument argument : valueArguments) {
                JetExpression argumentExpression = argument.getArgumentExpression();
                if (argumentExpression != null) {
                    positionedValueArguments.add(argumentExpression);
                }
            }

            positionedValueArguments.addAll(functionLiteralArguments);

            List<JetType> valueArgumentTypes = new ArrayList<JetType>();
            for (JetExpression valueArgument : positionedValueArguments) {
                valueArgumentTypes.add(safeGetType(scope, valueArgument, false));
            }

            OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(types, valueArgumentTypes);
            if (resolutionResult.isSuccess()) {
                return resolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
            }
        }
        return null;
    }

    @Nullable
462
    public JetType checkConstructorCall(JetScope scope, @NotNull JetTypeReference typeReference, @NotNull JetCall call) {
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        JetTypeElement typeElement = typeReference.getTypeElement();
        if (typeElement instanceof JetUserType) {
            JetUserType userType = (JetUserType) typeElement;
            // TODO : to infer constructor parameters, one will need to
            //  1) resolve a _class_ from the typeReference
            //  2) rely on the overload domain of constructors of this class to infer type arguments
            // For now we assume that the type arguments are provided, and thus the typeReference can be
            // resolved into a valid type
            JetType receiverType = typeResolver.resolveType(scope, typeReference);
            DeclarationDescriptor declarationDescriptor = receiverType.getConstructor().getDeclarationDescriptor();
            if (declarationDescriptor instanceof ClassDescriptor) {
                ClassDescriptor classDescriptor = (ClassDescriptor) declarationDescriptor;

                for (JetTypeProjection typeProjection : userType.getTypeArguments()) {
                    switch (typeProjection.getProjectionKind()) {
                        case IN:
                        case OUT:
                        case STAR:
                            // TODO : Bug in the editor
482
                            trace.getErrorHandler().genericError(typeProjection.getProjectionNode(), "Projections are not allowed in constructor type arguments");
483 484 485 486 487 488 489 490
                            break;
                        case NONE:
                            break;
                    }
                }

                JetSimpleNameExpression referenceExpression = userType.getReferenceExpression();
                if (referenceExpression != null) {
491
                    return checkClassConstructorCall(scope, referenceExpression, classDescriptor, receiverType, call);
492 493 494
                }
            }
            else {
495
                trace.getErrorHandler().genericError(((JetElement) call).getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : review the message
496 497 498 499
            }
        }
        else {
            if (typeElement != null) {
500
                trace.getErrorHandler().genericError(typeElement.getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : Better message
501 502 503 504 505
            }
        }
        return null;
    }

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    @Nullable
    public JetType checkClassConstructorCall(
            @NotNull JetScope scope,
            @NotNull JetReferenceExpression referenceExpression,
            @NotNull ClassDescriptor classDescriptor,
            @NotNull JetType receiverType,
            @NotNull JetCall call) {
        // When one writes 'new Array<in T>(...)' this does not make much sense, and an instance
        // of 'Array<T>' must be created anyway.
        // Thus, we should either prohibit projections in type arguments in such contexts,
        // or treat them as an automatic upcast to the desired type, i.e. for the user not
        // to be forced to write
        //   val a : Array<in T> = new Array<T>(...)
        // NOTE: Array may be a bad example here, some classes may have substantial functionality
        //       not involving their type parameters
        //
        // The code below upcasts the type automatically

        List<TypeProjection> typeArguments = receiverType.getArguments();

        List<TypeProjection> projectionsStripped = new ArrayList<TypeProjection>();
        for (TypeProjection typeArgument : typeArguments) {
            if (typeArgument.getProjectionKind() != Variance.INVARIANT) {
                projectionsStripped.add(new TypeProjection(typeArgument.getType()));
            }
            else
                projectionsStripped.add(typeArgument);
        }

        FunctionGroup constructors = classDescriptor.getConstructors(projectionsStripped);
        OverloadDomain constructorsOverloadDomain = semanticServices.getOverloadResolver().getOverloadDomain(constructors);
        JetType constructorReturnedType = resolveOverloads(
                scope,
                wrapForTracing(constructorsOverloadDomain, referenceExpression, call.getValueArgumentList(), false),
                Collections.<JetTypeProjection>emptyList(),
                call.getValueArguments(),
                call.getFunctionLiteralArguments());
        if (constructorReturnedType == null && !ErrorUtils.isErrorType(receiverType)) {
            DeclarationDescriptor declarationDescriptor = receiverType.getConstructor().getDeclarationDescriptor();
            assert declarationDescriptor != null;
            trace.recordReferenceResolution(referenceExpression, declarationDescriptor);
            // TODO : more helpful message
            JetArgumentList argumentList = call.getValueArgumentList();
            if (argumentList != null) {
550
                trace.getErrorHandler().genericError(argumentList.getNode(), "Cannot find an overload for these arguments");
551 552 553 554 555 556 557 558 559 560
            }
            constructorReturnedType = receiverType;
        }
        // If no upcast needed:
        return constructorReturnedType;

        // Automatic upcast:
//                            result = receiverType;
    }

561 562 563

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

A
Andrey Breslav 已提交
564
    private class TypeInferrerVisitor extends JetVisitor {
565
        protected final JetScope scope;
A
Andrey Breslav 已提交
566
        private final boolean preferBlock;
A
Andrey Breslav 已提交
567

568
        protected JetType result;
A
Andrey Breslav 已提交
569

570
        private TypeInferrerVisitor(@NotNull JetScope scope, boolean preferBlock) {
A
Andrey Breslav 已提交
571 572 573 574
            this.scope = scope;
            this.preferBlock = preferBlock;
        }

575 576 577 578 579 580 581
        @Nullable
        public JetType getType(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
            TypeInferrerVisitor visitor;
            if (this.scope == scope && this.preferBlock == preferBlock && result == null) {
                visitor = this;
            }
            else {
582
                visitor = createNew(scope, preferBlock);
583 584 585 586 587 588
            }
            JetType type = visitor.getType(expression);
            visitor.result = null;
            return type;
        }

589 590 591 592 593
        @NotNull
        public TypeInferrerVisitor createNew(JetScope scope, boolean preferBlock) {
            return new TypeInferrerVisitor(scope, preferBlock);
        }

594 595 596 597 598 599
        @Nullable
        public JetType getType(@NotNull JetExpression expression) {
            assert result == null;
            expression.accept(this);
            if (result != null) {
                trace.recordExpressionType(expression, result);
600
                if (JetStandardClasses.isNothing(result) && !result.isNullable()) {
601 602
                    markDominatedExpressionsAsUnreachable(expression);
                }
603
            }
604

A
Andrey Breslav 已提交
605 606 607
            return result;
        }

608 609 610 611
        public void resetResult() {
            result = null;
        }

612 613 614 615 616 617 618
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void markDominatedExpressionsAsUnreachable(JetExpression expression) {
            List<JetElement> dominated = new ArrayList<JetElement>();
            flowInformationProvider.collectDominatedExpressions(expression, dominated);
            Set<JetElement> rootExpressions = JetPsiUtil.findRootExpressions(dominated);
            for (JetElement rootExpression : rootExpressions) {
619
                trace.getErrorHandler().genericError(rootExpression.getNode(),
620 621 622 623
                        "This code is unreachable, because '" + expression.getText() + "' never terminates normally");
            }
        }

A
Andrey Breslav 已提交
624 625
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

A
Andrey Breslav 已提交
626
        @Override
627
        public void visitSimpleNameExpression(JetSimpleNameExpression expression) {
A
Andrey Breslav 已提交
628 629
            // TODO : other members
            // TODO : type substitutions???
630 631 632 633
            String referencedName = expression.getReferencedName();
            if (expression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER
                    && referencedName != null) {
                PropertyDescriptor property = scope.getPropertyByFieldReference(referencedName);
A
Andrey Breslav 已提交
634
                if (property == null) {
635
                    trace.getErrorHandler().unresolvedReference(expression);
A
Andrey Breslav 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648 649
                }
                else {
                    trace.recordReferenceResolution(expression, property);
                    result = property.getOutType();
                }
            }
            else {
                assert  expression.getReferencedNameElementType() == JetTokens.IDENTIFIER;
                if (referencedName != null) {
                    VariableDescriptor variable = scope.getVariable(referencedName);
                    if (variable != null) {
                        trace.recordReferenceResolution(expression, variable);
                        result = variable.getOutType();
                        if (result == null) {
650
                            trace.getErrorHandler().genericError(expression.getNode(), "This variable is not readable in this context");
A
Andrey Breslav 已提交
651
                        }
652
                        return;
653 654
                    } else if (furtherNameLookup(expression, referencedName)) {
                        return;
655
                    }
656
                    trace.getErrorHandler().unresolvedReference(expression);
A
Andrey Breslav 已提交
657 658 659 660
                }
            }
        }

661 662 663
        protected boolean furtherNameLookup(@NotNull JetSimpleNameExpression expression, @NotNull String referencedName) {
            NamespaceType namespaceType = lookupNamespaceType(expression, referencedName);
            if (namespaceType != null) {
664
                trace.getErrorHandler().genericError(expression.getNode(), "Expression expected, but a namespace name found");
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
                return true;
            }
            return false;
        }

        @Nullable
        protected NamespaceType lookupNamespaceType(@NotNull JetSimpleNameExpression expression, @NotNull String referencedName) {
            NamespaceDescriptor namespace = scope.getNamespace(referencedName);
            if (namespace == null) {
                return null;
            }
            trace.recordReferenceResolution(expression, namespace);
            return namespace.getNamespaceType();
        }

A
Andrey Breslav 已提交
680 681 682
        @Override
        public void visitFunctionLiteralExpression(JetFunctionLiteralExpression expression) {
            if (preferBlock && !expression.hasParameterSpecification()) {
683
                trace.recordBlock(expression);
684
                result = getBlockReturnedType(scope, expression.getBody());
A
Andrey Breslav 已提交
685 686 687
                return;
            }

688
            FunctionDescriptorImpl functionDescriptor = new FunctionDescriptorImpl(scope.getContainingDeclaration(), Collections.<Annotation>emptyList(), "<anonymous>");
A
Andrey Breslav 已提交
689 690 691 692 693 694 695 696 697 698 699 700

            JetTypeReference returnTypeRef = expression.getReturnTypeRef();

            JetTypeReference receiverTypeRef = expression.getReceiverTypeRef();
            final JetType receiverType;
            if (receiverTypeRef != null) {
                receiverType = typeResolver.resolveType(scope, receiverTypeRef);
            } else {
                receiverType = scope.getThisType();
            }

            List<JetElement> body = expression.getBody();
701
            final Map<String, VariableDescriptor> parameterDescriptors = new HashMap<String, VariableDescriptor>();
A
Andrey Breslav 已提交
702 703 704 705 706 707
            List<JetType> parameterTypes = new ArrayList<JetType>();
            for (JetParameter parameter : expression.getParameters()) {
                JetTypeReference typeReference = parameter.getTypeReference();
                if (typeReference == null) {
                    throw new UnsupportedOperationException("Type inference for parameters is not implemented yet");
                }
708 709 710
                VariableDescriptor variableDescriptor = classDescriptorResolver.resolveLocalVariableDescriptor(functionDescriptor, scope, parameter);
                parameterDescriptors.put(parameter.getName(), variableDescriptor);
                parameterTypes.add(variableDescriptor.getOutType());
A
Andrey Breslav 已提交
711 712 713 714 715
            }
            JetType returnType;
            if (returnTypeRef != null) {
                returnType = typeResolver.resolveType(scope, returnTypeRef);
            } else {
716
                WritableScope writableScope = new WritableScopeImpl(scope, functionDescriptor, trace.getErrorHandler(), null);
717 718
                for (VariableDescriptor variableDescriptor : parameterDescriptors.values()) {
                    writableScope.addVariableDescriptor(variableDescriptor);
A
Andrey Breslav 已提交
719 720
                }
                writableScope.setThisType(receiverType);
721
                returnType = getBlockReturnedType(writableScope, body);
A
Andrey Breslav 已提交
722
            }
723 724
            JetType effectiveReceiverType = receiverTypeRef == null ? null : receiverType;
            JetType safeReturnType = returnType == null ? ErrorUtils.createErrorType("<return type>") : returnType;
725
            result = JetStandardClasses.getFunctionType(Collections.<Annotation>emptyList(), effectiveReceiverType, parameterTypes, safeReturnType);
A
Andrey Breslav 已提交
726 727 728 729
        }

        @Override
        public void visitParenthesizedExpression(JetParenthesizedExpression expression) {
730 731 732 733
            JetExpression inner = expression.getExpression();
            if (inner != null) {
                result = getType(scope, inner, false);
            }
A
Andrey Breslav 已提交
734 735 736 737 738 739 740
        }

        @Override
        public void visitConstantExpression(JetConstantExpression expression) {
            IElementType elementType = expression.getNode().getElementType();
            JetStandardLibrary standardLibrary = semanticServices.getStandardLibrary();
            if (elementType == JetNodeTypes.INTEGER_CONSTANT) {
741 742
                Object value = expression.getValue();
                if (value == null) {
743
                    trace.getErrorHandler().genericError(expression.getNode(), "Number is of range for Long");
744 745
                }
                else if (value instanceof Long) {
A
Andrey Breslav 已提交
746 747 748 749 750 751
                    result = standardLibrary.getLongType();
                }
                else {
                    result = standardLibrary.getIntType();
                }
                // TODO : other ranges
A
Cleanup  
Andrey Breslav 已提交
752 753
            }
            else if (elementType == JetNodeTypes.LONG_CONSTANT) {
A
Andrey Breslav 已提交
754
                result = standardLibrary.getLongType();
A
Cleanup  
Andrey Breslav 已提交
755 756
            }
            else if (elementType == JetNodeTypes.FLOAT_CONSTANT) {
A
Andrey Breslav 已提交
757 758 759 760 761
                String text = expression.getText();
                assert text.length() > 0;
                char lastChar = text.charAt(text.length() - 1);
                if (lastChar == 'f' || lastChar == 'F') {
                    result = standardLibrary.getFloatType();
A
Cleanup  
Andrey Breslav 已提交
762 763
                }
                else {
A
Andrey Breslav 已提交
764 765
                    result = standardLibrary.getDoubleType();
                }
A
Cleanup  
Andrey Breslav 已提交
766 767
            }
            else if (elementType == JetNodeTypes.BOOLEAN_CONSTANT) {
A
Andrey Breslav 已提交
768
                result = standardLibrary.getBooleanType();
A
Cleanup  
Andrey Breslav 已提交
769 770
            }
            else if (elementType == JetNodeTypes.CHARACTER_CONSTANT) {
A
Andrey Breslav 已提交
771
                result = standardLibrary.getCharType();
A
Cleanup  
Andrey Breslav 已提交
772 773
            }
            else if (elementType == JetNodeTypes.STRING_CONSTANT) {
A
Andrey Breslav 已提交
774
                result = standardLibrary.getStringType();
A
Cleanup  
Andrey Breslav 已提交
775 776
            }
            else if (elementType == JetNodeTypes.NULL) {
A
Andrey Breslav 已提交
777
                result = JetStandardClasses.getNullableNothingType();
A
Cleanup  
Andrey Breslav 已提交
778 779
            }
            else {
A
Andrey Breslav 已提交
780 781 782 783 784 785
                throw new IllegalArgumentException("Unsupported constant: " + expression);
            }
        }

        @Override
        public void visitThrowExpression(JetThrowExpression expression) {
A
Andrey Breslav 已提交
786 787 788 789 790
            JetExpression thrownExpression = expression.getThrownExpression();
            if (thrownExpression != null) {
                JetType type = getType(scope, thrownExpression, false);
                // TODO : check that it inherits Throwable
            }
A
Andrey Breslav 已提交
791 792 793 794 795 796
            result = JetStandardClasses.getNothingType();
        }

        @Override
        public void visitReturnExpression(JetReturnExpression expression) {
            JetExpression returnedExpression = expression.getReturnedExpression();
A
Andrey Breslav 已提交
797

A
Andrey Breslav 已提交
798
            if (returnedExpression != null) {
A
Cleanup  
Andrey Breslav 已提交
799
                getType(scope, returnedExpression, false);
A
Andrey Breslav 已提交
800 801
            }

A
Andrey Breslav 已提交
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
            result = JetStandardClasses.getNothingType();
        }

        @Override
        public void visitBreakExpression(JetBreakExpression expression) {
            result = JetStandardClasses.getNothingType();
        }

        @Override
        public void visitContinueExpression(JetContinueExpression expression) {
            result = JetStandardClasses.getNothingType();
        }

        @Override
        public void visitTypeofExpression(JetTypeofExpression expression) {
A
Andrey Breslav 已提交
817 818
            JetType type = safeGetType(scope, expression.getBaseExpression(), false);
            result = semanticServices.getStandardLibrary().getTypeInfoType(type);
A
Andrey Breslav 已提交
819 820 821 822
        }

        @Override
        public void visitBinaryWithTypeRHSExpression(JetBinaryExpressionWithTypeRHS expression) {
A
Andrey Breslav 已提交
823 824 825 826 827 828 829
            IElementType operationType = expression.getOperationSign().getReferencedNameElementType();
            JetType actualType = getType(scope, expression.getLeft(), false);
            JetTypeReference right = expression.getRight();
            if (right != null) {
                JetType targetType = typeResolver.resolveType(scope, right);
                if (operationType == JetTokens.COLON) {
                    if (actualType != null && !semanticServices.getTypeChecker().isSubtypeOf(actualType, targetType)) {
830
                        trace.getErrorHandler().typeMismatch(expression.getLeft(), targetType, actualType);
A
Andrey Breslav 已提交
831
                    }
A
Andrey Breslav 已提交
832
                    result = targetType;
A
Andrey Breslav 已提交
833
                }
A
Andrey Breslav 已提交
834
                else if (operationType == JetTokens.AS_KEYWORD) {
835
                    checkForCastImpossibility(expression, actualType, targetType);
A
Andrey Breslav 已提交
836 837 838
                    result = targetType;
                }
                else if (operationType == JetTokens.AS_SAFE) {
839
                    checkForCastImpossibility(expression, actualType, targetType);
A
Andrey Breslav 已提交
840
                    result = TypeUtils.makeNullable(targetType);
A
Andrey Breslav 已提交
841 842
                }
                else {
843
                    trace.getErrorHandler().genericError(expression.getOperationSign().getNode(), "Unsupported binary operation");
A
Andrey Breslav 已提交
844
                }
A
Andrey Breslav 已提交
845 846 847
            }
        }

848 849 850 851 852 853
        private void checkForCastImpossibility(JetBinaryExpressionWithTypeRHS expression, JetType actualType, JetType targetType) {
            if (actualType == null) return;

            JetTypeChecker typeChecker = semanticServices.getTypeChecker();
            if (!typeChecker.isSubtypeOf(targetType, actualType)) {
                if (typeChecker.isSubtypeOf(actualType, targetType)) {
854
                    trace.getErrorHandler().genericWarning(expression.getOperationSign().getNode(), "No cast needed, use ':' instead");
855 856
                }
                else {
857
                    trace.getErrorHandler().genericError(expression.getOperationSign().getNode(), "This cast can never succeed");
858 859 860 861
                }
            }
            else {
                if (typeChecker.isSubtypeOf(actualType, targetType)) {
862
                    trace.getErrorHandler().genericWarning(expression.getOperationSign().getNode(), "No cast needed");
863 864 865 866
                }
            }
        }

A
Andrey Breslav 已提交
867
        @Override
868 869 870 871 872 873 874 875 876
        public void visitTupleExpression(JetTupleExpression expression) {
            List<JetExpression> entries = expression.getEntries();
            List<JetType> types = new ArrayList<JetType>();
            for (JetExpression entry : entries) {
                types.add(getType(scope, entry, false));
            }
            // TODO : labels
            result = JetStandardClasses.getTupleType(types);
        }
A
Andrey Breslav 已提交
877

878 879
        @Override
        public void visitThisExpression(JetThisExpression expression) {
880
            // TODO : qualified this, e.g. this@Foo<Bar>
A
Andrey Breslav 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
            JetType thisType = null;
            String labelName = expression.getLabelName();
            if (labelName != null) {
                Collection<DeclarationDescriptor> declarationsByLabel = scope.getDeclarationsByLabel(labelName);
                int size = declarationsByLabel.size();
                if (size == 1) {
                    DeclarationDescriptor declarationDescriptor = declarationsByLabel.iterator().next();
                    if (declarationDescriptor instanceof ClassDescriptor) {
                        ClassDescriptor classDescriptor = (ClassDescriptor) declarationDescriptor;
                        thisType = classDescriptor.getDefaultType();
                    }
                    else {
                        throw new UnsupportedOperationException(); // TODO
                    }
                }
                else if (size == 0) {
897
                    trace.getErrorHandler().unresolvedReference(expression.getTargetLabel());
A
Andrey Breslav 已提交
898 899
                }
                else {
900
                    JetSimpleNameExpression labelElement = expression.getTargetLabel();
A
Andrey Breslav 已提交
901
                    assert labelElement != null;
902
                    trace.getErrorHandler().genericError(labelElement.getNode(), "Ambiguous label");
A
Andrey Breslav 已提交
903 904 905 906 907 908 909 910
                }
            }
            else {
                thisType = scope.getThisType();
            }

            if (thisType != null) {
                if (JetStandardClasses.isNothing(thisType)) {
911
                    trace.getErrorHandler().genericError(expression.getNode(), "'this' is not defined in this context");
A
Andrey Breslav 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925
                }
                else {
                    JetTypeReference superTypeQualifier = expression.getSuperTypeQualifier();
                    if (superTypeQualifier != null) {
                        JetTypeElement superTypeElement = superTypeQualifier.getTypeElement();
                        // Errors are reported by the parser
                        if (superTypeElement instanceof JetUserType) {
                            JetUserType typeElement = (JetUserType) superTypeElement;

                            ClassifierDescriptor classifierCandidate = typeResolver.resolveClass(scope, typeElement);
                            if (classifierCandidate instanceof ClassDescriptor) {
                                ClassDescriptor superclass = (ClassDescriptor) classifierCandidate;

                                Collection<? extends JetType> supertypes = thisType.getConstructor().getSupertypes();
926
                                TypeSubstitutor substitutor = TypeSubstitutor.create(thisType);
A
Andrey Breslav 已提交
927 928
                                for (JetType declaredSupertype : supertypes) {
                                    if (declaredSupertype.getConstructor().equals(superclass.getTypeConstructor())) {
929
                                        result = substitutor.safeSubstitute(declaredSupertype, Variance.INVARIANT);
A
Andrey Breslav 已提交
930 931 932 933
                                        break;
                                    }
                                }
                                if (result == null) {
934
                                    trace.getErrorHandler().genericError(superTypeElement.getNode(), "Not a superclass");
A
Andrey Breslav 已提交
935
                                }
936 937
                            }
                        }
A
Andrey Breslav 已提交
938 939
                    } else {
                        result = thisType;
940
                    }
A
Andrey Breslav 已提交
941
                }
A
Andrey Breslav 已提交
942 943 944
            }
        }

945 946
        @Override
        public void visitBlockExpression(JetBlockExpression expression) {
947
            result = getBlockReturnedType(scope, expression.getStatements());
948 949
        }

A
Andrey Breslav 已提交
950 951 952 953 954 955 956 957 958 959 960 961 962 963
        @Override
        public void visitWhenExpression(JetWhenExpression expression) {
            // TODO :change scope according to the bound value in the when header
            List<JetType> expressions = new ArrayList<JetType>();
            collectAllReturnTypes(expression, scope, expressions);
            result = semanticServices.getTypeChecker().commonSupertype(expressions);
        }

        @Override
        public void visitTryExpression(JetTryExpression expression) {
            JetExpression tryBlock = expression.getTryBlock();
            List<JetCatchClause> catchClauses = expression.getCatchClauses();
            JetFinallySection finallyBlock = expression.getFinallyBlock();
            List<JetType> types = new ArrayList<JetType>();
964 965 966 967 968
            for (JetCatchClause catchClause : catchClauses) {
                JetParameter catchParameter = catchClause.getCatchParameter();
                JetExpression catchBody = catchClause.getCatchBody();
                if (catchParameter != null) {
                    VariableDescriptor variableDescriptor = classDescriptorResolver.resolveLocalVariableDescriptor(scope.getContainingDeclaration(), scope, catchParameter);
969
                    if (catchBody != null) {
970
                        WritableScope catchScope = new WritableScopeImpl(scope, scope.getContainingDeclaration(), trace.getErrorHandler(), null);
971 972 973 974 975
                        catchScope.addVariableDescriptor(variableDescriptor);
                        JetType type = getType(catchScope, catchBody, true);
                        if (type != null) {
                            types.add(type);
                        }
976
                    }
A
Andrey Breslav 已提交
977 978
                }
            }
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
            if (finallyBlock != null) {
                types.clear(); // Do not need the list for the check, but need the code above to typecheck catch bodies
                JetType type = getType(scope, finallyBlock.getFinalExpression(), true);
                if (type != null) {
                    types.add(type);
                }
            }
            JetType type = getType(scope, tryBlock, true);
            if (type != null) {
                types.add(type);
            }
            if (types.isEmpty()) {
                result = null;
            }
            else {
                result = semanticServices.getTypeChecker().commonSupertype(types);
            }
A
Andrey Breslav 已提交
996 997 998
        }

        @Override
999 1000 1001
        public void visitIfExpression(JetIfExpression expression) {
            checkCondition(scope, expression.getCondition());

1002
            // TODO : change types according to is and null checks
1003
            JetExpression elseBranch = expression.getElse();
1004
            JetExpression thenBranch = expression.getThen();
1005 1006 1007 1008 1009 1010

            if (elseBranch == null) {
                if (thenBranch != null) {
                    getType(scope, thenBranch, true);
                    result = JetStandardClasses.getUnitType();
                }
1011
            }
1012 1013 1014 1015 1016 1017
            else if (thenBranch == null) {
                getType(scope, elseBranch, true);
                result = JetStandardClasses.getUnitType();
            }
            else {
                JetType thenType = getType(scope, thenBranch, true);
1018
                JetType elseType = getType(scope, elseBranch, true);
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
                if (thenType == null) {
                    result = elseType;
                }
                else if (elseType == null) {
                    result = thenType;
                }
                else {
                    result = semanticServices.getTypeChecker().commonSupertype(Arrays.asList(thenType, elseType));
                }
            }
A
Andrey Breslav 已提交
1029 1030
        }

1031 1032 1033 1034 1035
        private void checkCondition(@NotNull JetScope scope, @Nullable JetExpression condition) {
            if (condition != null) {
                JetType conditionType = getType(scope, condition, false);

                if (conditionType != null && !isBoolean(conditionType)) {
1036
                    trace.getErrorHandler().genericError(condition.getNode(), "Condition must be of type Boolean, but was of type " + conditionType);
A
Andrey Breslav 已提交
1037 1038 1039 1040 1041
                }
            }
        }

        @Override
1042 1043 1044 1045 1046 1047 1048
        public void visitWhileExpression(JetWhileExpression expression) {
            checkCondition(scope, expression.getCondition());
            JetExpression body = expression.getBody();
            if (body != null) {
                getType(scope, body, true);
            }
            result = JetStandardClasses.getUnitType();
A
Andrey Breslav 已提交
1049 1050 1051
        }

        @Override
1052 1053
        public void visitDoWhileExpression(JetDoWhileExpression expression) {
            JetExpression body = expression.getBody();
A
Andrey Breslav 已提交
1054 1055 1056 1057
            JetScope conditionScope = scope;
            if (body instanceof JetFunctionLiteralExpression) {
                JetFunctionLiteralExpression function = (JetFunctionLiteralExpression) body;
                if (!function.hasParameterSpecification()) {
1058
                    WritableScope writableScope = new WritableScopeImpl(scope, scope.getContainingDeclaration(), trace.getErrorHandler(), null);
A
Andrey Breslav 已提交
1059
                    conditionScope = writableScope;
1060
                    getBlockReturnedTypeWithWritableScope(writableScope, function.getBody());
A
Andrey Breslav 已提交
1061
                    trace.recordBlock(function);
A
Andrey Breslav 已提交
1062 1063 1064 1065 1066
                } else {
                    getType(scope, body, true);
                }
            }
            else if (body != null) {
1067
                WritableScope writableScope = new WritableScopeImpl(scope, scope.getContainingDeclaration(), trace.getErrorHandler(), null);
A
Andrey Breslav 已提交
1068
                conditionScope = writableScope;
1069
                getBlockReturnedTypeWithWritableScope(writableScope, Collections.singletonList(body));
1070 1071 1072 1073 1074 1075 1076 1077 1078
            }
            checkCondition(conditionScope, expression.getCondition());
            result = JetStandardClasses.getUnitType();
        }

        @Override
        public void visitForExpression(JetForExpression expression) {
            JetParameter loopParameter = expression.getLoopParameter();
            JetExpression loopRange = expression.getLoopRange();
1079 1080 1081 1082
            JetType loopRangeType = null;
            if (loopRange != null) {
                loopRangeType = getType(scope, loopRange, false);
            }
1083 1084
            JetType expectedParameterType = null;
            if (loopRangeType != null) {
1085 1086 1087
                expectedParameterType = checkIterableConvention(loopRangeType, loopRange.getNode());
            }

1088
            WritableScope loopScope = new WritableScopeImpl(scope, scope.getContainingDeclaration(), trace.getErrorHandler(), null);
1089 1090 1091

            if (loopParameter != null) {
                JetTypeReference typeReference = loopParameter.getTypeReference();
1092
                VariableDescriptor variableDescriptor;
1093
                if (typeReference != null) {
1094 1095
                    variableDescriptor = classDescriptorResolver.resolveLocalVariableDescriptor(scope.getContainingDeclaration(), scope, loopParameter);
                    JetType actualParameterType = variableDescriptor.getOutType();
1096 1097 1098
                    if (expectedParameterType != null &&
                            actualParameterType != null &&
                            !semanticServices.getTypeChecker().isSubtypeOf(expectedParameterType, actualParameterType)) {
1099
                        trace.getErrorHandler().genericError(typeReference.getNode(), "The loop iterates over values of type " + expectedParameterType + " but the parameter is declared to be " + actualParameterType);
1100
                    }
1101 1102
                }
                else {
1103 1104
                    if (expectedParameterType == null) {
                        expectedParameterType = ErrorUtils.createErrorType("Error");
1105
                    }
1106
                    variableDescriptor = classDescriptorResolver.resolveLocalVariableDescriptor(scope.getContainingDeclaration(), loopParameter, expectedParameterType);
1107
                }
1108
                loopScope.addVariableDescriptor(variableDescriptor);
1109 1110
            }

1111 1112 1113 1114
            JetExpression body = expression.getBody();
            if (body != null) {
                getType(loopScope, body, true); // TODO
            }
1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
            result = JetStandardClasses.getUnitType();
        }

        @Nullable
        private JetType checkIterableConvention(@NotNull JetType type, @NotNull ASTNode reportErrorsOn) {
            OverloadResolutionResult iteratorResolutionResult = resolveNoParametersFunction(type, scope, "iterator");
            if (iteratorResolutionResult.isSuccess()) {
                JetType iteratorType = iteratorResolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
                boolean hasNextFunctionSupported = checkHasNextFunctionSupport(reportErrorsOn, iteratorType);
                boolean hasNextPropertySupported = checkHasNextPropertySupport(reportErrorsOn, iteratorType);
1126
                if (hasNextFunctionSupported && hasNextPropertySupported && !ErrorUtils.isErrorType(iteratorType)) {
1127
                    // TODO : overload resolution rules impose priorities here???
1128
                    trace.getErrorHandler().genericError(reportErrorsOn, "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext()' property");
1129 1130
                }
                else if (!hasNextFunctionSupported && !hasNextPropertySupported) {
1131
                    trace.getErrorHandler().genericError(reportErrorsOn, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property");
1132 1133 1134 1135
                }

                OverloadResolutionResult nextResolutionResult = resolveNoParametersFunction(iteratorType, scope, "next");
                if (nextResolutionResult.isAmbiguity()) {
1136
                    trace.getErrorHandler().genericError(reportErrorsOn, "Method 'iterator().next()' is ambiguous for this expression");
1137
                } else if (nextResolutionResult.isNothing()) {
1138
                    trace.getErrorHandler().genericError(reportErrorsOn, "Loop range must have an 'iterator().next()' method");
1139 1140
                } else {
                    return nextResolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
1141 1142 1143
                }
            }
            else {
1144 1145 1146
                String errorMessage = "For-loop range must have an iterator() method";
                if (iteratorResolutionResult.isAmbiguity()) {
                    errorMessage = "Method 'iterator()' is ambiguous for this expression";
1147
                }
1148
                trace.getErrorHandler().genericError(reportErrorsOn, errorMessage);
1149
            }
1150 1151
            return null;
        }
1152

1153 1154 1155
        private boolean checkHasNextFunctionSupport(@NotNull ASTNode reportErrorsOn, @NotNull JetType iteratorType) {
            OverloadResolutionResult hasNextResolutionResult = resolveNoParametersFunction(iteratorType, scope, "hasNext");
            if (hasNextResolutionResult.isAmbiguity()) {
1156
                trace.getErrorHandler().genericError(reportErrorsOn, "Method 'iterator().hasNext()' is ambiguous for this expression");
1157 1158 1159 1160 1161
            } else if (hasNextResolutionResult.isNothing()) {
                return false;
            } else {
                JetType hasNextReturnType = hasNextResolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
                if (!isBoolean(hasNextReturnType)) {
1162
                    trace.getErrorHandler().genericError(reportErrorsOn, "The 'iterator().hasNext()' method of the loop range must return Boolean, but returns " + hasNextReturnType);
1163
                }
1164
            }
1165 1166
            return true;
        }
1167

1168
        private boolean checkHasNextPropertySupport(@NotNull ASTNode reportErrorsOn, @NotNull JetType iteratorType) {
1169
            VariableDescriptor hasNextProperty = iteratorType.getMemberScope().getVariable("hasNext");
1170 1171 1172 1173 1174 1175 1176
            // TODO :extension properties
            if (hasNextProperty == null) {
                return false;
            } else {
                JetType hasNextReturnType = hasNextProperty.getOutType();
                if (hasNextReturnType == null) {
                    // TODO : accessibility
1177
                    trace.getErrorHandler().genericError(reportErrorsOn, "The 'iterator().hasNext' property of the loop range must be readable");
1178 1179
                }
                else if (!isBoolean(hasNextReturnType)) {
1180
                    trace.getErrorHandler().genericError(reportErrorsOn, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns " + hasNextReturnType);
1181 1182 1183 1184 1185 1186 1187 1188 1189
                }
            }
            return true;
        }

        @NotNull
        private OverloadResolutionResult resolveNoParametersFunction(@NotNull JetType receiverType, @NotNull JetScope scope, @NotNull String name) {
            OverloadDomain overloadDomain = semanticServices.getOverloadResolver().getOverloadDomain(receiverType, scope, name);
            return overloadDomain.getFunctionDescriptorForPositionedArguments(Collections.<JetType>emptyList(), Collections.<JetType>emptyList());
A
Andrey Breslav 已提交
1190 1191 1192 1193 1194 1195
        }

        @Override
        public void visitNewExpression(JetNewExpression expression) {
            // TODO : type argument inference
            JetTypeReference typeReference = expression.getTypeReference();
1196
            if (typeReference != null) {
1197
                result = checkConstructorCall(scope, typeReference, expression);
1198
            }
A
Andrey Breslav 已提交
1199 1200 1201
        }

        @Override
A
Andrey Breslav 已提交
1202
        public void visitHashQualifiedExpression(JetHashQualifiedExpression expression) {
1203
            trace.getErrorHandler().genericError(expression.getOperationTokenNode(), "Unsupported");
A
Andrey Breslav 已提交
1204 1205 1206 1207
        }

        @Override
        public void visitQualifiedExpression(JetQualifiedExpression expression) {
A
Andrey Breslav 已提交
1208 1209
            // TODO : functions
            JetExpression selectorExpression = expression.getSelectorExpression();
1210
            JetExpression receiverExpression = expression.getReceiverExpression();
1211
            JetType receiverType = new TypeInferrerVisitorWithNamespaces(scope, false).getType(receiverExpression);
A
Andrey Breslav 已提交
1212 1213
            if (receiverType != null) {
                checkNullSafety(receiverType, expression);
A
Andrey Breslav 已提交
1214 1215 1216 1217
                JetType selectorReturnType = getSelectorReturnType(receiverType, selectorExpression);
                if (expression.getOperationSign() == JetTokens.QUEST) {
                    if (selectorReturnType != null && !isBoolean(selectorReturnType)) {
                        // TODO : more comprehensible error message
1218
                        trace.getErrorHandler().typeMismatch(selectorExpression, semanticServices.getStandardLibrary().getBooleanType(), selectorReturnType);
A
Andrey Breslav 已提交
1219 1220
                    }
                    result = TypeUtils.makeNullable(receiverType);
A
Andrey Breslav 已提交
1221
                }
A
Andrey Breslav 已提交
1222 1223
                else {
                    result = selectorReturnType;
1224
                }
1225 1226 1227
                if (selectorExpression != null && result != null) {
                    trace.recordExpressionType(selectorExpression, result);
                }
A
Andrey Breslav 已提交
1228 1229 1230
            }
        }

A
Andrey Breslav 已提交
1231 1232 1233 1234
        private JetType getSelectorReturnType(JetType receiverType, JetExpression selectorExpression) {
            JetScope compositeScope = new ScopeWithReceiver(scope, receiverType);
            if (selectorExpression instanceof JetCallExpression) {
                JetCallExpression callExpression = (JetCallExpression) selectorExpression;
1235
                OverloadDomain overloadDomain = getOverloadDomain(compositeScope, callExpression.getCalleeExpression(), callExpression.getValueArgumentList());
A
Andrey Breslav 已提交
1236 1237 1238 1239 1240 1241 1242
                return resolveOverloads(scope, callExpression, overloadDomain);
            }
            else if (selectorExpression instanceof JetSimpleNameExpression) {
                return getType(compositeScope, selectorExpression, false);
            }
            else if (selectorExpression != null) {
                // TODO : not a simple name -> resolve in scope, expect property type or a function type
1243
                trace.getErrorHandler().genericError(selectorExpression.getNode(), "Unsupported selector element type: " + selectorExpression);
A
Andrey Breslav 已提交
1244 1245 1246 1247
            }
            return receiverType;
        }

A
Andrey Breslav 已提交
1248 1249 1250
        @Override
        public void visitCallExpression(JetCallExpression expression) {
            JetExpression calleeExpression = expression.getCalleeExpression();
1251
            OverloadDomain overloadDomain = getOverloadDomain(scope, calleeExpression, expression.getValueArgumentList());
A
Andrey Breslav 已提交
1252
            result = resolveOverloads(scope, expression, overloadDomain);
1253
        }
A
Andrey Breslav 已提交
1254

A
Andrey Breslav 已提交
1255 1256 1257 1258 1259 1260
        @Override
        public void visitIsExpression(JetIsExpression expression) {
            // TODO : patterns and everything
            result = semanticServices.getStandardLibrary().getBooleanType();
        }

A
Andrey Breslav 已提交
1261
        @Override
1262
        public void visitUnaryExpression(JetUnaryExpression expression) {
A
Andrey Breslav 已提交
1263
            JetSimpleNameExpression operationSign = expression.getOperationSign();
1264 1265 1266 1267 1268
            if (JetTokens.LABELS.contains(operationSign.getReferencedNameElementType())) {
                // TODO : Some processing for the label?
                result = getType(expression.getBaseExpression());
                return;
            }
A
Andrey Breslav 已提交
1269 1270
            IElementType operationType = operationSign.getReferencedNameElementType();
            String name = unaryOperationNames.get(operationType);
1271
            if (name == null) {
1272
                trace.getErrorHandler().genericError(operationSign.getNode(), "Unknown unary operation");
1273 1274
            }
            else {
A
Andrey Breslav 已提交
1275 1276 1277
                JetType receiverType = getType(scope, expression.getBaseExpression(), false);
                if (receiverType != null) {
                    FunctionDescriptor functionDescriptor = lookupFunction(scope, expression.getOperationSign(), name, receiverType, Collections.<JetType>emptyList(), true);
A
Andrey Breslav 已提交
1278
                    if (functionDescriptor != null) {
A
Andrey Breslav 已提交
1279 1280
                        JetType returnType = functionDescriptor.getUnsubstitutedReturnType();
                        if (operationType == JetTokens.PLUSPLUS || operationType == JetTokens.MINUSMINUS) {
1281 1282 1283 1284 1285
                            if (semanticServices.getTypeChecker().isSubtypeOf(returnType, JetStandardClasses.getUnitType())) {
                                 result = JetStandardClasses.getUnitType();
                            }
                            else {
                                if (!semanticServices.getTypeChecker().isSubtypeOf(returnType, receiverType)) {
1286
                                    trace.getErrorHandler().genericError(operationSign.getNode(), name + " must return " + receiverType + " but returns " + returnType);
1287 1288 1289
                                }
                                // TODO : Maybe returnType?
                                result = receiverType;
A
Andrey Breslav 已提交
1290 1291 1292 1293
                            }
                        } else {
                            result = returnType;
                        }
A
Andrey Breslav 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302
                    }
                }
            }
        }

        @Override
        public void visitBinaryExpression(JetBinaryExpression expression) {
            JetSimpleNameExpression operationSign = expression.getOperationReference();

A
Andrey Breslav 已提交
1303 1304 1305
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();

A
Andrey Breslav 已提交
1306 1307
            IElementType operationType = operationSign.getReferencedNameElementType();
            if (operationType == JetTokens.IDENTIFIER) {
1308 1309 1310 1311
                String referencedName = operationSign.getReferencedName();
                if (referencedName != null) {
                    result = getTypeForBinaryCall(expression, referencedName, scope, true);
                }
A
Andrey Breslav 已提交
1312
            }
1313
            else if (binaryOperationNames.containsKey(operationType)) {
A
Andrey Breslav 已提交
1314
                result = getTypeForBinaryCall(expression, binaryOperationNames.get(operationType), scope, true);
A
Andrey Breslav 已提交
1315 1316
            }
            else if (operationType == JetTokens.EQ) {
A
Andrey Breslav 已提交
1317 1318 1319 1320
                visitAssignment(expression);
            }
            else if (assignmentOperationNames.containsKey(operationType)) {
                visitAssignmentOperation(expression);
A
Andrey Breslav 已提交
1321
            }
1322
            else if (comparisonOperations.contains(operationType)) {
A
Andrey Breslav 已提交
1323
                JetType compareToReturnType = getTypeForBinaryCall(expression, "compareTo", scope, true);
A
Andrey Breslav 已提交
1324 1325 1326 1327 1328 1329 1330
                if (compareToReturnType != null) {
                    TypeConstructor constructor = compareToReturnType.getConstructor();
                    JetStandardLibrary standardLibrary = semanticServices.getStandardLibrary();
                    TypeConstructor intTypeConstructor = standardLibrary.getInt().getTypeConstructor();
                    if (constructor.equals(intTypeConstructor)) {
                        result = standardLibrary.getBooleanType();
                    } else {
1331
                        trace.getErrorHandler().genericError(operationSign.getNode(), "compareTo must return Int, but returns " + compareToReturnType);
A
Andrey Breslav 已提交
1332
                    }
A
Andrey Breslav 已提交
1333
                }
A
Andrey Breslav 已提交
1334
            }
A
Equals  
Andrey Breslav 已提交
1335
            else if (equalsOperations.contains(operationType)) {
A
Andrey Breslav 已提交
1336
                String name = "equals";
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
                if (right != null) {
                    JetType leftType = getType(scope, left, false);
                    if (leftType != null) {
                        JetType rightType = getType(scope, right, false);
                        if (rightType != null) {
                            FunctionDescriptor equals = lookupFunction(
                                    scope, operationSign, "equals",
                                    leftType, Collections.singletonList(JetStandardClasses.getNullableAnyType()), false);
                            if (equals != null) {
                                if (ensureBooleanResult(operationSign, name, equals.getUnsubstitutedReturnType())) {
                                    ensureNonemptyIntersectionOfOperandTypes(expression);
                                }
                            }
                            else {
1351
                                trace.getErrorHandler().genericError(operationSign.getNode(), "No method 'equals(Any?) : Boolean' available");
1352 1353 1354 1355 1356
                            }
                        }
                    }
                }
                result = semanticServices.getStandardLibrary().getBooleanType();
1357 1358 1359 1360 1361 1362
            }
            else if (operationType == JetTokens.EQEQEQ || operationType == JetTokens.EXCLEQEQEQ) {
                ensureNonemptyIntersectionOfOperandTypes(expression);

                // TODO : Check comparison pointlessness
                result = semanticServices.getStandardLibrary().getBooleanType();
A
Andrey Breslav 已提交
1363 1364 1365
            }
            else if (inOperations.contains(operationType)) {
                if (right == null) {
A
rename  
Andrey Breslav 已提交
1366
                    result = ErrorUtils.createErrorType("No right argument"); // TODO
A
Andrey Breslav 已提交
1367
                    return;
A
Andrey Breslav 已提交
1368
                }
A
Andrey Breslav 已提交
1369 1370
                String name = "contains";
                JetType containsType = getTypeForBinaryCall(scope, right, expression.getOperationReference(), expression.getLeft(), name, true);
1371 1372
                ensureBooleanResult(operationSign, name, containsType);
                result = semanticServices.getStandardLibrary().getBooleanType();
A
Equals  
Andrey Breslav 已提交
1373
            }
A
Andrey Breslav 已提交
1374 1375 1376 1377
            else if (operationType == JetTokens.ANDAND || operationType == JetTokens.OROR) {
                JetType leftType = getType(scope, left, false);
                JetType rightType = right == null ? null : getType(scope, right, false);
                if (leftType != null && !isBoolean(leftType)) {
1378
                    trace.getErrorHandler().typeMismatch(left, semanticServices.getStandardLibrary().getBooleanType(), leftType);
A
Andrey Breslav 已提交
1379 1380
                }
                if (rightType != null && !isBoolean(rightType)) {
1381
                    trace.getErrorHandler().typeMismatch(right, semanticServices.getStandardLibrary().getBooleanType(), rightType);
A
Andrey Breslav 已提交
1382 1383 1384
                }
                result = semanticServices.getStandardLibrary().getBooleanType();
            }
A
Andrey Breslav 已提交
1385 1386 1387 1388 1389
            else if (operationType == JetTokens.ELVIS) {
                JetType leftType = getType(scope, left, false);
                JetType rightType = right == null ? null : getType(scope, right, false);
                if (leftType != null) {
                    if (!leftType.isNullable()) {
1390
                        trace.getErrorHandler().genericWarning(left.getNode(), "Elvis operator (?:) is always returns the left operand of non-nullable type " + leftType);
A
Andrey Breslav 已提交
1391 1392 1393 1394 1395 1396
                    }
                    if (rightType != null) {
                        result = TypeUtils.makeNullableAsSpecified(semanticServices.getTypeChecker().commonSupertype(leftType, rightType), rightType.isNullable());
                    }
                }
            }
A
Equals  
Andrey Breslav 已提交
1397
            else {
1398
                trace.getErrorHandler().genericError(operationSign.getNode(), "Unknown operation");
A
Andrey Breslav 已提交
1399 1400 1401
            }
        }

1402 1403 1404 1405 1406 1407 1408
        private void ensureNonemptyIntersectionOfOperandTypes(JetBinaryExpression expression) {
            JetSimpleNameExpression operationSign = expression.getOperationReference();
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();

            // TODO : duplicated effort for == and !=
            JetType leftType = getType(scope, left, false);
1409
            if (leftType != null && right != null) {
1410 1411
                JetType rightType = getType(scope, right, false);

1412 1413 1414
                if (rightType != null) {
                    JetType intersect = TypeUtils.intersect(semanticServices.getTypeChecker(), new HashSet<JetType>(Arrays.asList(leftType, rightType)));
                    if (intersect == null) {
1415
                        trace.getErrorHandler().genericError(expression.getNode(), "Operator " + operationSign.getReferencedName() + " cannot be applied to " + leftType + " and " + rightType);
1416
                    }
1417 1418 1419 1420
                }
            }
        }

A
Andrey Breslav 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429
        protected void visitAssignmentOperation(JetBinaryExpression expression) {
            assignmentIsNotAnExpressionError(expression);
        }

        protected void visitAssignment(JetBinaryExpression expression) {
            assignmentIsNotAnExpressionError(expression);
        }

        private void assignmentIsNotAnExpressionError(JetBinaryExpression expression) {
1430
            trace.getErrorHandler().genericError(expression.getNode(), "Assignments are not expressions, and only expressions are allowed in this context");
A
Andrey Breslav 已提交
1431 1432
        }

1433
        private boolean ensureBooleanResult(JetSimpleNameExpression operationSign, String name, JetType resultType) {
A
Andrey Breslav 已提交
1434 1435
            if (resultType != null) {
                // TODO : Relax?
A
Andrey Breslav 已提交
1436
                if (!isBoolean(resultType)) {
1437
                    trace.getErrorHandler().genericError(operationSign.getNode(), "'" + name + "' must return Boolean but returns " + resultType);
1438
                    return false;
A
Andrey Breslav 已提交
1439 1440
                }
            }
1441
            return true;
A
Andrey Breslav 已提交
1442 1443
        }

A
Andrey Breslav 已提交
1444
        private boolean isBoolean(@NotNull JetType type) {
A
Andrey Breslav 已提交
1445
            return semanticServices.getTypeChecker().isConvertibleTo(type,  semanticServices.getStandardLibrary().getBooleanType());
A
Andrey Breslav 已提交
1446 1447
        }

A
Andrey Breslav 已提交
1448 1449 1450 1451 1452 1453 1454 1455
        @Override
        public void visitArrayAccessExpression(JetArrayAccessExpression expression) {
            JetExpression arrayExpression = expression.getArrayExpression();
            JetType receiverType = getType(scope, arrayExpression, false);
            List<JetExpression> indexExpressions = expression.getIndexExpressions();
            List<JetType> argumentTypes = getTypes(scope, indexExpressions);
            if (argumentTypes == null) return;

1456 1457 1458 1459 1460
            if (receiverType != null) {
                FunctionDescriptor functionDescriptor = lookupFunction(scope, expression, "get", receiverType, argumentTypes, true);
                if (functionDescriptor != null) {
                    result = functionDescriptor.getUnsubstitutedReturnType();
                }
A
Andrey Breslav 已提交
1461 1462 1463
            }
        }

1464
        @Nullable
1465 1466 1467 1468 1469
        protected JetType getTypeForBinaryCall(
                @NotNull JetBinaryExpression expression,
                @NotNull String name,
                @NotNull JetScope scope,
                boolean reportUnresolved) {
A
Andrey Breslav 已提交
1470 1471 1472
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();
            if (right == null) {
1473
                return null;
A
Andrey Breslav 已提交
1474
            }
A
Andrey Breslav 已提交
1475 1476 1477 1478
            JetSimpleNameExpression operationSign = expression.getOperationReference();
            return getTypeForBinaryCall(scope, left, operationSign, right, name, reportUnresolved);
        }

1479
        @Nullable
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        private JetType getTypeForBinaryCall(
                @NotNull JetScope scope,
                @NotNull JetExpression left,
                @NotNull JetSimpleNameExpression operationSign,
                @NotNull JetExpression right,
                @NotNull String name,
                boolean reportUnresolved) {
            JetType leftType = getType(scope, left, false);
            JetType rightType = getType(scope, right, false);
            if (leftType == null || rightType == null) {
1490 1491
                return null;
            }
A
Andrey Breslav 已提交
1492
            FunctionDescriptor functionDescriptor = lookupFunction(scope, operationSign, name, leftType, Collections.singletonList(rightType), reportUnresolved);
A
Andrey Breslav 已提交
1493
            if (functionDescriptor != null) {
1494 1495
                if (leftType.isNullable()) {
                    // TODO : better error message for '1 + nullableVar' case
1496
                    trace.getErrorHandler().genericError(operationSign.getNode(),
1497 1498 1499 1500 1501 1502
                            "Infix call corresponds to a dot-qualified call '" +
                            left.getText() + "." + name + "(" + right.getText() + ")'" +
                            " which is not allowed on a nullable receiver '" + right.getText() + "'." +
                            " Use '?.'-qualified call instead");
                }

A
Andrey Breslav 已提交
1503 1504 1505 1506
                return functionDescriptor.getUnsubstitutedReturnType();
            }
            return null;
        }
A
Andrey Breslav 已提交
1507 1508 1509

        @Override
        public void visitDeclaration(JetDeclaration dcl) {
1510
            trace.getErrorHandler().genericError(dcl.getNode(), "Declarations are not allowed in this position");
A
Andrey Breslav 已提交
1511 1512
        }

1513 1514
        @Override
        public void visitRootNamespaceExpression(JetRootNamespaceExpression expression) {
1515
            trace.getErrorHandler().genericError(expression.getNode(), "'namespace' is not an expression");
1516 1517 1518
            result = null;
        }

A
Andrey Breslav 已提交
1519 1520
        @Override
        public void visitJetElement(JetElement elem) {
1521
            trace.getErrorHandler().genericError(elem.getNode(), "[JetTypeInferrer] Unsupported element: " + elem + " " + elem.getClass().getCanonicalName());
A
Andrey Breslav 已提交
1522 1523 1524
        }
    }

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    private class TypeInferrerVisitorWithNamespaces extends TypeInferrerVisitor {
        private TypeInferrerVisitorWithNamespaces(@NotNull JetScope scope, boolean preferBlock) {
            super(scope, preferBlock);
        }

        @NotNull
        @Override
        public TypeInferrerVisitor createNew(JetScope scope, boolean preferBlock) {
            return new TypeInferrerVisitorWithNamespaces(scope, preferBlock);
        }

        @Override
        public void visitRootNamespaceExpression(JetRootNamespaceExpression expression) {
            result = JetModuleUtil.getRootNamespaceType(expression);
        }

        @Override
        protected boolean furtherNameLookup(@NotNull JetSimpleNameExpression expression, @NotNull String referencedName) {
            result = lookupNamespaceType(expression, referencedName);
            return result != null;
        }

    }

A
Andrey Breslav 已提交
1549 1550 1551
    private class TypeInferrerVisitorWithWritableScope extends TypeInferrerVisitor {
        private final WritableScope scope;

1552 1553
        public TypeInferrerVisitorWithWritableScope(@NotNull WritableScope scope, boolean preferBlock) {
            super(scope, preferBlock);
A
Andrey Breslav 已提交
1554 1555 1556 1557 1558
            this.scope = scope;
        }

        @Override
        public void visitProperty(JetProperty property) {
1559 1560 1561

            JetPropertyAccessor getter = property.getGetter();
            if (getter != null) {
1562
                trace.getErrorHandler().genericError(getter.getNode(), "Local variables are not allowed to have getters");
1563 1564 1565 1566
            }

            JetPropertyAccessor setter = property.getSetter();
            if (setter != null) {
1567
                trace.getErrorHandler().genericError(setter.getNode(), "Local variables are not allowed to have setters");
1568 1569
            }

1570
            VariableDescriptor propertyDescriptor = classDescriptorResolver.resolveLocalVariableDescriptor(scope.getContainingDeclaration(), scope, property);
1571 1572 1573 1574 1575 1576 1577
            JetExpression initializer = property.getInitializer();
            if (property.getPropertyTypeRef() != null && initializer != null) {
                JetType initializerType = getType(scope, initializer, false);
                JetType outType = propertyDescriptor.getOutType();
                if (outType != null &&
                    initializerType != null &&
                    !semanticServices.getTypeChecker().isConvertibleTo(initializerType, outType)) {
1578
                    trace.getErrorHandler().typeMismatch(initializer, outType, initializerType);
1579 1580 1581
                }
            }

1582
            scope.addVariableDescriptor(propertyDescriptor);
A
Andrey Breslav 已提交
1583 1584 1585 1586
        }

        @Override
        public void visitFunction(JetFunction function) {
1587
            scope.addFunctionDescriptor(classDescriptorResolver.resolveFunctionDescriptor(scope.getContainingDeclaration(), scope, function));
A
Andrey Breslav 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
        }

        @Override
        public void visitClass(JetClass klass) {
            super.visitClass(klass); // TODO
        }

        @Override
        public void visitExtension(JetExtension extension) {
            super.visitExtension(extension); // TODO
        }

        @Override
        public void visitTypedef(JetTypedef typedef) {
            super.visitTypedef(typedef); // TODO
        }

        @Override
        public void visitDeclaration(JetDeclaration dcl) {
            visitJetElement(dcl);
        }

        @Override
        protected void visitAssignmentOperation(JetBinaryExpression expression) {
            IElementType operationType = expression.getOperationReference().getReferencedNameElementType();
            String name = assignmentOperationNames.get(operationType);
            JetType assignmentOperationType = getTypeForBinaryCall(expression, name, scope, false);

            if (assignmentOperationType == null) {
                String counterpartName = binaryOperationNames.get(assignmentOperationCounterparts.get(operationType));
                getTypeForBinaryCall(expression, counterpartName, scope, true);
            }
1620
            result = null; // not an expression
A
Andrey Breslav 已提交
1621 1622 1623 1624 1625
        }

        @Override
        protected void visitAssignment(JetBinaryExpression expression) {
            JetExpression left = expression.getLeft();
1626
            JetExpression deparenthesized = JetPsiUtil.deparenthesize(left);
A
Andrey Breslav 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
            JetExpression right = expression.getRight();
            if (deparenthesized instanceof JetArrayAccessExpression) {
                JetArrayAccessExpression arrayAccessExpression = (JetArrayAccessExpression) deparenthesized;
                resolveArrayAccessToLValue(arrayAccessExpression, right, expression.getOperationReference());
            }
            else {
                JetType leftType = getType(scope, left, false);
                if (right != null) {
                    JetType rightType = getType(scope, right, false);
                    if (rightType != null &&
                        leftType != null &&
                            !semanticServices.getTypeChecker().isConvertibleTo(rightType, leftType)) {
1639
                        trace.getErrorHandler().typeMismatch(right, leftType, rightType);
A
Andrey Breslav 已提交
1640 1641 1642
                    }
                }
            }
A
Andrey Breslav 已提交
1643
            result = null; // This is not an element
A
Andrey Breslav 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
        }

        private void resolveArrayAccessToLValue(JetArrayAccessExpression arrayAccessExpression, JetExpression rightHandSide, JetSimpleNameExpression operationSign) {
            List<JetType> argumentTypes = getTypes(scope, arrayAccessExpression.getIndexExpressions());
            if (argumentTypes == null) return;
            JetType rhsType = getType(scope, rightHandSide, false);
            if (rhsType == null) return;
            argumentTypes.add(rhsType);

            JetType receiverType = getType(scope, arrayAccessExpression.getArrayExpression(), false);
            if (receiverType == null) return;

            // TODO : nasty hack: effort is duplicated
            lookupFunction(scope, arrayAccessExpression, "set", receiverType, argumentTypes, true);
            FunctionDescriptor functionDescriptor = lookupFunction(scope, operationSign, "set", receiverType, argumentTypes, true);
            if (functionDescriptor != null) {
                result = functionDescriptor.getUnsubstitutedReturnType();
            }
        }

        @Override
        public void visitJetElement(JetElement elem) {
1666
            trace.getErrorHandler().genericError(elem.getNode(), "Unsupported element in a block: " + elem + " " + elem.getClass().getCanonicalName());
A
Andrey Breslav 已提交
1667
        }
A
Andrey Breslav 已提交
1668
    }
A
Andrey Breslav 已提交
1669

1670
    private class CachedBindingTrace extends BindingTraceAdapter {
A
Andrey Breslav 已提交
1671

1672
        public CachedBindingTrace(BindingTrace originalTrace) {
1673
            super(originalTrace);
1674
        }
A
Andrey Breslav 已提交
1675

1676
        @Override
1677
        public void recordExpressionType(@NotNull JetExpression expression, @NotNull JetType type) {
1678
            super.recordExpressionType(expression, type);
1679 1680
            typeCache.put(expression, type);
        }
A
Andrey Breslav 已提交
1681
    }
1682
}