Skip to content

refactor: update field generation logic and improve logging in compiler extensions / fix multiple generations and errors in same constructor call for different qualifiers #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ import io.github.stslex.compiler_plugin.model.DistinctChangeConfig
import io.github.stslex.compiler_plugin.utils.RuntimeLogger
import org.jetbrains.kotlin.utils.addToStdlib.runIf

internal class DistinctChangeCache(
private val config: DistinctChangeConfig
) {
internal const val GENERATED_FIELD_NAME = "_generatedField"

internal class DistinctChangeCache {

private val cache = mutableMapOf<String, Pair<List<Any?>, Any?>>()
private val logger = runIf(config.logging) { RuntimeLogger.tag("DistinctChangeLogger") }

@Suppress("UNCHECKED_CAST")
internal operator fun <R> invoke(
key: String,
args: List<Any?>,
config: DistinctChangeConfig,
body: () -> R,
): R {
val entry = cache[key]
val logger = runIf(config.logging) { RuntimeLogger.tag("DistinctChangeLogger") }

logger?.i("name: ${config.name} key: $key, config:$config, entry: $entry, args: $args")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ internal class IrFunctionTransformer(
val argsListExpr = pluginContext.buildArgsListExpression(declaration)
val lambdaExpr = pluginContext.buildLambdaForBody(originalBody, declaration)

val backingField = pluginContext.generateFields(declaration, qualifierArgs, logger)
val backingField = pluginContext.generateFields(declaration, logger)

logger.i("backingField = $backingField")
val memoizeCall = pluginContext.buildSaveInCacheCall(
Expand All @@ -58,7 +58,8 @@ internal class IrFunctionTransformer(
lambdaExpr = lambdaExpr,
function = declaration,
backingField = backingField,
logger = logger
logger = logger,
qualifierArgs = qualifierArgs
)

declaration.body = pluginContext.irFactory.createExpressionBody(memoizeCall)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package io.github.stslex.compiler_plugin.utils

import io.github.stslex.compiler_plugin.DistinctChangeCache
import io.github.stslex.compiler_plugin.GENERATED_FIELD_NAME
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
import org.jetbrains.kotlin.backend.jvm.ir.fileParentOrNull
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.builders.declarations.buildFun
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrConstructor
Expand Down Expand Up @@ -116,7 +118,8 @@ internal fun IrPluginContext.buildSaveInCacheCall(
lambdaExpr: IrExpression,
function: IrSimpleFunction,
logger: CompileLogger,
backingField: IrFieldSymbolImpl
backingField: IrFieldSymbolImpl,
qualifierArgs: IrExpression
): IrExpression {
logger.i("buildSaveInCacheCall for ${function.name}, args: ${argsListExpr.dump()}")

Expand Down Expand Up @@ -150,7 +153,7 @@ internal fun IrPluginContext.buildSaveInCacheCall(
type = function.returnType,
symbol = invokeFunSymbol.symbol,
typeArgumentsCount = 1,
valueArgumentsCount = 3,
valueArgumentsCount = 4,
origin = null
)
.also { it.patchDeclarationParents(function.parent) }
Expand All @@ -160,21 +163,36 @@ internal fun IrPluginContext.buildSaveInCacheCall(
putTypeArgument(0, function.returnType)
putValueArgument(0, keyLiteral)
putValueArgument(1, argsListExpr)
putValueArgument(2, lambdaExpr)
putValueArgument(2, qualifierArgs)
putValueArgument(3, lambdaExpr)
}
}

@OptIn(UnsafeDuringIrConstructionAPI::class)
@OptIn(UnsafeDuringIrConstructionAPI::class, ObsoleteDescriptorBasedAPI::class)
internal fun IrPluginContext.generateFields(
function: IrSimpleFunction,
qualifierArgs: IrExpression,
logger: CompileLogger
): IrFieldSymbolImpl {
logger.i("generateFields for ${function.name} parent: ${function.file}")

val parentClass = function.parentClassOrNull
val parentFile = function.fileParentOrNull

// check if parentClass or parentFile already contains _generatedField
val createdField = when {
parentClass != null -> parentClass.declarations.find {
it.descriptor.name.identifierOrNullIfSpecial == GENERATED_FIELD_NAME
}

parentFile != null -> parentFile.declarations.find {
it.descriptor.name.identifierOrNullIfSpecial == GENERATED_FIELD_NAME
}

else -> null
}?.symbol as? IrFieldSymbolImpl

if (createdField != null) return createdField

val errorNotFound =
"function ${function.name} in ${function.file} couldn't be used with @DistinctUntilChangeFun"

Expand All @@ -194,7 +212,7 @@ internal fun IrPluginContext.generateFields(
endOffset = endOffset,
origin = IrDeclarationOrigin.PROPERTY_BACKING_FIELD,
symbol = fieldSymbol,
name = Name.identifier("_distinctCache"),
name = Name.identifier(GENERATED_FIELD_NAME),
type = distinctChangeClass.defaultType,
visibility = DescriptorVisibilities.PRIVATE,
isFinal = true,
Expand All @@ -213,9 +231,6 @@ internal fun IrPluginContext.generateFields(
type = distinctChangeClass.defaultType,
constructorSymbol = constructorSymbol.symbol
)
.apply {
putValueArgument(0, qualifierArgs)
}

backingField.parent = function.parent
backingField.initializer = irFactory.createExpressionBody(callDistInit)
Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ activity = "1.10.0"
constraintLayout = "2.2.0"
jetbrainsKotlinJvm = "2.0.20"

stslexCompilerPlugin = "0.0.4"
stslexCompilerPlugin = "0.0.5"

[libraries]
android-desugarJdkLibs = { module = "com.android.tools:desugar_jdk_libs", version.ref = "androidDesugarJdkLibs" }
Expand Down