Search in sources :

Example 41 with KotlinType

use of org.jetbrains.kotlin.types.KotlinType in project kotlin by JetBrains.

the class ExpectedResolveData method checkResult.

public final void checkResult(BindingContext bindingContext) {
    Set<PsiElement> unresolvedReferences = Sets.newHashSet();
    for (Diagnostic diagnostic : bindingContext.getDiagnostics()) {
        if (Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS.contains(diagnostic.getFactory())) {
            unresolvedReferences.add(diagnostic.getPsiElement());
        }
    }
    Map<String, PsiElement> nameToDeclaration = Maps.newHashMap();
    Map<PsiElement, String> declarationToName = Maps.newHashMap();
    for (Map.Entry<String, Position> entry : declarationToPosition.entrySet()) {
        String name = entry.getKey();
        Position position = entry.getValue();
        PsiElement element = position.getElement();
        PsiElement ancestorOfType;
        if (name.equals("file")) {
            ancestorOfType = element.getContainingFile();
        } else {
            ancestorOfType = getAncestorOfType(KtDeclaration.class, element);
            if (ancestorOfType == null) {
                KtPackageDirective directive = getAncestorOfType(KtPackageDirective.class, element);
                assert directive != null : "Not a declaration: " + name;
                ancestorOfType = element;
            }
        }
        nameToDeclaration.put(name, ancestorOfType);
        declarationToName.put(ancestorOfType, name);
    }
    for (Map.Entry<Position, String> entry : positionToReference.entrySet()) {
        Position position = entry.getKey();
        String name = entry.getValue();
        PsiElement element = position.getElement();
        KtReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(element, KtReferenceExpression.class);
        DeclarationDescriptor referenceTarget = bindingContext.get(REFERENCE_TARGET, referenceExpression);
        if ("!".equals(name)) {
            assertTrue("Must have been unresolved: " + renderReferenceInContext(referenceExpression) + " but was resolved to " + renderNullableDescriptor(referenceTarget), unresolvedReferences.contains(referenceExpression));
            assertTrue(String.format("Reference =%s= has a reference target =%s= but expected to be unresolved", renderReferenceInContext(referenceExpression), renderNullableDescriptor(referenceTarget)), referenceTarget == null);
            continue;
        }
        if ("!!".equals(name)) {
            assertTrue("Must have been resolved to multiple descriptors: " + renderReferenceInContext(referenceExpression) + " but was resolved to " + renderNullableDescriptor(referenceTarget), bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null);
            continue;
        } else if ("!null".equals(name)) {
            assertTrue("Must have been resolved to null: " + renderReferenceInContext(referenceExpression) + " but was resolved to " + renderNullableDescriptor(referenceTarget), referenceTarget == null);
            continue;
        } else if ("!error".equals(name)) {
            assertTrue("Must have been resolved to error: " + renderReferenceInContext(referenceExpression) + " but was resolved to " + renderNullableDescriptor(referenceTarget), ErrorUtils.isError(referenceTarget));
            continue;
        }
        PsiElement expected = nameToDeclaration.get(name);
        if (expected == null) {
            expected = nameToPsiElement.get(name);
        }
        KtReferenceExpression reference = getAncestorOfType(KtReferenceExpression.class, element);
        if (expected == null && name.startsWith(STANDARD_PREFIX)) {
            DeclarationDescriptor expectedDescriptor = nameToDescriptor.get(name);
            KtTypeReference typeReference = getAncestorOfType(KtTypeReference.class, element);
            if (expectedDescriptor != null) {
                DeclarationDescriptor actual = bindingContext.get(REFERENCE_TARGET, reference);
                assertDescriptorsEqual("Expected: " + name, expectedDescriptor.getOriginal(), actual == null ? null : actual.getOriginal());
                continue;
            }
            KotlinType actualType = bindingContext.get(BindingContext.TYPE, typeReference);
            assertNotNull("Type " + name + " not resolved for reference " + name, actualType);
            ClassifierDescriptor expectedClass = getBuiltinClass(name.substring(STANDARD_PREFIX.length()));
            assertTypeConstructorEquals("Type resolution mismatch: ", expectedClass.getTypeConstructor(), actualType.getConstructor());
            continue;
        }
        assert expected != null : "No declaration for " + name;
        if (referenceTarget instanceof PackageViewDescriptor) {
            KtPackageDirective expectedDirective = PsiTreeUtil.getParentOfType(expected, KtPackageDirective.class);
            FqName expectedFqName;
            if (expectedDirective != null) {
                expectedFqName = expectedDirective.getFqName();
            } else if (expected instanceof PsiQualifiedNamedElement) {
                String qualifiedName = ((PsiQualifiedNamedElement) expected).getQualifiedName();
                assert qualifiedName != null : "No qualified name for " + name;
                expectedFqName = new FqName(qualifiedName);
            } else {
                throw new IllegalStateException(expected.getClass().getName() + " name=" + name);
            }
            assertEquals(expectedFqName, ((PackageViewDescriptor) referenceTarget).getFqName());
            continue;
        }
        PsiElement actual = referenceTarget == null ? bindingContext.get(BindingContext.LABEL_TARGET, referenceExpression) : DescriptorToSourceUtils.descriptorToDeclaration(referenceTarget);
        if (actual instanceof KtSimpleNameExpression) {
            actual = ((KtSimpleNameExpression) actual).getIdentifier();
        }
        String actualName = null;
        if (actual != null) {
            actualName = declarationToName.get(actual);
            if (actualName == null) {
                actualName = actual.toString();
            }
        }
        assertNotNull(element.getText(), reference);
        assertEquals("Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", expected, actual);
    }
    for (Map.Entry<Position, String> entry : positionToType.entrySet()) {
        Position position = entry.getKey();
        String typeName = entry.getValue();
        PsiElement element = position.getElement();
        KtExpression expression = getAncestorOfType(KtExpression.class, element);
        KotlinType expressionType = bindingContext.getType(expression);
        TypeConstructor expectedTypeConstructor;
        if (typeName.startsWith(STANDARD_PREFIX)) {
            String name = typeName.substring(STANDARD_PREFIX.length());
            ClassifierDescriptor expectedClass = getBuiltinClass(name);
            expectedTypeConstructor = expectedClass.getTypeConstructor();
        } else {
            Position declarationPosition = declarationToPosition.get(typeName);
            assertNotNull("Undeclared: " + typeName, declarationPosition);
            PsiElement declElement = declarationPosition.getElement();
            assertNotNull(declarationPosition);
            KtDeclaration declaration = getAncestorOfType(KtDeclaration.class, declElement);
            assertNotNull(declaration);
            if (declaration instanceof KtClass) {
                ClassDescriptor classDescriptor = bindingContext.get(BindingContext.CLASS, declaration);
                expectedTypeConstructor = classDescriptor.getTypeConstructor();
            } else if (declaration instanceof KtTypeParameter) {
                TypeParameterDescriptor typeParameterDescriptor = bindingContext.get(BindingContext.TYPE_PARAMETER, (KtTypeParameter) declaration);
                expectedTypeConstructor = typeParameterDescriptor.getTypeConstructor();
            } else {
                fail("Unsupported declaration: " + declaration);
                return;
            }
        }
        assertNotNull(expression.getText() + " type is null", expressionType);
        assertTypeConstructorEquals("At " + position + ": ", expectedTypeConstructor, expressionType.getConstructor());
    }
}
Also used : FqName(org.jetbrains.kotlin.name.FqName) KotlinType(org.jetbrains.kotlin.types.KotlinType) Diagnostic(org.jetbrains.kotlin.diagnostics.Diagnostic) PsiQualifiedNamedElement(com.intellij.psi.PsiQualifiedNamedElement) PsiElement(com.intellij.psi.PsiElement) TypeConstructor(org.jetbrains.kotlin.types.TypeConstructor) Map(java.util.Map)

Example 42 with KotlinType

use of org.jetbrains.kotlin.types.KotlinType in project kotlin by JetBrains.

the class HtmlTabledDescriptorRenderer method renderFunctionArguments.

private void renderFunctionArguments(@Nullable KotlinType receiverType, @NotNull List<KotlinType> argumentTypes, Predicate<ConstraintPosition> isErrorPosition, StringBuilder result, @NotNull RenderingContext context) {
    boolean hasReceiver = receiverType != null;
    tdSpace(result);
    String receiver = "";
    if (hasReceiver) {
        boolean error = false;
        if (isErrorPosition.apply(RECEIVER_POSITION.position())) {
            error = true;
        }
        receiver = "receiver: " + RenderersUtilKt.renderStrong(getTypeRenderer().render(receiverType, context), error);
    }
    td(result, receiver);
    td(result, hasReceiver ? "arguments: " : "");
    if (argumentTypes.isEmpty()) {
        tdBold(result, "( )");
        return;
    }
    td(result, RenderersUtilKt.renderStrong("("));
    int i = 0;
    for (Iterator<KotlinType> iterator = argumentTypes.iterator(); iterator.hasNext(); ) {
        KotlinType argumentType = iterator.next();
        boolean error = false;
        if (isErrorPosition.apply(VALUE_PARAMETER_POSITION.position(i))) {
            error = true;
        }
        String renderedArgument = argumentType == null ? "unknown" : getTypeRenderer().render(argumentType, context);
        tdRight(result, RenderersUtilKt.renderStrong(renderedArgument, error) + (iterator.hasNext() ? RenderersUtilKt.renderStrong(",") : ""));
        i++;
    }
    td(result, RenderersUtilKt.renderStrong(")"));
}
Also used : KotlinType(org.jetbrains.kotlin.types.KotlinType)

Example 43 with KotlinType

use of org.jetbrains.kotlin.types.KotlinType in project kotlin by JetBrains.

the class DestructuringDeclarationTranslator method translate.

private JsVars translate() {
    if (initializer != null) {
        context().getCurrentBlock().getStatements().add(JsAstUtils.newVar(multiObjectName, initializer));
    }
    List<JsVars.JsVar> jsVars = new ArrayList<JsVars.JsVar>();
    JsNameRef multiObjNameRef = multiObjectName.makeRef();
    for (KtDestructuringDeclarationEntry entry : multiDeclaration.getEntries()) {
        VariableDescriptor descriptor = BindingContextUtils.getNotNull(context().bindingContext(), BindingContext.VARIABLE, entry);
        // Do not call `componentX` for destructuring entry called _
        if (descriptor.getName().isSpecial())
            continue;
        ResolvedCall<FunctionDescriptor> entryInitCall = context().bindingContext().get(BindingContext.COMPONENT_RESOLVED_CALL, entry);
        assert entryInitCall != null : "Entry init call must be not null";
        JsExpression entryInitializer = CallTranslator.translate(context(), entryInitCall, multiObjNameRef);
        FunctionDescriptor candidateDescriptor = entryInitCall.getCandidateDescriptor();
        if (CallExpressionTranslator.shouldBeInlined(candidateDescriptor, context())) {
            setInlineCallMetadata(entryInitializer, entry, entryInitCall, context());
        }
        KotlinType returnType = candidateDescriptor.getReturnType();
        if (returnType != null && KotlinBuiltIns.isCharOrNullableChar(returnType) && !KotlinBuiltIns.isCharOrNullableChar(descriptor.getType())) {
            entryInitializer = JsAstUtils.charToBoxedChar(entryInitializer);
        }
        JsName name = context().getNameForDescriptor(descriptor);
        if (isVarCapturedInClosure(context().bindingContext(), descriptor)) {
            JsNameRef alias = getCapturedVarAccessor(name.makeRef());
            entryInitializer = JsAstUtils.wrapValue(alias, entryInitializer);
        }
        jsVars.add(new JsVars.JsVar(name, entryInitializer));
    }
    return new JsVars(jsVars, true);
}
Also used : JsExpression(org.jetbrains.kotlin.js.backend.ast.JsExpression) KotlinType(org.jetbrains.kotlin.types.KotlinType) ArrayList(java.util.ArrayList) FunctionDescriptor(org.jetbrains.kotlin.descriptors.FunctionDescriptor) VariableDescriptor(org.jetbrains.kotlin.descriptors.VariableDescriptor) JsName(org.jetbrains.kotlin.js.backend.ast.JsName) JsNameRef(org.jetbrains.kotlin.js.backend.ast.JsNameRef) JsVars(org.jetbrains.kotlin.js.backend.ast.JsVars) KtDestructuringDeclarationEntry(org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry)

Example 44 with KotlinType

use of org.jetbrains.kotlin.types.KotlinType in project kotlin by JetBrains.

the class ExpressionVisitor method visitReturnExpression.

@Override
@NotNull
public JsNode visitReturnExpression(@NotNull KtReturnExpression jetReturnExpression, @NotNull TranslationContext context) {
    KtExpression returned = jetReturnExpression.getReturnedExpression();
    // TODO: add related descriptor to context and use it here
    KtDeclarationWithBody parent = PsiTreeUtil.getParentOfType(jetReturnExpression, KtDeclarationWithBody.class);
    if (parent instanceof KtSecondaryConstructor) {
        return new JsReturn(new JsNameRef(Namer.ANOTHER_THIS_PARAMETER_NAME)).source(jetReturnExpression);
    }
    JsReturn jsReturn;
    if (returned == null) {
        jsReturn = new JsReturn(null);
    } else {
        JsExpression jsReturnExpression = translateAsExpression(returned, context);
        KotlinType returnedType = context.bindingContext().getType(returned);
        assert returnedType != null : "Resolved return expression is expected to have type: " + PsiUtilsKt.getTextWithLocation(jetReturnExpression);
        if (KotlinBuiltIns.isCharOrNullableChar(returnedType) && TranslationUtils.shouldBoxReturnValue((CallableDescriptor) context.getDeclarationDescriptor())) {
            jsReturnExpression = JsAstUtils.charToBoxedChar(jsReturnExpression);
        }
        jsReturn = new JsReturn(jsReturnExpression);
    }
    MetadataProperties.setReturnTarget(jsReturn, getNonLocalReturnTarget(jetReturnExpression, context));
    return jsReturn.source(jetReturnExpression);
}
Also used : KotlinType(org.jetbrains.kotlin.types.KotlinType) NotNull(org.jetbrains.annotations.NotNull)

Example 45 with KotlinType

use of org.jetbrains.kotlin.types.KotlinType in project kotlin by JetBrains.

the class ExpressionVisitor method visitClassLiteralExpression.

@Override
public JsNode visitClassLiteralExpression(@NotNull KtClassLiteralExpression expression, TranslationContext context) {
    KtExpression receiverExpression = expression.getReceiverExpression();
    assert receiverExpression != null : "Class literal expression should have a left-hand side";
    DoubleColonLHS lhs = context.bindingContext().get(DOUBLE_COLON_LHS, receiverExpression);
    assert lhs != null : "Class literal expression should have LHS resolved";
    if (lhs instanceof DoubleColonLHS.Expression && !((DoubleColonLHS.Expression) lhs).isObjectQualifier()) {
        JsExpression receiver = translateAsExpression(receiverExpression, context);
        KotlinType type = context.bindingContext().getType(receiverExpression);
        if (type != null && KotlinBuiltIns.isChar(type)) {
            receiver = JsAstUtils.charToBoxedChar(receiver);
        }
        return new JsInvocation(context.namer().kotlin(GET_KCLASS_FROM_EXPRESSION), receiver);
    }
    return new JsInvocation(context.namer().kotlin(GET_KCLASS), UtilsKt.getReferenceToJsClass(lhs.getType(), context));
}
Also used : Translation.translateAsExpression(org.jetbrains.kotlin.js.translate.general.Translation.translateAsExpression) ExpressionTypingUtils.isFunctionExpression(org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionExpression) DoubleColonLHS(org.jetbrains.kotlin.types.expressions.DoubleColonLHS) KotlinType(org.jetbrains.kotlin.types.KotlinType)

Aggregations

KotlinType (org.jetbrains.kotlin.types.KotlinType)110 NotNull (org.jetbrains.annotations.NotNull)34 IElementType (com.intellij.psi.tree.IElementType)16 Type (org.jetbrains.org.objectweb.asm.Type)16 Nullable (org.jetbrains.annotations.Nullable)10 JsExpression (org.jetbrains.kotlin.js.backend.ast.JsExpression)7 PsiElement (com.intellij.psi.PsiElement)6 Name (org.jetbrains.kotlin.name.Name)6 ArrayList (java.util.ArrayList)4 KtExpression (org.jetbrains.kotlin.psi.KtExpression)4 Map (java.util.Map)3 BothSignatureWriter (org.jetbrains.kotlin.codegen.signature.BothSignatureWriter)3 JvmSignatureWriter (org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter)3 VariableDescriptor (org.jetbrains.kotlin.descriptors.VariableDescriptor)3 LocalVariableDescriptor (org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor)3 DataFlowInfo (org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo)3 ExpressionReceiver (org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver)3 PrimitiveType (org.jetbrains.kotlin.builtins.PrimitiveType)2 CallableDescriptor (org.jetbrains.kotlin.descriptors.CallableDescriptor)2 DeclarationDescriptor (org.jetbrains.kotlin.descriptors.DeclarationDescriptor)2