[Test] Fix proper use of annotation parameter names in generated classes

When an annotation parameter has a different name than "value" or there is more than one annotation parameter we need to specify annotation parameter names explicitly in generated Java source code.

Fix using classes as annotation parameters in generated classes
This commit is contained in:
Dmitriy Dolovov
2022-01-26 19:38:44 +03:00
parent 938baa5cfe
commit 18cd07ea5f
2 changed files with 33 additions and 12 deletions
@@ -0,0 +1,15 @@
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.generators.model
class AnnotationArgumentModel(
val name: String = DEFAULT_NAME,
val value: Any
) {
companion object {
const val DEFAULT_NAME = "value"
}
}
@@ -10,15 +10,17 @@ import org.jetbrains.kotlin.utils.Printer
class AnnotationModel( class AnnotationModel(
val annotation: Class<out Annotation>, val annotation: Class<out Annotation>,
val arguments: List<Any> val arguments: List<AnnotationArgumentModel>
) { ) {
fun generate(p: Printer) { fun generate(p: Printer) {
val argumentsString = arguments.joinToString(separator = ",") { val needExplicitNames = arguments.singleOrNull()?.name != AnnotationArgumentModel.DEFAULT_NAME
when (it) { val argumentsString = arguments.joinToString(separator = ", ") { argument ->
is Enum<*> -> "${it.javaClass.simpleName}.${it.name}" val valueString = when (val value = argument.value) {
is Class<*> -> "${it.simpleName}.class" is Enum<*> -> "${value.javaClass.simpleName}.${value.name}"
else -> "\"$it\"" is Class<*> -> "${value.simpleName}.class"
else -> "\"$value\""
} }
if (needExplicitNames) "${argument.name} = $valueString" else valueString
} }
p.print("@${annotation.simpleName}($argumentsString)") p.print("@${annotation.simpleName}($argumentsString)")
} }
@@ -27,10 +29,10 @@ class AnnotationModel(
fun imports(): List<Class<*>> { fun imports(): List<Class<*>> {
return buildList { return buildList {
add(annotation) add(annotation)
arguments.mapNotNullTo(this) { arguments.mapNotNullTo(this) { argument ->
when (it) { when (val value = argument.value) {
is Enum<*> -> it.javaClass is Enum<*> -> value.javaClass
is Class<*> -> it is Class<*> -> value
else -> null else -> null
} }
} }
@@ -38,6 +40,10 @@ class AnnotationModel(
} }
} }
fun annotation(annotation: Class<out Annotation>, vararg arguments: Any): AnnotationModel { fun annotation(annotation: Class<out Annotation>, singleArgumentValue: Any): AnnotationModel {
return AnnotationModel(annotation, arguments.toList()) return AnnotationModel(annotation, listOf(AnnotationArgumentModel(value = singleArgumentValue)))
}
fun annotation(annotation: Class<out Annotation>, vararg arguments: Pair<String, Any>): AnnotationModel {
return AnnotationModel(annotation, arguments.map { AnnotationArgumentModel(it.first, it.second) })
} }