Slide 1

Slide 1 text

Meta-Programming with Kotlin @_jitinsharma Jitin Sharma

Slide 2

Slide 2 text

Open Ended

Slide 3

Slide 3 text

Open Ended Automation

Slide 4

Slide 4 text

Open Ended Automation Kotlin

Slide 5

Slide 5 text

Meta-Programming

Slide 6

Slide 6 text

Code Generators Code Parsers

Slide 7

Slide 7 text

Code Generators Code Parsers Annotation Processors?

Slide 8

Slide 8 text

Code Generators Code Parsers Annotation Processors? Retrofit Gson Dagger

Slide 9

Slide 9 text

Source Code Parsers

Slide 10

Slide 10 text

Source Code Parsers? • Gain insights over large codebase • Build static analysis tools • Documentation!

Slide 11

Slide 11 text

Anatomy of Source Code

Slide 12

Slide 12 text

File Class class… Functions Variables • abstract • interface • static • …. • private • protected • public • ….

Slide 13

Slide 13 text

File Classes Functions Variables class… Functions Variables • abstract • interface • object • companion • data • …. • private • internal • typealias • ….

Slide 14

Slide 14 text

val source: String = System.getProperty("user.dir") class Generator : GeneratorConfig { private var replaceIfNecessary = false override fun createConfig(config: Config) { } inner class Template { ... } data class Model(...) }

Slide 15

Slide 15 text

Program Structure Interface

Slide 16

Slide 16 text

PSI • Provides hierarchal content of code • Works across languages

Slide 17

Slide 17 text

PSI PsiFileFactory .getInstance(project) .createFileFromText(KotlinLanguage.INSTANCE, text)

Slide 18

Slide 18 text

PSI PsiFileFactory .getInstance(project) .createFileFromText(KotlinLanguage.INSTANCE, text) private val project by lazy { KotlinCoreEnvironment.createForProduction( Disposer.newDisposable(), CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES ).project }

Slide 19

Slide 19 text

implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.3.61")

Slide 20

Slide 20 text

PsiFile PsiElement PsiElement PsiElement …

Slide 21

Slide 21 text

PsiFile PsiElement PsiElement PsiElement … KtFile

Slide 22

Slide 22 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 23

Slide 23 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 24

Slide 24 text

ArrowView.kt KtFile }

Slide 25

Slide 25 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 26

Slide 26 text

import android.content.Context import android.graphics.Canvas import android.graphics.Color KtImportList KtImportDirective }

Slide 27

Slide 27 text

import android.content.Context import android.graphics.Canvas import android.graphics.Color KtImportList KtImportAlias as AndroidColor KtImportDirective }

Slide 28

Slide 28 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 29

Slide 29 text

class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { KtClass KtSuperTypeEntries } } KtPrimaryConstructor }

Slide 30

Slide 30 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 31

Slide 31 text

private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView } KtParameter KtModifierKeywordToken KtTypeReference KtBlockExpression } } } } KtExpression

Slide 32

Slide 32 text

private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView } /** * Generates an imageview dynamically */ KDoc }

Slide 33

Slide 33 text

ArrowView.kt import android.content.Context import android.graphics.Canvas import android.graphics.Color class ArrowView(context: Context, sides: Float, val base: Float) : View(context) { private fun createIconView(drawable: Drawable): ImageView { val imageView = AppCompatImageView(context) imageView.scaleType = ImageView.ScaleType.CENTER ... return imageView }

Slide 34

Slide 34 text

PSI-Tree ktFile.acceptChildren(// PsiElementVisitor()) ktFile.acceptChildren(classRecursiveVisitor { ktClass -> }) ktFile.acceptChildren(namedFunctionRecursiveVisitor { ktFunction -> })

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

Plugin

Slide 37

Slide 37 text

Source Code as Data Source Code

Slide 38

Slide 38 text

Source Code as Data Source Code @Serializable data class ParsedFile( var name: String, var doc: String? = null, @SerialName("classes") var parsedClasses: List? = null, @SerialName("functions") var parsedFunctions: List? = null, @SerialName("properties") var parsedVariables: List? = null )

Slide 39

Slide 39 text

Source Code as Data Source Code @Serializable data class ParsedFile( var name: String, var doc: String? = null, @SerialName("classes") var parsedClasses: List? = null, @SerialName("functions") var parsedFunctions: List? = null, @SerialName("properties") var parsedVariables: List? = null )

Slide 40

Slide 40 text

Documentation • dokka != configurable • Build custom documentation

Slide 41

Slide 41 text

Static Analysis • Access to every piece of code in your codebase • ktlint!

Slide 42

Slide 42 text

Source Code Generators

Slide 43

Slide 43 text

Source Code Generators? • Avoid manual boilerplate code • Promote templating • Create more formalised code base

Slide 44

Slide 44 text

Writing Source Code • Easy string manipulation with regex and indent extensions • Java8 provides better file operations and Streams! • Coroutines for async

Slide 45

Slide 45 text

Writing Templates val text = """ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } } """.trimIndent() Files.write(path, text)

Slide 46

Slide 46 text

Writing Templates val text = """ class $activityName : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.$layoutName) } } """.trimIndent() Files.write(path, text)

Slide 47

Slide 47 text

Structured Codegen https://github.com/square/kotlinpoet

Slide 48

Slide 48 text

Structured Codegen FileSpec.builder("in.jitinsharma", "MainActivity.kt") TypeSpec.classBuilder() FunSpec.builder("onCreate") addParameter() addModifiers(KModifier.INTERNAL) superclass(TypeVariableName.invoke("AppCompatActivity"))

Slide 49

Slide 49 text

Schema based Codegen { "source": "...", “type": "...", "paths": [] } Source Code

Slide 50

Slide 50 text

Schema based Codegen { "sourceClass": "MainActivity.kt", "sourceXml": "activity_main", "adapter": "CountryListAdapter", "views": [ { "layoutFileName": "country_list_header.xml", "layoutType": "TextView", "viewHolderName": "CountryListHeaderViewHolder" } ] }

Slide 51

Slide 51 text

SqlDelight CREATE TABLE Photos ( id INTEGER NOT NULL, title TEXT NOT NULL ); insert: INSERT INTO Photos (id, title) VALUES (?, ?); getAll: SELECT * FROM Photos;

Slide 52

Slide 52 text

SqlDelight interface PhotoQueries : Transacter { fun getAll(mapper: ( id: String, title: String ) -> T): Query fun getAll(): Query fun insert( id: String, title: String ) }

Slide 53

Slide 53 text

val db = Database(AndroidSqliteDriver(Database.Schema, context, “photo.db”)) db.photoQueries.getAll() -> List SqlDelight - MPP

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

T.use()

Slide 56

Slide 56 text

T.use() codeString .lineSequence() .map { line -> }

Slide 57

Slide 57 text

T.use() codeString .lineSequence() .map { line -> } Files.find(path, 10, BiPredicate { path, _ -> })

Slide 58

Slide 58 text

T.use() codeString .lineSequence() .map { line -> } Files.find(path, 10, BiPredicate { path, _ -> }) Files.write( path, classString.toByteArray(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING)

Slide 59

Slide 59 text

. ├── app ├── module-1 ├── module-2 ├── … └── tools-module java -jar project/build/libs/tools.jar --param

Slide 60

Slide 60 text

. ├── app ├── module-1 ├── module-2 ├── … └── script.kts kscript

Slide 61

Slide 61 text

Fun fact

Slide 62

Slide 62 text

Thanks @_jitinsharma