Apply constant folding for collection literals to use in annotations

Currently this is achieved with several hacks:
- Postpone computation of argument type info when there is no candidate resolver. We have to do this, because we don't have expected type and therefore we could write wrong information to trace
- Presume that for annotation calls there is only one candidate resolver and then resolve arguments with expected type (see `getArgumentTypeInfo`), otherwise because of quadratic complexity of the algorithm resolve would be slow
This commit is contained in:
Mikhail Zarechenskiy
2017-03-20 16:31:02 +03:00
parent c85f6e7d0e
commit e49b2811ec
12 changed files with 321 additions and 19 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,6 +36,8 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope;
import org.jetbrains.kotlin.storage.StorageManager;
import org.jetbrains.kotlin.types.ErrorUtils;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext;
import javax.inject.Inject;
import java.util.ArrayList;
@@ -216,6 +216,14 @@ public class ArgumentTypeResolver {
return getCallableReferenceTypeInfo(expression, callableReferenceExpression, context, resolveArgumentsMode);
}
if (isCollectionLiteralInsideAnnotation(expression, context)) {
// We assume that there is only one candidate resolver for annotation call
// And to resolve collection literal correctly, we need mapping of argument to parameter to get expected type and
// to choose corresponding call (i.e arrayOf/intArrayOf...)
ResolutionContext newContext = context.replaceContextDependency(INDEPENDENT);
return expressionTypingServices.getTypeInfo(expression, newContext);
}
KotlinTypeInfo recordedTypeInfo = getRecordedTypeInfo(expression, context.trace.getBindingContext());
if (recordedTypeInfo != null) {
return recordedTypeInfo;
@@ -356,6 +364,10 @@ public class ArgumentTypeResolver {
KtExpression expression = argument.getArgumentExpression();
if (expression == null) continue;
if (isCollectionLiteralInsideAnnotation(expression, context)) {
continue;
}
CallResolutionContext<?> newContext = context.replaceDataFlowInfo(infoForArguments.getInfo(argument));
// Here we go inside arguments and determine additional data flow information for them
KotlinTypeInfo typeInfoForCall = getArgumentTypeInfo(expression, newContext, resolveArgumentsMode);
@@ -379,4 +391,8 @@ public class ArgumentTypeResolver {
}
return null;
}
private static boolean isCollectionLiteralInsideAnnotation(KtExpression expression, CallResolutionContext<?> context) {
return expression instanceof KtCollectionLiteralExpression && context.call.getCallElement() instanceof KtAnnotationEntry;
}
}
@@ -33,6 +33,7 @@ import org.jetbrains.kotlin.name.isSubpackageOf
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.BindingContext.COLLECTION_LITERAL_CALL
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
@@ -125,12 +126,10 @@ class ConstantExpressionEvaluator(
// array(1, <!>null<!>, 3) - error should be reported on inner expression
if (argumentExpression is KtCallExpression) {
val arrayArgument = getArgumentExpressionsForArrayCall(argumentExpression, trace)
if (arrayArgument != null) {
for (expression in arrayArgument.first) {
checkCompileTimeConstant(expression, arrayArgument.second!!, trace)
}
}
getArgumentExpressionsForArrayCall(argumentExpression, trace)?.let { checkArgumentsAreCompileTimeConstants(it, trace) }
}
if (argumentExpression is KtCollectionLiteralExpression) {
getArgumentExpressionsForCollectionLiteralCall(argumentExpression, trace)?.let { checkArgumentsAreCompileTimeConstants(it, trace) }
}
val constant = ConstantExpressionEvaluator.getConstant(argumentExpression, trace.bindingContext)
@@ -164,12 +163,30 @@ class ConstantExpressionEvaluator(
}
}
private fun checkArgumentsAreCompileTimeConstants(argumentsWithComponentType: Pair<List<KtExpression>, KotlinType?>, trace: BindingTrace) {
val (arguments, componentType) = argumentsWithComponentType
for (expression in arguments) {
checkCompileTimeConstant(expression, componentType!!, trace)
}
}
private fun getArgumentExpressionsForArrayCall(
expression: KtCallExpression,
trace: BindingTrace
): Pair<List<KtExpression>, KotlinType?>? {
val resolvedCall = expression.getResolvedCall(trace.bindingContext)
if (resolvedCall == null || !CompileTimeConstantUtils.isArrayFunctionCall(resolvedCall)) {
val resolvedCall = expression.getResolvedCall(trace.bindingContext) ?: return null
return getArgumentExpressionsForArrayLikeCall(resolvedCall)
}
fun getArgumentExpressionsForCollectionLiteralCall(
expression: KtCollectionLiteralExpression,
trace: BindingTrace): Pair<List<KtExpression>, KotlinType?>? {
val resolvedCall = trace[COLLECTION_LITERAL_CALL, expression] ?: return null
return getArgumentExpressionsForArrayLikeCall(resolvedCall)
}
private fun getArgumentExpressionsForArrayLikeCall(resolvedCall: ResolvedCall<*>): Pair<List<KtExpression>, KotlinType>? {
if (!CompileTimeConstantUtils.isArrayFunctionCall(resolvedCall)) {
return null
}
@@ -448,6 +465,11 @@ private class ConstantExpressionEvaluatorVisitor(
}
}
override fun visitCollectionLiteralExpression(expression: KtCollectionLiteralExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val resolvedCall = trace.bindingContext[COLLECTION_LITERAL_CALL, expression] ?: return null
return createConstantValueForArrayFunctionCall(resolvedCall)
}
private fun evaluateCall(callExpression: KtExpression, receiverExpression: KtExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val resolvedCall = callExpression.getResolvedCall(trace.bindingContext) ?: return null
@@ -673,16 +695,7 @@ private class ConstantExpressionEvaluatorVisitor(
// arrayOf() or emptyArray()
if (CompileTimeConstantUtils.isArrayFunctionCall(call)) {
val returnType = resultingDescriptor.returnType ?: return null
val componentType = constantExpressionEvaluator.builtIns.getArrayElementType(returnType)
val arguments = call.valueArguments.values.flatMap { resolveArguments(it.arguments, componentType) }
return factory.createArrayValue(arguments.map { it.toConstantValue(componentType) }, resultingDescriptor.returnType!!).
wrap(
usesVariableAsConstant = arguments.any { it.usesVariableAsConstant },
usesNonConstValAsConstant = arguments.any { it.usesNonConstValAsConstant }
)
return createConstantValueForArrayFunctionCall(call)
}
// Ann()
@@ -701,6 +714,21 @@ private class ConstantExpressionEvaluatorVisitor(
return null
}
private fun createConstantValueForArrayFunctionCall(
call: ResolvedCall<*>
): TypedCompileTimeConstant<List<ConstantValue<*>>>? {
val returnType = call.resultingDescriptor.returnType ?: return null
val componentType = constantExpressionEvaluator.builtIns.getArrayElementType(returnType)
val arguments = call.valueArguments.values.flatMap { resolveArguments(it.arguments, componentType) }
return factory.createArrayValue(arguments.map { it.toConstantValue(componentType) }, returnType)
.wrap(
usesVariableAsConstant = arguments.any { it.usesVariableAsConstant },
usesNonConstValAsConstant = arguments.any { it.usesNonConstValAsConstant }
)
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val jetType = trace.getType(expression)!!
if (jetType.isError) return null
@@ -0,0 +1,28 @@
annotation class Foo(val a: IntArray, val b: Array<String>, val c: FloatArray)
@Foo([1], ["/"], [1f])
fun test1() {}
@Foo([], [], [])
fun test2() {}
@Foo([<!CONSTANT_EXPECTED_TYPE_MISMATCH!>1f<!>], <!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH!>[' ']<!>, [<!CONSTANT_EXPECTED_TYPE_MISMATCH!>1<!>])
fun test3() {}
@Foo(c = [1f], b = [""], a = [1])
fun test4() {}
@Foo([1 + 2], ["Hello, " + "Kotlin"], [<!DIVISION_BY_ZERO!>1 / 0f<!>])
fun test5() {}
const val ONE = 1
val two = 2
@Foo([ONE], [], [])
fun test6() {}
@Foo(<!NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION!>[<!NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION!>ONE + two<!>]<!>, [], [])
fun test7() {}
@Foo(<!NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION!>[<!NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION!>two<!>]<!>, [], [])
fun test8() {}
@@ -0,0 +1,22 @@
package
public const val ONE: kotlin.Int = 1
public val two: kotlin.Int = 2
@Foo(a = {1}, b = {"/"}, c = {1.0.toFloat()}) public fun test1(): kotlin.Unit
@Foo(a = {}, b = {}, c = {}) public fun test2(): kotlin.Unit
@Foo public fun test3(): kotlin.Unit
@Foo(a = {1}, b = {""}, c = {1.0.toFloat()}) public fun test4(): kotlin.Unit
@Foo(a = {3}, b = {"Hello, Kotlin"}, c = {Infinity.toFloat()}) public fun test5(): kotlin.Unit
@Foo(a = {1}, b = {}, c = {}) public fun test6(): kotlin.Unit
@Foo(a = {3}, b = {}, c = {}) public fun test7(): kotlin.Unit
@Foo(a = {2}, b = {}, c = {}) public fun test8(): kotlin.Unit
public final annotation class Foo : kotlin.Annotation {
public constructor Foo(/*0*/ a: kotlin.IntArray, /*1*/ b: kotlin.Array<kotlin.String>, /*2*/ c: kotlin.FloatArray)
public final val a: kotlin.IntArray
public final val b: kotlin.Array<kotlin.String>
public final val c: kotlin.FloatArray
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -0,0 +1,28 @@
import kotlin.reflect.KClass
annotation class Foo(val a: Array<KClass<*>> = [])
class Gen<T>
annotation class Bar(val a: Array<KClass<*>> = [Int::class, Array<Int>::class, Gen::class])
@Foo([])
fun test1() {}
@Foo([Int::class, String::class])
fun test2() {}
@Foo([<!ARRAY_CLASS_LITERAL_REQUIRES_ARGUMENT!>Array::class<!>])
fun test3() {}
@Foo([<!CLASS_LITERAL_LHS_NOT_A_CLASS!>Gen<Int>::class<!>])
fun test4() {}
@Foo(<!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH!>[""]<!>)
fun test5() {}
@Foo(<!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH!>[Int::class, 1]<!>)
fun test6() {}
@Bar
fun test7() {}
@@ -0,0 +1,32 @@
package
@Foo(a = {}) public fun test1(): kotlin.Unit
@Foo(a = {kotlin.Int::class, kotlin.String::class}) public fun test2(): kotlin.Unit
@Foo(a = {kotlin.Array<*>::class}) public fun test3(): kotlin.Unit
@Foo(a = {Gen<kotlin.Int>::class}) public fun test4(): kotlin.Unit
@Foo public fun test5(): kotlin.Unit
@Foo public fun test6(): kotlin.Unit
@Bar public fun test7(): kotlin.Unit
public final annotation class Bar : kotlin.Annotation {
public constructor Bar(/*0*/ a: kotlin.Array<kotlin.reflect.KClass<*>> = ...)
public final val a: kotlin.Array<kotlin.reflect.KClass<*>>
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Foo : kotlin.Annotation {
public constructor Foo(/*0*/ a: kotlin.Array<kotlin.reflect.KClass<*>> = ...)
public final val a: kotlin.Array<kotlin.reflect.KClass<*>>
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final class Gen</*0*/ T> {
public constructor Gen</*0*/ T>()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -0,0 +1,23 @@
annotation class Foo(
val a: Array<String> = ["/"],
val b: Array<String> = [],
val c: Array<String> = ["1", "2"]
)
annotation class Bar(
val a: Array<String> = <!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH, ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[' ']<!>,
val b: Array<String> = <!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH, ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>["", <!EMPTY_CHARACTER_LITERAL!>''<!>]<!>,
val c: Array<String> = <!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH, ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[1]<!>
)
annotation class Base(
val a0: IntArray = [],
val a1: IntArray = [1],
val b1: FloatArray = [1f],
val b0: FloatArray = []
)
annotation class Err(
val a: IntArray = <!ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[<!CONSTANT_EXPECTED_TYPE_MISMATCH!>1L<!>]<!>,
val b: Array<String> = <!TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH, ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[1]<!>
)
@@ -0,0 +1,41 @@
package
public final annotation class Bar : kotlin.Annotation {
public constructor Bar(/*0*/ a: kotlin.Array<kotlin.String> = ..., /*1*/ b: kotlin.Array<kotlin.String> = ..., /*2*/ c: kotlin.Array<kotlin.String> = ...)
public final val a: kotlin.Array<kotlin.String>
public final val b: kotlin.Array<kotlin.String>
public final val c: kotlin.Array<kotlin.String>
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Base : kotlin.Annotation {
public constructor Base(/*0*/ a0: kotlin.IntArray = ..., /*1*/ a1: kotlin.IntArray = ..., /*2*/ b1: kotlin.FloatArray = ..., /*3*/ b0: kotlin.FloatArray = ...)
public final val a0: kotlin.IntArray
public final val a1: kotlin.IntArray
public final val b0: kotlin.FloatArray
public final val b1: kotlin.FloatArray
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Err : kotlin.Annotation {
public constructor Err(/*0*/ a: kotlin.IntArray = ..., /*1*/ b: kotlin.Array<kotlin.String> = ...)
public final val a: kotlin.IntArray
public final val b: kotlin.Array<kotlin.String>
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Foo : kotlin.Annotation {
public constructor Foo(/*0*/ a: kotlin.Array<kotlin.String> = ..., /*1*/ b: kotlin.Array<kotlin.String> = ..., /*2*/ c: kotlin.Array<kotlin.String> = ...)
public final val a: kotlin.Array<kotlin.String>
public final val b: kotlin.Array<kotlin.String>
public final val c: kotlin.Array<kotlin.String>
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -0,0 +1,23 @@
const val ONE = 1
annotation class Foo(
val a: IntArray = [ONE],
val b: IntArray = [ONE, 2, 3]
)
val TWO = 2
fun getOne() = ONE
fun getTwo() = TWO
annotation class Bar(
val a: IntArray = <!ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[TWO]<!>,
val b: IntArray = <!ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[1, TWO]<!>,
val c: IntArray = [getOne(), getTwo()]
)
annotation class Baz(
val a: IntArray = <!ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[<!NULL_FOR_NONNULL_TYPE!>null<!>]<!>,
val b: IntArray = <!ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT!>[1, <!NULL_FOR_NONNULL_TYPE!>null<!>, 2]<!>,
val c: IntArray = [<!NO_THIS!>this<!>]
)
@@ -0,0 +1,35 @@
package
public const val ONE: kotlin.Int = 1
public val TWO: kotlin.Int = 2
public fun getOne(): kotlin.Int
public fun getTwo(): kotlin.Int
public final annotation class Bar : kotlin.Annotation {
public constructor Bar(/*0*/ a: kotlin.IntArray = ..., /*1*/ b: kotlin.IntArray = ..., /*2*/ c: kotlin.IntArray = ...)
public final val a: kotlin.IntArray
public final val b: kotlin.IntArray
public final val c: kotlin.IntArray
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Baz : kotlin.Annotation {
public constructor Baz(/*0*/ a: kotlin.IntArray = ..., /*1*/ b: kotlin.IntArray = ..., /*2*/ c: kotlin.IntArray = ...)
public final val a: kotlin.IntArray
public final val b: kotlin.IntArray
public final val c: kotlin.IntArray
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class Foo : kotlin.Annotation {
public constructor Foo(/*0*/ a: kotlin.IntArray = ..., /*1*/ b: kotlin.IntArray = ...)
public final val a: kotlin.IntArray
public final val b: kotlin.IntArray
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -3340,6 +3340,18 @@ public class DiagnosticsTestGenerated extends AbstractDiagnosticsTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/diagnostics/tests/collectionLiterals"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("argumentsOfAnnotation.kt")
public void testArgumentsOfAnnotation() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/argumentsOfAnnotation.kt");
doTest(fileName);
}
@TestMetadata("argumentsOfAnnotationWithKClass.kt")
public void testArgumentsOfAnnotationWithKClass() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/argumentsOfAnnotationWithKClass.kt");
doTest(fileName);
}
@TestMetadata("basicCollectionLiterals.kt")
public void testBasicCollectionLiterals() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/basicCollectionLiterals.kt");
@@ -3351,6 +3363,18 @@ public class DiagnosticsTestGenerated extends AbstractDiagnosticsTest {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/collectionLiteralsAsPrimitiveArrays.kt");
doTest(fileName);
}
@TestMetadata("defaultValuesInAnnotation.kt")
public void testDefaultValuesInAnnotation() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/defaultValuesInAnnotation.kt");
doTest(fileName);
}
@TestMetadata("defaultValuesWithConstantsInAnnotation.kt")
public void testDefaultValuesWithConstantsInAnnotation() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/collectionLiterals/defaultValuesWithConstantsInAnnotation.kt");
doTest(fileName);
}
}
@TestMetadata("compiler/testData/diagnostics/tests/constructorConsistency")