[KxSerialization] Fix "IllegalAccessError: Update to static final field"

Fixes #KT-57647

For value classes, if you add code to companion anonymous init block in IR, it will be executed in the instance constructor. This causes an error when initializing static fields, because writing to them can only occur from the <clinit> method.

The solution is to transfer the static field initialization code from an anonymous init block to the IR initializer of this field

Merge-request: KT-MR-9633
Merged-by: Sergey Shanshin <Sergey.Shanshin@jetbrains.com>
This commit is contained in:
Sergey.Shanshin
2023-04-21 12:37:32 +00:00
committed by Space Team
parent 803a11003f
commit d8d643b7d7
11 changed files with 126 additions and 19 deletions
@@ -398,8 +398,8 @@ abstract class BaseIrGenerator(private val currentClass: IrClass, final override
val kSerializerType = kSerializerClass.typeWith(compilerContext.irBuiltIns.anyType)
val arrayType = compilerContext.irBuiltIns.arrayClass.typeWith(kSerializerType)
return addValPropertyWithJvmField(arrayType, SerialEntityNames.CACHED_CHILD_SERIALIZERS_PROPERTY_NAME) {
+createArrayOfExpression(kSerializerType, cacheableSerializers.map { it ?: irNull() })
return addValPropertyWithJvmFieldInitializer(arrayType, SerialEntityNames.CACHED_CHILD_SERIALIZERS_PROPERTY_NAME) {
createArrayOfExpression(kSerializerType, cacheableSerializers.map { it ?: irNull() })
}
}
@@ -161,6 +161,30 @@ interface IrBuilderWithPluginContext {
}
}
fun IrClass.addValPropertyWithJvmFieldInitializer(
type: IrType,
name: Name,
visibility: DescriptorVisibility = DescriptorVisibilities.PRIVATE,
initializer: IrBuilderWithScope.() -> IrExpression
): IrProperty {
return generateSimplePropertyWithBackingField(name, type, this, visibility).apply {
val field = backingField!!
val builder = DeclarationIrBuilder(
compilerContext,
field.symbol,
field.startOffset,
field.endOffset
)
field.initializer = IrExpressionBodyImpl(builder.initializer())
val annotationCtor = compilerContext.jvmFieldClassSymbol.constructors.single { it.owner.isPrimary }
val annotationType = compilerContext.jvmFieldClassSymbol.defaultType
field.annotations += IrConstructorCallImpl.fromSymbolOwner(startOffset, endOffset, annotationType, annotationCtor)
}
}
/**
* Add all statements to the builder, except the last one.
* The last statement should be an expression, it will return as a result