Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
KSPを使ってコード生成
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Takuji Nishibayashi
December 05, 2023
Technology
480
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
KSPを使ってコード生成
Takuji Nishibayashi
December 05, 2023
More Decks by Takuji Nishibayashi
See All by Takuji Nishibayashi
compose-hot-reload を試そうとした話
takuji31
0
160
CameraX使ってみた
takuji31
0
310
kotlinx.datetime 使ってみた
takuji31
0
1.1k
HiltのCustom Componentについて
takuji31
0
380
java.timeをAndroidで使う
takuji31
0
200
Kotlin Symbol Processing API (KSP) を使って Kotlin ア プリケーションの開発を効率化する
takuji31
1
3.2k
kotlinx.serialization
takuji31
0
700
kanmoba-returns-02.pdf
takuji31
0
290
AndroidXとKotlin Coroutines
takuji31
0
440
Other Decks in Technology
See All in Technology
Foxgloveについて 実際にExtensionを開発して公開するまでの話 / About Foxglove: The Story of Developing and Releasing an Extension
ry0_ka
0
140
LiDAR SLAMの実装とセンサ融合 ~Lie群からContinuous-Time LIOまで~
naokiakai
1
970
勉強会企画をアプリで構造化してみた 〜そこで見えた、AIとの付き合い方〜 / I've structured a study group plan using an app.
pauli
0
320
テスト設計の本質を改めて考えてみる~生成AIを活用する時代だからこそ、作ったテストの説明性を高めよう~
yamasaki696
1
290
実装だけじゃない! CCA-F取得エンジニアが教えるClaude Code開発プロセス活用術
diggymo
1
110
はてなのサービス基盤を支える Kubernetes《足腰》
masayoshimaezawa
0
440
SRE Lounge Hiroshimaへの招待
grimoh
0
230
完全自律ロボットを作りたくて、先に開発を自律させた話(ROS Japan UG #63 LT)
rryz09
0
250
認証認可だけじゃない! ID管理の構成要素と ライフサイクルを意識しよう
ritou
1
490
product engineering with qa
nealle
0
140
Why is RC4 still being used?
tamaiyutaro
0
290
美しいコードを書くためにF#を学んでみた話
yud0uhu
1
200
Featured
See All Featured
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Max Prin - Stacking Signals: How International SEO Comes Together (And Falls Apart)
techseoconnect
PRO
0
200
Intergalactic Javascript Robots from Outer Space
tanoku
273
27k
The SEO Collaboration Effect
kristinabergwall1
1
500
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2k
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
580
B2B Lead Gen: Tactics, Traps & Triumph
marketingsoph
0
170
Rebuilding a faster, lazier Slack
samanthasiow
85
9.5k
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
220
So, you think you're a good person
axbom
PRO
2
2.1k
Done Done
chrislema
186
16k
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
270
Transcript
KSP を使ってコード生成 関西モバイルアプリ研究会 A @takuji31
自己紹介 西林 拓志(にしばやし たくじ) Twitter/GitHub takuji31 株式会社はてな Android アプリケーションエンジ ニア
Android (2009〜) Kotlin (2014〜) 2
KSP 使ってますか? 3
今日は KSP のプロセッサーの作り方(≠ 使い方)について話 します 4
KSP? 5
Kotlin Symbol Processor 6
google/ksp 7
コードにつけられたアノテーションを処理する 8
Kotlin friendly 9
Incremental proccessing 10
KMP 対応 11
Supported libs Dagger / Hilt (alpha) Room Moshi Glide etc.
12
プロセッサーの 作り方 13
source code // これを @SimpleGeneration interface Hoge // こうだ abstract
class AbstractHoge: Hoge 14
build.gradle.kts // ... dependencies { // KSP のAPI implementation("com.google.devtools.ksp:symbol-processing-api:1.9.21-1.0.15") //
KotlinPoet implementation("com.squareup:kotlinpoet:1.15.3") // KotlinPoet のKSP 用拡張 implementation("com.squareup:kotlinpoet-ksp:1.15.3") } 15
SymbolProcessor class ExampleSymbolProcessor( private val codeGenerator: CodeGenerator, private val logger:
KSPLogger ) : SymbolProcessor { override fun process(resolver: Resolver): List<KSAnnotated> { resolver .getSymbolsWithAnnotation(SimpleGeneration::class.qualifiedName!!) .filterIsInstance<KSClassDeclaration>() .forEach { it.accept(SimpleGenerationVisitor(codeGenerator, logger), Unit) } return emptyList() } } 16
Visitor class SimpleGenerationVisitor( private val codeGenerator: CodeGenerator, private val logger:
KSPLogger ) : KSVisitorVoid() { override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) { if (classDeclaration.classKind != ClassKind.INTERFACE) { logger.error("Only interface allowed", classDeclaration) return } val packageName = classDeclaration.packageName.asString() val className = ClassName(packageName, "Abstract" + classDeclaration.simpleName.asString()) val typeSpec = TypeSpec.classBuilder(className) .addModifiers(KModifier.ABSTRACT) .addSuperinterface(classDeclaration.toClassName()) FileSpec.builder(packageName, className.simpleName) .addType(typeSpec.build()) .build() .writeTo( codeGenerator, Dependencies( aggregating = false, classDeclaration.containingFile!! ) ) } } 17
SymbolProcessorProvider class ExampleSymbolProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment):
SymbolProcessor { return ExampleSymbolProcessor(environment.codeGenerator, environment.logger) } } 18
Service Provider // resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider jp.takuji31.kotlinfest2022.compiler.ExampleSymbolProcessorProvider 19
Incremental Processing 20
生成するファイルの依存を定義すれば Processor 側で適 切に処理される 21
Isolated 22
1:N 23
Isolated Dependencies(aggregating = false, classDeclaration.containingFile!!) 24
Aggregated 25
N:1 26
Aggregated (集約) val dependencies: Array<KSAnnotated> = // ... Dependencies(aggregating =
true, *dependencies.mapNotNull { it.containingFile }) 27
依存をちゃんと指定しないと「なぜかコード生成されな い」みたいな事態になる 28
テスト 29
tschuchortdev/kotlin-compile-testing 30
テストコード val source = SourceFile.kotlin( "ExampleClass.kt", """ package jp.takuji31.kotlinfest2022.compiler import
jp.takuji31.kotlinfest2022.compiler.annotation.SimpleGeneration @SimpleGeneration interface SimpleInterface { fun printHelloWorld() } """.trimIndent() ) 31
テストコード val compilation = KotlinCompilation().apply { sources = listOf(source) inheritClassPath
= true symbolProcessorProviders = listOf(ExampleSymbolProcessorProvider()) kspWithCompilation = true } val result = compilation.compile() assertThat(result.exitCode) .isEqualTo(KotlinCompilation.ExitCode.OK) 32
ドキュメント/サンプルコード https://kotlinlang.org/docs/ksp-overview.html 公式ドキュメント https://github.com/google/ksp/tree/main/examples/playground 公式サンプル https://github.com/takuji31/kotlinfest2022-ksp-example 今回のスライドに出てきたソースコード https://github.com/takuji31/navigation-compose-screen 複雑な例 https://speakerdeck.com/takuji31/kotlin-symbol-processing-api-ksp-woshi-tute-
kotlin-a-purikesiyonnokai-fa-woxiao-lu-hua-suru Kotlin Fest 2022 で発表した時のスライド もう少し踏み込んだ話はこちら 33
Enjoy KSP Life! 34