Refactor ConstantValue implementations

Remove KotlinBuiltIns and take a ModuleDescriptor instance in getType
instead. This will allow to create constant values in contexts where
there's no module or built-ins accessible (such as, deserialization of
module annotations during indexing of .kotlin_module files in IDE).

Note that some values (KClassValue, EnumValue, AnnotationValue) still
take module-dependent objects (KotlinType, ClassDescriptor and
AnnotationDescriptor respectively). This is to be refactored later
This commit is contained in:
Alexander Udalov
2017-12-29 13:04:36 +01:00
parent 5e97517c8b
commit 907f53e539
22 changed files with 207 additions and 247 deletions
@@ -370,8 +370,9 @@ public abstract class AnnotationCodegen {
@Override
public Void visitEnumValue(EnumValue value, Void data) {
String propertyName = value.getValue().getName().asString();
annotationVisitor.visitEnum(name, typeMapper.mapType(value.getType()).getDescriptor(), propertyName);
String enumClassInternalName = AsmUtil.asmTypeByClassId(value.getEnumClassId()).getDescriptor();
String enumEntryName = value.getEnumEntryName().asString();
annotationVisitor.visitEnum(name, enumClassInternalName, enumEntryName);
return null;
}
@@ -20,21 +20,19 @@ import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.load.java.structure.JavaField
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.constants.ConstantValueFactory
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
class JavaPropertyInitializerEvaluatorImpl : JavaPropertyInitializerEvaluator {
override fun getInitializerConstant(field: JavaField, descriptor: PropertyDescriptor): ConstantValue<*>? {
val evaluated = field.initializerValue ?: return null
val factory = ConstantValueFactory(descriptor.builtIns)
return when (evaluated) {
//Note: evaluated expression may be of class that does not match field type in some cases
// tested for Int, left other checks just in case
is Byte, is Short, is Int, is Long -> {
factory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type)
ConstantValueFactory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type)
}
else -> {
factory.createConstantValue(evaluated)
ConstantValueFactory.createConstantValue(evaluated)
}
}
}
@@ -18,10 +18,13 @@ package org.jetbrains.kotlin.script
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.TypeUtils
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
@@ -33,10 +36,11 @@ internal fun String?.orAnonymous(kind: String = ""): String =
this ?: "<anonymous" + (if (kind.isNotBlank()) " $kind" else "") + ">"
internal fun constructAnnotation(psi: KtAnnotationEntry, targetClass: KClass<out Annotation>): Annotation {
val module = ModuleDescriptorImpl(Name.special("<script-annotations-preprocessing>"), LockBasedStorageManager(), DefaultBuiltIns.Instance)
val evaluator = ConstantExpressionEvaluator(module, LanguageVersionSettingsImpl.DEFAULT)
val trace = BindingTraceContext()
val valueArguments = psi.valueArguments.map { arg ->
val evaluator = ConstantExpressionEvaluator(DefaultBuiltIns.Instance, LanguageVersionSettingsImpl.DEFAULT)
val trace = BindingTraceContext()
val result = evaluator.evaluateToConstantValue(arg.getArgumentExpression()!!, trace, TypeUtils.NO_EXPECTED_TYPE)
// TODO: consider inspecting `trace` to find diagnostics reported during the computation (such as division by zero, integer overflow, invalid annotation parameters etc.)
val argName = arg.getArgumentName()?.asName?.toString()
@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.tower.*
import org.jetbrains.kotlin.resolve.constants.CompileTimeConstantChecker
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@@ -242,9 +242,9 @@ class DiagnosticReporterByTrackingStrategy(
private fun reportConstantTypeMismatch(constraintError: NewConstraintError, expression: KtExpression): Boolean {
if (expression is KtConstantExpression) {
val builtIns = context.scope.ownerDescriptor.builtIns
val module = context.scope.ownerDescriptor.module
val constantValue = constantExpressionEvaluator.evaluateToConstantValue(expression, trace, context.expectedType)
val hasConstantTypeError = CompileTimeConstantChecker(context, builtIns, true)
val hasConstantTypeError = CompileTimeConstantChecker(context, module, true)
.checkConstantExpressionType(constantValue, expression, constraintError.upperType)
if (hasConstantTypeError) return true
}
@@ -22,6 +22,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.KtNodeTypes;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
import org.jetbrains.kotlin.diagnostics.DiagnosticUtilsKt;
@@ -42,20 +43,22 @@ public class CompileTimeConstantChecker {
private static final Set<DiagnosticFactory<?>> errorsThatDependOnExpectedType =
Sets.newHashSet(CONSTANT_EXPECTED_TYPE_MISMATCH, NULL_FOR_NONNULL_TYPE);
private final KotlinBuiltIns builtIns;
private final BindingTrace trace;
private final boolean checkOnlyErrorsThatDependOnExpectedType;
private final ResolutionContext<?> context;
private final ModuleDescriptor module;
private final KotlinBuiltIns builtIns;
private final boolean checkOnlyErrorsThatDependOnExpectedType;
private final BindingTrace trace;
public CompileTimeConstantChecker(
@NotNull ResolutionContext<?> context,
@NotNull KotlinBuiltIns builtIns,
@NotNull ModuleDescriptor module,
boolean checkOnlyErrorsThatDependOnExpectedType
) {
this.checkOnlyErrorsThatDependOnExpectedType = checkOnlyErrorsThatDependOnExpectedType;
this.builtIns = builtIns;
this.trace = context.trace;
this.context = context;
this.module = module;
this.builtIns = module.getBuiltIns();
this.checkOnlyErrorsThatDependOnExpectedType = checkOnlyErrorsThatDependOnExpectedType;
this.trace = context.trace;
}
// return true if there is an error
@@ -98,7 +101,7 @@ public class CompileTimeConstantChecker {
}
if (!noExpectedTypeOrError(expectedType)) {
KotlinType valueType = value.getType();
KotlinType valueType = value.getType(module);
if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(valueType, expectedType)) {
return reportConstantExpectedTypeMismatch(expression, "integer", expectedType, null);
}
@@ -115,7 +118,7 @@ public class CompileTimeConstantChecker {
return reportError(FLOAT_LITERAL_OUT_OF_RANGE.on(expression));
}
if (!noExpectedTypeOrError(expectedType)) {
KotlinType valueType = value.getType();
KotlinType valueType = value.getType(module);
if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(valueType, expectedType)) {
return reportConstantExpectedTypeMismatch(expression, "floating-point", expectedType, null);
}
@@ -51,11 +51,9 @@ import java.math.BigInteger
import java.util.*
class ConstantExpressionEvaluator(
internal val builtIns: KotlinBuiltIns,
internal val module: ModuleDescriptor,
internal val languageVersionSettings: LanguageVersionSettings
) {
internal val constantValueFactory = ConstantValueFactory(builtIns)
fun updateNumberType(
numberType: KotlinType,
expression: KtExpression?,
@@ -106,7 +104,7 @@ class ConstantExpressionEvaluator(
if (parameterDescriptor.declaresDefaultValue() && compileTimeConstants.isEmpty()) return null
return constantValueFactory.createArrayValue(constants, parameterDescriptor.type)
return ConstantValueFactory.createArrayValue(constants, parameterDescriptor.type)
} else {
// we should actually get only one element, but just in case of getting many, we take the last one
return constants.lastOrNull()
@@ -116,7 +114,7 @@ class ConstantExpressionEvaluator(
private fun isArrayPassedInNamedForm(constants: List<ConstantValue<Any?>>, resolvedArgument: ResolvedValueArgument): Boolean {
val constant = constants.singleOrNull() ?: return false
val argument = resolvedArgument.arguments.singleOrNull() ?: return false
return KotlinBuiltIns.isArrayOrPrimitiveArray(constant.type) && argument.isNamed()
return constant is ArrayValue && argument.isNamed()
}
private fun checkCompileTimeConstant(
@@ -205,7 +203,7 @@ class ConstantExpressionEvaluator(
}
val returnType = resolvedCall.resultingDescriptor.returnType ?: return null
val componentType = builtIns.getArrayElementType(returnType)
val componentType = module.builtIns.getArrayElementType(returnType)
val result = arrayListOf<KtExpression>()
for ((_, resolvedValueArgument) in resolvedCall.valueArguments) {
@@ -289,8 +287,7 @@ private class ConstantExpressionEvaluatorVisitor(
private val constantExpressionEvaluator: ConstantExpressionEvaluator,
private val trace: BindingTrace
) : KtVisitor<CompileTimeConstant<*>?, KotlinType>() {
private val factory = constantExpressionEvaluator.constantValueFactory
private val builtIns = constantExpressionEvaluator.module.builtIns
fun evaluate(expression: KtExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val recordedCompileTimeConstant = ConstantExpressionEvaluator.getPossiblyErrorConstant(expression, trace.bindingContext)
@@ -314,8 +311,8 @@ private class ConstantExpressionEvaluatorVisitor(
}
return when (constantValue) {
is ErrorValue, is EnumValue -> return null
is NullValue -> factory.createStringValue("null")
else -> factory.createStringValue(constantValue.value.toString())
is NullValue -> ConstantValueFactory.createStringValue("null")
else -> ConstantValueFactory.createStringValue(constantValue.value.toString())
}.wrap(compileTimeConstant.parameters)
}
@@ -329,23 +326,26 @@ private class ConstantExpressionEvaluatorVisitor(
): TypedCompileTimeConstant<String>? {
val expression = entry.expression ?: return null
return evaluate(expression, constantExpressionEvaluator.builtIns.stringType)?.let {
return evaluate(expression, builtIns.stringType)?.let {
createStringConstant(it)
}
}
override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry, data: Nothing?) =
factory.createStringValue(entry.text).wrap()
override fun visitLiteralStringTemplateEntry(
entry: KtLiteralStringTemplateEntry,
data: Nothing?
): TypedCompileTimeConstant<String> =
ConstantValueFactory.createStringValue(entry.text).wrap()
override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry, data: Nothing?) =
factory.createStringValue(entry.unescapedValue).wrap()
override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry, data: Nothing?): TypedCompileTimeConstant<String> =
ConstantValueFactory.createStringValue(entry.unescapedValue).wrap()
}
override fun visitConstantExpression(expression: KtConstantExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val text = expression.text ?: return null
val nodeElementType = expression.node.elementType
if (nodeElementType == KtNodeTypes.NULL) return factory.createNullValue().wrap()
if (nodeElementType == KtNodeTypes.NULL) return ConstantValueFactory.createNullValue().wrap()
val result: Any? = when (nodeElementType) {
KtNodeTypes.INTEGER_CONSTANT, KtNodeTypes.FLOAT_CONSTANT -> parseNumericLiteral(text, nodeElementType)
@@ -461,7 +461,7 @@ private class ConstantExpressionEvaluatorVisitor(
val operationToken = expression.operationToken
if (OperatorConventions.BOOLEAN_OPERATIONS.containsKey(operationToken)) {
val booleanType = constantExpressionEvaluator.builtIns.booleanType
val booleanType = builtIns.booleanType
val leftConstant = evaluate(leftExpression, booleanType) ?: return null
val rightExpression = expression.right ?: return null
@@ -545,7 +545,7 @@ private class ConstantExpressionEvaluatorVisitor(
if ((isIntegerType(argumentForReceiver.value) && isIntegerType(argumentForParameter.value)) ||
!constantExpressionEvaluator.languageVersionSettings.supportsFeature(LanguageFeature.DivisionByZeroInConstantExpressions)) {
return factory.createErrorValue("Division by zero").wrap()
return ConstantValueFactory.createErrorValue("Division by zero").wrap()
}
}
@@ -563,10 +563,8 @@ private class ConstantExpressionEvaluatorVisitor(
val parameters =
CompileTimeConstant.Parameters(canBeUsedInAnnotation, areArgumentsPure, usesVariableAsConstant, usesNonConstValAsConstant)
return when (resultingDescriptorName) {
OperatorNameConventions.COMPARE_TO -> createCompileTimeConstantForCompareTo(result, callExpression, factory)?.wrap(
parameters
)
OperatorNameConventions.EQUALS -> createCompileTimeConstantForEquals(result, callExpression, factory)?.wrap(parameters)
OperatorNameConventions.COMPARE_TO -> createCompileTimeConstantForCompareTo(result, callExpression)?.wrap(parameters)
OperatorNameConventions.EQUALS -> createCompileTimeConstantForEquals(result, callExpression)?.wrap(parameters)
else -> {
createConstant(result, expectedType, parameters)
}
@@ -664,7 +662,7 @@ private class ConstantExpressionEvaluatorVisitor(
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val enumDescriptor = trace.bindingContext.get(BindingContext.REFERENCE_TARGET, expression)
if (enumDescriptor != null && DescriptorUtils.isEnumEntry(enumDescriptor)) {
return factory.createEnumValue(enumDescriptor as ClassDescriptor).wrap()
return ConstantValueFactory.createEnumValue(enumDescriptor as ClassDescriptor).wrap()
}
val resolvedCall = expression.getResolvedCall(trace.bindingContext)
@@ -764,14 +762,14 @@ private class ConstantExpressionEvaluatorVisitor(
call: ResolvedCall<*>
): TypedCompileTimeConstant<List<ConstantValue<*>>>? {
val returnType = call.resultingDescriptor.returnType ?: return null
val componentType = constantExpressionEvaluator.builtIns.getArrayElementType(returnType)
val componentType = builtIns.getArrayElementType(returnType)
val arguments = call.valueArguments.values.flatMap { resolveArguments(it.arguments, componentType) }
// not evaluated arguments are not constants: function-calls, properties with custom getter...
val evaluatedArguments = arguments.filterNotNull()
return factory.createArrayValue(evaluatedArguments.map { it.toConstantValue(componentType) }, returnType)
return ConstantValueFactory.createArrayValue(evaluatedArguments.map { it.toConstantValue(componentType) }, returnType)
.wrap(
usesVariableAsConstant = evaluatedArguments.any { it.usesVariableAsConstant },
usesNonConstValAsConstant = arguments.any { it == null || it.usesNonConstValAsConstant }
@@ -781,7 +779,7 @@ private class ConstantExpressionEvaluatorVisitor(
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val type = trace.getType(expression)!!
if (type.isError) return null
return factory.createKClassValue(type).wrap()
return ConstantValueFactory.createKClassValue(type).wrap()
}
private fun resolveArguments(valueArguments: List<ValueArgument>, expectedType: KotlinType): List<CompileTimeConstant<*>?> {
@@ -823,10 +821,8 @@ private class ConstantExpressionEvaluatorVisitor(
return createOperationArgument(argumentExpression, parameter.type, argumentCompileTimeType)
}
private fun getCompileTimeType(c: KotlinType): CompileTimeType<out Any>? {
val builtIns = constantExpressionEvaluator.builtIns
return when (TypeUtils.makeNotNullable(c)) {
private fun getCompileTimeType(c: KotlinType): CompileTimeType<out Any>? =
when (TypeUtils.makeNotNullable(c)) {
builtIns.intType -> INT
builtIns.byteType -> BYTE
builtIns.shortType -> SHORT
@@ -839,7 +835,6 @@ private class ConstantExpressionEvaluatorVisitor(
builtIns.anyType -> ANY
else -> null
}
}
private fun createOperationArgument(
expression: KtExpression,
@@ -860,7 +855,7 @@ private class ConstantExpressionEvaluatorVisitor(
return if (parameters.isPure) {
return createCompileTimeConstant(value, parameters, expectedType ?: TypeUtils.NO_EXPECTED_TYPE)
} else {
factory.createConstantValue(value)?.wrap(parameters)
ConstantValueFactory.createConstantValue(value)?.wrap(parameters)
}
}
@@ -871,7 +866,7 @@ private class ConstantExpressionEvaluatorVisitor(
): CompileTimeConstant<*>? {
return when (value) {
is Byte, is Short, is Int, is Long -> createIntegerCompileTimeConstant((value as Number).toLong(), parameters, expectedType)
else -> factory.createConstantValue(value)?.wrap(parameters)
else -> ConstantValueFactory.createConstantValue(value)?.wrap(parameters)
}
}
@@ -881,20 +876,20 @@ private class ConstantExpressionEvaluatorVisitor(
expectedType: KotlinType
): CompileTimeConstant<*>? {
if (TypeUtils.noExpectedType(expectedType) || expectedType.isError) {
return IntegerValueTypeConstant(value, constantExpressionEvaluator.builtIns, parameters)
return IntegerValueTypeConstant(value, builtIns, parameters)
}
val integerValue = factory.createIntegerConstantValue(value, expectedType)
val integerValue = ConstantValueFactory.createIntegerConstantValue(value, expectedType)
if (integerValue != null) {
return integerValue.wrap(parameters)
}
return when (value) {
value.toInt().toLong() -> factory.createIntValue(value.toInt())
else -> factory.createLongValue(value)
value.toInt().toLong() -> ConstantValueFactory.createIntValue(value.toInt())
else -> ConstantValueFactory.createLongValue(value)
}.wrap(parameters)
}
private fun <T> ConstantValue<T>.wrap(parameters: CompileTimeConstant.Parameters): TypedCompileTimeConstant<T> =
TypedCompileTimeConstant(this, parameters)
TypedCompileTimeConstant(this, constantExpressionEvaluator.module, parameters)
private fun <T> ConstantValue<T>.wrap(
canBeUsedInAnnotation: Boolean = this !is NullValue,
@@ -962,11 +957,7 @@ private fun parseBoolean(text: String): Boolean {
}
private fun createCompileTimeConstantForEquals(
result: Any?,
operationReference: KtExpression,
factory: ConstantValueFactory
): ConstantValue<*>? {
private fun createCompileTimeConstantForEquals(result: Any?, operationReference: KtExpression): ConstantValue<*>? {
if (result is Boolean) {
assert(operationReference is KtSimpleNameExpression) { "This method should be called only for equals operations" }
val operationToken = (operationReference as KtSimpleNameExpression).getReferencedNameElementType()
@@ -979,27 +970,23 @@ private fun createCompileTimeConstantForEquals(
}
else -> throw IllegalStateException("Unknown equals operation token: $operationToken ${operationReference.text}")
}
return factory.createBooleanValue(value)
return ConstantValueFactory.createBooleanValue(value)
}
return null
}
private fun createCompileTimeConstantForCompareTo(
result: Any?,
operationReference: KtExpression,
factory: ConstantValueFactory
): ConstantValue<*>? {
private fun createCompileTimeConstantForCompareTo(result: Any?, operationReference: KtExpression): ConstantValue<*>? {
if (result is Int) {
assert(operationReference is KtSimpleNameExpression) { "This method should be called only for compareTo operations" }
val operationToken = (operationReference as KtSimpleNameExpression).getReferencedNameElementType()
return when (operationToken) {
KtTokens.LT -> factory.createBooleanValue(result < 0)
KtTokens.LTEQ -> factory.createBooleanValue(result <= 0)
KtTokens.GT -> factory.createBooleanValue(result > 0)
KtTokens.GTEQ -> factory.createBooleanValue(result >= 0)
KtTokens.LT -> ConstantValueFactory.createBooleanValue(result < 0)
KtTokens.LTEQ -> ConstantValueFactory.createBooleanValue(result <= 0)
KtTokens.GT -> ConstantValueFactory.createBooleanValue(result > 0)
KtTokens.GTEQ -> ConstantValueFactory.createBooleanValue(result >= 0)
KtTokens.IDENTIFIER -> {
assert(operationReference.getReferencedNameAsName() == OperatorNameConventions.COMPARE_TO) { "This method should be called only for compareTo operations" }
return factory.createIntValue(result)
return ConstantValueFactory.createIntValue(result)
}
else -> throw IllegalStateException("Unknown compareTo operation token: $operationToken")
}
@@ -208,13 +208,15 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
);
if (!(compileTimeConstant instanceof IntegerValueTypeConstant)) {
CompileTimeConstantChecker constantChecker = new CompileTimeConstantChecker(context, components.builtIns, false);
CompileTimeConstantChecker constantChecker = new CompileTimeConstantChecker(context, components.moduleDescriptor, false);
ConstantValue constantValue =
compileTimeConstant != null ? ((TypedCompileTimeConstant) compileTimeConstant).getConstantValue() : null;
boolean hasError = constantChecker.checkConstantExpressionType(constantValue, expression, context.expectedType);
if (hasError) {
return TypeInfoFactoryKt.createTypeInfo(constantValue != null ? constantValue.getType() : getDefaultType(elementType),
context);
return TypeInfoFactoryKt.createTypeInfo(
constantValue != null ? constantValue.getType(components.moduleDescriptor) : getDefaultType(elementType),
context
);
}
}
@@ -53,11 +53,10 @@ import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEP
import static org.jetbrains.kotlin.types.TypeUtils.*;
public class DataFlowAnalyzer {
private final Iterable<AdditionalTypeChecker> additionalTypeCheckers;
private final ConstantExpressionEvaluator constantExpressionEvaluator;
private final ModuleDescriptor module;
private final KotlinBuiltIns builtIns;
private final SmartCastManager smartCastManager;
private final ExpressionTypingFacade facade;
private final LanguageVersionSettings languageVersionSettings;
private final EffectSystem effectSystem;
@@ -65,16 +64,16 @@ public class DataFlowAnalyzer {
public DataFlowAnalyzer(
@NotNull Iterable<AdditionalTypeChecker> additionalTypeCheckers,
@NotNull ConstantExpressionEvaluator constantExpressionEvaluator,
@NotNull ModuleDescriptor module,
@NotNull KotlinBuiltIns builtIns,
@NotNull SmartCastManager smartCastManager,
@NotNull ExpressionTypingFacade facade,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull EffectSystem effectSystem
) {
this.additionalTypeCheckers = additionalTypeCheckers;
this.constantExpressionEvaluator = constantExpressionEvaluator;
this.module = module;
this.builtIns = builtIns;
this.smartCastManager = smartCastManager;
this.facade = facade;
this.languageVersionSettings = languageVersionSettings;
this.effectSystem = effectSystem;
@@ -285,7 +284,7 @@ public class DataFlowAnalyzer {
if (expression instanceof KtConstantExpression && reportErrorForTypeMismatch) {
ConstantValue<?> constantValue = constantExpressionEvaluator.evaluateToConstantValue(expression, c.trace, c.expectedType);
boolean error = new CompileTimeConstantChecker(c, builtIns, true)
boolean error = new CompileTimeConstantChecker(c, module, true)
.checkConstantExpressionType(constantValue, (KtConstantExpression) expression, c.expectedType);
hasError.set(error);
return expressionType;
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.context.GlobalContext;
import org.jetbrains.kotlin.contracts.EffectSystem;
import org.jetbrains.kotlin.contracts.parsing.ContractParsingServices;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.incremental.components.LookupTracker;
import org.jetbrains.kotlin.platform.PlatformToKotlinClassMap;
import org.jetbrains.kotlin.resolve.*;
@@ -36,6 +37,7 @@ import javax.inject.Inject;
public class ExpressionTypingComponents {
/*package*/ GlobalContext globalContext;
/*package*/ ModuleDescriptor moduleDescriptor;
/*package*/ ExpressionTypingServices expressionTypingServices;
/*package*/ CallResolver callResolver;
/*package*/ PlatformToKotlinClassMap platformToKotlinClassMap;
@@ -74,6 +76,11 @@ public class ExpressionTypingComponents {
this.globalContext = globalContext;
}
@Inject
public void setModuleDescriptor(@NotNull ModuleDescriptor moduleDescriptor) {
this.moduleDescriptor = moduleDescriptor;
}
@Inject
public void setExpressionTypingServices(@NotNull ExpressionTypingServices expressionTypingServices) {
this.expressionTypingServices = expressionTypingServices;
@@ -207,7 +207,7 @@ class StatementGenerator(
fun generateConstantExpression(expression: KtExpression, constant: CompileTimeConstant<*>): IrExpression {
val constantValue = constant.toConstantValue(getInferredTypeWithImplicitCastsOrFail(expression))
val constantType = constantValue.type
val constantType = constantValue.getType(context.moduleDescriptor)
return when (constantValue) {
is StringValue ->
@@ -231,7 +231,7 @@ class StatementGenerator(
is ShortValue ->
IrConstImpl.short(expression.startOffset, expression.endOffset, constantType, constantValue.value)
else ->
TODO("handle other literal types: ${constantValue.type}")
TODO("handle other literal types: $constantType")
}
}
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.annotation.AbstractAnnotationDescriptorResolveTest
import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
@@ -65,12 +65,11 @@ abstract class AbstractCompileTimeConstantEvaluatorTest : AbstractAnnotationDesc
private fun evaluateInitializer(context: BindingContext, property: VariableDescriptor): CompileTimeConstant<*>? {
val propertyDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(property) as KtProperty
val compileTimeConstant = ConstantExpressionEvaluator(property.builtIns, LanguageVersionSettingsImpl.DEFAULT).evaluateExpression(
return ConstantExpressionEvaluator(property.module, LanguageVersionSettingsImpl.DEFAULT).evaluateExpression(
propertyDeclaration.initializer!!,
DelegatingBindingTrace(context, "trace for evaluating compile time constant"),
property.type
)
return compileTimeConstant
}
private fun doTest(path: String, getValueToTest: (VariableDescriptor, BindingContext) -> String) {