commit 9dba095da411177aabac217c89b60918353a4c24 Author: Harsh Shandilya Date: Fri Aug 18 04:12:55 2023 +0530 Initial commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9e62d0d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,93 @@ +# This .editorconfig section approximates ktfmt's formatting rules. You can include it in an +# existing .editorconfig file or use it standalone by copying it to /.editorconfig +# and making sure your editor is set to read settings from .editorconfig files. +# +# It includes editor-specific config options for IntelliJ IDEA. +# +# If any option is wrong, PR are welcome + +[{*.kt,*.kts}] +indent_style = space +insert_final_newline = true +max_line_length = 100 +indent_size = 2 +ij_continuation_indent_size = 2 +ij_java_names_count_to_use_import_on_demand = 9999 +ij_kotlin_align_in_columns_case_branch = false +ij_kotlin_align_multiline_binary_operation = false +ij_kotlin_align_multiline_extends_list = false +ij_kotlin_align_multiline_method_parentheses = false +ij_kotlin_align_multiline_parameters = true +ij_kotlin_align_multiline_parameters_in_calls = false +ij_kotlin_allow_trailing_comma = true +ij_kotlin_allow_trailing_comma_on_call_site = true +ij_kotlin_assignment_wrap = normal +ij_kotlin_blank_lines_after_class_header = 0 +ij_kotlin_blank_lines_around_block_when_branches = 0 +ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1 +ij_kotlin_block_comment_at_first_column = true +ij_kotlin_call_parameters_new_line_after_left_paren = true +ij_kotlin_call_parameters_right_paren_on_new_line = false +ij_kotlin_call_parameters_wrap = on_every_item +ij_kotlin_catch_on_new_line = false +ij_kotlin_class_annotation_wrap = split_into_lines +ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL +ij_kotlin_continuation_indent_for_chained_calls = true +ij_kotlin_continuation_indent_for_expression_bodies = true +ij_kotlin_continuation_indent_in_argument_lists = true +ij_kotlin_continuation_indent_in_elvis = false +ij_kotlin_continuation_indent_in_if_conditions = false +ij_kotlin_continuation_indent_in_parameter_lists = false +ij_kotlin_continuation_indent_in_supertype_lists = false +ij_kotlin_else_on_new_line = false +ij_kotlin_enum_constants_wrap = off +ij_kotlin_extends_list_wrap = normal +ij_kotlin_field_annotation_wrap = split_into_lines +ij_kotlin_finally_on_new_line = false +ij_kotlin_if_rparen_on_new_line = false +ij_kotlin_import_nested_classes = false +ij_kotlin_insert_whitespaces_in_simple_one_line_method = true +ij_kotlin_keep_blank_lines_before_right_brace = 2 +ij_kotlin_keep_blank_lines_in_code = 2 +ij_kotlin_keep_blank_lines_in_declarations = 2 +ij_kotlin_keep_first_column_comment = true +ij_kotlin_keep_indents_on_empty_lines = false +ij_kotlin_keep_line_breaks = true +ij_kotlin_lbrace_on_next_line = false +ij_kotlin_line_comment_add_space = false +ij_kotlin_line_comment_at_first_column = true +ij_kotlin_method_annotation_wrap = split_into_lines +ij_kotlin_method_call_chain_wrap = normal +ij_kotlin_method_parameters_new_line_after_left_paren = true +ij_kotlin_method_parameters_right_paren_on_new_line = true +ij_kotlin_method_parameters_wrap = on_every_item +ij_kotlin_name_count_to_use_star_import = 9999 +ij_kotlin_name_count_to_use_star_import_for_members = 9999 +ij_kotlin_parameter_annotation_wrap = off +ij_kotlin_space_after_comma = true +ij_kotlin_space_after_extend_colon = true +ij_kotlin_space_after_type_colon = true +ij_kotlin_space_before_catch_parentheses = true +ij_kotlin_space_before_comma = false +ij_kotlin_space_before_extend_colon = true +ij_kotlin_space_before_for_parentheses = true +ij_kotlin_space_before_if_parentheses = true +ij_kotlin_space_before_lambda_arrow = true +ij_kotlin_space_before_type_colon = false +ij_kotlin_space_before_when_parentheses = true +ij_kotlin_space_before_while_parentheses = true +ij_kotlin_spaces_around_additive_operators = true +ij_kotlin_spaces_around_assignment_operators = true +ij_kotlin_spaces_around_equality_operators = true +ij_kotlin_spaces_around_function_type_arrow = true +ij_kotlin_spaces_around_logical_operators = true +ij_kotlin_spaces_around_multiplicative_operators = true +ij_kotlin_spaces_around_range = false +ij_kotlin_spaces_around_relational_operators = true +ij_kotlin_spaces_around_unary_operator = false +ij_kotlin_spaces_around_when_arrow = true +ij_kotlin_variable_annotation_wrap = off +ij_kotlin_while_on_new_line = false +ij_kotlin_wrap_elvis_expressions = 1 +ij_kotlin_wrap_expression_body_functions = 1 +ij_kotlin_wrap_first_method_in_call_chain = false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f385ad2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/misc.xml +.idea/workspace.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..1bec35e --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..35ac5d0 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..df543e3 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..fdf8d99 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/ktfmt.xml b/.idea/ktfmt.xml new file mode 100644 index 0000000..701fb68 --- /dev/null +++ b/.idea/ktfmt.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/annotations/build.gradle.kts b/annotations/build.gradle.kts new file mode 100644 index 0000000..08e16a1 --- /dev/null +++ b/annotations/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + alias(libs.plugins.kotlin.jvm) + `maven-publish` +} + +group = "dev.msfjarvis.tracelog" + +version = "1.0.0-SNAPSHOT" + +kotlin.jvmToolchain(11) + +kotlin.explicitApi() diff --git a/annotations/src/main/kotlin/dev/msfjarvis/tracelog/annotations/DebugLog.kt b/annotations/src/main/kotlin/dev/msfjarvis/tracelog/annotations/DebugLog.kt new file mode 100644 index 0000000..b211745 --- /dev/null +++ b/annotations/src/main/kotlin/dev/msfjarvis/tracelog/annotations/DebugLog.kt @@ -0,0 +1,3 @@ +package dev.msfjarvis.tracelog.annotations + +@Retention(AnnotationRetention.RUNTIME) public annotation class DebugLog diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..d13582f --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + alias(libs.plugins.spotless) + alias(libs.plugins.kotlin.jvm) apply false +} + +spotless { + kotlin { + target("**/*.kt") + ktfmt() + } + kotlinGradle { + target("**/*.kts") + ktfmt() + } +} diff --git a/compiler-plugin/build.gradle.kts b/compiler-plugin/build.gradle.kts new file mode 100644 index 0000000..470a2d8 --- /dev/null +++ b/compiler-plugin/build.gradle.kts @@ -0,0 +1,42 @@ +import org.gradle.api.tasks.testing.logging.TestLogEvent + +plugins { + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.ksp) + alias(libs.plugins.buildconfig) + `maven-publish` +} + +group = "dev.msfjarvis.tracelog" + +version = "1.0.0-SNAPSHOT" + +kotlin.jvmToolchain(11) + +kotlin.explicitApi() + +buildConfig { + packageName("${group}.compiler.plugin") + useKotlinOutput { internalVisibility = true } + buildConfigField("String", "KOTLIN_PLUGIN_GROUP", "\"${project.group}\"") + buildConfigField("String", "KOTLIN_PLUGIN_NAME", "\"${project.name}\"") + buildConfigField("String", "KOTLIN_PLUGIN_VERSION", "\"${project.version}\"") +} + +tasks.test.configure { + testLogging { events(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED) } + useJUnitPlatform() +} + +dependencies { + compileOnly(libs.kotlin.compiler) + ksp(libs.auto.ksp) + compileOnly(libs.auto.annotations) + compileOnly(projects.annotations) + testImplementation(projects.annotations) + testImplementation(libs.kct) + testImplementation(libs.junit.jupiter.api) + testImplementation(libs.junit.jupiter.engine) + testImplementation(libs.truth) { exclude("org.junit") } + testCompileOnly(libs.junit.legacy) +} diff --git a/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformer.kt b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformer.kt new file mode 100644 index 0000000..9d33d66 --- /dev/null +++ b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformer.kt @@ -0,0 +1,164 @@ +package dev.msfjarvis.tracelog.compiler.plugin + +import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext +import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext +import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder +import org.jetbrains.kotlin.backend.common.lower.irCatch +import org.jetbrains.kotlin.backend.common.lower.irThrow +import org.jetbrains.kotlin.ir.IrStatement +import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope +import org.jetbrains.kotlin.ir.builders.declarations.buildVariable +import org.jetbrains.kotlin.ir.builders.irBlock +import org.jetbrains.kotlin.ir.builders.irBlockBody +import org.jetbrains.kotlin.ir.builders.irCall +import org.jetbrains.kotlin.ir.builders.irConcat +import org.jetbrains.kotlin.ir.builders.irGet +import org.jetbrains.kotlin.ir.builders.irGetObject +import org.jetbrains.kotlin.ir.builders.irString +import org.jetbrains.kotlin.ir.builders.irTemporary +import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin +import org.jetbrains.kotlin.ir.declarations.IrFunction +import org.jetbrains.kotlin.ir.declarations.IrValueDeclaration +import org.jetbrains.kotlin.ir.declarations.IrVariable +import org.jetbrains.kotlin.ir.expressions.IrBlockBody +import org.jetbrains.kotlin.ir.expressions.IrBody +import org.jetbrains.kotlin.ir.expressions.IrCall +import org.jetbrains.kotlin.ir.expressions.IrExpression +import org.jetbrains.kotlin.ir.expressions.IrReturn +import org.jetbrains.kotlin.ir.expressions.addArgument +import org.jetbrains.kotlin.ir.expressions.impl.IrTryImpl +import org.jetbrains.kotlin.ir.symbols.IrClassSymbol +import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol +import org.jetbrains.kotlin.ir.util.hasAnnotation +import org.jetbrains.kotlin.ir.util.statements +import org.jetbrains.kotlin.name.CallableId +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name + +public class DebugLogTransformer( + private val pluginContext: IrPluginContext, + private val annotationClass: IrClassSymbol, + private val logFunction: IrSimpleFunctionSymbol, +) : IrElementTransformerVoidWithContext() { + private val typeUnit = pluginContext.irBuiltIns.unitType + private val typeThrowable = pluginContext.irBuiltIns.throwableType + + private val classMonotonic = + pluginContext.referenceClass( + ClassId(KOTLIN_TIME_FQNAME, Name.identifier("TimeSource.Monotonic")))!! + + private val funMarkNow = + pluginContext + .referenceFunctions( + CallableId( + KOTLIN_TIME_FQNAME.child(Name.identifier("TimeSource")), + Name.identifier("markNow"))) + .single() + + private val funElapsedNow = + pluginContext + .referenceFunctions( + CallableId( + KOTLIN_TIME_FQNAME.child(Name.identifier("TimeMark")), + Name.identifier("elapsedNow"))) + .single() + + override fun visitFunctionNew(declaration: IrFunction): IrStatement { + val body = declaration.body + if (body != null && declaration.hasAnnotation(annotationClass)) { + declaration.body = irDebug(declaration, body) + } + return super.visitFunctionNew(declaration) + } + + private fun IrBuilderWithScope.irDebugEnter(function: IrFunction): IrCall { + val concat = irConcat() + concat.addArgument(irString("⇢ ${function.name}(")) + for ((index, valueParameter) in function.valueParameters.withIndex()) { + if (index > 0) concat.addArgument(irString(", ")) + concat.addArgument(irString("${valueParameter.name}=")) + concat.addArgument(irGet(valueParameter)) + } + concat.addArgument(irString(")")) + + return irCall(logFunction).also { call -> call.putValueArgument(0, concat) } + } + + private fun IrBuilderWithScope.irDebugExit( + function: IrFunction, + startTime: IrValueDeclaration, + result: IrExpression? = null + ): IrCall { + val concat = irConcat() + concat.addArgument(irString("⇠ ${function.name} [")) + concat.addArgument( + irCall(funElapsedNow).also { call -> call.dispatchReceiver = irGet(startTime) }) + if (result != null) { + concat.addArgument(irString("] = ")) + concat.addArgument(result) + } else { + concat.addArgument(irString("]")) + } + + return irCall(logFunction).also { call -> call.putValueArgument(0, concat) } + } + + private fun irDebug(function: IrFunction, body: IrBody): IrBlockBody { + return DeclarationIrBuilder(pluginContext, function.symbol).irBlockBody { + +irDebugEnter(function) + + val startTime = + irTemporary( + irCall(funMarkNow).also { call -> + call.dispatchReceiver = irGetObject(classMonotonic) + }) + + val tryBlock = + irBlock(resultType = function.returnType) { + for (statement in body.statements) +statement + if (function.returnType == typeUnit) +irDebugExit(function, startTime) + } + .transform(DebugLogReturnTransformer(function, startTime), null) + + val throwable = + buildVariable( + scope.getLocalDeclarationParent(), + startOffset, + endOffset, + IrDeclarationOrigin.CATCH_PARAMETER, + Name.identifier("t"), + typeThrowable) + + +IrTryImpl(startOffset, endOffset, tryBlock.type).also { irTry -> + irTry.tryResult = tryBlock + irTry.catches += + irCatch( + throwable, + irBlock { + +irDebugExit(function, startTime, irGet(throwable)) + +irThrow(irGet(throwable)) + }) + } + } + } + + private inner class DebugLogReturnTransformer( + private val function: IrFunction, + private val startTime: IrVariable + ) : IrElementTransformerVoidWithContext() { + override fun visitReturn(expression: IrReturn): IrExpression { + if (expression.returnTargetSymbol != function.symbol) return super.visitReturn(expression) + + return DeclarationIrBuilder(pluginContext, function.symbol).irBlock { + val result = irTemporary(expression.value) + +irDebugExit(function, startTime, irGet(result)) + +expression.apply { value = irGet(result) } + } + } + } + + private companion object { + private val KOTLIN_TIME_FQNAME = FqName("kotlin.time") + } +} diff --git a/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCommandLineProcessor.kt b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCommandLineProcessor.kt new file mode 100644 index 0000000..1f66d6c --- /dev/null +++ b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCommandLineProcessor.kt @@ -0,0 +1,14 @@ +package dev.msfjarvis.tracelog.compiler.plugin + +import com.google.auto.service.AutoService +import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption +import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi + +@OptIn(ExperimentalCompilerApi::class) +@AutoService(CommandLineProcessor::class) +public class TracingCommandLineProcessor : CommandLineProcessor { + + override val pluginId: String = "dev.msfjarvis.tracelog" + override val pluginOptions: Collection = emptyList() +} diff --git a/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCompilerPluginRegistrar.kt b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCompilerPluginRegistrar.kt new file mode 100644 index 0000000..ca66ef8 --- /dev/null +++ b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingCompilerPluginRegistrar.kt @@ -0,0 +1,18 @@ +package dev.msfjarvis.tracelog.compiler.plugin + +import com.google.auto.service.AutoService +import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension +import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi +import org.jetbrains.kotlin.config.CompilerConfiguration + +@OptIn(ExperimentalCompilerApi::class) +@AutoService(CompilerPluginRegistrar::class) +public class TracingCompilerPluginRegistrar : CompilerPluginRegistrar() { + + override val supportsK2: Boolean = true + + override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) { + IrGenerationExtension.registerExtension(TracingIrGenerationExtension()) + } +} diff --git a/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingIrGenerationExtension.kt b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingIrGenerationExtension.kt new file mode 100644 index 0000000..46afea6 --- /dev/null +++ b/compiler-plugin/src/main/kotlin/dev/msfjarvis/tracelog/compiler/plugin/TracingIrGenerationExtension.kt @@ -0,0 +1,31 @@ +package dev.msfjarvis.tracelog.compiler.plugin + +import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension +import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext +import org.jetbrains.kotlin.ir.declarations.IrModuleFragment +import org.jetbrains.kotlin.ir.types.isNullableAny +import org.jetbrains.kotlin.name.CallableId +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name + +public class TracingIrGenerationExtension : IrGenerationExtension { + + override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) { + val debugLogAnnotation = + pluginContext.referenceClass( + ClassId( + FqName("${BuildConfig.KOTLIN_PLUGIN_GROUP}.annotations"), + Name.identifier("DebugLog"), + ))!! + val funPrintln = + pluginContext + .referenceFunctions(CallableId(FqName("kotlin.io"), Name.identifier("println"))) + .first { + val parameters = it.owner.valueParameters + parameters.size == 1 && parameters[0].type.isNullableAny() + } + moduleFragment.transform( + DebugLogTransformer(pluginContext, debugLogAnnotation, funPrintln), null) + } +} diff --git a/compiler-plugin/src/test/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformerTest.kt b/compiler-plugin/src/test/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformerTest.kt new file mode 100644 index 0000000..bacf995 --- /dev/null +++ b/compiler-plugin/src/test/kotlin/dev/msfjarvis/tracelog/compiler/plugin/DebugLogTransformerTest.kt @@ -0,0 +1,96 @@ +package dev.msfjarvis.tracelog.compiler.plugin + +import com.tschuchort.compiletesting.KotlinCompilation +import com.tschuchort.compiletesting.KotlinCompilation.ExitCode +import com.tschuchort.compiletesting.SourceFile.Companion.kotlin +import java.io.ByteArrayOutputStream +import java.io.PrintStream +import java.nio.charset.StandardCharsets +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertInstanceOf +import org.junit.jupiter.api.Test + +@OptIn(ExperimentalCompilerApi::class) +class DebugLogTransformerTest { + + private val standardOut = System.out + private val outputStreamCaptor = ByteArrayOutputStream() + + @AfterEach + fun tearDown() { + System.setOut(standardOut) + } + + @Test + fun `compiler plugin successfully transforms code`() { + val srcFile = + kotlin( + "SourceFile.kt", + """ + import ${BuildConfig.KOTLIN_PLUGIN_GROUP}.annotations.DebugLog + + @DebugLog + fun transformable() { + println("In a transformable function!") + } + + @DebugLog + fun transformableWithReturnValue(): String { + println("In a transformable function!") + return "Return value!" + } + + fun nonTransformable() { + println("Not in a transformable function!") + } + + class TracingTest { + @DebugLog + fun transformableInClass() { + println("In a transformable function!") + } + + fun nonTransformable() { + println("Not in a transformable function!") + } + } + """ + .trimIndent()) + + val result = + KotlinCompilation() + .apply { + sources = listOf(srcFile) + compilerPluginRegistrars = listOf(TracingCompilerPluginRegistrar()) + commandLineProcessors = listOf(TracingCommandLineProcessor()) + noOptimize = true + + inheritClassPath = true + messageOutputStream = System.out + } + .compile() + assertEquals(ExitCode.OK, result.exitCode) + + System.setOut(PrintStream(outputStreamCaptor)) + val kClazz = result.classLoader.loadClass("SourceFileKt") + val transformableWithReturnValue = + kClazz.declaredMethods.first { it.name == "transformableWithReturnValue" } + val retVal = transformableWithReturnValue.invoke(null) + assertInstanceOf(String::class.java, retVal) + assertEquals("Return value!", retVal) + assertEquals( + """ + ⇢ transformableWithReturnValue() + In a transformable function! + ⇠ transformableWithReturnValue [] = Return value! + """ + .trimIndent(), + outputStreamCaptor + .toString(StandardCharsets.UTF_8) + .trim() + .replace("\\[.*]".toRegex(), "[]"), + ) + } +} diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts new file mode 100644 index 0000000..10d6245 --- /dev/null +++ b/gradle-plugin/build.gradle.kts @@ -0,0 +1,35 @@ +plugins { + `java-gradle-plugin` + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.buildconfig) + alias(libs.plugins.ksp) + `maven-publish` +} + +group = "dev.msfjarvis.tracelog" + +version = "1.0.0-SNAPSHOT" + +kotlin.jvmToolchain(11) + +kotlin.explicitApi() + +buildConfig { + val project = projects.compilerPlugin + packageName("${group}.gradle.plugin") + useKotlinOutput { internalVisibility = true } + buildConfigField("String", "KOTLIN_PLUGIN_GROUP", "\"${project.group}\"") + buildConfigField("String", "KOTLIN_PLUGIN_NAME", "\"${project.name}\"") + buildConfigField("String", "KOTLIN_PLUGIN_VERSION", "\"${project.version}\"") +} + +gradlePlugin.plugins.register("dev.msfjarvis.tracelog") { + id = group.toString() + implementationClass = "$group.gradle.plugin.TraceLogGradlePlugin" +} + +dependencies { + compileOnly(libs.kotlin.gradle.plugin) + ksp(libs.auto.ksp) + compileOnly(libs.auto.annotations) +} diff --git a/gradle-plugin/src/main/kotlin/dev/msfjarvis/tracelog/gradle/plugin/TraceLogGradlePlugin.kt b/gradle-plugin/src/main/kotlin/dev/msfjarvis/tracelog/gradle/plugin/TraceLogGradlePlugin.kt new file mode 100644 index 0000000..3c553c4 --- /dev/null +++ b/gradle-plugin/src/main/kotlin/dev/msfjarvis/tracelog/gradle/plugin/TraceLogGradlePlugin.kt @@ -0,0 +1,30 @@ +package dev.msfjarvis.tracelog.gradle.plugin + +import com.google.auto.service.AutoService +import org.gradle.api.Plugin +import org.gradle.api.provider.Provider +import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation +import org.jetbrains.kotlin.gradle.plugin.KotlinCompilerPluginSupportPlugin +import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact +import org.jetbrains.kotlin.gradle.plugin.SubpluginOption + +@AutoService(Plugin::class) +public class TraceLogGradlePlugin : KotlinCompilerPluginSupportPlugin { + + override fun applyToCompilation( + kotlinCompilation: KotlinCompilation<*> + ): Provider> { + return kotlinCompilation.target.project.provider { emptyList() } + } + + override fun getCompilerPluginId(): String = BuildConfig.KOTLIN_PLUGIN_GROUP + + override fun getPluginArtifact(): SubpluginArtifact = + SubpluginArtifact( + groupId = BuildConfig.KOTLIN_PLUGIN_GROUP, + artifactId = BuildConfig.KOTLIN_PLUGIN_NAME, + version = BuildConfig.KOTLIN_PLUGIN_VERSION + ) + + override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean = true +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..533b329 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,20 @@ +[versions] +junit = "5.10.0" +kotlin = "1.9.0" + +[plugins] +buildconfig = "com.github.gmazzo.buildconfig:4.1.2" +kotlin-jvm = {id = "org.jetbrains.kotlin.jvm", version.ref="kotlin"} +ksp = "com.google.devtools.ksp:1.9.0-1.0.13" +spotless = "com.diffplug.spotless:6.20.0" + +[libraries] +auto-annotations = "com.google.auto.service:auto-service-annotations:1.1.1" +auto-ksp = "dev.zacsweers.autoservice:auto-service-ksp:1.1.0" +junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit" } +junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit" } +junit-legacy = "junit:junit:4.13.2" +kotlin-compiler = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable", version.ref = "kotlin" } +kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin"} +kct = "dev.zacsweers.kctfork:core:0.3.0" +truth = "com.google.truth:truth:1.1.5" diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..864d6c4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=591855b517fc635b9e04de1d05d5e76ada3f89f5fc76f87978d1b245b4f69225 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..0adc8e1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5d6e679 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,24 @@ +@file:Suppress("UnstableApiUsage") + +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { repositories { mavenCentral() } } + +plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "0.7.0" } + +rootProject.name = "tracelog" + +include( + "annotations", + "compiler-plugin", + "gradle-plugin", +) + +enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") + +enableFeaturePreview("STABLE_CONFIGURATION_CACHE")