aboutsummaryrefslogtreecommitdiff
path: root/plugins/kotlin-as-java/src/main/kotlin/converters/KotlinToJavaConverter.kt
blob: 3b0f69f6d143d3fa73ba94b82dfd114a8c6e5bac (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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package org.jetbrains.dokka.kotlinAsJava.converters

import org.jetbrains.dokka.links.Callable
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.links.withClass
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.model.Annotation
import org.jetbrains.dokka.model.Enum
import org.jetbrains.dokka.model.Function
import org.jetbrains.dokka.model.properties.PropertyContainer
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType

private fun <T : WithExpectActual> List<T>.groupedByLocation() =
    map { it.sources to it }
        .groupBy({ (location, _) ->
            location.let {
                it.map.entries.first().value.path.split("/").last().split(".").first() + "Kt"
            } // TODO: first() does not look reasonable
        }) { it.second }

internal fun Package.asJava(): Package {
    @Suppress("UNCHECKED_CAST")
    val syntheticClasses = ((properties + functions) as List<WithExpectActual>)
        .groupedByLocation()
        .map { (syntheticClassName, nodes) ->
            Class(
                dri = dri.withClass(syntheticClassName),
                name = syntheticClassName,
                properties = nodes.filterIsInstance<Property>().map { it.asJava() },
                constructors = emptyList(),
                functions = (
                        nodes.filterIsInstance<Property>()
                            .map { it.javaAccessors() } +
                                nodes.filterIsInstance<Function>()
                                    .map { it.asJava(syntheticClassName) }) as List<Function>, // TODO: methods are static and receiver is a param
                classlikes = emptyList(),
                sources = PlatformDependent.empty(),
                visibility = PlatformDependent(
                    platformData.map {
                        it to JavaVisibility.Public
                    }.toMap()
                ),
                companion = null,
                generics = emptyList(),
                supertypes = PlatformDependent.empty(),
                documentation = PlatformDependent.empty(),
                modifier = JavaModifier.Final,
                platformData = platformData,
                extra = PropertyContainer.empty()
            )
        }

    return copy(
        functions = emptyList(),
        properties = emptyList(),
        classlikes = classlikes.map { it.asJava() } + syntheticClasses
    )
}

internal fun Property.asJava(isTopLevel: Boolean = false, relocateToClass: String? = null) =
    copy(
        dri = if (relocateToClass.isNullOrBlank()) {
            dri
        } else {
            dri.withClass(relocateToClass)
        },
        modifier = if (setter == null) {
            JavaModifier.Final
        } else {
            JavaModifier.Empty
        },
        visibility = visibility.copy(
            map = visibility.mapValues { JavaVisibility.Private }
        ),
        type = type.asJava(isTopLevel), // TODO: check
        setter = null,
        getter = null, // Removing getters and setters as they will be available as functions
        extra = if (isTopLevel) extra.plus(extra.mergeAdditionalModifiers(setOf(ExtraModifiers.STATIC))) else extra
    )

internal fun Property.javaAccessors(isTopLevel: Boolean = false, relocateToClass: String? = null): List<Function> =
    listOfNotNull(
        getter?.copy(
            dri = if (relocateToClass.isNullOrBlank()) {
                dri
            } else {
                dri.withClass(relocateToClass)
            },
            name = "get" + name.capitalize(),
            modifier = if (setter == null) {
                JavaModifier.Final
            } else {
                JavaModifier.Empty
            },
            visibility = visibility.copy(
                map = visibility.mapValues { JavaVisibility.Public }
            ),
            type = type.asJava(isTopLevel), // TODO: check
            extra = if (isTopLevel) getter!!.extra.plus(getter!!.extra.mergeAdditionalModifiers(setOf(ExtraModifiers.STATIC))) else getter!!.extra
        ),
        setter?.copy(
            dri = if (relocateToClass.isNullOrBlank()) {
                dri
            } else {
                dri.withClass(relocateToClass)
            },
            name = "set" + name.capitalize(),
            modifier = if (setter == null) {
                JavaModifier.Final
            } else {
                JavaModifier.Empty
            },
            visibility = visibility.copy(
                map = visibility.mapValues { JavaVisibility.Public }
            ),
            type = type.asJava(isTopLevel), // TODO: check
            extra = if (isTopLevel) setter!!.extra.plus(setter!!.extra.mergeAdditionalModifiers(setOf(ExtraModifiers.STATIC))) else setter!!.extra
        )
    )


internal fun Function.asJava(containingClassName: String): Function {
    val newName = when {
        isConstructor -> containingClassName
        else -> name
    }
    return copy(
//        dri = dri.copy(callable = dri.callable?.asJava()),
        name = newName,
        type = type.asJava(),
        modifier = if(modifier is KotlinModifier.Final && isConstructor) JavaModifier.Empty else modifier,
        parameters = listOfNotNull(receiver?.asJava()) + parameters.map { it.asJava() },
        receiver = null
    ) // TODO static if toplevel
}

internal fun Classlike.asJava(): Classlike = when (this) {
    is Class -> asJava()
    is Enum -> asJava()
    is Annotation -> asJava()
    is Object -> asJava()
    is Interface -> asJava()
    else -> throw IllegalArgumentException("$this shouldn't be here")
}

internal fun Class.asJava(): Class = copy(
    constructors = constructors.map { it.asJava(name) },
    functions = (functions + properties.map { it.getter } + properties.map { it.setter }).filterNotNull().map {
        it.asJava(name)
    },
    properties = properties.map { it.asJava() },
    classlikes = classlikes.map { it.asJava() },
    generics = generics.map { it.asJava() },
    supertypes = supertypes.copy(
        map = supertypes.mapValues { it.value.map { it.possiblyAsJava() } }
    ),
    modifier = if (modifier is KotlinModifier.Empty) JavaModifier.Final else modifier
)

private fun TypeParameter.asJava(): TypeParameter = copy(
    dri = dri.possiblyAsJava(),
    bounds = bounds.map { it.asJava() }
)

private fun Bound.asJava(): Bound = when (this) {
    is TypeConstructor -> copy(
        dri = dri.possiblyAsJava()
    )
    is Nullable -> copy(
        inner = inner.asJava()
    )
    else -> this
}

internal fun Enum.asJava(): Enum = copy(
    constructors = constructors.map { it.asJava(name) },
    functions = (functions + properties.map { it.getter } + properties.map { it.setter }).filterNotNull().map {
        it.asJava(name)
    },
    properties = properties.map { it.asJava() },
    classlikes = classlikes.map { it.asJava() },
    supertypes = supertypes.copy(
        map = supertypes.mapValues { it.value.map { it.possiblyAsJava() } }
    )
//    , entries = entries.map { it.asJava() }
)

internal fun Object.asJava(): Object = copy(
    functions = (functions + properties.map { it.getter } + properties.map { it.setter })
        .filterNotNull()
        .map { it.asJava(name.orEmpty()) },
    properties = properties.map { it.asJava() } +
            Property(
                name = "INSTANCE",
                modifier = JavaModifier.Final,
                dri = dri.copy(callable = Callable("INSTANCE", null, emptyList())),
                documentation = PlatformDependent.empty(),
                sources = PlatformDependent.empty(),
                visibility = PlatformDependent(
                    platformData.map {
                        it to JavaVisibility.Public
                    }.toMap()
                ),
                type = JavaTypeWrapper(
                    dri.packageName?.split(".").orEmpty() +
                            dri.classNames?.split(".").orEmpty(),
                    emptyList(),
                    dri,
                    false
                ),
                setter = null,
                getter = null,
                platformData = platformData,
                receiver = null,
                extra = PropertyContainer.empty<Property>() + AdditionalModifiers(setOf(ExtraModifiers.STATIC))
            ),
    classlikes = classlikes.map { it.asJava() },
    supertypes = supertypes.copy(
        map = supertypes.mapValues { it.value.map { it.possiblyAsJava() } }
    )
)

internal fun Interface.asJava(): Interface = copy(
    functions = (functions + properties.map { it.getter } + properties.map { it.setter })
        .filterNotNull()
        .map { it.asJava(name) },
    properties = emptyList(),
    classlikes = classlikes.map { it.asJava() }, // TODO: public static final class DefaultImpls with impls for methods
    generics = generics.map { it.asJava() },
    supertypes = supertypes.copy(
        map = supertypes.mapValues { it.value.map { it.possiblyAsJava() } }
    )
)

internal fun Annotation.asJava(): Annotation = copy(
    properties = properties.map { it.asJava() },
    constructors = emptyList(),
    classlikes = classlikes.map { it.asJava() }
) // TODO investigate if annotation class can have methods and properties not from constructor

internal fun Parameter.asJava(): Parameter = copy(
    type = type.asJava(),
    name = if (name.isNullOrBlank()) "\$self" else name
)

internal fun String.getAsPrimitive(): JvmPrimitiveType? = org.jetbrains.kotlin.builtins.PrimitiveType.values()
    .find { it.typeFqName.asString() == this }
    ?.let { JvmPrimitiveType.get(it) }

internal fun TypeWrapper.getAsType(classId: ClassId, fqName: String, top: Boolean): TypeWrapper {
    val fqNameSplit = fqName
        .takeIf { top }
        ?.getAsPrimitive()
        ?.name?.toLowerCase()
        ?.let(::listOf)
        ?: classId.asString().split("/")

    return JavaTypeWrapper(
        fqNameSplit,
        arguments.map { it.asJava(false) },
        classId.toDRI(dri),
        fqNameSplit.last()[0].isLowerCase()
    )
}

private fun DRI.partialFqName() = packageName?.let { "$it." } + classNames
private fun DRI.possiblyAsJava() = this.partialFqName().mapToJava()?.toDRI(this) ?: this

internal fun TypeWrapper.asJava(top: Boolean = true): TypeWrapper = constructorFqName
    ?.let { if (it.endsWith(".Unit")) return VoidTypeWrapper() else it }
    ?.let { fqName -> fqName.mapToJava()?.let { getAsType(it, fqName, top) } } ?: this

private data class VoidTypeWrapper(
    override val constructorFqName: String = "void",
    override val constructorNamePathSegments: List<String> = listOf("void"),
    override val arguments: List<TypeWrapper> = emptyList(),
    override val dri: DRI = DRI("java.lang", "Void")
) : TypeWrapper

private fun String.mapToJava(): ClassId? =
    JavaToKotlinClassMap.mapKotlinToJava(FqName(this).toUnsafe())

internal fun ClassId.toDRI(dri: DRI?): DRI = DRI(
    packageName = packageFqName.asString(),
    classNames = classNames(),
    callable = dri?.callable,//?.asJava(), TODO: check this
    extra = null,
    target = null
)

private fun PropertyContainer<out Documentable>.mergeAdditionalModifiers(second: Set<ExtraModifiers>) =
    this[AdditionalModifiers.AdditionalKey]?.squash(AdditionalModifiers(second)) ?: AdditionalModifiers(second)

private fun AdditionalModifiers.squash(second: AdditionalModifiers) =
    AdditionalModifiers(content + second.content)

internal fun ClassId.classNames(): String =
    shortClassName.identifier + (outerClassId?.classNames()?.let { ".$it" } ?: "")