Skip to content

Commit

Permalink
Parsing of JvmName
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcinAman committed Dec 22, 2020
1 parent 6f14e29 commit 706c0d2
Show file tree
Hide file tree
Showing 14 changed files with 64 additions and 57 deletions.
19 changes: 11 additions & 8 deletions core/src/main/kotlin/model/additionalExtras.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ class AdditionalModifiers(val content: SourceSetDependent<Set<ExtraModifiers>>)

fun SourceSetDependent<Set<ExtraModifiers>>.toAdditionalModifiers() = AdditionalModifiers(this)

class Annotations(
@Deprecated("Use directAnnotations or fileLevelAnnotations")
val content: SourceSetDependent<List<Annotation>>
data class Annotations(
private val myContent: SourceSetDependent<List<Annotation>>
) : ExtraProperty<Documentable> {
companion object : ExtraProperty.Key<Documentable, Annotations> {
override fun mergeStrategyFor(left: Annotations, right: Annotations): MergeStrategy<Documentable> =
MergeStrategy.Replace(Annotations(left.content + right.content))
MergeStrategy.Replace(Annotations(left.myContent + right.myContent))
}

override val key: ExtraProperty.Key<Documentable, *> = Annotations
Expand All @@ -46,20 +45,24 @@ class Annotations(
override fun hashCode(): Int = dri.hashCode()
}

@Deprecated("Use directAnnotations or fileLevelAnnotations")
val content: SourceSetDependent<List<Annotation>>
get() = myContent

val directAnnotations: SourceSetDependent<List<Annotation>> = annotationsByScope(AnnotationScope.DIRECT)

val fileLevelAnnotations: SourceSetDependent<List<Annotation>> = annotationsByScope(AnnotationScope.FILE)

private fun annotationsByScope(scope: AnnotationScope): SourceSetDependent<List<Annotation>> =
content.entries.mapNotNull { (key, value) ->
myContent.entries.mapNotNull { (key, value) ->
val withoutFileLevel = value.filter { it.scope == scope }
if (withoutFileLevel.isEmpty()) null
else Pair(key, withoutFileLevel)
}.toMap()
}

enum class AnnotationScope {
DIRECT, FILE
enum class AnnotationScope {
DIRECT, FILE
}
}

fun SourceSetDependent<List<Annotations.Annotation>>.toAnnotations() = Annotations(this)
Expand Down
3 changes: 3 additions & 0 deletions plugins/base/src/main/kotlin/translators/annotationsValue.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.jetbrains.dokka.base.translators

internal fun unquotedValue(value: String): String = value.removeSurrounding("\"")
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import org.jetbrains.dokka.analysis.from
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.parsers.MarkdownParser
import org.jetbrains.dokka.base.translators.isDirectlyAnException
import org.jetbrains.dokka.base.translators.unquotedValue
import org.jetbrains.dokka.links.*
import org.jetbrains.dokka.links.Callable
import org.jetbrains.dokka.model.*
Expand Down Expand Up @@ -588,7 +589,7 @@ private class DokkaDescriptorVisitor(
val name = run {
val modifier = if (isGetter) "get" else "set"
val rawName = propertyDescriptor.name.asString()
"$modifier${rawName[0].toUpperCase()}${rawName.drop(1)}"
"$modifier${rawName.capitalize()}"
}

val parameters =
Expand Down Expand Up @@ -782,8 +783,7 @@ private class DokkaDescriptorVisitor(

private suspend fun org.jetbrains.kotlin.descriptors.annotations.Annotations.getPresentableName(): String? =
map { it.toAnnotation() }.singleOrNull { it.dri.classNames == "ParameterName" }?.params?.get("name")
.safeAs<StringValue>()?.value?.drop(1)
?.dropLast(1) // Dropping enclosing doublequotes because we don't want to have it in our custom signature serializer
.safeAs<StringValue>()?.value?.let { unquotedValue(it) }

private suspend fun KotlinType.toBound(): Bound = when (this) {

Expand Down Expand Up @@ -931,13 +931,7 @@ private class DokkaDescriptorVisitor(
else -> StringValue(unquotedValue(toString()))
}

private fun unquotedValue(value: String): String = if (value.startsWith('"') && value.endsWith('"')) {
if (value.length == 2) "" else value.substring(1, value.lastIndex)
} else {
value
}

private suspend fun AnnotationDescriptor.toAnnotation(scope: AnnotationScope = AnnotationScope.DIRECT): Annotations.Annotation {
private suspend fun AnnotationDescriptor.toAnnotation(scope: Annotations.AnnotationScope = Annotations.AnnotationScope.DIRECT): Annotations.Annotation {
val dri = DRI.from(annotationClass as DeclarationDescriptor)
return Annotations.Annotation(
DRI.from(annotationClass as DeclarationDescriptor),
Expand Down Expand Up @@ -1023,7 +1017,7 @@ private class DokkaDescriptorVisitor(
?.let { file -> resolutionFacade.resolveSession.getFileAnnotations(file) }
?.toList()
.orEmpty()
.parallelMap { it.toAnnotation(scope = AnnotationScope.FILE) }
.parallelMap { it.toAnnotation(scope = Annotations.AnnotationScope.FILE) }
}

private data class AncestryLevel(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.translators.isDirectlyAnException
import org.jetbrains.dokka.base.translators.psi.parsers.JavaDocumentationParser
import org.jetbrains.dokka.base.translators.psi.parsers.JavadocParser
import org.jetbrains.dokka.base.translators.unquotedValue
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.links.nextTarget
import org.jetbrains.dokka.links.withClass
Expand Down Expand Up @@ -530,6 +531,9 @@ class DefaultPsiToDocumentableTranslator(
private fun JvmAnnotationAttribute.toValue(): AnnotationParameterValue = when (this) {
is PsiNameValuePair -> value?.toValue() ?: StringValue("")
else -> StringValue(this.attributeName)
}.let { annotationValue ->
if (annotationValue is StringValue) annotationValue.copy(unquotedValue(annotationValue.value))
else annotationValue
}

private fun PsiAnnotationMemberValue.toValue(): AnnotationParameterValue? = when (this) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import org.jetbrains.dokka.pages.ContentPage
import org.jetbrains.dokka.pages.PackagePageNode
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.AnnotationScope
import org.jetbrains.dokka.model.Annotations
import org.jetbrains.dokka.model.StringValue
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
Expand Down Expand Up @@ -243,7 +242,7 @@ class ContentForAnnotationsTest : BaseAbstractTest() {
fun expectedAnnotation(name: String) = Annotations.Annotation(
dri = DRI("kotlin.jvm", "JvmName"),
params = mapOf("name" to StringValue(name)),
scope = AnnotationScope.DIRECT,
scope = Annotations.AnnotationScope.DIRECT,
mustBeDocumented = false
)

Expand All @@ -257,11 +256,11 @@ class ContentForAnnotationsTest : BaseAbstractTest() {

assertEquals(expectedAnnotation("xd"), getterAnnotation)
assertFalse(getterAnnotation?.mustBeDocumented!!)
assertEquals(AnnotationScope.DIRECT, getterAnnotation.scope)
assertEquals(Annotations.AnnotationScope.DIRECT, getterAnnotation.scope)

assertEquals(expectedAnnotation("asd"), setterAnnotation)
assertFalse(setterAnnotation?.mustBeDocumented!!)
assertEquals(AnnotationScope.DIRECT, setterAnnotation.scope)
assertEquals(Annotations.AnnotationScope.DIRECT, setterAnnotation.scope)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package content.annotations

import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.AnnotationScope
import org.jetbrains.dokka.model.Annotations
import org.jetbrains.dokka.model.StringValue
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import kotlin.test.assertEquals
Expand Down Expand Up @@ -67,14 +65,15 @@ class FileLevelJvmNameTest : BaseAbstractTest() {

@ParameterizedTest
@ValueSource(strings = [functionTest, extensionFunctionTest])
fun `jvm name should be included in functions extra`(query: String){
fun `jvm name should be included in functions extra`(query: String) {
testInline(
query.trimIndent(), testConfiguration) {
query.trimIndent(), testConfiguration
) {
documentablesCreationStage = { modules ->
val expectedAnnotation = Annotations.Annotation(
dri = DRI("kotlin.jvm", "JvmName"),
params = mapOf("name" to StringValue("CustomJvmName")),
scope = AnnotationScope.FILE,
scope = Annotations.AnnotationScope.FILE,
mustBeDocumented = false
)
val function = modules.flatMap { it.packages }.first().functions.first()
Expand All @@ -89,14 +88,15 @@ class FileLevelJvmNameTest : BaseAbstractTest() {

@ParameterizedTest
@ValueSource(strings = [propertyTest, extensionPropertyTest])
fun `jvm name should be included in properties extra`(query: String){
fun `jvm name should be included in properties extra`(query: String) {
testInline(
query.trimIndent(), testConfiguration) {
query.trimIndent(), testConfiguration
) {
documentablesCreationStage = { modules ->
val expectedAnnotation = Annotations.Annotation(
dri = DRI("kotlin.jvm", "JvmName"),
params = mapOf("name" to StringValue("CustomJvmName")),
scope = AnnotationScope.FILE,
scope = Annotations.AnnotationScope.FILE,
mustBeDocumented = false
)
val properties = modules.flatMap { it.packages }.first().properties.first()
Expand Down
6 changes: 3 additions & 3 deletions plugins/base/src/test/kotlin/model/ClassesTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ class ClassesTest : AbstractModelTest("/src/main/kotlin/classes/Test.kt", "class
with(first()) {
dri.classNames equals "Deprecated"
params.entries counts 1
(params["message"].assertNotNull("message") as StringValue).value equals "\"should no longer be used\""
(params["message"].assertNotNull("message") as StringValue).value equals "should no longer be used"
}
}
}
Expand Down Expand Up @@ -366,7 +366,7 @@ class ClassesTest : AbstractModelTest("/src/main/kotlin/classes/Test.kt", "class
with(first()) {
dri.classNames equals "SinceKotlin"
params.entries counts 1
(params["version"].assertNotNull("version") as StringValue).value equals "\"1.1\""
(params["version"].assertNotNull("version") as StringValue).value equals "1.1"
}
}
}
Expand Down Expand Up @@ -428,7 +428,7 @@ class ClassesTest : AbstractModelTest("/src/main/kotlin/classes/Test.kt", "class
with((this / "classes" / "Foo").cast<DClass>()) {
with(extra[Annotations]?.directAnnotations?.values?.firstOrNull()?.firstOrNull().assertNotNull("annotations")) {
dri.toString() equals "kotlin/Suppress///PointingToDeclaration/"
(params["names"].assertNotNull("param") as ArrayValue).value equals listOf(StringValue("\"abc\""))
(params["names"].assertNotNull("param") as ArrayValue).value equals listOf(StringValue("abc"))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/base/src/test/kotlin/model/FunctionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class FunctionTest : AbstractModelTest("/src/main/kotlin/function/Test.kt", "fun
with(first()) {
dri.classNames equals "Suppress"
params.entries counts 1
(params["names"].assertNotNull("param") as ArrayValue).value equals listOf(StringValue("\"FOO\""))
(params["names"].assertNotNull("param") as ArrayValue).value equals listOf(StringValue("FOO"))
}
}
}
Expand Down Expand Up @@ -386,7 +386,7 @@ class FunctionTest : AbstractModelTest("/src/main/kotlin/function/Test.kt", "fun
with(first()) {
dri.classNames equals "SinceKotlin"
params.entries counts 1
(params["version"].assertNotNull("version") as StringValue).value equals "\"1.1\""
(params["version"].assertNotNull("version") as StringValue).value equals "1.1"
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/base/src/test/kotlin/model/PropertyTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class PropertyTest : AbstractModelTest("/src/main/kotlin/property/Test.kt", "pro
with(first()) {
dri.classNames equals "SinceKotlin"
params.entries counts 1
(params["version"].assertNotNull("version") as StringValue).value equals "\"1.1\""
(params["version"].assertNotNull("version") as StringValue).value equals "1.1"
}
}
}
Expand Down
12 changes: 4 additions & 8 deletions plugins/base/src/test/kotlin/signatures/SignatureTest.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package signatures

import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.DokkaSourceSetID
import org.jetbrains.dokka.jdk
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.junit.jupiter.api.Test
import utils.*

Expand Down Expand Up @@ -295,7 +291,7 @@ class SignatureTest : BaseAbstractTest() {
.firstSignature()
.match(
Div(
Div("@", A("Marking"), "(", Span("msg = ", Span("\"Nenya\"")), Wbr, ")"),
Div("@", A("Marking"), "(", Span("msg = ", Span("Nenya")), Wbr, ")"),
Div("@", A("Marking2"), "(", Span("int = ", Span("1")), Wbr, ")")
),
"fun ", A("simpleFun"),
Expand Down Expand Up @@ -332,9 +328,9 @@ class SignatureTest : BaseAbstractTest() {
Div(
"@", A("Marking"), "(", Span(
"msg = [",
Span(Span("\"Nenya\""), ", "), Wbr,
Span(Span("\"Vilya\""), ", "), Wbr,
Span(Span("\"Narya\"")), Wbr, "]"
Span(Span("Nenya"), ", "), Wbr,
Span(Span("Vilya"), ", "), Wbr,
Span(Span("Narya")), Wbr, "]"
), Wbr, ")"
)
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,13 @@ internal class JavadocClasslikeTemplateMapTest : AbstractJavadocTemplateMapTest(
val map = allPagesOfType<JavadocClasslikePageNode>().first { it.name == "TestClass" }.templateMap
assertEquals("TestClass", map["name"])
val signature = assertIsInstance<Map<String, Any?>>(map["signature"])
assertEquals("@<a href=Author.html>Author</a>(name = \"Benjamin Franklin\")", signature["annotations"])
assertEquals("@<a href=Author.html>Author</a>(name = Benjamin Franklin)", signature["annotations"])

val methods = assertIsInstance<Map<Any, Any?>>(map["methods"])
val ownMethods = assertIsInstance<List<*>>(methods["own"])
val method = assertIsInstance<Map<String, Any?>>(ownMethods.single())
val methodSignature = assertIsInstance<Map<String, Any?>>(method["signature"])
assertEquals("@<a href=Author.html>Author</a>(name = \"Franklin D. Roosevelt\")", methodSignature["annotations"])
assertEquals("@<a href=Author.html>Author</a>(name = Franklin D. Roosevelt)", methodSignature["annotations"])
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@ internal fun DPackage.asJava(): DPackage {
.groupBy({ it.first }) { it.second }
.map { (syntheticClassName, nodes) ->
DClass(
dri = dri.withClass(syntheticClassName),
name = syntheticClassName,
dri = dri.withClass(syntheticClassName.name),
name = syntheticClassName.name,
properties = nodes.filterIsInstance<DProperty>().map { it.asJava(true) },
constructors = emptyList(),
functions = (
nodes
.filterIsInstance<DProperty>()
.filterNot { it.isConst }
.flatMap { it.javaAccessors(relocateToClass = syntheticClassName) } +
.flatMap { it.javaAccessors(relocateToClass = syntheticClassName.name) } +
nodes.filterIsInstance<DFunction>()
.map { it.asJava(syntheticClassName) }), // TODO: methods are static and receiver is a param
.map { it.asJava(syntheticClassName.name) }), // TODO: methods are static and receiver is a param
classlikes = emptyList(),
sources = emptyMap(),
expectPresentInSet = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,30 @@ import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.model.properties.WithExtraProperties
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult

data class Name(val fqName: String){
val name = fqName.substringAfterLast(".")
}

class JvmNameProvider {
fun <T> nameFor(entry: T): String where T : Documentable, T : WithExtraProperties<out Documentable> =
entry.directlyAnnotatedJvmName()?.jvmNameAsString()
?: entry.name
?: throw IllegalStateException("Failed to provide a name for ${entry.javaClass.canonicalName}")

fun <T> nameForSyntheticClass(entry: T): String where T : WithSources, T : WithExtraProperties<out Documentable> =
entry.extra[Annotations]?.let {
fun <T> nameForSyntheticClass(entry: T): Name where T : WithSources, T : WithExtraProperties<out Documentable>, T: Documentable {
val name = entry.extra[Annotations]?.let {
it.fileLevelAnnotations.entries.firstNotNullResult { (_, annotations) ->
annotations.jvmNameAnnotation()?.jvmNameAsString()
}
} ?: entry.sources.entries.first().value.path.split("/").last().split(".").first().capitalize() + "Kt"
return Name("${entry.dri.packageName}.$name")
}

fun nameAsJavaGetter(entry: DProperty): String = entry.getter?.directlyAnnotatedJvmName()?.jvmNameAsString() ?: "get" + entry.name.capitalize()
fun nameAsJavaGetter(entry: DProperty): String =
entry.getter?.directlyAnnotatedJvmName()?.jvmNameAsString() ?: "get" + entry.name.capitalize()

fun nameAsJavaSetter(entry: DProperty): String = entry.setter?.directlyAnnotatedJvmName()?.jvmNameAsString() ?: "set" + entry.name.capitalize()
fun nameAsJavaSetter(entry: DProperty): String =
entry.setter?.directlyAnnotatedJvmName()?.jvmNameAsString() ?: "set" + entry.name.capitalize()

private fun List<Annotations.Annotation>.jvmNameAnnotation(): Annotations.Annotation? =
firstOrNull { it.isJvmName() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ class KotlinAsJavaPluginTest : BaseAbstractTest() {
) {
renderingStage = { _, _ ->
writerPlugin.writer.renderedContent("root/kotlinAsJavaPlugin/-a-b-c/some-fun.html").signature().first().match(
"final ", A("Integer"), A("someFun"), "(", A("Integer"), A("xd"), ")", Span()
"final ", A("Integer"), A("someFun"), "(", A("Integer"), "xd)", Span()
)
}
}
Expand Down Expand Up @@ -368,7 +368,7 @@ class KotlinAsJavaPluginTest : BaseAbstractTest() {
renderingStage = { _, _ ->
writerPlugin.writer.renderedContent("root/kotlinAsJavaPlugin/-a-b-c/some-fun.html").signature().first().match(
"final ", A("Integer"), A("someFun"), "(", A("Map"), "<", A("String"),
", ", A("Integer"), ">", A("xd"), ")", Span()
", ", A("Integer"), "> xd)", Span()
)
}
}
Expand Down

0 comments on commit 706c0d2

Please sign in to comment.