Analysis API: fix annotation rendering for types

This commit is contained in:
Ilya Kirillov
2021-11-18 19:09:21 +01:00
parent 3a5e503f29
commit 193df3e3c4
18 changed files with 262 additions and 75 deletions
@@ -8,10 +8,12 @@ package org.jetbrains.kotlin.analysis.api.descriptors.utils
import org.jetbrains.kotlin.analysis.api.components.KtDeclarationRendererOptions import org.jetbrains.kotlin.analysis.api.components.KtDeclarationRendererOptions
import org.jetbrains.kotlin.analysis.api.components.RendererModifier import org.jetbrains.kotlin.analysis.api.components.RendererModifier
import org.jetbrains.kotlin.analysis.api.descriptors.Fe10AnalysisContext import org.jetbrains.kotlin.analysis.api.descriptors.Fe10AnalysisContext
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.*
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.classId import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.classId
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.isExplicitOverride import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.isExplicitOverride
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.ktModality import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.ktModality
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.ktVisibility import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.ktVisibility
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtConstantValueRenderer
import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor
@@ -103,11 +105,6 @@ internal class KtFe10Renderer(
return return
} }
renderAnnotations(type.annotations) { classId ->
!options.typeRendererOptions.renderFunctionType
|| classId != StandardClassIds.Annotations.ExtensionFunctionType
}
typeRenderer.render(type, this) typeRenderer.render(type, this)
} }
@@ -510,35 +507,7 @@ internal class KtFe10Renderer(
return return
} }
for (annotation in annotations) { renderFe10Annotations(annotations, predicate)
val annotationClass = annotation.annotationClass ?: continue
val classId = annotationClass.classId
if (classId != null && !predicate(classId)) {
continue
}
if (annotationClass.fqNameSafe != StandardNames.FqNames.parameterName) {
append('@')
renderType(annotation.type)
val valueArguments = annotation.allValueArguments.entries.sortedBy { it.key.asString() }
renderList(valueArguments, separator = ", ", prefix = "(", postfix = ")", renderWhenEmpty = false) { (name, value) ->
append(name.render())
append(" = ")
when (value) {
is UByteValue -> append(value.value.toUByte().toString())
is UShortValue -> append(value.value.toUShort().toString())
is UIntValue -> append(value.value.toUInt().toString())
is ULongValue -> append(value.value.toULong().toString())
is EnumValue, is AnnotationValue, is KClassValue, is ArrayValue, is ErrorValue -> append("NOT_CONST_EXPRESSION")
else -> append(value.value)
}
}
append(' ')
}
}
} }
private fun KtFe10RendererConsumer.renderModifiers(descriptor: DeclarationDescriptor) { private fun KtFe10RendererConsumer.renderModifiers(descriptor: DeclarationDescriptor) {
@@ -44,6 +44,10 @@ internal class KtFe10TypeRenderer(private val options: KtTypeRendererOptions, pr
private fun KtFe10RendererConsumer.renderType(type: KotlinType) { private fun KtFe10RendererConsumer.renderType(type: KotlinType) {
if (isDebugText) { if (isDebugText) {
renderTypeAnnotationsDebug(type) renderTypeAnnotationsDebug(type)
} else {
renderFe10Annotations(type.annotations) { classId ->
classId != StandardClassIds.Annotations.ExtensionFunctionType
}
} }
when (val unwrappedType = type.unwrap()) { when (val unwrappedType = type.unwrap()) {
is FlexibleType -> renderFlexibleType(unwrappedType) is FlexibleType -> renderFlexibleType(unwrappedType)
@@ -0,0 +1,40 @@
/*
* Copyright 2010-2021 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.analysis.api.descriptors.utils
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.classId
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.toKtConstantValue
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtConstantValueRenderer
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
internal fun KtFe10RendererConsumer.renderFe10Annotations(annotations: Annotations, predicate: (ClassId) -> Boolean = { true }) {
for (annotation in annotations) {
val annotationClass = annotation.annotationClass ?: continue
val classId = annotationClass.classId
if (classId != null && !predicate(classId)) {
continue
}
if (annotationClass.fqNameSafe != StandardNames.FqNames.parameterName) {
append('@')
append(annotation.fqName?.shortName()?.asString() ?: "ERROR")
val valueArguments = annotation.allValueArguments.entries.sortedBy { it.key.asString() }
renderList(valueArguments, separator = ", ", prefix = "(", postfix = ")", renderWhenEmpty = false) { (name, value) ->
append(name.render())
append(" = ")
append(KtConstantValueRenderer.render(value.toKtConstantValue()))
}
append(' ')
}
}
}
@@ -185,4 +185,26 @@ public class KtFe10RendererTestGenerated extends AbstractKtFe10RendererTest {
public void testWhere() throws Exception { public void testWhere() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/where.kt"); runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/where.kt");
} }
@Nested
@TestMetadata("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types")
@TestDataPath("$PROJECT_ROOT")
public class Types {
@Test
public void testAllFilesPresentInTypes() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@Test
@TestMetadata("annotaionOnTypes.kt")
public void testAnnotaionOnTypes() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types/annotaionOnTypes.kt");
}
@Test
@TestMetadata("annotaionOnTypesWithComplexExpression.kt")
public void testAnnotaionOnTypesWithComplexExpression() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types/annotaionOnTypesWithComplexExpression.kt");
}
}
} }
@@ -39,19 +39,13 @@ internal class ConeTypeIdeRenderer(
if (message != null) append(" <$message>") if (message != null) append(" <$message>")
} }
private var filterExtensionFunctionType: Boolean = false private fun StringBuilder.renderAnnotationList(type: ConeKotlinType) {
if (options.renderTypeAnnotations) {
private fun StringBuilder.renderAnnotationList(annotations: List<FirAnnotation>?) { renderAnnotations(this@ConeTypeIdeRenderer, type.customAnnotations, session)
if (annotations != null) {
val filteredExtensionIfNeeded = annotations.applyIf(filterExtensionFunctionType) {
annotations.filterNot { it.toAnnotationClassId() == StandardClassIds.Annotations.ExtensionFunctionType }
}
renderAnnotations(this@ConeTypeIdeRenderer, filteredExtensionIfNeeded, session)
} }
} }
fun renderType(type: ConeTypeProjection, annotations: List<FirAnnotation>? = null): String = buildString { fun renderType(type: ConeTypeProjection): String = buildString {
when (type) { when (type) {
is ConeKotlinErrorType -> { is ConeKotlinErrorType -> {
renderErrorType(type) renderErrorType(type)
@@ -59,39 +53,36 @@ internal class ConeTypeIdeRenderer(
//is Dynamic??? -> append("dynamic") //is Dynamic??? -> append("dynamic")
is ConeClassLikeType -> { is ConeClassLikeType -> {
if (options.renderFunctionType && shouldRenderAsPrettyFunctionType(type)) { if (options.renderFunctionType && shouldRenderAsPrettyFunctionType(type)) {
val oldFilterExtensionFunctionType = filterExtensionFunctionType renderAnnotationList(type)
filterExtensionFunctionType = true
renderAnnotationList(annotations)
renderFunctionType(type) renderFunctionType(type)
filterExtensionFunctionType = oldFilterExtensionFunctionType
} else { } else {
renderAnnotationList(annotations) renderAnnotationList(type)
renderTypeConstructorAndArguments(type) renderTypeConstructorAndArguments(type)
} }
} }
is ConeTypeParameterType -> { is ConeTypeParameterType -> {
renderAnnotationList(annotations) renderAnnotationList(type)
append(type.lookupTag.name.asString()) append(type.lookupTag.name.asString())
renderNullability(type.type) renderNullability(type.type)
} }
is ConeIntersectionType -> { is ConeIntersectionType -> {
renderAnnotationList(annotations) renderAnnotationList(type)
type.intersectedTypes.joinTo(this, "&", prefix = "(", postfix = ")") { type.intersectedTypes.joinTo(this, "&", prefix = "(", postfix = ")") {
renderType(it) renderType(it)
} }
renderNullability(type.type) renderNullability(type.type)
} }
is ConeFlexibleType -> { is ConeFlexibleType -> {
renderAnnotationList(annotations) renderAnnotationList(type)
append(renderFlexibleType(renderType(type.lowerBound), renderType(type.upperBound))) append(renderFlexibleType(renderType(type.lowerBound), renderType(type.upperBound)))
} }
is ConeCapturedType -> { is ConeCapturedType -> {
renderAnnotationList(annotations) renderAnnotationList(type)
append(type.render()) append(type.render())
renderNullability(type.type) renderNullability(type.type)
} }
is ConeDefinitelyNotNullType -> { is ConeDefinitelyNotNullType -> {
renderAnnotationList(annotations) renderAnnotationList(type)
append(renderType(type.original)) append(renderType(type.original))
append("!!") append("!!")
} }
@@ -214,7 +205,9 @@ internal class ConeTypeIdeRenderer(
else -> error("Invalid declaration ${declaration.renderWithType()}") else -> error("Invalid declaration ${declaration.renderWithType()}")
} ?: return listOf(declaration) } ?: return listOf(declaration)
return if(containingClass.isLocal) { containingClass.collectForLocal().reversed() } else null return if (containingClass.isLocal) {
containingClass.collectForLocal().reversed()
} else null
} }
private fun StringBuilder.renderTypeConstructorAndArguments(type: ConeClassLikeType) { private fun StringBuilder.renderTypeConstructorAndArguments(type: ConeClassLikeType) {
@@ -6,6 +6,10 @@
package org.jetbrains.kotlin.analysis.api.fir.renderer package org.jetbrains.kotlin.analysis.api.fir.renderer
import org.jetbrains.kotlin.analysis.api.fir.annotations.mapAnnotationParameters import org.jetbrains.kotlin.analysis.api.fir.annotations.mapAnnotationParameters
import org.jetbrains.kotlin.analysis.api.fir.evaluate.FirCompileTimeConstantEvaluator
import org.jetbrains.kotlin.analysis.api.fir.evaluate.KtFirConstantValueConverter
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtConstantValueRenderer
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtUnsupportedConstantValue
import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.toAnnotationClassId import org.jetbrains.kotlin.fir.declarations.toAnnotationClassId
@@ -47,14 +51,15 @@ private fun renderAnnotation(annotation: FirAnnotation, coneTypeIdeRenderer: Con
private fun renderAndSortAnnotationArguments(descriptor: FirAnnotation, session: FirSession): List<String> { private fun renderAndSortAnnotationArguments(descriptor: FirAnnotation, session: FirSession): List<String> {
val argumentList = mapAnnotationParameters(descriptor, session).entries.map { (name, value) -> val argumentList = mapAnnotationParameters(descriptor, session).entries.map { (name, value) ->
"$name = ${renderConstant(value)}" "$name = ${renderConstant(value, session)}"
} }
return argumentList.sorted() return argumentList.sorted()
} }
private fun renderConstant(value: FirExpression): String { private fun renderConstant(value: FirExpression, useSiteSession: FirSession): String {
return when (value) { val evaluated = FirCompileTimeConstantEvaluator.evaluate(value)
is FirConstExpression<*> -> value.toString() val constantValue = KtFirConstantValueConverter.toConstantValue(evaluated ?: value, useSiteSession)
else -> "NOT_CONST_EXPRESSION" ?: KtUnsupportedConstantValue
}
return KtConstantValueRenderer.render(constantValue)
} }
@@ -43,8 +43,8 @@ internal class FirIdeRenderer private constructor(
} }
} }
private fun renderType(type: ConeTypeProjection, annotations: List<FirAnnotation>? = null): String = private fun renderType(type: ConeTypeProjection): String =
typeIdeRenderer.renderType(type, annotations) typeIdeRenderer.renderType(type)
private fun renderType(firRef: FirTypeRef, approximate: Boolean = false): String { private fun renderType(firRef: FirTypeRef, approximate: Boolean = false): String {
require(firRef is FirResolvedTypeRef) require(firRef is FirResolvedTypeRef)
@@ -52,12 +52,7 @@ internal class FirIdeRenderer private constructor(
val approximatedIfNeeded = approximate.ifTrue { val approximatedIfNeeded = approximate.ifTrue {
PublicTypeApproximator.approximateTypeToPublicDenotable(firRef.coneType, session, approximateLocalTypes = true) PublicTypeApproximator.approximateTypeToPublicDenotable(firRef.coneType, session, approximateLocalTypes = true)
} ?: firRef.coneType } ?: firRef.coneType
val annotations = if (RendererModifier.ANNOTATIONS in options.modifiers) { return renderType(approximatedIfNeeded)
firRef.annotations
} else {
null
}
return renderType(approximatedIfNeeded, annotations)
} }
private fun StringBuilder.renderName(declaration: FirDeclaration) { private fun StringBuilder.renderName(declaration: FirDeclaration) {
@@ -653,7 +648,7 @@ internal class FirIdeRenderer private constructor(
append(": ") append(": ")
val parameterType = typeToRender.coneType val parameterType = typeToRender.coneType
if (isVarArg) { if (isVarArg) {
append(renderType(parameterType.arrayElementType() ?: parameterType, typeToRender.annotations)) append(renderType(parameterType.arrayElementType() ?: parameterType))
} else { } else {
append(renderType(typeToRender)) append(renderType(typeToRender))
} }
@@ -185,4 +185,26 @@ public class FirRendererTestGenerated extends AbstractFirRendererTest {
public void testWhere() throws Exception { public void testWhere() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/where.kt"); runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/where.kt");
} }
@Nested
@TestMetadata("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types")
@TestDataPath("$PROJECT_ROOT")
public class Types {
@Test
public void testAllFilesPresentInTypes() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@Test
@TestMetadata("annotaionOnTypes.kt")
public void testAnnotaionOnTypes() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types/annotaionOnTypes.kt");
}
@Test
@TestMetadata("annotaionOnTypesWithComplexExpression.kt")
public void testAnnotaionOnTypesWithComplexExpression() throws Exception {
runTest("analysis/analysis-api/testData/components/symbolDeclarationRenderer/renderDeclaration/types/annotaionOnTypesWithComplexExpression.kt");
}
}
} }
@@ -35,7 +35,12 @@ public data class KtTypeRendererOptions(
/** /**
* Whether to render type arguments. * Whether to render type arguments.
*/ */
public val renderTypeArguments: Boolean = true public val renderTypeArguments: Boolean = true,
/**
* Should annotations on types be rendered.
*/
public val renderTypeAnnotations: Boolean = true
) { ) {
public companion object { public companion object {
public val DEFAULT: KtTypeRendererOptions = KtTypeRendererOptions() public val DEFAULT: KtTypeRendererOptions = KtTypeRendererOptions()
@@ -0,0 +1,103 @@
/*
* Copyright 2010-2021 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.analysis.api.symbols.markers
import org.jetbrains.kotlin.analysis.api.annotations.KtNamedConstantValue
import org.jetbrains.kotlin.types.ConstantValueKind
public object KtConstantValueRenderer {
public fun render(value: KtConstantValue): String = buildString {
renderConstantValue(value)
}
private fun StringBuilder.renderConstantValue(value: KtConstantValue) {
when (value) {
is KtAnnotationConstantValue -> {
renderAnnotationConstantValue(value)
}
is KtArrayConstantValue -> {
renderArrayConstantValue(value)
}
is KtEnumEntryConstantValue -> {
renderEnumEntryConstantValue(value)
}
is KtErrorValue -> {
append("ERROR")
}
is KtLiteralConstantValue<*> -> {
renderLiteralConstantValue(value)
}
KtUnsupportedConstantValue -> {
append("KtUnsupportedConstantValue")
}
}
}
private fun StringBuilder.renderLiteralConstantValue(value: KtLiteralConstantValue<*>) {
when (value.constantValueKind) {
ConstantValueKind.String -> {
append('"')
append(value.value)
append('"')
}
ConstantValueKind.Char -> {
append("'")
append(value.value)
append("'")
}
else -> {
append(value.value)
}
}
}
private fun StringBuilder.renderEnumEntryConstantValue(value: KtEnumEntryConstantValue) {
append(value.callableId?.asSingleFqName()?.asString())
}
private fun StringBuilder.renderAnnotationConstantValue(value: KtAnnotationConstantValue) {
append(value.classId)
if (value.arguments.isNotEmpty()) {
append("(")
renderNamedConstantValueList(value.arguments)
append(")")
}
}
private fun StringBuilder.renderArrayConstantValue(value: KtArrayConstantValue) {
append("[")
renderConstantValueList(value.values)
append("]")
}
private fun StringBuilder.renderConstantValueList(list: Collection<KtConstantValue>) {
renderWithSeparator(list, ", ") { constantValue ->
renderConstantValue(constantValue)
}
}
private fun StringBuilder.renderNamedConstantValueList(list: Collection<KtNamedConstantValue>) {
renderWithSeparator(list, ", ") { namedValue ->
append(namedValue.name)
append(" = ")
renderConstantValue(namedValue.expression)
append(", ")
}
}
private inline fun <E> StringBuilder.renderWithSeparator(
collection: Collection<E>,
separator: String,
render: StringBuilder.(E) -> Unit
) {
collection.forEachIndexed { index, element ->
render(element)
if (index != collection.size - 1) {
append(separator)
}
}
}
}
@@ -1,4 +1,4 @@
@Target(allowedTargets = NOT_CONST_EXPRESSION) annotation class base @Target(allowedTargets = [kotlin.annotation.AnnotationTarget.ANNOTATION_CLASS]) annotation class base
@base annotation class derived @base annotation class derived
@base class correct { @base class correct {
constructor(x: Int) constructor(x: Int)
@@ -1,4 +1,4 @@
@Target(allowedTargets = NOT_CONST_EXPRESSION) annotation class base @Target(allowedTargets = [kotlin.annotation.AnnotationTarget.ANNOTATION_CLASS]) annotation class base
@base annotation class derived @base annotation class derived
@base class correct { @base class correct {
constructor(@base x: Int) constructor(@base x: Int)
@@ -0,0 +1,9 @@
@Target(AnnotationTarget.TYPE)
annotation class A1
@Target(AnnotationTarget.TYPE)
annotation class A2(val value: String)
fun x(): @A1 @A2("LIST") List<@A2("INT") Int> {
TODO()
}
@@ -0,0 +1,6 @@
@Target(allowedTargets = [kotlin.annotation.AnnotationTarget.TYPE]) annotation class A1
@Target(allowedTargets = [kotlin.annotation.AnnotationTarget.TYPE]) annotation class A2 {
constructor(value: String)
val value: String
}
fun x(): @A1 @A2(value = "LIST") List<@A2(value = "INT") Int>
@@ -0,0 +1,6 @@
@Target(AnnotationTarget.TYPE)
annotation class A(val value: Int)
fun x(): @A(1 + 2) Int {
TODO()
}
@@ -0,0 +1,5 @@
@Target(allowedTargets = [kotlin.annotation.AnnotationTarget.TYPE]) annotation class A {
constructor(value: Int)
val value: Int
}
fun x(): @A(value = 3) Int
@@ -0,0 +1,3 @@
@Target(allowedTargets = [kotlin.annotation.AnnotationTarget.ANNOTATION_CLASS, kotlin.annotation.AnnotationTarget.VALUE_PARAMETER, kotlin.annotation.AnnotationTarget.TYPE]) annotation class base
fun foo1(vararg ints: Int)
fun foo2(@base vararg ints: @base Int)
@@ -1,3 +1,3 @@
@Target(allowedTargets = NOT_CONST_EXPRESSION) annotation class base @Target(allowedTargets = [kotlin.annotation.AnnotationTarget.ANNOTATION_CLASS, kotlin.annotation.AnnotationTarget.VALUE_PARAMETER, kotlin.annotation.AnnotationTarget.TYPE]) annotation class base
fun foo1(vararg ints: Int) fun foo1(vararg ints: Int)
fun foo2(@base vararg ints: @base Int) fun foo2(@base vararg ints: Int)