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

3
import com.intellij.psi.PsiElement;
4 5 6 7 8 9 10 11
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;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.*;
import org.jetbrains.jet.lexer.JetTokens;
12
import org.jetbrains.jet.resolve.DescriptorUtil;
13 14 15 16 17 18 19 20

import java.util.*;

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

A
Andrey Breslav 已提交
21 22 23 24
    private static final Map<IElementType, String> unaryOperationNames = new HashMap<IElementType, String>();
    static {
        unaryOperationNames.put(JetTokens.PLUSPLUS, "inc");
        unaryOperationNames.put(JetTokens.MINUSMINUS, "dec");
25 26
        unaryOperationNames.put(JetTokens.PLUS, "plus");
        unaryOperationNames.put(JetTokens.MINUS, "minus");
A
Andrey Breslav 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
        unaryOperationNames.put(JetTokens.EXCL, "not");
    }

    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));

    private static final Map<IElementType, String> assignmentOperationNames = new HashMap<IElementType, String>();
    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);
    }

63 64
    private final BindingTrace trace;
    private final JetSemanticServices semanticServices;
A
Andrey Breslav 已提交
65 66
    private final TypeResolver typeResolver;
    private final ClassDescriptorResolver classDescriptorResolver;
67 68 69 70

    public JetTypeInferrer(BindingTrace trace, JetSemanticServices semanticServices) {
        this.trace = trace;
        this.semanticServices = semanticServices;
A
Andrey Breslav 已提交
71
        this.typeResolver = new TypeResolver(trace, semanticServices);
72
        this.classDescriptorResolver = semanticServices.getClassDescriptorResolver(trace);
73 74
    }

75
    @NotNull
A
Andrey Breslav 已提交
76 77
    public JetType safeGetType(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
        JetType type = getType(scope, expression, preferBlock);
78 79 80 81 82
        if (type != null) {
            return type;
        }
        return ErrorType.createErrorType("Type for " + expression.getText());
    }
83

84
    @Nullable
A
Andrey Breslav 已提交
85
    public JetType getType(@NotNull final JetScope scope, @NotNull JetExpression expression, final boolean preferBlock) {
A
Andrey Breslav 已提交
86 87 88 89 90
        TypeInferrerVisitor visitor = new TypeInferrerVisitor(scope, preferBlock);
        expression.accept(visitor);
        JetType result = visitor.getResult();
        if (result != null) {
            trace.recordExpressionType(expression, result);
A
Andrey Breslav 已提交
91
        }
A
Andrey Breslav 已提交
92
        return result;
93 94
    }

95 96 97 98 99 100 101 102
    @NotNull
    private JetExpression deparenthesize(@NotNull JetExpression expression) {
        while (expression instanceof JetParenthesizedExpression) {
            expression = ((JetParenthesizedExpression) expression).getExpression();
        }
        return expression;
    }

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

116 117 118 119 120 121 122 123 124 125
    @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);
126 127
        OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(Collections.<JetType>emptyList(), argumentTypes);
        return resolutionResult.isSuccess() ? resolutionResult.getFunctionDescriptor() : null;
128 129
    }

130

131 132 133 134 135
    private OverloadDomain getOverloadDomain(
            @NotNull final JetScope scope,
            @NotNull JetExpression calleeExpression,
            @Nullable PsiElement argumentList
    ) {
136
        final OverloadDomain[] result = new OverloadDomain[1];
137
        final JetSimpleNameExpression[] reference = new JetSimpleNameExpression[1];
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        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 已提交
155 156 157
                JetType receiverType = getType(scope, expression.getReceiverExpression(), false);
                checkNullSafety(receiverType, expression);

158
                JetExpression selectorExpression = expression.getSelectorExpression();
159 160
                if (selectorExpression instanceof JetSimpleNameExpression) {
                    JetSimpleNameExpression referenceExpression = (JetSimpleNameExpression) selectorExpression;
161

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

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

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

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

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

210 211
    private OverloadDomain wrapForTracing(
            @Nullable final OverloadDomain overloadDomain,
212
            final JetReferenceExpression referenceExpression,
213
            @Nullable final PsiElement argumentList,
214
            final boolean reportErrors) {
215
        if (overloadDomain == null) return OverloadDomain.EMPTY;
216
        assert referenceExpression != null;
217
        return new OverloadDomain() {
218
            @NotNull
219
            @Override
220 221 222 223
            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;
224 225
            }

226
            @NotNull
227
            @Override
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            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:
                            semanticServices.getErrorHandler().unresolvedReference(referenceExpression);
                            break;
                        case SINGLE_FUNCTION_ARGUMENT_MISMATCH:
                            if (argumentList != null) {
                                // TODO : More helpful message. NOTE: there's a separate handling for this for constructors
246
                                semanticServices.getErrorHandler().genericError(argumentList.getNode(), "Arguments do not match " + DescriptorUtil.renderPresentableText(resolutionResult.getFunctionDescriptor()));
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
                            }
                            else {
                                semanticServices.getErrorHandler().unresolvedReference(referenceExpression);
                            }
                            break;
                        case AMBIGUITY:
                            if (argumentList != null) {
                                // TODO : More helpful message. NOTE: there's a separate handling for this for constructors
                                semanticServices.getErrorHandler().genericError(argumentList.getNode(), "Overload ambiguity [TODO : more helpful message]");
                            }
                            else {
                                semanticServices.getErrorHandler().unresolvedReference(referenceExpression);
                            }
                            break;
                        default:
                            // Not a success
263
                    }
A
Andrey Breslav 已提交
264
                }
265 266 267 268 269
            }

            @Override
            public boolean isEmpty() {
                return overloadDomain.isEmpty();
270 271 272 273
            }
        };
    }

274

A
Andrey Breslav 已提交
275
    private JetType getBlockReturnedType(@NotNull JetScope outerScope, List<JetElement> block) {
276 277 278
        if (block.isEmpty()) {
            return JetStandardClasses.getUnitType();
        } else {
279
            DeclarationDescriptor containingDescriptor = outerScope.getContainingDeclaration();
280
            WritableScope scope = semanticServices.createWritableScope(outerScope, containingDescriptor);
A
Andrey Breslav 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293
            return getBlockReturnedTypeWithWritableScope(scope, block);
        }
    }

    private JetType getBlockReturnedTypeWithWritableScope(@NotNull WritableScope scope, @NotNull List<? extends JetElement> block) {
        assert !block.isEmpty();
        TypeInferrerVisitorWithWritableScope blockLevelVisitor = new TypeInferrerVisitorWithWritableScope(scope, true);
        JetType result = null;
        for (JetElement statement : block) {
            statement.accept(blockLevelVisitor);
            result = blockLevelVisitor.getResult();
            if (result != null) {
                trace.recordExpressionType((JetExpression) statement, result);
294
            }
A
Andrey Breslav 已提交
295
            blockLevelVisitor.resetResult(); // TODO : maybe it's better to recreate the visitors with the same scope?
296
        }
A
Andrey Breslav 已提交
297
        return result;
298 299
    }

A
Andrey Breslav 已提交
300
    private void collectAllReturnTypes(JetWhenExpression whenExpression, JetScope scope, List<JetType> result) {
301 302 303 304 305 306 307 308 309 310 311 312 313
        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));
                }
            }
        }
    }

A
Andrey Breslav 已提交
314 315
    private class TypeInferrerVisitor extends JetVisitor {
        private final JetScope scope;
A
Andrey Breslav 已提交
316
        protected JetType result;
A
Andrey Breslav 已提交
317 318 319 320 321 322 323 324 325 326 327 328
        private final boolean preferBlock;

        public TypeInferrerVisitor(JetScope scope, boolean preferBlock) {
            this.scope = scope;
            this.preferBlock = preferBlock;
        }

        public JetType getResult() {
            return result;
        }

        @Override
329
        public void visitSimpleNameExpression(JetSimpleNameExpression expression) {
A
Andrey Breslav 已提交
330 331 332
            // TODO : other members
            // TODO : type substitutions???
            String referencedName = expression.getReferencedName();
333 334 335 336
            if (referencedName != null) {
                PropertyDescriptor property = scope.getProperty(referencedName);
                if (property != null) {
                    trace.recordReferenceResolution(expression, property);
A
Andrey Breslav 已提交
337
                    result = property.getOutType();
338 339 340
                    if (result == null) {
                        semanticServices.getErrorHandler().genericError(expression.getNode(), "This property is not readable in this context");
                    }
A
Andrey Breslav 已提交
341
                    return;
342 343 344 345 346 347 348
                } else {
                    NamespaceDescriptor namespace = scope.getNamespace(referencedName);
                    if (namespace != null) {
                        trace.recordReferenceResolution(expression, namespace);
                        result = namespace.getNamespaceType();
                        return;
                    }
A
Andrey Breslav 已提交
349
                }
350
                semanticServices.getErrorHandler().unresolvedReference(expression);
A
Andrey Breslav 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            }
        }

        @Override
        public void visitFunctionLiteralExpression(JetFunctionLiteralExpression expression) {
            if (preferBlock && !expression.hasParameterSpecification()) {
                result = getBlockReturnedType(scope, expression.getBody());
                return;
            }

            FunctionDescriptorImpl functionDescriptor = new FunctionDescriptorImpl(scope.getContainingDeclaration(), Collections.<Attribute>emptyList(), "<anonymous>");

            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();
            final Map<String, PropertyDescriptor> parameterDescriptors = new HashMap<String, PropertyDescriptor>();
            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");
                }
381
                PropertyDescriptor propertyDescriptor = classDescriptorResolver.resolveValueParameterDescriptor(functionDescriptor, scope, parameter);
A
Andrey Breslav 已提交
382
                parameterDescriptors.put(parameter.getName(), propertyDescriptor);
A
Andrey Breslav 已提交
383
                parameterTypes.add(propertyDescriptor.getOutType());
A
Andrey Breslav 已提交
384 385 386 387 388
            }
            JetType returnType;
            if (returnTypeRef != null) {
                returnType = typeResolver.resolveType(scope, returnTypeRef);
            } else {
389
                WritableScope writableScope = semanticServices.createWritableScope(scope, functionDescriptor);
A
Andrey Breslav 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 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 462 463 464
                for (PropertyDescriptor propertyDescriptor : parameterDescriptors.values()) {
                    writableScope.addPropertyDescriptor(propertyDescriptor);
                }
                writableScope.setThisType(receiverType);
                returnType = getBlockReturnedType(writableScope, body);
            }
            result = JetStandardClasses.getFunctionType(null, receiverTypeRef == null ? null : receiverType, parameterTypes, returnType);
        }

        @Override
        public void visitParenthesizedExpression(JetParenthesizedExpression expression) {
            result = getType(scope, expression.getExpression(), false);
        }

        @Override
        public void visitConstantExpression(JetConstantExpression expression) {
            IElementType elementType = expression.getNode().getElementType();
            JetStandardLibrary standardLibrary = semanticServices.getStandardLibrary();
            if (elementType == JetNodeTypes.INTEGER_CONSTANT) {
                result = standardLibrary.getIntType();
            } else if (elementType == JetNodeTypes.LONG_CONSTANT) {
                result = standardLibrary.getLongType();
            } else if (elementType == JetNodeTypes.FLOAT_CONSTANT) {
                String text = expression.getText();
                assert text.length() > 0;
                char lastChar = text.charAt(text.length() - 1);
                if (lastChar == 'f' || lastChar == 'F') {
                    result = standardLibrary.getFloatType();
                } else {
                    result = standardLibrary.getDoubleType();
                }
            } else if (elementType == JetNodeTypes.BOOLEAN_CONSTANT) {
                result = standardLibrary.getBooleanType();
            } else if (elementType == JetNodeTypes.CHARACTER_CONSTANT) {
                result = standardLibrary.getCharType();
            } else if (elementType == JetNodeTypes.STRING_CONSTANT) {
                result = standardLibrary.getStringType();
            } else if (elementType == JetNodeTypes.NULL) {
                result = JetStandardClasses.getNullableNothingType();
            } else {
                throw new IllegalArgumentException("Unsupported constant: " + expression);
            }
        }

        @Override
        public void visitThrowExpression(JetThrowExpression expression) {
            result = JetStandardClasses.getNothingType();
        }

        @Override
        public void visitReturnExpression(JetReturnExpression expression) {
            JetExpression returnedExpression = expression.getReturnedExpression();
            if (returnedExpression != null) {
                getType(scope, returnedExpression, false);
            }
            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) {
            throw new UnsupportedOperationException("Return some reflection interface"); // TODO
        }

        @Override
        public void visitBinaryWithTypeRHSExpression(JetBinaryExpressionWithTypeRHS expression) {
A
Andrey Breslav 已提交
465 466 467 468 469 470 471 472 473
            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)) {
                        semanticServices.getErrorHandler().typeMismatch(expression.getLeft(), targetType, actualType);
                    }
A
Andrey Breslav 已提交
474
                }
A
Andrey Breslav 已提交
475 476 477 478
                else if (operationType == JetTokens.AS_KEYWORD) {
                    // TODO : Check for cast impossibility
                }
                else {
A
Andrey Breslav 已提交
479
                    semanticServices.getErrorHandler().genericError(expression.getOperationSign().getNode(), "Unsupported binary operation");
A
Andrey Breslav 已提交
480 481
                }
                result = targetType;
A
Andrey Breslav 已提交
482 483 484 485
            }
        }

        @Override
486 487 488 489 490 491 492 493 494
        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 已提交
495

496 497 498 499 500 501 502 503 504 505
        @Override
        public void visitThisExpression(JetThisExpression expression) {
            // TODO : qualified this, e.g. Foo.this<Bar>
            JetType thisType = scope.getThisType();
            JetTypeReference superTypeQualifier = expression.getSuperTypeQualifier();
            if (superTypeQualifier != null) {
                // This cast must be safe (assuming the PSI doesn't contain errors)
                JetUserType typeElement = (JetUserType) superTypeQualifier.getTypeElement();
                ClassDescriptor superclass = typeResolver.resolveClass(scope, typeElement);
                Collection<? extends JetType> supertypes = thisType.getConstructor().getSupertypes();
506
                Map<TypeConstructor, TypeProjection> substitutionContext = TypeUtils.buildSubstitutionContext(thisType);
507 508
                for (JetType declaredSupertype : supertypes) {
                    if (declaredSupertype.getConstructor().equals(superclass.getTypeConstructor())) {
509
                        result = TypeSubstitutor.INSTANCE.safeSubstitute(substitutionContext, declaredSupertype, Variance.INVARIANT);
510 511
                        break;
                    }
A
Andrey Breslav 已提交
512
                }
513
                assert result != null;
A
Andrey Breslav 已提交
514
            } else {
515
                result = thisType;
A
Andrey Breslav 已提交
516 517 518
            }
        }

519 520 521 522 523
        @Override
        public void visitBlockExpression(JetBlockExpression expression) {
            result = getBlockReturnedType(scope, expression.getStatements());
        }

A
Andrey Breslav 已提交
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 550
        @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>();
            if (finallyBlock == null) {
                for (JetCatchClause catchClause : catchClauses) {
                    // TODO: change scope here
                    types.add(getType(scope, catchClause.getCatchBody(), true));
                }
            } else {
                types.add(getType(scope, finallyBlock.getFinalExpression(), true));
            }
            types.add(getType(scope, tryBlock, true));
            result = semanticServices.getTypeChecker().commonSupertype(types);
        }

        @Override
551 552 553
        public void visitIfExpression(JetIfExpression expression) {
            checkCondition(scope, expression.getCondition());

554
            // TODO : change types according to is and null checks
555
            JetExpression elseBranch = expression.getElse();
556 557 558 559 560 561
            JetExpression thenBranch = expression.getThen();
            JetType thenType = null;
            if (thenBranch != null) {
                thenType = getType(scope, thenBranch, true);
            }
            if (elseBranch != null) {
562
                JetType elseType = getType(scope, elseBranch, true);
563 564 565 566 567 568 569 570 571 572 573 574
                if (thenType == null) {
                    result = elseType;
                }
                else if (elseType == null) {
                    result = thenType;
                }
                else {
                    result = semanticServices.getTypeChecker().commonSupertype(Arrays.asList(thenType, elseType));
                }
            }
            else {
                result = JetStandardClasses.getUnitType();
A
Andrey Breslav 已提交
575 576 577
            }
        }

578 579 580 581 582 583
        private void checkCondition(@NotNull JetScope scope, @Nullable JetExpression condition) {
            if (condition != null) {
                JetType conditionType = getType(scope, condition, false);

                if (conditionType != null && !isBoolean(conditionType)) {
                    semanticServices.getErrorHandler().genericError(condition.getNode(), "Condition must be of type Boolean, but was of type " + conditionType);
A
Andrey Breslav 已提交
584 585 586 587 588
                }
            }
        }

        @Override
589 590 591 592 593 594 595
        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 已提交
596 597 598
        }

        @Override
599 600
        public void visitDoWhileExpression(JetDoWhileExpression expression) {
            JetExpression body = expression.getBody();
A
Andrey Breslav 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
            JetScope conditionScope = scope;
            if (body instanceof JetFunctionLiteralExpression) {
                JetFunctionLiteralExpression function = (JetFunctionLiteralExpression) body;
                if (!function.hasParameterSpecification()) {
                    WritableScope writableScope = semanticServices.createWritableScope(scope, scope.getContainingDeclaration());
                    conditionScope = writableScope;
                    getBlockReturnedTypeWithWritableScope(writableScope, function.getBody());
                } else {
                    getType(scope, body, true);
                }
            }
            else if (body != null) {
                WritableScope writableScope = semanticServices.createWritableScope(scope, scope.getContainingDeclaration());
                conditionScope = writableScope;
                getBlockReturnedTypeWithWritableScope(writableScope, Collections.singletonList(body));
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
            }
            checkCondition(conditionScope, expression.getCondition());
            result = JetStandardClasses.getUnitType();
        }

        @Override
        public void visitForExpression(JetForExpression expression) {
            JetParameter loopParameter = expression.getLoopParameter();
            JetExpression loopRange = expression.getLoopRange();
            JetType loopRangeType = getType(scope, loopRange, false);
            JetType expectedParameterType = null;
            if (loopRangeType != null) {
                if (!semanticServices.getTypeChecker().isSubtypeOf(loopRangeType, semanticServices.getStandardLibrary().getIterableType(JetStandardClasses.getNullableAnyType()))) {
                    semanticServices.getErrorHandler().genericError(loopRange.getNode(), "Expecting an Iterable, but found " + loopRangeType);
                }
                else {
                    TypeProjection typeProjection = loopRangeType.getArguments().get(0);
                    if (!typeProjection.getProjectionKind().allowsOutPosition()) {
                        expectedParameterType = JetStandardClasses.getDefaultBound();
                    }
                    else {
                        expectedParameterType = typeProjection.getType();
                    }
                }
            }

            WritableScope loopScope = semanticServices.createWritableScope(scope, scope.getContainingDeclaration());

            JetTypeReference typeReference = loopParameter.getTypeReference();
            PropertyDescriptor propertyDescriptor;
            if (typeReference != null) {
647
                propertyDescriptor = semanticServices.getClassDescriptorResolver(trace).resolveValueParameterDescriptor(scope.getContainingDeclaration(), scope, loopParameter);
A
Andrey Breslav 已提交
648
                JetType actualParameterType = propertyDescriptor.getOutType();
649 650 651 652 653 654 655 656 657
                if (expectedParameterType != null &&
                        !semanticServices.getTypeChecker().isSubtypeOf(expectedParameterType, actualParameterType)) {
                    semanticServices.getErrorHandler().genericError(typeReference.getNode(), "The loop iterates over values of type " + expectedParameterType + " but the parameter is declared to be " + actualParameterType);
                }
            }
            else {
                if (expectedParameterType == null) {
                    expectedParameterType = ErrorType.createErrorType("Error");
                }
658
                propertyDescriptor = semanticServices.getClassDescriptorResolver(trace).resolveValueParameterDescriptor(scope.getContainingDeclaration(), loopParameter, expectedParameterType);
659 660 661 662 663 664 665 666
            }
            loopScope.addPropertyDescriptor(propertyDescriptor);

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

A
Andrey Breslav 已提交
667 668 669 670 671 672 673
            result = JetStandardClasses.getUnitType();
        }

        @Override
        public void visitNewExpression(JetNewExpression expression) {
            // TODO : type argument inference
            JetTypeReference typeReference = expression.getTypeReference();
674
            if (typeReference != null) {
675 676 677 678 679 680 681 682 683 684 685 686 687
                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;

688 689 690 691 692 693 694 695 696 697 698 699 700
                        for (JetTypeProjection typeProjection : userType.getTypeArguments()) {
                            switch (typeProjection.getProjectionKind()) {
                                case IN:
                                case OUT:
                                case STAR:
                                    // TODO : Bug in the editor
                                    semanticServices.getErrorHandler().genericError(typeProjection.getProjectionNode(), "Projections are not allowed in constructor type arguments");
                                    break;
                                case NONE:
                                    break;
                            }
                        }

701 702
                        JetSimpleNameExpression referenceExpression = userType.getReferenceExpression();
                        if (referenceExpression != null) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                            // 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);
726
                            OverloadDomain constructorsOverloadDomain = semanticServices.getOverloadResolver().getOverloadDomain(constructors);
727
                            JetType constructorReturnedType = resolveOverloads(
728
                                    scope,
729
                                    wrapForTracing(constructorsOverloadDomain, referenceExpression, expression.getArgumentList(), false),
730 731 732
                                    Collections.<JetTypeProjection>emptyList(),
                                    expression.getArguments(),
                                    expression.getFunctionLiteralArguments());
733
                            if (constructorReturnedType == null && !ErrorType.isErrorType(receiverType)) {
734 735 736 737 738 739
                                trace.recordReferenceResolution(referenceExpression, receiverType.getConstructor().getDeclarationDescriptor());
                                // TODO : more helpful message
                                JetArgumentList argumentList = expression.getArgumentList();
                                if (argumentList != null) {
                                    semanticServices.getErrorHandler().genericError(argumentList.getNode(), "Cannot find an overload for these arguments");
                                }
740
                                constructorReturnedType = receiverType;
741
                            }
742 743 744 745
                            // If no upcast needed:
                            result = constructorReturnedType;

                            // Automatic upcast:
746
//                            result = receiverType;
747 748 749 750 751 752 753
                        }
                    }
                    else {
                        semanticServices.getErrorHandler().genericError(expression.getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : review the message
                    }
                }
                else {
754 755 756
                    if (typeElement != null) {
                        semanticServices.getErrorHandler().genericError(typeElement.getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : Better message
                    }
757
                }
758
            }
A
Andrey Breslav 已提交
759 760 761
        }

        @Override
A
Andrey Breslav 已提交
762 763 764 765 766 767
        public void visitHashQualifiedExpression(JetHashQualifiedExpression expression) {
            throw new UnsupportedOperationException(); // TODO
        }

        @Override
        public void visitQualifiedExpression(JetQualifiedExpression expression) {
A
Andrey Breslav 已提交
768 769
            // TODO : functions
            JetExpression selectorExpression = expression.getSelectorExpression();
770
            JetExpression receiverExpression = expression.getReceiverExpression();
A
Andrey Breslav 已提交
771
            JetType receiverType = getType(scope, receiverExpression, false);
A
Andrey Breslav 已提交
772 773
            if (receiverType != null) {
                checkNullSafety(receiverType, expression);
A
Andrey Breslav 已提交
774 775 776 777 778 779 780
                JetType selectorReturnType = getSelectorReturnType(receiverType, selectorExpression);
                if (expression.getOperationSign() == JetTokens.QUEST) {
                    if (selectorReturnType != null && !isBoolean(selectorReturnType)) {
                        // TODO : more comprehensible error message
                        semanticServices.getErrorHandler().typeMismatch(selectorExpression, semanticServices.getStandardLibrary().getBooleanType(), selectorReturnType);
                    }
                    result = TypeUtils.makeNullable(receiverType);
A
Andrey Breslav 已提交
781
                }
A
Andrey Breslav 已提交
782 783
                else {
                    result = selectorReturnType;
784
                }
785 786 787
                if (selectorExpression != null && result != null) {
                    trace.recordExpressionType(selectorExpression, result);
                }
A
Andrey Breslav 已提交
788 789 790
            }
        }

A
Andrey Breslav 已提交
791 792 793 794
        private JetType getSelectorReturnType(JetType receiverType, JetExpression selectorExpression) {
            JetScope compositeScope = new ScopeWithReceiver(scope, receiverType);
            if (selectorExpression instanceof JetCallExpression) {
                JetCallExpression callExpression = (JetCallExpression) selectorExpression;
795
                OverloadDomain overloadDomain = getOverloadDomain(compositeScope, callExpression.getCalleeExpression(), callExpression.getValueArgumentList());
A
Andrey Breslav 已提交
796 797 798 799 800 801 802
                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
803
                semanticServices.getErrorHandler().genericError(selectorExpression.getNode(), "Unsupported selector expression type: " + selectorExpression);
A
Andrey Breslav 已提交
804 805 806 807
            }
            return receiverType;
        }

A
Andrey Breslav 已提交
808 809 810
        @Override
        public void visitCallExpression(JetCallExpression expression) {
            JetExpression calleeExpression = expression.getCalleeExpression();
811
            OverloadDomain overloadDomain = getOverloadDomain(scope, calleeExpression, expression.getValueArgumentList());
A
Andrey Breslav 已提交
812
            result = resolveOverloads(scope, expression, overloadDomain);
813
        }
A
Andrey Breslav 已提交
814

815
        @Nullable
A
Andrey Breslav 已提交
816
        private JetType resolveOverloads(JetScope scope, JetCallExpression expression, OverloadDomain overloadDomain) {
817 818 819 820 821 822 823 824 825 826 827 828 829
            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) {
A
Andrey Breslav 已提交
830 831 832
            // 1) ends with a name -> (scope, name) to look up
            // 2) ends with something else -> just check types

833 834 835 836 837
            for (JetTypeProjection typeArgument : typeArguments) {
                if (typeArgument.getProjectionKind() != JetProjectionKind.NONE) {
                    semanticServices.getErrorHandler().genericError(typeArgument.getNode(), "Projections are not allowed on type parameters for methods"); // TODO : better positioning
                }
            }
A
Andrey Breslav 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864

            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
                    types.add(typeResolver.resolveType(scope, projection.getTypeReference()));
                }

                List<JetExpression> positionedValueArguments = new ArrayList<JetExpression>();
                for (JetArgument argument : valueArguments) {
865 866 867 868
                    JetExpression argumentExpression = argument.getArgumentExpression();
                    if (argumentExpression != null) {
                        positionedValueArguments.add(argumentExpression);
                    }
A
Andrey Breslav 已提交
869 870 871 872 873 874
                }

                positionedValueArguments.addAll(functionLiteralArguments);

                List<JetType> valueArgumentTypes = new ArrayList<JetType>();
                for (JetExpression valueArgument : positionedValueArguments) {
A
Andrey Breslav 已提交
875
                    valueArgumentTypes.add(safeGetType(scope, valueArgument, false));
A
Andrey Breslav 已提交
876 877
                }

878 879 880
                OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(types, valueArgumentTypes);
                if (resolutionResult.isSuccess()) {
                    return resolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
A
Andrey Breslav 已提交
881 882
                }
            }
A
Andrey Breslav 已提交
883
            return null;
A
Andrey Breslav 已提交
884 885
        }

A
Andrey Breslav 已提交
886 887 888 889 890 891 892
        @Override
        public void visitIsExpression(JetIsExpression expression) {
            // TODO : patterns and everything
            System.out.println("Pattern matching is not supported yet.");
            result = semanticServices.getStandardLibrary().getBooleanType();
        }

A
Andrey Breslav 已提交
893
        @Override
894
        public void visitUnaryExpression(JetUnaryExpression expression) {
A
Andrey Breslav 已提交
895
            JetSimpleNameExpression operationSign = expression.getOperationSign();
A
Andrey Breslav 已提交
896 897
            IElementType operationType = operationSign.getReferencedNameElementType();
            String name = unaryOperationNames.get(operationType);
898
            if (name == null) {
A
Andrey Breslav 已提交
899
                semanticServices.getErrorHandler().genericError(operationSign.getNode(), "Unknown unary operation");
900 901
            }
            else {
A
Andrey Breslav 已提交
902 903 904
                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 已提交
905
                    if (functionDescriptor != null) {
A
Andrey Breslav 已提交
906 907 908 909 910 911 912 913 914 915
                        JetType returnType = functionDescriptor.getUnsubstitutedReturnType();
                        if (operationType == JetTokens.PLUSPLUS || operationType == JetTokens.MINUSMINUS) {
                            if (!semanticServices.getTypeChecker().isSubtypeOf(returnType, receiverType)) {
                                 semanticServices.getErrorHandler().genericError(operationSign.getNode(), name + " must return " + receiverType + " but returns " + returnType);
                            }
                            // TODO : Maybe returnType?
                            result = receiverType;
                        } else {
                            result = returnType;
                        }
A
Andrey Breslav 已提交
916 917 918 919 920 921 922 923 924
                    }
                }
            }
        }

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

A
Andrey Breslav 已提交
925 926 927
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();

A
Andrey Breslav 已提交
928 929
            IElementType operationType = operationSign.getReferencedNameElementType();
            if (operationType == JetTokens.IDENTIFIER) {
930 931 932 933
                String referencedName = operationSign.getReferencedName();
                if (referencedName != null) {
                    result = getTypeForBinaryCall(expression, referencedName, scope, true);
                }
A
Andrey Breslav 已提交
934
            }
935
            else if (binaryOperationNames.containsKey(operationType)) {
A
Andrey Breslav 已提交
936
                result = getTypeForBinaryCall(expression, binaryOperationNames.get(operationType), scope, true);
A
Andrey Breslav 已提交
937 938
            }
            else if (operationType == JetTokens.EQ) {
A
Andrey Breslav 已提交
939 940 941 942
                visitAssignment(expression);
            }
            else if (assignmentOperationNames.containsKey(operationType)) {
                visitAssignmentOperation(expression);
A
Andrey Breslav 已提交
943
            }
944
            else if (comparisonOperations.contains(operationType)) {
A
Andrey Breslav 已提交
945
                JetType compareToReturnType = getTypeForBinaryCall(expression, "compareTo", scope, true);
A
Andrey Breslav 已提交
946 947 948 949 950 951 952
                if (compareToReturnType != null) {
                    TypeConstructor constructor = compareToReturnType.getConstructor();
                    JetStandardLibrary standardLibrary = semanticServices.getStandardLibrary();
                    TypeConstructor intTypeConstructor = standardLibrary.getInt().getTypeConstructor();
                    if (constructor.equals(intTypeConstructor)) {
                        result = standardLibrary.getBooleanType();
                    } else {
A
Andrey Breslav 已提交
953
                        semanticServices.getErrorHandler().genericError(operationSign.getNode(), "compareTo must return Int, but returns " + compareToReturnType);
A
Andrey Breslav 已提交
954
                    }
A
Andrey Breslav 已提交
955
                }
A
Andrey Breslav 已提交
956
            }
A
Equals  
Andrey Breslav 已提交
957
            else if (equalsOperations.contains(operationType)) {
A
Andrey Breslav 已提交
958 959 960 961 962 963 964 965
                String name = "equals";
                JetType equalsType = getTypeForBinaryCall(expression, name, scope, true);
                assureBooleanResult(operationSign, name, equalsType);
            }
            else if (inOperations.contains(operationType)) {
                if (right == null) {
                    result = ErrorType.createErrorType("No right argument"); // TODO
                    return;
A
Andrey Breslav 已提交
966
                }
A
Andrey Breslav 已提交
967 968 969
                String name = "contains";
                JetType containsType = getTypeForBinaryCall(scope, right, expression.getOperationReference(), expression.getLeft(), name, true);
                result = assureBooleanResult(operationSign, name, containsType);
A
Equals  
Andrey Breslav 已提交
970
            }
A
Andrey Breslav 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
            else if (operationType == JetTokens.EQEQEQ || operationType == JetTokens.EXCLEQEQEQ) {
                JetType leftType = getType(scope, left, false);
                JetType rightType = right == null ? null : getType(scope, right, false);
                // TODO : Check comparison pointlessness
                result = semanticServices.getStandardLibrary().getBooleanType();
            }
            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)) {
                    semanticServices.getErrorHandler().typeMismatch(left, semanticServices.getStandardLibrary().getBooleanType(), leftType);
                }
                if (rightType != null && !isBoolean(rightType)) {
                    semanticServices.getErrorHandler().typeMismatch(left, semanticServices.getStandardLibrary().getBooleanType(), rightType);
                    semanticServices.getErrorHandler().typeMismatch(right, semanticServices.getStandardLibrary().getBooleanType(), rightType);
                }
                result = semanticServices.getStandardLibrary().getBooleanType();
            }
A
Andrey Breslav 已提交
989 990 991 992 993 994 995 996 997 998 999 1000
            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()) {
                        semanticServices.getErrorHandler().genericWarning(left.getNode(), "Elvis operator (?:) is always returns the left operand of non-nullable type " + leftType);
                    }
                    if (rightType != null) {
                        result = TypeUtils.makeNullableAsSpecified(semanticServices.getTypeChecker().commonSupertype(leftType, rightType), rightType.isNullable());
                    }
                }
            }
A
Equals  
Andrey Breslav 已提交
1001
            else {
A
Andrey Breslav 已提交
1002
                semanticServices.getErrorHandler().genericError(operationSign.getNode(), "Unknown operation");
A
Andrey Breslav 已提交
1003 1004 1005
            }
        }

A
Andrey Breslav 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        protected void visitAssignmentOperation(JetBinaryExpression expression) {
            assignmentIsNotAnExpressionError(expression);
        }

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

        private void assignmentIsNotAnExpressionError(JetBinaryExpression expression) {
            semanticServices.getErrorHandler().genericError(expression.getNode(), "Assignments are not expressions, and only expressions are allowed in this context");
        }

A
Andrey Breslav 已提交
1018 1019 1020
        private JetType assureBooleanResult(JetSimpleNameExpression operationSign, String name, JetType resultType) {
            if (resultType != null) {
                // TODO : Relax?
A
Andrey Breslav 已提交
1021
                if (!isBoolean(resultType)) {
A
Andrey Breslav 已提交
1022
                    semanticServices.getErrorHandler().genericError(operationSign.getNode(), "'" + name + "' must return Boolean but returns " + resultType);
A
Andrey Breslav 已提交
1023 1024 1025 1026 1027 1028 1029 1030
                    return null;
                } else {
                    return resultType;
                }
            }
            return resultType;
        }

A
Andrey Breslav 已提交
1031
        private boolean isBoolean(@NotNull JetType type) {
A
Andrey Breslav 已提交
1032
            TypeConstructor booleanTypeConstructor = semanticServices.getStandardLibrary().getBoolean().getTypeConstructor();
A
Andrey Breslav 已提交
1033
            return type.getConstructor().equals(booleanTypeConstructor) || ErrorType.isErrorType(type);
A
Andrey Breslav 已提交
1034 1035
        }

A
Andrey Breslav 已提交
1036 1037 1038 1039 1040 1041 1042 1043
        @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;

1044 1045 1046 1047 1048
            if (receiverType != null) {
                FunctionDescriptor functionDescriptor = lookupFunction(scope, expression, "get", receiverType, argumentTypes, true);
                if (functionDescriptor != null) {
                    result = functionDescriptor.getUnsubstitutedReturnType();
                }
A
Andrey Breslav 已提交
1049 1050 1051
            }
        }

1052
        @Nullable
A
Andrey Breslav 已提交
1053
        protected JetType getTypeForBinaryCall(JetBinaryExpression expression, @NotNull String name, JetScope scope, boolean reportUnresolved) {
A
Andrey Breslav 已提交
1054 1055 1056
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();
            if (right == null) {
1057
                return null;
A
Andrey Breslav 已提交
1058
            }
A
Andrey Breslav 已提交
1059 1060 1061 1062
            JetSimpleNameExpression operationSign = expression.getOperationReference();
            return getTypeForBinaryCall(scope, left, operationSign, right, name, reportUnresolved);
        }

1063
        @Nullable
A
Andrey Breslav 已提交
1064
        private JetType getTypeForBinaryCall(JetScope scope, JetExpression left, JetSimpleNameExpression operationSign, @NotNull JetExpression right, String name, boolean reportUnresolved) {
1065 1066
            JetType leftType = safeGetType(scope, left, false);
            JetType rightType = safeGetType(scope, right, false);
1067 1068 1069
            if (ErrorType.isErrorType(leftType)) {
                return null;
            }
A
Andrey Breslav 已提交
1070
            FunctionDescriptor functionDescriptor = lookupFunction(scope, operationSign, name, leftType, Collections.singletonList(rightType), reportUnresolved);
A
Andrey Breslav 已提交
1071 1072 1073 1074 1075
            if (functionDescriptor != null) {
                return functionDescriptor.getUnsubstitutedReturnType();
            }
            return null;
        }
A
Andrey Breslav 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101

        @Override
        public void visitDeclaration(JetDeclaration dcl) {
            semanticServices.getErrorHandler().genericError(dcl.getNode(), "Declarations are not allowed in this position");
        }

        @Override
        public void visitJetElement(JetElement elem) {
            semanticServices.getErrorHandler().genericError(elem.getNode(), "Unsupported element: " + elem + " " + elem.getClass().getCanonicalName());
        }
    }

    private class TypeInferrerVisitorWithWritableScope extends TypeInferrerVisitor {
        private final WritableScope scope;

        public TypeInferrerVisitorWithWritableScope(@NotNull WritableScope scope, boolean preferBlock) {
            super(scope, preferBlock);
            this.scope = scope;
        }

        public void resetResult() {
            this.result = null;
        }

        @Override
        public void visitProperty(JetProperty property) {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

            JetPropertyAccessor getter = property.getGetter();
            if (getter != null) {
                semanticServices.getErrorHandler().genericError(getter.getNode(), "Local variables are not allowed to have getters");
            }

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

A
Andrey Breslav 已提交
1113
            PropertyDescriptor propertyDescriptor = classDescriptorResolver.resolvePropertyDescriptor(scope.getContainingDeclaration(), scope, property);
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
            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)) {
                    semanticServices.getErrorHandler().typeMismatch(initializer, outType, initializerType);
                }
            }

A
Andrey Breslav 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
            scope.addPropertyDescriptor(propertyDescriptor);
        }

        @Override
        public void visitFunction(JetFunction function) {
            super.visitFunction(function); // TODO
        }

        @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);
            }
            result = null; // not an expression
        }

        @Override
        protected void visitAssignment(JetBinaryExpression expression) {
            JetExpression left = expression.getLeft();
            JetExpression deparenthesized = deparenthesize(left);
            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)) {
                        semanticServices.getErrorHandler().typeMismatch(right, leftType, rightType);
                    }
                }
            }
            result = null; // This is not an expression
        }

        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) {
            semanticServices.getErrorHandler().genericError(elem.getNode(), "Unsupported element in a block: " + elem + " " + elem.getClass().getCanonicalName());
        }
A
Andrey Breslav 已提交
1211
    }
1212
}