aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/links/DRI.kt
blob: abc8893993118c4562f5dbe95cc1a8d4a451f87d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package org.jetbrains.dokka.links

import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiParameter
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull

/**
 * [DRI] stands for DokkaResourceIdentifier
 */
data class DRI(
    val packageName: String? = null,
    val classNames: String? = null,
    val callable: Callable? = null,
    val target: Int? = null,
    val genericTarget: Int? = null,
    val extra: String? = null
) {
    override fun toString(): String =
        "${packageName.orEmpty()}/${classNames.orEmpty()}/${callable?.name.orEmpty()}/${callable?.signature().orEmpty()}/${target?.toString().orEmpty()}/${extra.orEmpty()}"

    companion object {
        fun from(descriptor: DeclarationDescriptor) = descriptor.parentsWithSelf.run {
            val callable = firstIsInstanceOrNull<CallableDescriptor>()
            val params = callable?.let { listOfNotNull(it.extensionReceiverParameter) + it.valueParameters }.orEmpty()
            DRI(
                firstIsInstanceOrNull<PackageFragmentDescriptor>()?.fqName?.asString(),
                filterIsInstance<ClassDescriptor>().toList().takeIf { it.isNotEmpty() }?.asReversed()
                    ?.joinToString(separator = ".") { it.name.asString() },
                callable?.let { Callable.from(it) },
                firstIsInstanceOrNull<ParameterDescriptor>()?.let { params.indexOf(it) },
                null
            )
        }

        fun from(psi: PsiElement) = psi.parentsWithSelf.run {
            val callable = firstIsInstanceOrNull<PsiMethod>()
            val params = (callable?.parameterList?.parameters).orEmpty()
            val classes = filterIsInstance<PsiClass>().toList()
            DRI(
                classes.lastOrNull()?.qualifiedName?.substringBeforeLast('.', ""),
                classes.toList().takeIf { it.isNotEmpty() }?.asReversed()?.mapNotNull { it.name }?.joinToString("."),
                callable?.let { Callable.from(it) },
                firstIsInstanceOrNull<PsiParameter>()?.let { params.indexOf(it) }
            )
        }
        val topLevel = DRI()
    }
}

val DriOfUnit = DRI("kotlin", "Unit")
val DriOfAny = DRI("kotlin", "Any")

fun DRI.withClass(name: String) = copy(classNames = if (classNames.isNullOrBlank()) name else "$classNames.$name")

val DRI.parent: DRI
    get() = when {
        extra != null -> copy(extra = null)
        genericTarget != null -> copy(genericTarget = null)
        target != null -> copy(target = null)
        callable != null -> copy(callable = null)
        classNames != null -> copy(classNames = classNames.substringBeforeLast('.').takeIf { it.isNotBlank() })
        else -> DRI.topLevel
    }

val DRI.sureClassNames
    get() = classNames ?: throw IllegalStateException("Malformed DRI. It requires classNames in this context.")

data class Callable(
    val name: String,
    val receiver: TypeReference? = null,
    val params: List<TypeReference>
) {
    fun signature() = "${receiver?.toString().orEmpty()}#${params.joinToString("#")}"

    companion object {
        fun from(descriptor: CallableDescriptor) = with(descriptor) {
            Callable(
                name.asString(),
                extensionReceiverParameter?.let { TypeReference.from(it) },
                valueParameters.mapNotNull { TypeReference.from(it) }
            )
        }
        fun from(psi: PsiMethod) = with(psi) {
            Callable(
                name,
                null,
                parameterList.parameters.map { param -> JavaClassReference(param.type.canonicalText) })
        }
    }
}

sealed class TypeReference {
    companion object {
        fun from(d: ReceiverParameterDescriptor): TypeReference? =
            when (d.value) {
                is ExtensionReceiver -> fromPossiblyNullable(d.type)
                else -> run {
                    println("Unknown value type for $d")
                    null
                }
            }

        fun from(d: ValueParameterDescriptor): TypeReference? =
            fromPossiblyNullable(d.type)

        fun from(p: PsiClass) = TypeReference

        private fun fromPossiblyNullable(t: KotlinType, self: KotlinType? = null): TypeReference =
            from(t, self).let { if (t.isMarkedNullable) Nullable(it) else it }

        private fun from(t: KotlinType, self: KotlinType? = null): TypeReference =
            if (self is KotlinType && self.constructor == t.constructor && self.arguments == t.arguments)
                SelfType
            else when (val d = t.constructor.declarationDescriptor) {
                is TypeParameterDescriptor -> TypeParam(
                    d.upperBounds.map { fromPossiblyNullable(it, self ?: t) }
                )
                else -> TypeConstructor(
                    t.constructorName.orEmpty(),
                    t.arguments.map { fromProjection(it, self) }
                )
            }

        private fun fromProjection(t: TypeProjection, r: KotlinType? = null): TypeReference =
            if (t.isStarProjection) {
                StarProjection
            } else {
                fromPossiblyNullable(t.type, r)
            }
    }
}

data class JavaClassReference(val name: String) : TypeReference() {
    override fun toString(): String = name
}

data class TypeParam(val bounds: List<TypeReference>) : TypeReference()

data class TypeConstructor(
    val fullyQualifiedName: String,
    val params: List<TypeReference>
) : TypeReference() {
    override fun toString() = fullyQualifiedName +
            (if (params.isNotEmpty()) "[${params.joinToString(",")}]" else "")
}

object SelfType : TypeReference() {
    override fun toString() = "^"
}

data class Nullable(val wrapped: TypeReference) : TypeReference() {
    override fun toString() = "$wrapped?"
}

object StarProjection : TypeReference() {
    override fun toString() = "*"
}

private operator fun <T> List<T>.component6(): T = get(5)

private val KotlinType.constructorName
    get() = constructor.declarationDescriptor?.fqNameSafe?.asString()