1 of 103

The Java

Virtual Machine

& the Kotlin Compiler

kotlinglang.org/education

|

Kotlin

2 of 103

The Java language

  • Was created in 1995.
  • Is an OOP language with strong static typing.
  • Has Just-in-time (JIT) compilation.
  • Uses the Java Virtual Machine (JVM).
  • Has a garbage collector, meaning you can allocate memory and it will be freed automatically.

3 of 103

Compilation process – Java vs C

4 of 103

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!");

}

}

​

5 of 103

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

6 of 103

Memory organisation

JVM memory is divided into two parts:

  • Static memory, or non-heap memory, is created when the JVM starts, and it primarily stores class structures, fields, method data, and the code for methods and constructors.
    • Loaded classes
    • Stacks of all threads
    • Service memory for the JVM itself
    • Small – roughly 1024 KB for stacks
  • Heap memory is the runtime data area shared among all JVM threads, and it is used to allocate memory for all Java objects.
    • All objects created during a program’s execution
    • Large – from several MB up to several TB

7 of 103

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

8 of 103

Generations

The memory of a program can be divided into two generations:

  • Young
  • Old

​

Garbage collection (GC) can be similarly divided:

  • Small GC clears only objects from young generation
  • Full GC clears objects from both generations

​

​

9 of 103

Dead objects

Stack

Young generation

Old generation

A

B

C

D

E

10 of 103

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.

​

  • In the serial garbage collector, the heap is divided into 4 areas:

○ 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

​

  • (Almost) All objects are created in the Eden area.

Tenured

Eden

Old generation

S0

S1

Young generation

11 of 103

How garbage collection works

No available space in Eden

Before GC:

Memory to free, dead objects

After GC:

Surviving objects

Current state:

12 of 103

How garbage collection works

After GC:

No available space in Eden

Before GC:

Current state:

13 of 103

How garbage collection works

No available space in Eden

Before GC:

After GC:

Current state:

14 of 103

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:

15 of 103

Just-in-time compilation

  • Program profiling occurs at runtime.
  • Pieces of code are compiled for a specific platform to optimize the execution time.

Interpreting a command is much slower than executing it directly on the processor.

​

​

​

Why, then, do we need the interpreter?

16 of 103

Just-in-time compilation

Interpreter

  • Starts working almost instantly.
  • The performance of the executable code is poor.

​

​

JIT-compiler

  • Kicks in after a long delay (needs time for optimizations).
  • The performance of the executable (compiled) code is high.

​

​

Why, then, do we need the interpreter?

vs

17 of 103

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?

18 of 103

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?

19 of 103

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

20 of 103

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;

}

21 of 103

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

22 of 103

The Kotlin language

  • Can be compiled into JVM bytecode.
  • Is interoperable with Java.
    • Can work in Java projects.
    • Can use Java libraries.
  • Is safe and concise.
  • Provides the ability to integrate into the compilation process (compiler plugins).
  • Is the main development language for Android applications, according to Google.

23 of 103

Kotlin compiler

Parser

Backend

Frontend

.kt files

24 of 103

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.?)

25 of 103

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

26 of 103

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.?)

27 of 103

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.?)

28 of 103

Kotlin compiler: PSI

29 of 103

Kotlin compiler: PSI

'String'

fun hello(user: String) = ...

FUN

'fun'

' '

'hello'

VALUE_PARAMETER_LIST

' '

'='

' '

...

VALUE_PARAMETER

')'

'('

'user'

':'

' '

...

30 of 103

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'

31 of 103

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'

32 of 103

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'

33 of 103

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.?)

34 of 103

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

35 of 103

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

36 of 103

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

37 of 103

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

38 of 103

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

39 of 103

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

40 of 103

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()

​

​

41 of 103

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.?)

42 of 103

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

43 of 103

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.?)

44 of 103

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

45 of 103

Java interoperability: nullability

Java sources�

public class Main {

public static String foo() {

// TODO

}

}

​

Kotlin sources��var a: ???? = foo()

  • Java nullable types in Kotlin

46 of 103

Java interoperability: nullability

Java sources�

public class Main {

public static String foo() {

// TODO

}

}

​

Kotlin sources��var a: ???? = foo()

String!

  • Java nullable types in Kotlin

47 of 103

Java interoperability: nullability

Java sources�

public class Main {

public static String foo() {

// TODO

}

}

​

Kotlin sources��var a: ???? = foo()

String!

  • Java nullable types in Kotlin
  • String! is the type range: [String..String?]

48 of 103

Java interoperability: nullability

Java sources�

public class Main {

@NotNull

public static String foo() {

// TODO

}

}

​

Kotlin sources��var a: String = foo()

  • Java nullable types in Kotlin
  • Nullability annotations @NotNull and @Nullable

49 of 103

Java interoperability: collection mapping

Java sources�

public class Main {

@NotNull

public static List<@NotNull String> foo() {

// TODO

}

}

​

  • Java collection types in Kotlin

Kotlin sources��var a: ???? = foo()

50 of 103

Java interoperability: collection mapping

Java sources�

public class Main {

@NotNull

public static List<@NotNull String> foo() {

// TODO

}

}

​

  • Java collection types in Kotlin
  • (Mutable)List<T> is the type range: [MutableList<T>..List<T>]

Kotlin sources��var a: ???? = foo()

(Mutable)List<String>

51 of 103

Kotlin compiler: control- and data-flow analysis

  • Variable initialization analysis
  • Return analysis
  • Smart cast 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.

52 of 103

Kotlin compiler: control- and data-flow analysis

  • Variable initialization analysis
  • Return analysis
  • Smart cast 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.

53 of 103

Kotlin compiler: control- and data-flow analysis

  • Variable initialization analysis
  • Return analysis
  • Smart cast 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.

54 of 103

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

55 of 103

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

56 of 103

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

57 of 103

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

58 of 103

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

59 of 103

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

60 of 103

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

61 of 103

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

62 of 103

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

63 of 103

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

64 of 103

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

65 of 103

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

66 of 103

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

67 of 103

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

68 of 103

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.?)

69 of 103

Kotlin compiler: diagnostics

70 of 103

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.?)

71 of 103

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.?)

72 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

73 of 103

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

74 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

Reference to value-parameter user: kotlin.String defined in example.hello

​

75 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

Type: kotlin.String

76 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

Type: kotlin.String

77 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

Type: kotlin.Unit

78 of 103

Kotlin compiler: resolved tree

fun hello(user: String) = println("Hello, $user")

​

Call: kotlin.io.println(kotlin.String)

79 of 103

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:

80 of 103

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:

81 of 103

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:

82 of 103

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:

83 of 103

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:

84 of 103

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:

85 of 103

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:

86 of 103

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:

87 of 103

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:

88 of 103

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:

89 of 103

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.?)

90 of 103

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

91 of 103

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

92 of 103

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

​

93 of 103

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"

* }

*/

​

94 of 103

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<*>? {

...

}

...

}

95 of 103

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<*>? {

...

}

...

}

​

96 of 103

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<*>? {

...

}

...

}

​

97 of 103

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<*>? {

...

}

...

}

98 of 103

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<*>? {

...

}

...

}

​

99 of 103

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()

...

}

​

100 of 103

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

}

​

}

​

101 of 103

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)!

​

​

102 of 103

Compiler plugins: popular plugins

  • kotlinx.serialization — Generates visitor code for serializable classes.
  • all-open — Marks all classes as open classes.
  • kapt — An annotation processor.
  • ksp — An API for developing lightweight compiler plugins.
  • Jetpack Compose — Generates efficient UI from its declarative description.
  • Arrow Meta — Compiler plugin API that empowers all Arrow libraries.
  • ...

103 of 103

Thank you

|

Kotlin