Skip to content

Instantly share code, notes, and snippets.

View drawers's full-sized avatar
🟩
In greenish twilight at the bottom of the Rhine

David Rawson drawers

🟩
In greenish twilight at the bottom of the Rhine
View GitHub Profile
@Test
fun `target is a data class`() {
val kotlinSource = SourceFile.kotlin(
"file1.kt",
"""
package com.tests.summable
import com.tsongkha.kspexample.annotation.IntSummable
@IntSummable
private fun KotlinCompilation.generatedSourceFor(fileName: String): String {
return kspSourcesDir.walkTopDown()
.firstOrNull { it.name == fileName }
?.readText()
?: throw IllegalArgumentException(
"Unable to find $fileName in ${
kspSourcesDir.walkTopDown().filter { it.isFile }.toList()
}"
)
}
private fun compilation(vararg source: SourceFile) = KotlinCompilation().apply {
sources = source.toList()
symbolProcessorProviders = listOf(IntSummableProcessorProvider())
workingDir = temporaryFolder.root
inheritClassPath = true
verbose = false
}
dependencies {
testImplementation("com.github.tschuchortdev:kotlin-compile-testing:1.4.4")
testImplementation("com.github.tschuchortdev:kotlin-compile-testing-ksp:1.4.4")
}
// continued from above
if (summables.isEmpty()) {
return
}
val fileSpec = FileSpec.builder(
packageName = packageName,
fileName = classDeclaration.simpleName.asString() + "Ext"
).apply {
addFunction(
dependencies {
implementation("com.squareup:kotlinpoet:1.10.1")
implementation("com.squareup:kotlinpoet-ksp:1.10.1")
}
inner class Visitor : KSVisitorVoid() {
private lateinit var className: String
private lateinit var packageName: String
private val summables: MutableList<String> = mutableListOf()
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val qualifiedName = classDeclaration.qualifiedName?.asString()
className = qualifiedName
packageName = classDeclaration.packageName.asString()
interface KSVisitor<D, R> {
fun visitNode(node: KSNode, data: D): R
fun visitAnnotated(annotated: KSAnnotated, data: D): R
// etc.
}
inner class Visitor : KSVisitorVoid() {
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val qualifiedName = classDeclaration.qualifiedName?.asString()
if (!classDeclaration.isDataClass()) {
logger.error(
"@IntSummable cannot target non-data class $qualifiedName",
classDeclaration
)
class IntSummableProcessor(
private val options: Map<String, String>,
private val codeGenerator: CodeGenerator,
private val logger: KSPLogger
) : SymbolProcessor {
private lateinit var intType: KSType
override fun process(resolver: Resolver): List<KSAnnotated> {
intType = resolver.builtIns.intType