The Java
Virtual Machine
& the Kotlin Compiler
kotlinglang.org/education
|
Kotlin
The Java language
Compilation process – Java vs C
Java bytecode
public class examples/Main {
public <init>()V
L0
LINENUMBER 3 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
RETURN
L1
LOCALVARIABLE this Lorg/examples/Main; L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1
public static main([Ljava/lang/String;)V
L0
LINENUMBER 5 L0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
LDC "Hello, World!"
ICONST_0
ANEWARRAY java/lang/Object
INVOKEVIRTUAL java/io/PrintStream.print
(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;
POP
L1
LINENUMBER 6 L1
RETURN
L2
LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
MAXSTACK = 3
MAXLOCALS = 1
}
public class Main {
public static void main(String[] args) {
System.out.print("Hello, World!");
}
}
The JVM under the hood
.сlass files�with bytecodes
Class loading�services
Memory management�(heap, GC)
JVM
bytecode -> machine code
translation services
Interpreter
JIT-compiler
Memory organisation
JVM memory is divided into two parts:
Weak generational hypothesis
According to the weak generational hypothesis, objects tend to die young.
A related assumption is that, as an object lives longer, the likelihood will be that it will continue to live increases.
total size of objects
lifetime
Generations
The memory of a program can be divided into two generations:
Garbage collection (GC) can be similarly divided:
Dead objects
Stack
Young generation
Old generation
A
B
C
D
E
Serial garbage collector
The first garbage collector created was the serial garbage collector, which is single-threaded, and the parallel and CMS garbage collectors are based on it.
○ Eden – Roughly 8/10 of the young generation
○ Survivor 0 – Roughly 1/10 of the young generation
○ Survivor 1 – Roughly 1/10 of the young generation
○ Tenured – Roughly 2/3 of the heap
Tenured
Eden
Old generation
S0
S1
Young generation
How garbage collection works
No available space in Eden
Before GC:
Memory to free, dead objects
After GC:
Surviving objects
Current state:
How garbage collection works
After GC:
No available space in Eden
Before GC:
Current state:
How garbage collection works
No available space in Eden
Before GC:
After GC:
Current state:
How garbage collection works
No available space in Eden
Before GC:
After GC:
Not enough space to move objects from Eden to Survivor 1
Current state:
Just-in-time compilation
Interpreting a command is much slower than executing it directly on the processor.
Why, then, do we need the interpreter?
Just-in-time compilation
Interpreter
JIT-compiler
Why, then, do we need the interpreter?
vs
Just-in-time compilation
Code that will take a long time to run or code that runs frequently, because the compilation overhead will be covered by the profit from having optimized execution.
What sorts of JIT code are worth compiling?
Just-in-time compilation
Some guy named Alan Turing said it is impossible.
But empirically it is possible. If a piece of code took a long enough time to execute once, then most likely the same will be true in the future.
How can we understand which pieces of code will take a long time to execute?
The JVM under the hood
Why does the compiler need to access the interpreter?
.сlass files�with bytecodes
Class loading�services
Memory management�(heap, GC)
JVM
bytecode -> machine code
translation services
Interpreter
JIT-compiler
The JVM under the hood
Why does the compiler need to access the interpreter?
class PiUtils {
private static final double PI = 3.141592653589;
public static double getPiSquared() {
return PI * PI;
}
}
public static double getPiSquared() {
return 9.869604401084375;
}
The JVM under the hood
Why does the compiler need to access the interpreter?
class PiUtils {
private static final double PI = 4;
public static double getPiSquared() {
return PI * PI;
}
}
public static double getPiSquared() {
return 9.869604401084375;
}
Reflection
The Kotlin language
Kotlin compiler
Parser
Backend
Frontend
.kt files
Kotlin compiler
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Parsing in a nutshell
'2 * 7 + 3'
'2'
'*'
'7'
'+'
'3'
Sum
'+'
'3'
Product
'*'
'2'
'7'
Sum
3
Product
2
7
Source code
List of tokens
CST
AST
left operand
right operand
left operand
right operand
Kotlin compiler
Splitting the program into tokens (keywords, identifiers, etc.).
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler
Converting the list of tokens into CST or AST
PSI or Lighter AST builder
Lexer
.kt files
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler: PSI
Kotlin compiler: PSI
'String'
fun hello(user: String) = ...
FUN
'fun'
' '
'hello'
VALUE_PARAMETER_LIST
' '
'='
' '
...
VALUE_PARAMETER
')'
'('
'user'
':'
' '
...
Kotlin compiler: PSI
CALL_EXPRESSION
REFERENCE_EXPRESSION
VALUE_ARGUMENT
')'
'('
fun hello(user: String) = println("Hello, $user")
VALUE_ARGUMENT_LIST
'println'
STRING_TEMPLATE
'\"'
LITERAL_STRING_TEMPLATE_ENTRY
SHORT_STRING_TEMPLATE_ENTRY
'\"'
'Hello, '
'$'
REFERENCE_EXPRESSION
'user'
Kotlin compiler: PSI
CALL_EXPRESSION
REFERENCE_EXPRESSION
VALUE_ARGUMENT
')'
'('
fun hello(user: String) = println("Hello, $user")
VALUE_ARGUMENT_LIST
'println'
STRING_TEMPLATE
'\"'
LITERAL_STRING_TEMPLATE_ENTRY
SHORT_STRING_TEMPLATE_ENTRY
'\"'
'Hello, '
'$'
REFERENCE_EXPRESSION
'user'
Kotlin compiler: PSI
CALL_EXPRESSION
REFERENCE_EXPRESSION
VALUE_ARGUMENT
')'
'('
fun hello(user: String) = println("Hello, $user")
VALUE_ARGUMENT_LIST
'println'
STRING_TEMPLATE
'\"'
LITERAL_STRING_TEMPLATE_ENTRY
SHORT_STRING_TEMPLATE_ENTRY
'\"'
'Hello, '
'$'
REFERENCE_EXPRESSION
'user'
Kotlin compiler
The so-called FIR tree is being built,. It’s an analogue of the PSI, but it’s mutable.
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
FIR? Another tree!
SimpleFunction (name = hello)
ValueParameter (name = user)
ResolvedTypeRef(=kotlin/String)
...
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef(=kotlin/Unit)
body
returnTypeRef
valueParameters
returnTypeRef
FIR? Another tree!
SimpleFunction (name = hello)
ValueParameter (name = user)
ResolvedTypeRef(=kotlin/String)
...
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef(=kotlin/Unit)
body
returnTypeRef
valueParameters
returnTypeRef
FIR? Another tree!
StringConcatenationCall
ArgumentList
FunctionCall
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef (=kotlin/String)
ConstExpression (value = "Hello, ", kind = String)
ResolvedTypeRef(=kotlin/String)
QualifiedAccessExpression
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = toString)
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = user)
typeRef
calleeReference
typeRef
calleeReference
explictReceiver
typeRef
arguments
arguments
typeRef
argumentList
FIR? Another tree!
StringConcatenationCall
ArgumentList
FunctionCall
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef (=kotlin/String)
ConstExpression (value = "Hello, ", kind = String)
ResolvedTypeRef(=kotlin/String)
QualifiedAccessExpression
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = toString)
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = user)
typeRef
calleeReference
typeRef
calleeReference
explictReceiver
typeRef
arguments
arguments
typeRef
argumentList
FIR? Another tree!
StringConcatenationCall
ArgumentList
FunctionCall
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef (=kotlin/String)
ConstExpression (value = "Hello, ", kind = String)
ResolvedTypeRef(=kotlin/String)
QualifiedAccessExpression
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = toString)
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = user)
typeRef
calleeReference
typeRef
calleeReference
explictReceiver
typeRef
arguments
arguments
typeRef
argumentList
FIR? Another tree!
StringConcatenationCall
ArgumentList
FunctionCall
fun hello(user: String) = println("Hello, $user")
ResolvedTypeRef (=kotlin/String)
ConstExpression (value = "Hello, ", kind = String)
ResolvedTypeRef(=kotlin/String)
QualifiedAccessExpression
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = toString)
ResolvedTypeRef (=kotlin/String)
ResolvedNameReference (name = user)
typeRef
calleeReference
typeRef
calleeReference
explictReceiver
typeRef
arguments
arguments
typeRef
argumentList
FIR: desugaring
if (b) {
println("Hello")
}
for (s in list) {
println(s)
}
val (a, b) = "a" to "b"
when {
b -> println("Hello")
}
val <iterator> = list.iterator()
while (<iterator>.hasNext()) {
val s = <iterator>.next()
println(s)
}
val <destruct> = "a" to "b"
val a = <destruct>.component1()
val b = <destruct>.component2()
Kotlin compiler
Resolving the FQ names
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler: resolve
fun myFunction() {
}
fun myFunction() {
}
Library A
Library B
Short FQ name: myFunction
Resolved FQ name: org.libraryA.myFunction
Short FQ name: myFunction
Resolved FQ name: org.libraryB.myFunction
Kotlin compiler
Infers all types and resolves functions bodies
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler
fun hello(user: String) = println("Hello, $user")
SimpleFirFunction (name = hello)
ValueParameter (name = user)
ConstExpression (value = "Hello, ", kind = String)
...
ResolvedTypeRef (=kotlin/String)
UserTypeRef (="String")
ImplicitTypeRef
ResolvedTypeRef (=kotlin/String)
ResolvedTypeRef (=kotlin/Unit)
body
valueParameters
returnTypeRef
returnTypeRef
typeRef
Type resolution
Type inference
Java interoperability: nullability
Java sources�
public class Main {
public static String foo() {
// TODO
}
}
Kotlin sources��var a: ???? = foo()
Java interoperability: nullability
Java sources�
public class Main {
public static String foo() {
// TODO
}
}
Kotlin sources��var a: ???? = foo()
String!
Java interoperability: nullability
Java sources�
public class Main {
public static String foo() {
// TODO
}
}
Kotlin sources��var a: ???? = foo()
String!
Java interoperability: nullability
Java sources�
public class Main {
@NotNull
public static String foo() {
// TODO
}
}
Kotlin sources��var a: String = foo()
Java interoperability: collection mapping
Java sources�
public class Main {
@NotNull
public static List<@NotNull String> foo() {
// TODO
}
}
Kotlin sources��var a: ???? = foo()
Java interoperability: collection mapping
Java sources�
public class Main {
@NotNull
public static List<@NotNull String> foo() {
// TODO
}
}
Kotlin sources��var a: ???? = foo()
(Mutable)List<String>
Kotlin compiler: control- and data-flow analysis
val a: Int
while(true) {
if (Random.nextBoolean()) {
a = 15
break
}
}
println(a) // It compiles!
Each variable is initialized before being used.
Each immutable variable is not reassigned after initialization.
Kotlin compiler: control- and data-flow analysis
fun bar(): Int {
print("Again")
while (true) {
print(" and again")
}
} // It compiles!
fun baz(): Long {
error("YOLO! :)")
} // It compiles!
If the return type is not Unit, then the function won’t return control unless it returns something.
Kotlin compiler: control- and data-flow analysis
fun Any?.printFirstElement() {
when (this) {
is List<*> -> get(0)
is Iterable<*> -> iterator().next()
}
}
fun String?.length(): Int =
if (this == null) 0
else length
fun Int?.isEven(): Boolean =
this != null && this % 2 == 0
If type check is successful, then the checked value is automatically casted to the corresponding type.
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Exit if
Exit loop block
Function call: x.foo()
Exit function bar
true
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Type operator: x as A
Jump: break
true
false
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
Kotlin compiler: control- and data-flow analysis
Enter function bar
Enter while loop
Evaluate loop condition
Exit loop
Enter loop block
Evaluate if condition
Enter if
Type operator: x as A
Exit if
Exit loop block
Jump: break
Function call: x.foo()
Exit function bar
true
true
false
false
interface A {
fun foo()
}
fun bar(x: Any, b: Boolean) {
while (true) {
if (b) {
x as A
break
}
}
x.foo()
}
Enter if branch
x is A
Kotlin compiler
Almost all checks you've ever seen in IntelliJ IDEA.
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler: diagnostics
Kotlin compiler
On the backend, we DO NOT resolve, but only use the received information
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler
IR, a representation slightly different from FIR.��It is still common for all platforms.
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
public fun hello(user: kotlin.String): kotlin.Unit defined in example in file Example.kt
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Reference to value-parameter user: kotlin.String defined in example.hello
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Type: kotlin.String
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Type: kotlin.String
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Type: kotlin.Unit
Kotlin compiler: resolved tree
fun hello(user: String) = println("Hello, $user")
Call: kotlin.io.println(kotlin.String)
IR? Yet another tree!
// file 'src/kotlin/example.kt'
package helloWorld
fun hello(user: String) = println("Hello, $user")
fun main(args: Array<String>) {
val user = args[0]
hello(user)
}
The code:
IR? Yet another tree!
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
FILE fqName:helloWorld fileName:/example.kt
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt'
type=kotlin.Unit origin=null
FUN name:main visibility:public modality: FINAL <>(args:kotlin.Array<kotlin.String>)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
VALUE_PARAMETER name:args index:0 type:kotlin.Array<kotlin.String>
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
VAR name:user type:kotlin.String [val]
STRING_CONCATENATION type=kotlin.String
CALL 'public final fun get (index: kotlin.Int): T of kotlin.Array [operator] declared in kotlin.Array'
type kotlin.String origin=null
CALL 'public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
type kotlin.Unit origin=null
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String
declared in helloWorld.hello'
type=kotlin.String origin=null
GET_VAR 'args: kotlin.Array<kotlin.String>
declared in helloworld.main'
type=kotlin.Array<kotLin.String> origin=null
CONST Int type=kotlin.Int value=0
GET_VAR 'val user: kotlin.String [val]
declared in helloworld.main'
type=kotlin.String origin=null
user:
index:
$this:
message:
Its IR:
Back-end intermediate representation: a closer look
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
fun hello(user: String) = println("Hello, $user")
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Back-end intermediate representation: a closer look
fun hello(user: String) = println("Hello, $user")
FUN name:hello visibility:public modality:FINAL <>(user:kotlin.String)
returnType:kotlin.Unit
VALUE_PARAMETER name:user index:0 type:kotlin.String
BLOCK_BODY
RETURN type=kotlin.Nothing
from='public final fun hello (user: kotlin.String): kotlin.Unit declared in helloworld'
STRING_CONCATENATION type=kotlin.String
CONST String type=kotlin.String value="Hello, "
GET VAR 'user: kotlin.String declared in helloworld.hello' type=kotlin.String origin=null
CALL 'public final fun println (message: kotlin.Any?): kotlin.Unit [inline] declared in kotlin.io.ConsoleKt' type=kotlin.Unit origin=null
message:
Kotlin compiler
Platform-specific code, such as bytecode for the JVM
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
Resolution
IR generator
IR optimizer
Parser
Frontend
Backend
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Kotlin compiler
Lexer
.kt files
PSI or Lighter AST builder
Diagnostics
Type inference
IR generator
IR optimizer
Parser
Frontend
Backend
Platform-specific code, such as bytecode for the JVM
JVM
JavaScript
Native
Other
(WASM, Python, etc.?)
Resolution
KLibs
JAR analogues – store a serialized IR for the subsequent use of cross-platform libraries.
Common code
JVM code
Native code
Kotlin/Native
Kotlin/JVM
Classes
Native objects
KLib
Compiler plugins
You can extend any compile phase via compiler plugins. To do so, you need to implement compiler extensions and register them.
To register extensions, you need to inherit from CompilerPluginRegistrar ( ComponentRegistrar for previous versions).
Don’t forget to use supportsK2 = true if you need to support the FIR frontend
Compiler plugins: FIR extensions
To get the full list of the extensions, please see: package org.jetbrains.kotlin.fir.extensions (link).
Consider an example:
/*
* Generates top level class
*
* package foo.bar
*
* public final class MyClass {
* fun foo(): String = "Hello world"
* }
*/
Compiler plugins: FIR extensions
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
companion object {
// foo.bar.MyClass
val MY_CLASS_ID = ClassId(
FqName.fromSegments(listOf("foo", "bar")),
Name.identifier("MyClass")
)
// foo.bar.MyClass.foo
val FOO_ID = CallableId(MY_CLASS_ID, Name.identifier("foo"))
}
override fun generateClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
...
}
...
}
Compiler plugins: FIR extensions
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
companion object {
// foo.bar.MyClass
val MY_CLASS_ID = ClassId(
FqName.fromSegments(listOf("foo", "bar")),
Name.identifier("MyClass")
)
// foo.bar.MyClass.foo
val FOO_ID = CallableId(MY_CLASS_ID, Name.identifier("foo"))
}
override fun generateClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
...
}
...
}
Compiler plugins: FIR extensions
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
companion object {
// foo.bar.MyClass
val MY_CLASS_ID = ClassId(
FqName.fromSegments(listOf("foo", "bar")),
Name.identifier("MyClass")
)
// foo.bar.MyClass.foo
val FOO_ID = CallableId(MY_CLASS_ID, Name.identifier("foo"))
}
override fun generateClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
...
}
...
}
Compiler plugins: FIR extensions
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
companion object {
// foo.bar.MyClass
val MY_CLASS_ID = ClassId(
FqName.fromSegments(listOf("foo", "bar")),
Name.identifier("MyClass")
)
// foo.bar.MyClass.foo
val FOO_ID = CallableId(MY_CLASS_ID, Name.identifier("foo"))
}
override fun generateClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
...
}
...
}
Compiler plugins: FIR extensions
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
companion object {
// foo.bar.MyClass
val MY_CLASS_ID = ClassId(
FqName.fromSegments(listOf("foo", "bar")),
Name.identifier("MyClass")
)
// foo.bar.MyClass.foo
val FOO_ID = CallableId(MY_CLASS_ID, Name.identifier("foo"))
}
override fun generateClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
...
}
...
}
Compiler plugins: FIR extensions
You use a special key to mark everything generated by the compiler and can transfer any information between frontend and backend. So it also helps to find the new declaration to generate it’s IR.
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
object Key : GeneratedDeclarationKey()
...
}
Compiler plugins: FIR extensions
Don’t forget to register all new declarations.
class SimpleClassGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
...
override fun getTopLevelClassIds(): Set<ClassId> {
return setOf(MY_CLASS_ID)
}
override fun hasPackage(packageFqName: FqName): Boolean {
return packageFqName == MY_CLASS_ID.packageFqName
}
}
Compiler plugins: IR extensions
Actually, the compiler has only one extension for IRs: IrGenerationExtension.
You just need to implement some transformers and accept them:
class SimpleIrGenerationExtension: IrGenerationExtension {
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
val transformers = listOf(SimpleIrBodyGenerator(pluginContext))
for (transformer in transformers) {
moduleFragment.acceptChildrenVoid(transformer)
}
}
}
Don’t forget to check the key (use the interestedIn function)!
Compiler plugins: popular plugins
Thank you
|
Kotlin