Share
Embed
Writing Kotlin Compiler Plugins with Arrow Meta
We’ll learn about how to write and test compiler plugins with Arrow Meta. This library provides an API for source transformations, automatic code refactoring, and much more. We’ll look at main use cases from type classes, comprehensions, and lenses that are made possible with Arrow Meta. We’ll also look at how to test each use case.
Mohit S
October 08, 2020
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
213 slides
-
Writing Compiler Plugins with Arrow Meta • Kotlin Compiler •
Compiler Plugin with Meta • Testing Compiler Plugins • IDE Plugins -
Motivations • How do we build tools with Kotlin? •
How do we introduce Functional Programming? -
Code Parsing Analysis Resolve Code-gen Done class UserRepo { fun
getUsers(): List<User> fun addUser() fun deleteUser(id: Int) } -
Code Parsing Analysis Resolve Code-gen Done class UserRepo { fun
getUsers(): List<User> fun addUser() fun deleteUser(id: Int) } Type Checking -
Code Parsing Analysis Resolve Code-gen Done if ("hello" "== 1)
{ } Operator ‘"==’cannot be applied to ‘String’ and ‘Int’ Type Checking -
arrow-kt/arrow-meta Code ! Issues Pull Requests rrow Meta Writing compiler
plugins, source transformations, IDEA plugins, linters, type search engines, automatic code refactoring,""... Gradle Build passing latest snapshot v1.3.61 -
Code Parsing Analysis Resolve Code-gen Done class UserRepo { fun
getUsers(): List<User> fun addUser() fun deleteUser(id: Int) } -
Code Parsing Analysis Resolve Code-gen Done Intermediate Representation (IR) Js
JVM Native Hook into IR -
Writing Complier Plugins with Arrow Meta - Simple Hello World
Plugin - Write & Test Plugin for logging - Combine Transformations - Custom Type Checker -
Steps to Write Compiler Plugin 1. Create Compiler Plugin(s) 2.
Register Plugin -
fun main() { helloWorld() } fun helloWorld() { } HelloWorldKt
src main kotlin com learn arrow-meta HelloWorldKt -
fun main() { helloWorld() } fun helloWorld() { println("Hello DroidCon
EMEA!”) } Generate HelloWorldKt src main kotlin com learn arrow-meta HelloWorldKt -
val Meta.helloWorld: CliPlugin data class Plugin<A>( val name: String, val
meta: A.() "-> List<ExtensionPhase> ) Name of compiler plugin -
val Meta.helloWorld: CliPlugin data class Plugin<A>( val name: String, val
meta: A.() "-> List<ExtensionPhase> ) Phases of compilation -
val Meta.helloWorld: CliPlugin get() = "Hello World" { } Creates
a Plugin object -
val Meta.helloWorld: CliPlugin get() = "Hello World" { } operator
fun String.invoke( phases: CompilerContext.() "-> List<ExtensionPhase> ): CliPlugin = Plugin(this, phases) -
val Meta.helloWorld: CliPlugin get() = "Hello World" { } How
do we hook into the parsing phase? -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( )
} Intercept compilation phases -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( )
} fun meta( vararg phases: ExtensionPhase ): List<ExtensionPhase> Define list of phases -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> } ) } Finds a function named “helloWorld" -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> } ) } Quote Template DSL fun nodeName { } Function, Expression -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> } ) } Quote Template DSL fun nodeName { } Specify Transformation -
val Meta.helloWorld: CliPlugin get() = "Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> } ) } Function -
val Meta.helloWorld: CliPlugin get() = “Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> Transform.replace( ) } ) } Replace Transformation -
val Meta.helloWorld: CliPlugin get() = “Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> Transform.replace( replacing = c newDeclaration = """|fun helloWorld(): Unit = | println("Hello DroidCon EMEA!") |""".function.syntheticScope ) } ) } Function to replace -
val Meta.helloWorld: CliPlugin get() = “Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> Transform.replace( replacing = c, newDeclaration = """|fun helloWorld(): Unit = | println("Hello DroidCon EMEA!") |""".function.syntheticScope ) } ) } Replacement -
val Meta.helloWorld: CliPlugin get() = “Hello World" { meta( namedFunction(this,
{ name "== "helloWorld" }) { c "-> Transform.replace( replacing = c, newDeclaration = """|fun helloWorld(): Unit = | println(“Hello DroidCon EMEA!") |""".function.syntheticScope ) } ) } -
Writing Complier Plugins with Arrow Meta 1. Create Compiler Plugin(s)
2. Register Plugin -
class MetaPlugin : Meta { override fun intercept(ctx: CompilerContext): List<CliPlugin>
= listOf( helloWorld ) } Create Meta Class -
class MetaPlugin : Meta { override fun intercept(ctx: CompilerContext): List<CliPlugin>
= listOf( helloWorld ) } Register All Plugins with Kotlin Compiler -
class MetaPlugin : Meta { override fun intercept(ctx: CompilerContext): List<CliPlugin>
= listOf( helloWorld ) } Register Hello World Plugin -
fun main() { helloWorld() } fun helloWorld() { } HelloWorldKt
src main kotlin com learn arrow-meta HelloWorldKt -
fun main() { helloWorld() } fun helloWorld() { println("Hello DroidCon
EMEA!”) } HelloWorld.kt Hello DroidCon EMEA! HelloWorldKt src main kotlin com learn arrow-meta HelloWorldKt -
fun main() { helloWorld() } fun helloWorld() { } HelloWorldKt
src main kotlin com learn arrow-meta HelloWorldKt -
fun main() { helloWorld() } fun helloWorld() { } HelloWorldKt
src main kotlin com learn arrow-meta HelloWorldKt -
Writing Complier Plugins with Arrow Meta - Simple Hello World
Plugin - Write & Test Plugin for logging - Combine Transformations - Custom Type Checker -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin fun calculate(n:
Int): Long = listOf(1L,2L,3L).take(n).last() -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() Annotation to log execution time -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Original Operation -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Log method name & argument -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Get current time -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Original Operation -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Calculate execution time -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } Log execution time -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long { println(""-> calculate(n=${'$'}n)") val startTime = System.currentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(""<- calculate[ran in ${'$'}timeToRun ms]") return result } How do we generate this code? -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() Filter -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin @DebugLog fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() Modify -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Specify plugin name -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Specify Extension Phases -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Find Function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Filter Function with DebugLog Annotation -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Create extension to find method -
fun KtAnnotated.hasAnnotation( vararg annotationNames: String ): Boolean { val names
= annotationNames.toHashSet() val predicate: (KtAnnotationEntry) "-> Boolean = { it.typeReference "?.typeElement "?.safeAs<KtUserType>() "?.referencedName in names } return annotationEntries.any(predicate) } Annotations to match -
fun KtAnnotated.hasAnnotation( vararg annotationNames: String ): Boolean { val names
= annotationNames.toHashSet() val predicate: (KtAnnotationEntry) "-> Boolean = { it.typeReference "?.typeElement "?.safeAs<KtUserType>() "?.referencedName in names } return annotationEntries.any(predicate) } Convert to set -
fun KtAnnotated.hasAnnotation( vararg annotationNames: String ): Boolean { val names
= annotationNames.toHashSet() val predicate: (KtAnnotationEntry) "-> Boolean = { it.typeReference "?.typeElement "?.safeAs<KtUserType>() "?.referencedName in names } return annotationEntries.any(predicate) } Match annotation’s name -
fun KtAnnotated.hasAnnotation( vararg annotationNames: String ): Boolean { val names
= annotationNames.toHashSet() val predicate: (KtAnnotationEntry) "-> Boolean = { it.typeReference "?.typeElement "?.safeAs<KtUserType>() "?.referencedName in names } return annotationEntries.any(predicate) } Check function’s annotations -
fun KtAnnotated.hasAnnotation( vararg annotationNames: String ): Boolean { val names
= annotationNames.toHashSet() val predicate: (KtAnnotationEntry) "-> Boolean = { it.typeReference "?.typeElement "?.safeAs<KtUserType>() "?.referencedName in names } return annotationEntries.any(predicate) } -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Filter function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Transform function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Add debug log to function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Modify Function -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } Get info on function -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } Create new function -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
fun replace(function: KtNamedFunction): String { val functionName = function.name val
paramName = function.valueParameters.first().name val functionBody = function.body()"?.bodySourceAsExpression() return """ |fun ${functionName}(${paramName}: Int): Long { | println(""-> $functionName(${paramName}=$${paramName})") | val startTime = System.currentTimeMillis() | val result = $functionBody | val timeToRun = System.currentTimeMillis() - startTime | println(""<- ${functionName}[ran in ${'$'}timeToRun ms]") | return result | }""" } -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } Convert to function -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } val String.function get() = NamedFunction( delegate.createFunction(trimMargin().trim()) ) -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } -
class DebugLogMetaPlugin : Meta { override fun intercept(ctx: CompilerContext): List<CliPlugin>
= listOf( debugLog ) } Register Debug Log Plugin -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin fun main()
{ calculate(10) } @DebugLog fun calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() -
DebugLogPlugin src main kotlin com learn arrow-meta DebugLogPlugin fun main()
{ calculate(10) } @DebugLog fun calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() DebugLogPlugin.kt "-> calculate(n=10) "<- calculate[ran in 36 ms] -
val Meta.debugLog: CliPlugin get() = "DebugLog" { meta( namedFunction(this, {
validateFunction() }) { c "-> Transform.replace( replacing = c, newDeclaration = replace(c).function ) } ) } How do we test this? -
arrow-kt/arrow-meta Code ! Issues Pull Requests compiler-plugin 447 commits 2060af5
2 days ago ide-plugin gradle-plugin prelude docs meta-testing -
arrow-kt/arrow-meta Code ! Issues Pull Requests compiler-plugin 447 commits 2060af5
2 days ago ide-plugin gradle-plugin prelude docs meta-testing Testing utilities -
val source = """ |annotation class DebugLog | |@DebugLog |fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source -
val source = """ |annotation class DebugLog | |@DebugLog |fun
prime(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source val String.source = Code.Source(text = this) -
val expectedOutput = """ |annotation class DebugLog | |fun calculate(n:
Int): Long { | println(""-> calculate(n=${'$'}n)") | val startTime = System.currentTimeMillis() | val result = listOf(1L,2L,3L).take(n).last() | val timeToRun = System.currentTimeMillis() - startTime | println(""<- calculate[ran in ${'$'}timeToRun ms]") | return result | }""".trimMargin().trim().source Plugin should generate this -
@Test fun `should log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source }, assert = { quoteOutputMatches(expectedOutput) } ) } Testing utility -
@Test fun `should log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source }, assert = { quoteOutputMatches(expectedOutput) } ) } Plugin to test -
@Test fun `should log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source }, assert = { quoteOutputMatches(expectedOutput) } ) } Source to test -
@Test fun `should log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source }, assert = { quoteOutputMatches(expectedOutput) } ) } Expected generate code -
@Test fun `should log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { debuglog }, assert = { quoteOutputMatches(expectedOutput) } ) } How do we run this test? -
@Test fun `sshould log function time execution`() { CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { debuglog }, assert = { quoteOutputMatches(expectedOutput) } ) } fun assertThis(compilerTest: CompilerTest) = compilerTest.run(interpreter) -
@Test fun `should log function time execution`() { val compilerTest
= CompilerTest(…) assertThis(compilerTest) } Run test -
@Test fun `should log function time execution`() { assertThis(CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source}, assert = { quoteOutputMatches(expectedOutput) } )) } How does this test run? -
val source = """ |annotation class DebugLog | |@DebugLog |fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source Source of compiler plugin -
val source = """ |annotation class DebugLog | |@DebugLog |fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source DebugLogPlugin.kt START quote.doAnalysis: [KtFile: Source.kt] Create a file with source -
val source = """ |annotation class DebugLog | |@DebugLog |fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source DebugLogPlugin.kt START quote.doAnalysis: [KtFile: Source.kt] Transform file into AST Transformed file: KtFile: Source.kt. -
val source = """ |annotation class DebugLog | |@DebugLog |fun
calculate(n: Int): Long = listOf(1L,2L,3L).take(n).last() | """.trimMargin().trim().source DebugLogPlugin.kt Transformed file: KtFile: Source.kt. [(KtFile: Source.kt, File(decls=[Structured(mods=[Lit(keyword=ANNOTATION)], ""... Structure of file -
@Test fun `should log function time execution`() { assertThis(CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source}, assert = { quoteOutputMatches(expectedOutput) } )) } DebugLogPlugin.kt Transformed file: KtFile: Source.kt. [(KtFile: Source.kt, File(decls=[Structured(mods=[Lit(keyword=ANNOTATION)], ""... Run test -
@Test fun `should log function time execution`() { assertThis(CompilerTest( config
= { listOf(addMetaPlugins(DebugLogMetaPlugin())) }, code = { source}, assert = { quoteOutputMatches(expectedOutput) } )) } DebugLogPlugin.kt ktFile: KtFile: Source.kt ——————————————— fun calculate(n: Int): Long { println(""-> calculate(n=$n)") val startTime = System.curentTimeMillis() val result = listOf(1L,2L,3L).take(n).last() val timeToRun = System.currentTimeMillis() - startTime println(“"<- calculate[ran in $timeToRun ms]") return result } Generate log -
Writing Complier Plugins with Arrow Meta - Simple Hello World
Plugin - Write & Test Plugin for logging - Combine Transformations - Custom Type Checker -
Transformations - Replace - Remove - New Sources - Combine
Transformations -
Quotes - Expressions - Declarations - Class & Object -
Properties - Type Reference -
fun main() { helloWorld() } fun helloWorld() { println("Hello DroidCon
EMEA!”) } Remove ReplacePluginKt src main kotlin com learn arrow-meta ReplacePluginKt -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } Define Plugin -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } Quote -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } Filter function -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } NamedFunction -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } Template -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } Convert to expression -
val Meta.removePlugin: CliPlugin get() = “Remove" { meta( namedFunction(this, {
name "== “helloWorld" }) { c "-> Transform.remove( removeIn = c, declaration = """println("Hello Droidcon EMEA!")""".expressionIn(c) ) } ) } -
fun main() { helloWorld() } fun helloWorld() { println("Hello DroidCon
EMEA!”) } ReplacePluginKt ReplacePluginKt src main kotlin com learn arrow-meta ReplacePluginKt Greeting is not printed -
Transformations - Replace - Remove - New Sources - Combine
Transformations -
data class User(""...) NewSourcePluginKt src main kotlin com learn arrow-meta
NewSourcePluginKt class UserAdapter_Generated { fun deserialize() = { } fun serialize() = { } } Generate adapter in new file -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Create Plugin -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Define Extension Phases -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Quote -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Find user class -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Transform class -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Create adapter in new file -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Adapter -
val Meta.adapterGenerator: CliPlugin get() = "Adapter Plugin" { meta( classDeclaration(this,
{ name "== "User" }) { Transform.newSources( """ package adapters class ${name}Adapter_Generated { fun deserialize() = { } fun serialize() = { } } """.file("${name}Adapter_Generated") ) } ) } Create a new file -
NewSourcePluginKt src main kotlin com learn arrow-meta UserAdapter_Generated.kt class UserAdapter_Generated
{ fun deserialize() = { } fun serialize() = { } } Generated file -
Transformations - Replace - Remove - New Sources - Combine
Transformations -
CombineTransformKt src main kotlin com learn arrow-meta CombineTransformKt public class
SimpleClass { fun printGreeting() { println("Hello DroidCon EMEA!”) } } -
CombineTransformKt src main kotlin com learn arrow-meta CombineTransformKt public class
SimpleClass { fun printGreeting() { println("Hello DroidCon EMEA!”) } } Change class visibility to private -
CombineTransformKt src main kotlin com learn arrow-meta CombineTransformKt public class
SimpleClass { fun printGreeting() { println("Hello DroidCon EMEA!”) } } Remove Expression -
CombineTransformKt src main kotlin com learn arrow-meta CombineTransformKt private class
SimpleClass { ""... } -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "ManySimpleCase" }) { c "-> changeClassVisibility("ManySimpleCase", c, this) + removeGreeting(c, this) } ) } -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility("SimpleClass", c, this) + removeGreeting(c, this) } ) } Filter Class -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility(“SimpleClass", c, this) + removeGreeting(c, this) } ) } Change Class visible to private -
fun CompilerContext.changeClassVisibility( className: String, context: KtClass, declaration: ClassDeclaration ): Transform<KtClass>
= declaration.run { } SimpleClass -
fun CompilerContext.changeClassVisibility( className: String, context: KtClass, declaration: ClassDeclaration ): Transform<KtClass>
= declaration.run { } Class to transform -
fun CompilerContext.changeClassVisibility( className: String, context: KtClass, declaration: ClassDeclaration ): Transform<KtClass>
= declaration.run { } Class’s Declaration -
fun CompilerContext.changeClassVisibility(""...): Transform<KtClass> = declaration.run { Transform.replace( replacing = context,
newDeclaration = """ | private class $className { | $body | } """.`class`.syntheticScope ) } -
fun CompilerContext.changeClassVisibility(""...): Transform<KtClass> = declaration.run { Transform.replace( replacing = context,
newDeclaration = """ | private class $className { | $body | } """.`class`.syntheticScope ) } New Identifier -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility(“SimpleClass", c, this) + removeGreeting(c, this) } ) } Remove Greeting -
fun CompilerContext.removeGreeting( context: KtClass, declaration: ClassDeclaration ): Transform<KtClass> = declaration.run
{ Transform.remove( removeIn = context, declaration = """ fun printFirst() = println("Hello DroidCon EMEA!") """.expressionIn(context) ) } -
fun CompilerContext.removeGreeting( context: KtClass, declaration: ClassDeclaration ): Transform<KtClass> = declaration.run
{ Transform.remove( removeIn = context, declaration = """ fun printGreeting() = println("Hello DroidCon EMEA!") """.expressionIn(context) ) } Remove Method -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility(“SimpleClass", c, this) + removeGreeting(c, this) } ) } Combine? -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility(“SimpleClass", c, this) + removeGreeting(c, this) } ) } Use Plus Operator + + -
val Meta.composeTransforms: CliPlugin get() = "Compose Transforms" { meta( classDeclaration(this,
{ name "== "SimpleClass" }) { c "-> changeClassVisibility(“SimpleClass", c, this) + removeGreeting(c, this) } ) } Remove Greeting -
CombineTransformKt src main kotlin com learn arrow-meta CombineTransformKt private class
SimpleClass { ""... } -
Transformations - Replace - Remove - New Sources - Combine
Transformations -
Writing Complier Plugins with Arrow Meta - Simple Hello World
Plugin - Write & Test Plugin for logging - Combine Transformations - Custom Type Checker -
val Meta.typeChecker: CliPlugin get() = “Custom Type Checker” { meta(
typeChecker { ProofTypeChecker(ctx) } } -
val Meta.typeChecker: CliPlugin get() = “Custom Type Checker” { meta(
typeChecker { CustomTypeChecker(ctx) } } -
class CustomTypeChecker() : NewKotlinTypeChecker { override fun isSubtypeOf( subtype: KotlinType,
supertype: KotlinType ): Boolean { override fun equalTypes( subtype: KotlinType, supertype: KotlinType ): Boolean = } Type Checker Provided by Kotlin Compiler -
class CustomTypeChecker() : NewKotlinTypeChecker { override fun isSubtypeOf( subtype: KotlinType,
supertype: KotlinType ): Boolean override fun equalTypes( subtype: KotlinType, supertype: KotlinType ): Boolean } Define Sub-typing -
class CustomTypeChecker() : NewKotlinTypeChecker { override fun isSubtypeOf( subtype: KotlinType,
supertype: KotlinType ): Boolean override fun equalTypes( subtype: KotlinType, supertype: KotlinType ): Boolean } Define Equality -
class CustomTypeChecker() : NewKotlinTypeChecker { override fun isSubtypeOf( subtype: KotlinType,
supertype: KotlinType ): Boolean override fun equalTypes( subtype: KotlinType, supertype: KotlinType ): Boolean } Define Equality -
class TasksViewModel { fun refreshTasks() { setState { ""... }
} } Show icon in IDE -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin” { } operator
fun String.invoke( phases: IdeContext.() "-> List<ExtensionPhase> ): IdePlugin -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin" { meta( )
} Add extension phases -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } Add marker for a node in AST -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } Path to icon in resources -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } AST Node -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } Message to show on mouse over -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } Filter function with property -
val MetaIde.mviPlugin: IdePlugin get() = “MVI Plugin".invoke { meta( addLineMarkerProvider(
icon = PluginIcons.UPDATE, composite = KtNamedFunction"::class.java, message = { f: KtNamedFunction "-> “State will be updated by action.” }, transform = { it.safeAs<KtNamedFunction>()"?.takeIf { f "-> f.name "== "setState" } } ) ) } -
class IdeMetaPlugin : MetaPlugin(),{ override fun intercept(ctx: IdeContext): List<IdePlugin> =
listOf( mviPlugin ) } Extend MetaPlugin -
class IdeMetaPlugin : MetaPlugin() { override fun intercept(ctx: IdeContext): List<IdePlugin>
= listOf( mviPlugin ) } Add all IDE plugins -
class TasksViewModel { fun refreshTasks() { setState { ""... }
} } Show icon in IDE -
class TasksViewModel { fun refreshTasks() { setState { ""... }
} } Show message for feature State will be updated by action. -
Thank you Arrow Team & All Contributors • Rachel M.
Carmena • Raúl Raja • Imran Settuba • Simon Veragauwen • and all contributors! -
Resources • Writing Kotlin Compiler Plugins with Arrow Meta •
Lambda World 2019 - Arrow Meta - Enabling Functional Programming in the Kotlin Compiler • Arrow Meta. Kotlin Metaprogramming for the masses • Type Proofs and FP for the Kotlin Type System