-
Notifications
You must be signed in to change notification settings - Fork 286
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for
KSAnnotation.toAnnotationSpec()
(#1196)
- Loading branch information
Showing
5 changed files
with
240 additions
and
18 deletions.
There are no files selected for viewing
120 changes: 120 additions & 0 deletions
120
interop/ksp/src/main/kotlin/com/squareup/kotlinpoet/ksp/annotations.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
/* | ||
* Copyright (C) 2021 Square, Inc. | ||
* | ||
* 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 | ||
* | ||
* https://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.squareup.kotlinpoet.ksp | ||
|
||
import com.google.devtools.ksp.symbol.AnnotationUseSiteTarget | ||
import com.google.devtools.ksp.symbol.ClassKind | ||
import com.google.devtools.ksp.symbol.KSAnnotation | ||
import com.google.devtools.ksp.symbol.KSClassDeclaration | ||
import com.google.devtools.ksp.symbol.KSName | ||
import com.google.devtools.ksp.symbol.KSType | ||
import com.google.devtools.ksp.symbol.KSTypeAlias | ||
import com.squareup.kotlinpoet.AnnotationSpec | ||
import com.squareup.kotlinpoet.AnnotationSpec.UseSiteTarget | ||
import com.squareup.kotlinpoet.ClassName | ||
import com.squareup.kotlinpoet.CodeBlock | ||
import com.squareup.kotlinpoet.ParameterizedTypeName | ||
|
||
/** Returns an [AnnotationSpec] representation of this [KSAnnotation] instance. */ | ||
@KotlinPoetKspPreview | ||
public fun KSAnnotation.toAnnotationSpec(): AnnotationSpec { | ||
val builder = when (val type = annotationType.resolve().unwrapTypeAlias().toTypeName()) { | ||
is ClassName -> AnnotationSpec.builder(type) | ||
is ParameterizedTypeName -> AnnotationSpec.builder(type) | ||
else -> error("This is never possible.") | ||
} | ||
useSiteTarget?.let { builder.useSiteTarget(it.kpAnalog) } | ||
// TODO support type params once they're exposed https://github.com/google/ksp/issues/753 | ||
for (argument in arguments) { | ||
val member = CodeBlock.builder() | ||
val name = argument.name!!.getShortName() | ||
member.add("%L = ", name) | ||
addValueToBlock(argument.value!!, member) | ||
builder.addMember(member.build()) | ||
} | ||
return builder.build() | ||
} | ||
|
||
private val AnnotationUseSiteTarget.kpAnalog: UseSiteTarget get() = when (this) { | ||
AnnotationUseSiteTarget.FILE -> UseSiteTarget.FILE | ||
AnnotationUseSiteTarget.PROPERTY -> UseSiteTarget.PROPERTY | ||
AnnotationUseSiteTarget.FIELD -> UseSiteTarget.FIELD | ||
AnnotationUseSiteTarget.GET -> UseSiteTarget.GET | ||
AnnotationUseSiteTarget.SET -> UseSiteTarget.SET | ||
AnnotationUseSiteTarget.RECEIVER -> UseSiteTarget.RECEIVER | ||
AnnotationUseSiteTarget.PARAM -> UseSiteTarget.PARAM | ||
AnnotationUseSiteTarget.SETPARAM -> UseSiteTarget.SETPARAM | ||
AnnotationUseSiteTarget.DELEGATE -> UseSiteTarget.DELEGATE | ||
} | ||
|
||
internal fun KSType.unwrapTypeAlias(): KSType { | ||
return if (this.declaration is KSTypeAlias) { | ||
(this.declaration as KSTypeAlias).type.resolve() | ||
} else { | ||
this | ||
} | ||
} | ||
|
||
@KotlinPoetKspPreview | ||
private fun addValueToBlock(value: Any, member: CodeBlock.Builder) { | ||
when (value) { | ||
is List<*> -> { | ||
// Array type | ||
member.add("arrayOf(⇥⇥") | ||
value.forEachIndexed { index, innerValue -> | ||
if (index > 0) member.add(", ") | ||
addValueToBlock(innerValue!!, member) | ||
} | ||
member.add("⇤⇤)") | ||
} | ||
is KSType -> { | ||
val unwrapped = value.unwrapTypeAlias() | ||
val isEnum = (unwrapped.declaration as KSClassDeclaration).classKind == ClassKind.ENUM_ENTRY | ||
if (isEnum) { | ||
val parent = unwrapped.declaration.parentDeclaration as KSClassDeclaration | ||
val entry = unwrapped.declaration.simpleName.getShortName() | ||
member.add("%T.%L", parent.toClassName(), entry) | ||
} else { | ||
member.add("%T::class", unwrapped.toClassName()) | ||
} | ||
} | ||
is KSName -> | ||
member.add( | ||
"%T.%L", ClassName.bestGuess(value.getQualifier()), | ||
value.getShortName() | ||
) | ||
is KSAnnotation -> member.add("%L", value.toAnnotationSpec()) | ||
else -> member.add(memberForValue(value)) | ||
} | ||
} | ||
|
||
/** | ||
* Creates a [CodeBlock] with parameter `format` depending on the given `value` object. | ||
* Handles a number of special cases, such as appending "f" to `Float` values, and uses | ||
* `%L` for other types. | ||
*/ | ||
internal fun memberForValue(value: Any) = when (value) { | ||
is Class<*> -> CodeBlock.of("%T::class", value) | ||
is Enum<*> -> CodeBlock.of("%T.%L", value.javaClass, value.name) | ||
is String -> CodeBlock.of("%S", value) | ||
is Float -> CodeBlock.of("%Lf", value) | ||
is Double -> CodeBlock.of("%L", value) | ||
is Char -> CodeBlock.of("$value.toChar()") | ||
is Byte -> CodeBlock.of("$value.toByte()") | ||
is Short -> CodeBlock.of("$value.toShort()") | ||
// Int or Boolean | ||
else -> CodeBlock.of("%L", value) | ||
} |
18 changes: 0 additions & 18 deletions
18
...processor/src/main/kotlin/com/squareup/kotlinpoet/ksp/test/processor/ExampleAnnotation.kt
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
...rocessor/src/main/kotlin/com/squareup/kotlinpoet/ksp/test/processor/exampleAnnotations.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/* | ||
* Copyright (C) 2021 Square, Inc. | ||
* | ||
* 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 | ||
* | ||
* https://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.squareup.kotlinpoet.ksp.test.processor | ||
|
||
import kotlin.reflect.KClass | ||
|
||
annotation class ExampleAnnotation | ||
|
||
annotation class ComprehensiveAnnotation<T : CharSequence>( | ||
val boolean: Boolean, | ||
val booleanArray: BooleanArray, | ||
val byte: Byte, | ||
val byteArray: ByteArray, | ||
val short: Short, | ||
val shortArray: ShortArray, | ||
val int: Int, | ||
val intArray: IntArray, | ||
val long: Long, | ||
val longArray: LongArray, | ||
val float: Float, | ||
val floatArray: FloatArray, | ||
val double: Double, | ||
val doubleArray: DoubleArray, | ||
val string: String, | ||
val stringArray: Array<String>, | ||
val someClass: KClass<*>, | ||
val someClasses: Array<KClass<*>>, | ||
val enumValue: AnnotationEnumValue, | ||
val enumValueArray: Array<AnnotationEnumValue>, | ||
val anotherAnnotation: AnotherAnnotation, | ||
val anotherAnnotationArray: Array<AnotherAnnotation>, | ||
// This is still included even when the argument is omitted until https://github.com/google/ksp/issues/674 | ||
val defaultingString: String = "defaultValue", | ||
) | ||
|
||
annotation class AnotherAnnotation(val input: String) | ||
|
||
enum class AnnotationEnumValue { | ||
ONE, TWO, THREE | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters