Search in sources :

Example 71 with KotlinType

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

the class ExpressionTypingServices method getTypeOfLastExpressionInBlock.

private KotlinTypeInfo getTypeOfLastExpressionInBlock(@NotNull KtExpression statementExpression, @NotNull ExpressionTypingContext context, @NotNull CoercionStrategy coercionStrategyForLastExpression, @NotNull ExpressionTypingInternals blockLevelVisitor) {
    if (context.expectedType != NO_EXPECTED_TYPE) {
        KotlinType expectedType;
        if (//the first check is necessary to avoid invocation 'isUnit(UNIT_EXPECTED_TYPE)'
        context.expectedType == UNIT_EXPECTED_TYPE || (coercionStrategyForLastExpression == COERCION_TO_UNIT && KotlinBuiltIns.isUnit(context.expectedType))) {
            expectedType = UNIT_EXPECTED_TYPE;
        } else {
            expectedType = context.expectedType;
        }
        return blockLevelVisitor.getTypeInfo(statementExpression, context.replaceExpectedType(expectedType), true);
    }
    KotlinTypeInfo result = blockLevelVisitor.getTypeInfo(statementExpression, context, true);
    if (coercionStrategyForLastExpression == COERCION_TO_UNIT) {
        boolean mightBeUnit = false;
        if (statementExpression instanceof KtDeclaration) {
            if (!(statementExpression instanceof KtNamedFunction) || statementExpression.getName() != null) {
                mightBeUnit = true;
            }
        }
        if (statementExpression instanceof KtBinaryExpression) {
            KtBinaryExpression binaryExpression = (KtBinaryExpression) statementExpression;
            IElementType operationType = binaryExpression.getOperationToken();
            //noinspection SuspiciousMethodCalls
            if (operationType == KtTokens.EQ || OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) {
                mightBeUnit = true;
            }
        }
        if (mightBeUnit) {
            // but (for correct assignment / initialization analysis) data flow info must be preserved
            assert result.getType() == null || KotlinBuiltIns.isUnit(result.getType());
            result = result.replaceType(expressionTypingComponents.builtIns.getUnitType());
        }
    }
    return result;
}
Also used : IElementType(com.intellij.psi.tree.IElementType) KotlinType(org.jetbrains.kotlin.types.KotlinType)

Example 72 with KotlinType

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

the class CallResolver method resolveFunctionCall.

@NotNull
public OverloadResolutionResults<FunctionDescriptor> resolveFunctionCall(@NotNull BasicCallResolutionContext context) {
    ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
    Call.CallType callType = context.call.getCallType();
    if (callType == Call.CallType.ARRAY_GET_METHOD || callType == Call.CallType.ARRAY_SET_METHOD) {
        Name name = callType == Call.CallType.ARRAY_GET_METHOD ? OperatorNameConventions.GET : OperatorNameConventions.SET;
        KtArrayAccessExpression arrayAccessExpression = (KtArrayAccessExpression) context.call.getCallElement();
        return computeTasksAndResolveCall(context, name, arrayAccessExpression, NewResolutionOldInference.ResolutionKind.Function.INSTANCE);
    }
    KtExpression calleeExpression = context.call.getCalleeExpression();
    if (calleeExpression instanceof KtSimpleNameExpression) {
        KtSimpleNameExpression expression = (KtSimpleNameExpression) calleeExpression;
        return computeTasksAndResolveCall(context, expression.getReferencedNameAsName(), expression, NewResolutionOldInference.ResolutionKind.Function.INSTANCE);
    } else if (calleeExpression instanceof KtConstructorCalleeExpression) {
        return (OverloadResolutionResults) resolveCallForConstructor(context, (KtConstructorCalleeExpression) calleeExpression);
    } else if (calleeExpression instanceof KtConstructorDelegationReferenceExpression) {
        KtConstructorDelegationCall delegationCall = (KtConstructorDelegationCall) context.call.getCallElement();
        DeclarationDescriptor container = context.scope.getOwnerDescriptor();
        assert container instanceof ConstructorDescriptor : "Trying to resolve JetConstructorDelegationCall not in constructor. scope.ownerDescriptor = " + container;
        return (OverloadResolutionResults) resolveConstructorDelegationCall(context, delegationCall, (KtConstructorDelegationReferenceExpression) calleeExpression, (ClassConstructorDescriptor) container);
    } else if (calleeExpression == null) {
        return checkArgumentTypesAndFail(context);
    }
    // Here we handle the case where the callee expression must be something of type function, e.g. (foo.bar())(1, 2)
    KotlinType expectedType = NO_EXPECTED_TYPE;
    if (calleeExpression instanceof KtLambdaExpression) {
        int parameterNumber = ((KtLambdaExpression) calleeExpression).getValueParameters().size();
        List<KotlinType> parameterTypes = new ArrayList<KotlinType>(parameterNumber);
        for (int i = 0; i < parameterNumber; i++) {
            parameterTypes.add(NO_EXPECTED_TYPE);
        }
        expectedType = FunctionTypesKt.createFunctionType(builtIns, Annotations.Companion.getEMPTY(), null, parameterTypes, null, context.expectedType);
    }
    KotlinType calleeType = expressionTypingServices.safeGetType(context.scope, calleeExpression, expectedType, context.dataFlowInfo, context.trace);
    ExpressionReceiver expressionReceiver = ExpressionReceiver.Companion.create(calleeExpression, calleeType, context.trace.getBindingContext());
    Call call = new CallTransformer.CallForImplicitInvoke(context.call.getExplicitReceiver(), expressionReceiver, context.call, false);
    TracingStrategyForInvoke tracingForInvoke = new TracingStrategyForInvoke(calleeExpression, call, calleeType);
    return resolveCallForInvoke(context.replaceCall(call), tracingForInvoke);
}
Also used : OverloadResolutionResults(org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults) KotlinType(org.jetbrains.kotlin.types.KotlinType) Name(org.jetbrains.kotlin.name.Name) ExpressionReceiver(org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver) NotNull(org.jetbrains.annotations.NotNull)

Example 73 with KotlinType

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

the class CallResolver method resolveConstructorDelegationCall.

@NotNull
private OverloadResolutionResults<ConstructorDescriptor> resolveConstructorDelegationCall(@NotNull BasicCallResolutionContext context, @NotNull KtConstructorDelegationCall call, @NotNull KtConstructorDelegationReferenceExpression calleeExpression, @NotNull ClassConstructorDescriptor calleeConstructor) {
    context.trace.record(BindingContext.LEXICAL_SCOPE, call, context.scope);
    ClassDescriptor currentClassDescriptor = calleeConstructor.getContainingDeclaration();
    boolean isThisCall = calleeExpression.isThis();
    if (currentClassDescriptor.getKind() == ClassKind.ENUM_CLASS && !isThisCall) {
        context.trace.report(DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR.on(calleeExpression));
        return checkArgumentTypesAndFail(context);
    }
    ClassDescriptor delegateClassDescriptor = isThisCall ? currentClassDescriptor : DescriptorUtilsKt.getSuperClassOrAny(currentClassDescriptor);
    Collection<ClassConstructorDescriptor> constructors = delegateClassDescriptor.getConstructors();
    if (!isThisCall && currentClassDescriptor.getUnsubstitutedPrimaryConstructor() != null) {
        if (DescriptorUtils.canHaveDeclaredConstructors(currentClassDescriptor)) {
            // Diagnostic is meaningless when reporting on interfaces and object
            context.trace.report(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED.on((KtConstructorDelegationCall) calleeExpression.getParent()));
        }
        if (call.isImplicit())
            return OverloadResolutionResultsImpl.nameNotFound();
    }
    if (constructors.isEmpty()) {
        context.trace.report(NO_CONSTRUCTOR.on(CallUtilKt.getValueArgumentListOrElement(context.call)));
        return checkArgumentTypesAndFail(context);
    }
    KotlinType superType = isThisCall ? calleeConstructor.getContainingDeclaration().getDefaultType() : DescriptorUtils.getSuperClassType(currentClassDescriptor);
    Pair<Collection<ResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> candidatesAndContext = prepareCandidatesAndContextForConstructorCall(superType, context);
    Collection<ResolutionCandidate<ConstructorDescriptor>> candidates = candidatesAndContext.getFirst();
    context = candidatesAndContext.getSecond();
    TracingStrategy tracing = call.isImplicit() ? new TracingStrategyForImplicitConstructorDelegationCall(call, context.call) : TracingStrategyImpl.create(calleeExpression, context.call);
    PsiElement reportOn = call.isImplicit() ? call : calleeExpression;
    if (delegateClassDescriptor.isInner() && !DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, reportOn, (ClassDescriptor) delegateClassDescriptor.getContainingDeclaration())) {
        return checkArgumentTypesAndFail(context);
    }
    return computeTasksFromCandidatesAndResolvedCall(context, candidates, tracing);
}
Also used : KotlinType(org.jetbrains.kotlin.types.KotlinType) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 74 with KotlinType

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

the class ReifiedTypeParameterSubstitutionChecker method check.

@Override
public void check(@NotNull ResolvedCall<?> resolvedCall, @NotNull PsiElement reportOn, @NotNull CallCheckerContext context) {
    Map<TypeParameterDescriptor, KotlinType> typeArguments = resolvedCall.getTypeArguments();
    for (Map.Entry<TypeParameterDescriptor, KotlinType> entry : typeArguments.entrySet()) {
        TypeParameterDescriptor parameter = entry.getKey();
        KotlinType argument = entry.getValue();
        ClassifierDescriptor argumentDeclarationDescriptor = argument.getConstructor().getDeclarationDescriptor();
        if (!parameter.isReified() && !isTypeParameterOfKotlinArray(parameter)) {
            continue;
        }
        KtTypeProjection typeProjection = CollectionsKt.getOrNull(resolvedCall.getCall().getTypeArguments(), parameter.getIndex());
        PsiElement reportErrorOn = typeProjection != null ? typeProjection : reportOn;
        if (argumentDeclarationDescriptor instanceof TypeParameterDescriptor && !((TypeParameterDescriptor) argumentDeclarationDescriptor).isReified()) {
            context.getTrace().report(Errors.TYPE_PARAMETER_AS_REIFIED.on(reportErrorOn, (TypeParameterDescriptor) argumentDeclarationDescriptor));
        } else if (TypeUtilsKt.cannotBeReified(argument)) {
            context.getTrace().report(Errors.REIFIED_TYPE_FORBIDDEN_SUBSTITUTION.on(reportErrorOn, argument));
        }
    // REIFIED_TYPE_UNSAFE_SUBSTITUTION is temporary disabled because it seems too strict now (see KT-10847)
    //else if (TypeUtilsKt.unsafeAsReifiedArgument(argument) && !hasPureReifiableAnnotation(parameter)) {
    //    context.getTrace().report(Errors.REIFIED_TYPE_UNSAFE_SUBSTITUTION.on(reportErrorOn, argument));
    //}
    }
}
Also used : TypeParameterDescriptor(org.jetbrains.kotlin.descriptors.TypeParameterDescriptor) KotlinType(org.jetbrains.kotlin.types.KotlinType) ClassifierDescriptor(org.jetbrains.kotlin.descriptors.ClassifierDescriptor) KtTypeProjection(org.jetbrains.kotlin.psi.KtTypeProjection) Map(java.util.Map) PsiElement(com.intellij.psi.PsiElement)

Example 75 with KotlinType

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

the class AbstractTracingStrategy method typeInferenceFailed.

@Override
public void typeInferenceFailed(@NotNull ResolutionContext<?> context, @NotNull InferenceErrorData data) {
    ConstraintSystem constraintSystem = data.constraintSystem;
    ConstraintSystemStatus status = constraintSystem.getStatus();
    assert !status.isSuccessful() : "Report error only for not successful constraint system";
    if (status.hasErrorInConstrainingTypes()) {
        // (it's useful, when the arguments, e.g. lambdas or calls are incomplete)
        return;
    }
    BindingTrace trace = context.trace;
    if (status.hasOnlyErrorsDerivedFrom(EXPECTED_TYPE_POSITION)) {
        KotlinType declaredReturnType = data.descriptor.getReturnType();
        if (declaredReturnType == null)
            return;
        ConstraintSystem systemWithoutExpectedTypeConstraint = filterConstraintsOut(constraintSystem, EXPECTED_TYPE_POSITION);
        KotlinType substitutedReturnType = systemWithoutExpectedTypeConstraint.getResultingSubstitutor().substitute(declaredReturnType, Variance.OUT_VARIANCE);
        //todo
        assert substitutedReturnType != null;
        assert !noExpectedType(data.expectedType) : "Expected type doesn't exist, but there is an expected type mismatch error";
        if (!DiagnosticUtilsKt.reportTypeMismatchDueToTypeProjection(context, call.getCallElement(), data.expectedType, substitutedReturnType)) {
            trace.report(TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH.on(call.getCallElement(), data.expectedType, substitutedReturnType));
        }
    } else if (status.hasCannotCaptureTypesError()) {
        trace.report(TYPE_INFERENCE_CANNOT_CAPTURE_TYPES.on(reference, data));
    } else if (status.hasViolatedUpperBound()) {
        trace.report(TYPE_INFERENCE_UPPER_BOUND_VIOLATED.on(reference, data));
    } else if (status.hasParameterConstraintError()) {
        trace.report(TYPE_INFERENCE_PARAMETER_CONSTRAINT_ERROR.on(reference, data));
    } else if (status.hasConflictingConstraints()) {
        trace.report(TYPE_INFERENCE_CONFLICTING_SUBSTITUTIONS.on(reference, data));
    } else if (status.hasTypeInferenceIncorporationError()) {
        trace.report(TYPE_INFERENCE_INCORPORATION_ERROR.on(reference));
    } else if (status.hasTypeParameterWithUnsatisfiedOnlyInputTypesError()) {
        //todo
        trace.report(TYPE_INFERENCE_ONLY_INPUT_TYPES.on(reference, data.descriptor.getTypeParameters().get(0)));
    } else {
        assert status.hasUnknownParameters();
        trace.report(TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER.on(reference, data));
    }
}
Also used : BindingTrace(org.jetbrains.kotlin.resolve.BindingTrace) ConstraintSystem(org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem) KotlinType(org.jetbrains.kotlin.types.KotlinType) ConstraintSystemStatus(org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemStatus)

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