1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2025-09-03 07:09:23 +00:00

add generation of class casts

This commit is contained in:
2022-08-05 16:31:39 +06:00
parent d8f6429385
commit a18eda3db6
66 changed files with 4798 additions and 3732 deletions

View File

@@ -0,0 +1,8 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
}
project.description = "Class Casts generator KSP library to include into your library"
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$publishGradlePath"

View File

@@ -0,0 +1,5 @@
package dev.inmo.tgbotapi.ksp.lib
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class ClassCastsIncluded

View File

@@ -0,0 +1,13 @@
plugins {
id "org.jetbrains.kotlin.jvm"
}
repositories {
mavenCentral()
}
dependencies {
implementation libs.kotlin.poet
implementation libs.ksp
implementation project(":tgbotapi.ksp:lib")
}

View File

@@ -0,0 +1,103 @@
package dev.inmo.tgbotapi.ksp.processor
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.ksp.*
private fun FileSpec.Builder.addTopLevelImport(className: ClassName) {
className.topLevelClassName().let {
addImport(it.packageName, it.simpleNames)
}
}
private fun FileSpec.Builder.createTypeDefinition(ksClassDeclaration: KSClassDeclaration): TypeName {
val className = ksClassDeclaration.toClassName()
return if (ksClassDeclaration.typeParameters.isNotEmpty()) {
className.parameterizedBy(
ksClassDeclaration.typeParameters.map {
it.bounds.first().resolve().also {
val typeClassName = it.toClassName()
addTopLevelImport(typeClassName)
}.toTypeName()
}
)
} else {
className
}
}
fun FileSpec.Builder.fill(
sourceKSClassDeclaration: KSClassDeclaration,
subtypesMap: Map<KSClassDeclaration, Set<KSClassDeclaration>>,
targetClassDeclaration: KSClassDeclaration = sourceKSClassDeclaration
) {
if (sourceKSClassDeclaration == targetClassDeclaration) {
subtypesMap[sourceKSClassDeclaration] ?.forEach {
fill(sourceKSClassDeclaration, subtypesMap, it)
}
} else {
val sourceClassName = sourceKSClassDeclaration.toClassName()
val targetClassClassName = targetClassDeclaration.toClassName()
val targetClassTypeDefinition = createTypeDefinition(targetClassDeclaration)
val simpleName = targetClassDeclaration.simpleName.asString()
val withFirstLowerCase = simpleName.replaceFirstChar { it.lowercase() }
val castedOrNullName = "${withFirstLowerCase}OrNull"
addTopLevelImport(targetClassClassName)
addFunction(
FunSpec.builder(castedOrNullName).apply {
receiver(sourceClassName)
addCode(
"return this as? %L",
targetClassTypeDefinition
)
returns(targetClassTypeDefinition.copy(nullable = true))
addModifiers(KModifier.INLINE)
}.build()
)
addFunction(
FunSpec.builder("${withFirstLowerCase}OrThrow").apply {
receiver(sourceClassName)
addCode(
"return this as %L",
targetClassTypeDefinition
)
returns(targetClassTypeDefinition)
addModifiers(KModifier.INLINE)
}.build()
)
addFunction(
FunSpec.builder("if$simpleName").apply {
val genericType = TypeVariableName("T", null)
addTypeVariable(genericType)
receiver(sourceClassName)
addParameter(
"block",
LambdaTypeName.get(
null,
targetClassTypeDefinition,
returnType = genericType
)
)
addCode(
"return ${castedOrNullName}() ?.let(block)",
targetClassTypeDefinition
)
returns(genericType.copy(nullable = true))
addModifiers(KModifier.INLINE)
}.build()
)
subtypesMap[targetClassDeclaration] ?.let {
if (it.count { it.classKind == ClassKind.CLASS } > 1) {
it
} else {
it.filter { it.classKind != ClassKind.CLASS }
}
} ?.forEach {
fill(sourceKSClassDeclaration, subtypesMap, it)
fill(targetClassDeclaration, subtypesMap, it)
}
}
}

View File

@@ -0,0 +1,65 @@
package dev.inmo.tgbotapi.ksp.processor
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.ksp.writeTo
import dev.inmo.tgbotapi.ksp.lib.ClassCastsIncluded
import java.io.File
class TelegramBotAPISymbolProcessor(
private val codeGenerator: CodeGenerator,
private val targetPackage: String = "",
private val outputFile: String = "Output",
private val outputFolder: String? = null
) : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
val classes = resolver.getSymbolsWithAnnotation(ClassCastsIncluded::class.qualifiedName!!).filterIsInstance<KSClassDeclaration>()
val classesSubtypes = mutableMapOf<KSClassDeclaration, MutableSet<KSClassDeclaration>>()
resolver.getAllFiles().forEach {
it.declarations.forEach { potentialSubtype ->
if (potentialSubtype is KSClassDeclaration) {
val allSupertypes = potentialSubtype.getAllSuperTypes().map { it.declaration }
classes.forEach {
if (it in allSupertypes) {
classesSubtypes.getOrPut(it) { mutableSetOf() }.add(potentialSubtype)
}
}
}
}
}
fun fillWithSealeds(source: KSClassDeclaration, current: KSClassDeclaration = source) {
current.getSealedSubclasses().forEach {
classesSubtypes.getOrPut(source) { mutableSetOf() }.add(it)
fillWithSealeds(source, it)
}
}
classes.forEach { fillWithSealeds(it) }
val fileSpec = FileSpec.builder(
targetPackage,
outputFile
).apply {
classes.forEach {
fill(
it,
classesSubtypes.toMap()
)
}
}.build()
runCatching {
outputFolder ?.also {
File(it).apply {
delete()
runCatching { mkdirs() }
fileSpec.writeTo(this)
}
} ?: fileSpec.writeTo(codeGenerator, false)
}
return emptyList()
}
}

View File

@@ -0,0 +1,14 @@
package dev.inmo.tgbotapi.ksp.processor
import com.google.devtools.ksp.processing.*
class TelegramBotAPISymbolProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
return TelegramBotAPISymbolProcessor(
environment.codeGenerator,
environment.options["cctargetPackage"] ?: "",
environment.options["ccoutputFileName"] ?: "Output",
environment.options["ccoutputFolder"],
)
}
}

View File

@@ -0,0 +1 @@
dev.inmo.tgbotapi.ksp.processor.TelegramBotAPISymbolProcessorProvider