JetTypeInferrer.java 62.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
        if (type != null) {
            return type;
        }
A
rename  
Andrey Breslav 已提交
81
        return ErrorUtils.createErrorType("Type for " + expression.getText());
82
    }
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
    @Nullable
    private static JetExpression deparenthesize(@NotNull JetExpression expression) {
        JetExpression result = expression;
        while (result instanceof JetParenthesizedExpression) {
            result = ((JetParenthesizedExpression) expression).getExpression();
100
        }
101
        return result;
102 103
    }

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

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

131

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

159
                JetExpression selectorExpression = expression.getSelectorExpression();
160 161
                if (selectorExpression instanceof JetSimpleNameExpression) {
                    JetSimpleNameExpression referenceExpression = (JetSimpleNameExpression) selectorExpression;
162
                    String referencedName = referenceExpression.getReferencedName();
163

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

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

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

            @Override
            public void visitJetElement(JetElement elem) {
191
                semanticServices.getErrorHandler().genericError(elem.getNode(), "Unsupported in call expression"); // TODO : Message
192 193
            }
        });
194
        return wrapForTracing(result[0], reference[0], argumentList, true);
195 196
    }

A
Andrey Breslav 已提交
197 198
    private void checkNullSafety(JetType receiverType, JetQualifiedExpression expression) {
        if (receiverType != null) {
199 200 201
            boolean namespaceType = receiverType instanceof NamespaceType;
            boolean nullable = !namespaceType && receiverType.isNullable();
            if (nullable && expression.getOperationSign() == JetTokens.DOT) {
A
Andrey Breslav 已提交
202 203
                semanticServices.getErrorHandler().genericError(expression.getOperationTokenNode(), "Only safe calls (?.) are allowed on a nullable receiver of type " + receiverType);
            }
204 205 206 207 208 209 210
            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 已提交
211 212 213 214
            }
        }
    }

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

231
            @NotNull
232
            @Override
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            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
251
                                semanticServices.getErrorHandler().genericError(argumentList.getNode(), "Arguments do not match " + DescriptorUtil.renderPresentableText(resolutionResult.getFunctionDescriptor()));
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                            }
                            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
268
                    }
A
Andrey Breslav 已提交
269
                }
270 271 272 273 274
            }

            @Override
            public boolean isEmpty() {
                return overloadDomain.isEmpty();
275 276 277 278
            }
        };
    }

279

A
Andrey Breslav 已提交
280
    private JetType getBlockReturnedType(@NotNull JetScope outerScope, List<JetElement> block) {
281 282 283
        if (block.isEmpty()) {
            return JetStandardClasses.getUnitType();
        } else {
284
            DeclarationDescriptor containingDescriptor = outerScope.getContainingDeclaration();
285
            WritableScope scope = semanticServices.createWritableScope(outerScope, containingDescriptor);
A
Andrey Breslav 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298
            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);
299
            }
A
Andrey Breslav 已提交
300
            blockLevelVisitor.resetResult(); // TODO : maybe it's better to recreate the visitors with the same scope?
301
        }
A
Andrey Breslav 已提交
302
        return result;
303 304
    }

A
Andrey Breslav 已提交
305
    private void collectAllReturnTypes(JetWhenExpression whenExpression, JetScope scope, List<JetType> result) {
306 307 308 309 310 311 312 313 314 315 316 317 318
        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 已提交
319 320
    private class TypeInferrerVisitor extends JetVisitor {
        private final JetScope scope;
A
Andrey Breslav 已提交
321
        protected JetType result;
A
Andrey Breslav 已提交
322 323 324 325 326 327 328 329 330 331 332 333
        private final boolean preferBlock;

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

        public JetType getResult() {
            return result;
        }

        @Override
334
        public void visitSimpleNameExpression(JetSimpleNameExpression expression) {
A
Andrey Breslav 已提交
335 336 337
            // TODO : other members
            // TODO : type substitutions???
            String referencedName = expression.getReferencedName();
338 339 340 341
            if (referencedName != null) {
                PropertyDescriptor property = scope.getProperty(referencedName);
                if (property != null) {
                    trace.recordReferenceResolution(expression, property);
A
Andrey Breslav 已提交
342
                    result = property.getOutType();
343 344 345
                    if (result == null) {
                        semanticServices.getErrorHandler().genericError(expression.getNode(), "This property is not readable in this context");
                    }
A
Andrey Breslav 已提交
346
                    return;
347 348 349 350 351 352 353
                } else {
                    NamespaceDescriptor namespace = scope.getNamespace(referencedName);
                    if (namespace != null) {
                        trace.recordReferenceResolution(expression, namespace);
                        result = namespace.getNamespaceType();
                        return;
                    }
A
Andrey Breslav 已提交
354
                }
355
                semanticServices.getErrorHandler().unresolvedReference(expression);
A
Andrey Breslav 已提交
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 381 382 383 384 385
            }
        }

        @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");
                }
386
                PropertyDescriptor propertyDescriptor = classDescriptorResolver.resolveValueParameterDescriptor(functionDescriptor, scope, parameter);
A
Andrey Breslav 已提交
387
                parameterDescriptors.put(parameter.getName(), propertyDescriptor);
A
Andrey Breslav 已提交
388
                parameterTypes.add(propertyDescriptor.getOutType());
A
Andrey Breslav 已提交
389 390 391 392 393
            }
            JetType returnType;
            if (returnTypeRef != null) {
                returnType = typeResolver.resolveType(scope, returnTypeRef);
            } else {
394
                WritableScope writableScope = semanticServices.createWritableScope(scope, functionDescriptor);
A
Andrey Breslav 已提交
395 396 397 398 399 400 401 402 403 404 405
                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) {
406 407 408 409
            JetExpression inner = expression.getExpression();
            if (inner != null) {
                result = getType(scope, inner, false);
            }
A
Andrey Breslav 已提交
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 465 466 467 468 469 470 471 472
        }

        @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 已提交
473 474 475 476 477 478 479 480 481
            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 已提交
482
                }
A
Andrey Breslav 已提交
483 484 485 486
                else if (operationType == JetTokens.AS_KEYWORD) {
                    // TODO : Check for cast impossibility
                }
                else {
A
Andrey Breslav 已提交
487
                    semanticServices.getErrorHandler().genericError(expression.getOperationSign().getNode(), "Unsupported binary operation");
A
Andrey Breslav 已提交
488 489
                }
                result = targetType;
A
Andrey Breslav 已提交
490 491 492 493
            }
        }

        @Override
494 495 496 497 498 499 500 501 502
        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 已提交
503

504 505
        @Override
        public void visitThisExpression(JetThisExpression expression) {
506
            // TODO : qualified this, e.g. this@Foo<Bar>
507 508 509
            JetType thisType = scope.getThisType();
            JetTypeReference superTypeQualifier = expression.getSuperTypeQualifier();
            if (superTypeQualifier != null) {
510 511 512 513
                JetTypeElement superTypeElement = superTypeQualifier.getTypeElement();
                // Errors are reported by the parser
                if (superTypeElement instanceof JetUserType) {
                    JetUserType typeElement = (JetUserType) superTypeElement;
A
Andrey Breslav 已提交
514 515 516 517 518

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

519 520 521 522 523 524 525 526 527 528 529
                        Collection<? extends JetType> supertypes = thisType.getConstructor().getSupertypes();
                        Map<TypeConstructor, TypeProjection> substitutionContext = TypeUtils.buildSubstitutionContext(thisType);
                        for (JetType declaredSupertype : supertypes) {
                            if (declaredSupertype.getConstructor().equals(superclass.getTypeConstructor())) {
                                result = TypeSubstitutor.INSTANCE.safeSubstitute(substitutionContext, declaredSupertype, Variance.INVARIANT);
                                break;
                            }
                        }
                        if (result == null) {
                            semanticServices.getErrorHandler().genericError(superTypeElement.getNode(), "Not a superclass");
                        }
530
                    }
A
Andrey Breslav 已提交
531
                }
A
Andrey Breslav 已提交
532
            } else {
533
                result = thisType;
A
Andrey Breslav 已提交
534 535 536
            }
        }

537 538 539 540 541
        @Override
        public void visitBlockExpression(JetBlockExpression expression) {
            result = getBlockReturnedType(scope, expression.getStatements());
        }

A
Andrey Breslav 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
        @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
559 560 561 562
                    JetExpression catchBody = catchClause.getCatchBody();
                    if (catchBody != null) {
                        types.add(getType(scope, catchBody, true));
                    }
A
Andrey Breslav 已提交
563 564 565 566 567 568 569 570 571
                }
            } else {
                types.add(getType(scope, finallyBlock.getFinalExpression(), true));
            }
            types.add(getType(scope, tryBlock, true));
            result = semanticServices.getTypeChecker().commonSupertype(types);
        }

        @Override
572 573 574
        public void visitIfExpression(JetIfExpression expression) {
            checkCondition(scope, expression.getCondition());

575
            // TODO : change types according to is and null checks
576
            JetExpression elseBranch = expression.getElse();
577 578 579 580 581 582
            JetExpression thenBranch = expression.getThen();
            JetType thenType = null;
            if (thenBranch != null) {
                thenType = getType(scope, thenBranch, true);
            }
            if (elseBranch != null) {
583
                JetType elseType = getType(scope, elseBranch, true);
584 585 586 587 588 589 590 591 592 593 594 595
                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 已提交
596 597 598
            }
        }

599 600 601 602 603 604
        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 已提交
605 606 607 608 609
                }
            }
        }

        @Override
610 611 612 613 614 615 616
        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 已提交
617 618 619
        }

        @Override
620 621
        public void visitDoWhileExpression(JetDoWhileExpression expression) {
            JetExpression body = expression.getBody();
A
Andrey Breslav 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
            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));
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
            }
            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) {
668
                propertyDescriptor = classDescriptorResolver.resolveValueParameterDescriptor(scope.getContainingDeclaration(), scope, loopParameter);
A
Andrey Breslav 已提交
669
                JetType actualParameterType = propertyDescriptor.getOutType();
670
                if (expectedParameterType != null &&
671
                        actualParameterType != null &&
672 673 674 675 676 677
                        !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) {
A
rename  
Andrey Breslav 已提交
678
                    expectedParameterType = ErrorUtils.createErrorType("Error");
679
                }
680
                propertyDescriptor = classDescriptorResolver.resolveValueParameterDescriptor(scope.getContainingDeclaration(), loopParameter, expectedParameterType);
681 682 683 684 685 686 687 688
            }
            loopScope.addPropertyDescriptor(propertyDescriptor);

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

A
Andrey Breslav 已提交
689 690 691 692 693 694 695
            result = JetStandardClasses.getUnitType();
        }

        @Override
        public void visitNewExpression(JetNewExpression expression) {
            // TODO : type argument inference
            JetTypeReference typeReference = expression.getTypeReference();
696
            if (typeReference != null) {
697 698 699 700 701 702 703 704 705 706 707 708 709
                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;

710 711 712 713 714 715 716 717 718 719 720 721 722
                        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;
                            }
                        }

723 724
                        JetSimpleNameExpression referenceExpression = userType.getReferenceExpression();
                        if (referenceExpression != null) {
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
                            // 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);
748
                            OverloadDomain constructorsOverloadDomain = semanticServices.getOverloadResolver().getOverloadDomain(constructors);
749
                            JetType constructorReturnedType = resolveOverloads(
750
                                    scope,
751
                                    wrapForTracing(constructorsOverloadDomain, referenceExpression, expression.getArgumentList(), false),
752 753 754
                                    Collections.<JetTypeProjection>emptyList(),
                                    expression.getArguments(),
                                    expression.getFunctionLiteralArguments());
A
rename  
Andrey Breslav 已提交
755
                            if (constructorReturnedType == null && !ErrorUtils.isErrorType(receiverType)) {
756 757 758 759 760 761
                                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");
                                }
762
                                constructorReturnedType = receiverType;
763
                            }
764 765 766 767
                            // If no upcast needed:
                            result = constructorReturnedType;

                            // Automatic upcast:
768
//                            result = receiverType;
769 770 771 772 773 774 775
                        }
                    }
                    else {
                        semanticServices.getErrorHandler().genericError(expression.getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : review the message
                    }
                }
                else {
776 777 778
                    if (typeElement != null) {
                        semanticServices.getErrorHandler().genericError(typeElement.getNode(), "Calling a constructor is only supported for ordinary classes"); // TODO : Better message
                    }
779
                }
780
            }
A
Andrey Breslav 已提交
781 782 783
        }

        @Override
A
Andrey Breslav 已提交
784 785 786 787 788 789
        public void visitHashQualifiedExpression(JetHashQualifiedExpression expression) {
            throw new UnsupportedOperationException(); // TODO
        }

        @Override
        public void visitQualifiedExpression(JetQualifiedExpression expression) {
A
Andrey Breslav 已提交
790 791
            // TODO : functions
            JetExpression selectorExpression = expression.getSelectorExpression();
792
            JetExpression receiverExpression = expression.getReceiverExpression();
A
Andrey Breslav 已提交
793
            JetType receiverType = getType(scope, receiverExpression, false);
A
Andrey Breslav 已提交
794 795
            if (receiverType != null) {
                checkNullSafety(receiverType, expression);
A
Andrey Breslav 已提交
796 797 798 799 800 801 802
                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 已提交
803
                }
A
Andrey Breslav 已提交
804 805
                else {
                    result = selectorReturnType;
806
                }
807 808 809
                if (selectorExpression != null && result != null) {
                    trace.recordExpressionType(selectorExpression, result);
                }
A
Andrey Breslav 已提交
810 811 812
            }
        }

A
Andrey Breslav 已提交
813 814 815 816
        private JetType getSelectorReturnType(JetType receiverType, JetExpression selectorExpression) {
            JetScope compositeScope = new ScopeWithReceiver(scope, receiverType);
            if (selectorExpression instanceof JetCallExpression) {
                JetCallExpression callExpression = (JetCallExpression) selectorExpression;
817
                OverloadDomain overloadDomain = getOverloadDomain(compositeScope, callExpression.getCalleeExpression(), callExpression.getValueArgumentList());
A
Andrey Breslav 已提交
818 819 820 821 822 823 824
                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
825
                semanticServices.getErrorHandler().genericError(selectorExpression.getNode(), "Unsupported selector expression type: " + selectorExpression);
A
Andrey Breslav 已提交
826 827 828 829
            }
            return receiverType;
        }

A
Andrey Breslav 已提交
830 831 832
        @Override
        public void visitCallExpression(JetCallExpression expression) {
            JetExpression calleeExpression = expression.getCalleeExpression();
833
            OverloadDomain overloadDomain = getOverloadDomain(scope, calleeExpression, expression.getValueArgumentList());
A
Andrey Breslav 已提交
834
            result = resolveOverloads(scope, expression, overloadDomain);
835
        }
A
Andrey Breslav 已提交
836

837
        @Nullable
A
Andrey Breslav 已提交
838
        private JetType resolveOverloads(JetScope scope, JetCallExpression expression, OverloadDomain overloadDomain) {
839 840 841 842 843 844 845 846 847 848 849 850 851
            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 已提交
852 853 854
            // 1) ends with a name -> (scope, name) to look up
            // 2) ends with something else -> just check types

855 856 857 858 859
            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 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881

            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
882 883 884 885
                    JetTypeReference typeReference = projection.getTypeReference();
                    if (typeReference != null) {
                        types.add(typeResolver.resolveType(scope, typeReference));
                    }
A
Andrey Breslav 已提交
886 887 888 889
                }

                List<JetExpression> positionedValueArguments = new ArrayList<JetExpression>();
                for (JetArgument argument : valueArguments) {
890 891 892 893
                    JetExpression argumentExpression = argument.getArgumentExpression();
                    if (argumentExpression != null) {
                        positionedValueArguments.add(argumentExpression);
                    }
A
Andrey Breslav 已提交
894 895 896 897 898 899
                }

                positionedValueArguments.addAll(functionLiteralArguments);

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

903 904 905
                OverloadResolutionResult resolutionResult = overloadDomain.getFunctionDescriptorForPositionedArguments(types, valueArgumentTypes);
                if (resolutionResult.isSuccess()) {
                    return resolutionResult.getFunctionDescriptor().getUnsubstitutedReturnType();
A
Andrey Breslav 已提交
906 907
                }
            }
A
Andrey Breslav 已提交
908
            return null;
A
Andrey Breslav 已提交
909 910
        }

A
Andrey Breslav 已提交
911 912 913 914 915 916
        @Override
        public void visitIsExpression(JetIsExpression expression) {
            // TODO : patterns and everything
            result = semanticServices.getStandardLibrary().getBooleanType();
        }

A
Andrey Breslav 已提交
917
        @Override
918
        public void visitUnaryExpression(JetUnaryExpression expression) {
A
Andrey Breslav 已提交
919
            JetSimpleNameExpression operationSign = expression.getOperationSign();
A
Andrey Breslav 已提交
920 921
            IElementType operationType = operationSign.getReferencedNameElementType();
            String name = unaryOperationNames.get(operationType);
922
            if (name == null) {
A
Andrey Breslav 已提交
923
                semanticServices.getErrorHandler().genericError(operationSign.getNode(), "Unknown unary operation");
924 925
            }
            else {
A
Andrey Breslav 已提交
926 927 928
                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 已提交
929
                    if (functionDescriptor != null) {
A
Andrey Breslav 已提交
930 931 932 933 934 935 936 937 938 939
                        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 已提交
940 941 942 943 944 945 946 947 948
                    }
                }
            }
        }

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

A
Andrey Breslav 已提交
949 950 951
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();

A
Andrey Breslav 已提交
952 953
            IElementType operationType = operationSign.getReferencedNameElementType();
            if (operationType == JetTokens.IDENTIFIER) {
954 955 956 957
                String referencedName = operationSign.getReferencedName();
                if (referencedName != null) {
                    result = getTypeForBinaryCall(expression, referencedName, scope, true);
                }
A
Andrey Breslav 已提交
958
            }
959
            else if (binaryOperationNames.containsKey(operationType)) {
A
Andrey Breslav 已提交
960
                result = getTypeForBinaryCall(expression, binaryOperationNames.get(operationType), scope, true);
A
Andrey Breslav 已提交
961 962
            }
            else if (operationType == JetTokens.EQ) {
A
Andrey Breslav 已提交
963 964 965 966
                visitAssignment(expression);
            }
            else if (assignmentOperationNames.containsKey(operationType)) {
                visitAssignmentOperation(expression);
A
Andrey Breslav 已提交
967
            }
968
            else if (comparisonOperations.contains(operationType)) {
A
Andrey Breslav 已提交
969
                JetType compareToReturnType = getTypeForBinaryCall(expression, "compareTo", scope, true);
A
Andrey Breslav 已提交
970 971 972 973 974 975 976
                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 已提交
977
                        semanticServices.getErrorHandler().genericError(operationSign.getNode(), "compareTo must return Int, but returns " + compareToReturnType);
A
Andrey Breslav 已提交
978
                    }
A
Andrey Breslav 已提交
979
                }
A
Andrey Breslav 已提交
980
            }
A
Equals  
Andrey Breslav 已提交
981
            else if (equalsOperations.contains(operationType)) {
A
Andrey Breslav 已提交
982 983
                String name = "equals";
                JetType equalsType = getTypeForBinaryCall(expression, name, scope, true);
A
Andrey Breslav 已提交
984 985
                result = assureBooleanResult(operationSign, name, equalsType);

986 987 988 989 990 991 992
                ensureNonemptyIntersectionOfOperandTypes(expression);
            }
            else if (operationType == JetTokens.EQEQEQ || operationType == JetTokens.EXCLEQEQEQ) {
                ensureNonemptyIntersectionOfOperandTypes(expression);

                // TODO : Check comparison pointlessness
                result = semanticServices.getStandardLibrary().getBooleanType();
A
Andrey Breslav 已提交
993 994 995
            }
            else if (inOperations.contains(operationType)) {
                if (right == null) {
A
rename  
Andrey Breslav 已提交
996
                    result = ErrorUtils.createErrorType("No right argument"); // TODO
A
Andrey Breslav 已提交
997
                    return;
A
Andrey Breslav 已提交
998
                }
A
Andrey Breslav 已提交
999 1000 1001
                String name = "contains";
                JetType containsType = getTypeForBinaryCall(scope, right, expression.getOperationReference(), expression.getLeft(), name, true);
                result = assureBooleanResult(operationSign, name, containsType);
A
Equals  
Andrey Breslav 已提交
1002
            }
A
Andrey Breslav 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
            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 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
            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 已提交
1027
            else {
A
Andrey Breslav 已提交
1028
                semanticServices.getErrorHandler().genericError(operationSign.getNode(), "Unknown operation");
A
Andrey Breslav 已提交
1029 1030 1031
            }
        }

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        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);
            if (right != null) {
                JetType rightType = getType(scope, right, false);

                JetType intersect = TypeUtils.intersect(semanticServices.getTypeChecker(), new HashSet<JetType>(Arrays.asList(leftType, rightType)));
                if (intersect == null) {
                    semanticServices.getErrorHandler().genericError(expression.getNode(), "Operator " + operationSign.getReferencedName() + " cannot be applied to " + leftType + " and " + rightType);
                }
            }
        }

A
Andrey Breslav 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        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 已提交
1061 1062 1063
        private JetType assureBooleanResult(JetSimpleNameExpression operationSign, String name, JetType resultType) {
            if (resultType != null) {
                // TODO : Relax?
A
Andrey Breslav 已提交
1064
                if (!isBoolean(resultType)) {
A
Andrey Breslav 已提交
1065
                    semanticServices.getErrorHandler().genericError(operationSign.getNode(), "'" + name + "' must return Boolean but returns " + resultType);
A
Andrey Breslav 已提交
1066 1067 1068 1069 1070 1071 1072 1073
                    return null;
                } else {
                    return resultType;
                }
            }
            return resultType;
        }

A
Andrey Breslav 已提交
1074
        private boolean isBoolean(@NotNull JetType type) {
A
Andrey Breslav 已提交
1075
            TypeConstructor booleanTypeConstructor = semanticServices.getStandardLibrary().getBoolean().getTypeConstructor();
A
rename  
Andrey Breslav 已提交
1076
            return type.getConstructor().equals(booleanTypeConstructor) || ErrorUtils.isErrorType(type);
A
Andrey Breslav 已提交
1077 1078
        }

A
Andrey Breslav 已提交
1079 1080 1081 1082 1083 1084 1085 1086
        @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;

1087 1088 1089 1090 1091
            if (receiverType != null) {
                FunctionDescriptor functionDescriptor = lookupFunction(scope, expression, "get", receiverType, argumentTypes, true);
                if (functionDescriptor != null) {
                    result = functionDescriptor.getUnsubstitutedReturnType();
                }
A
Andrey Breslav 已提交
1092 1093 1094
            }
        }

1095
        @Nullable
A
Andrey Breslav 已提交
1096
        protected JetType getTypeForBinaryCall(JetBinaryExpression expression, @NotNull String name, JetScope scope, boolean reportUnresolved) {
A
Andrey Breslav 已提交
1097 1098 1099
            JetExpression left = expression.getLeft();
            JetExpression right = expression.getRight();
            if (right == null) {
1100
                return null;
A
Andrey Breslav 已提交
1101
            }
A
Andrey Breslav 已提交
1102 1103 1104 1105
            JetSimpleNameExpression operationSign = expression.getOperationReference();
            return getTypeForBinaryCall(scope, left, operationSign, right, name, reportUnresolved);
        }

1106
        @Nullable
A
Andrey Breslav 已提交
1107
        private JetType getTypeForBinaryCall(JetScope scope, JetExpression left, JetSimpleNameExpression operationSign, @NotNull JetExpression right, String name, boolean reportUnresolved) {
1108 1109
            JetType leftType = safeGetType(scope, left, false);
            JetType rightType = safeGetType(scope, right, false);
A
rename  
Andrey Breslav 已提交
1110
            if (ErrorUtils.isErrorType(leftType)) {
1111 1112
                return null;
            }
A
Andrey Breslav 已提交
1113
            FunctionDescriptor functionDescriptor = lookupFunction(scope, operationSign, name, leftType, Collections.singletonList(rightType), reportUnresolved);
A
Andrey Breslav 已提交
1114 1115 1116 1117 1118
            if (functionDescriptor != null) {
                return functionDescriptor.getUnsubstitutedReturnType();
            }
            return null;
        }
A
Andrey Breslav 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

        @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) {
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

            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 已提交
1156
            PropertyDescriptor propertyDescriptor = classDescriptorResolver.resolvePropertyDescriptor(scope.getContainingDeclaration(), scope, property);
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
            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 已提交
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 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
            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 已提交
1254
    }
1255
}