codegen.FactoryClass.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mmkv-compiler Show documentation
Show all versions of mmkv-compiler Show documentation
A strong Kotlin-flavored MMKV extension library.
The newest version!
/*
* Copyright (C) 2024 Meowool
*
* This file is part of the MMKV-KTX project .
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meowool.mmkv.ktx.compiler.codegen
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.meowool.mmkv.ktx.compiler.Names
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.ksp.toClassName
open class FactoryClass : CodegenStep() {
override fun generate() {
val className = context.factoryClassName
val classBuilder = TypeSpec.interfaceBuilder(className)
val preferences = context.preferences
preferences.process {
val propertySpec = PropertySpec.builder(
name = it.preferencesName(),
type = context.preferencesClassName(it),
).build()
classBuilder.addProperty(propertySpec)
}
val classSpec = classBuilder.build()
val factorySpec = FunSpec.builder(className.simpleName)
.addModifiers(KModifier.INLINE)
.returns(className)
.addParameters(context.classTypeConvertersParams)
.addStatement(
"return·%T(%L)",
context.factoryImplClassName,
context.classTypeConvertersParams.joinToString { it.name }
)
.build()
// if (context.needInjectTypeConverters) {
// factorySpec
// .addParameters(context.classTypeConvertersParams)
// .addStatement(
// "return·%T(%L)",
// context.factoryImplClassName,
// context.classTypeConvertersParams.joinToString { it.name }
// )
// .build()
// } else {
// factorySpec.addStatement("return %T()", context.factoryImplClassName)
// }
// TODO: Add KDoc for generated symbols.
FileSpec.builder(className)
.addAnnotation(
AnnotationSpec.builder(Suppress::class)
.addMember("%S", "NOTHING_TO_INLINE")
.build()
)
.addType(classSpec)
.addFunction(factorySpec)
.build()
.write(preferences)
}
fun KSClassDeclaration.preferencesName(): String {
val annotation = requireNotNull(findAnnotation(Names.Preferences))
return annotation.findStringArgument("name") ?: simpleName.asString().lowercaseFirstChar()
}
}