aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/com/replaymod/gradle/remap/PsiUtils.kt
blob: 63f0e76db2aa05b93ea2b0ad50409ef5c92d6b73 (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
package com.replaymod.gradle.remap

import org.cadixdev.bombe.type.ArrayType
import org.cadixdev.bombe.type.FieldType
import org.cadixdev.bombe.type.MethodDescriptor
import org.cadixdev.bombe.type.ObjectType
import org.cadixdev.bombe.type.Type
import org.cadixdev.bombe.type.VoidType
import org.cadixdev.bombe.type.signature.MethodSignature
import org.jetbrains.kotlin.com.intellij.psi.*
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.com.intellij.psi.util.TypeConversionUtil

internal val PsiClass.dollarQualifiedName: String? get() {
    val parent = PsiTreeUtil.getParentOfType<PsiClass>(this, PsiClass::class.java) ?: return qualifiedName
    val parentName = parent.dollarQualifiedName ?: return qualifiedName
    val selfName = name ?: return qualifiedName
    return "$parentName$$selfName"
}

internal object PsiUtils {
    fun getSignature(method: PsiMethod): MethodSignature = MethodSignature(method.name, getDescriptor(method))

    private fun getDescriptor(method: PsiMethod): MethodDescriptor = MethodDescriptor(
            method.parameterList.parameters.map { getFieldType(it.type) },
            getType(method.returnType)
    )

    private fun getFieldType(type: PsiType?): FieldType = when (val erasedType = TypeConversionUtil.erasure(type)) {
        is PsiPrimitiveType -> FieldType.of(erasedType.kind.binaryName)
        is PsiArrayType -> {
            val array = erasedType as PsiArrayType?
            ArrayType(array!!.arrayDimensions, getFieldType(array.deepComponentType))
        }
        is PsiClassType -> {
            val resolved = erasedType.resolve() ?: throw NullPointerException("Failed to resolve type $erasedType")
            val qualifiedName = resolved.dollarQualifiedName
                    ?: throw NullPointerException("Type $erasedType has no qualified name.")
            ObjectType(qualifiedName)
        }
        else -> throw IllegalArgumentException("Cannot translate type " + erasedType!!)
    }

    private fun getType(type: PsiType?): Type = if (TypeConversionUtil.isVoidType(type)) {
        VoidType.INSTANCE
    } else {
        getFieldType(type)
    }
}