summaryrefslogtreecommitdiff
path: root/plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/kotlinConvertParentUtils.kt
blob: 4bb81ad0e0482567cf9ba51e6511d5c4e5778557 (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
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.uast.kotlin

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.toLightGetter
import org.jetbrains.kotlin.asJava.toLightSetter
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable

internal fun convertParentImpl(
    service: BaseKotlinUastResolveProviderService,
    uElement: UElement
): UElement? {
    @Suppress("DEPRECATION")
    val psi = uElement.psi //TODO: `psi` is deprecated but it seems that it couldn't be simply replaced for this case
    var parent = psi?.parent ?: uElement.sourcePsi?.parent ?: psi?.containingFile

    if (psi is PsiMethod && psi !is KtLightMethod) { // handling of synthetic things not represented in lightclasses directly
        when (parent) {
            is KtClassBody -> {
                val grandParent = parent.parent
                convertParentImpl(service, uElement, grandParent)?.let { return it }
                parent = grandParent
            }
            is KtFile -> {
                parent.toUElementOfType<UClass>()?.let { return it } // mutlifile facade class
            }
        }

    }

    if (psi is KtLightElement<*, *> && uElement.sourcePsi.safeAs<KtClassOrObject>()?.isLocal == true) {
        val originParent = psi.kotlinOrigin?.parent
        parent = when (originParent) {
            null -> parent
            is KtClassBody -> originParent.parent
            else -> originParent
        }
    }

    if (psi is KtAnnotationEntry) {
        val parentUnwrapped = service.baseKotlinConverter.unwrapElements(parent) ?: return null
        when (psi.useSiteTarget?.getAnnotationUseSiteTarget()) {
            AnnotationUseSiteTarget.PROPERTY_GETTER ->
                parent = (parentUnwrapped as? KtProperty)?.getter
                         ?: (parentUnwrapped as? KtParameter)?.toLightGetter()
                         ?: parent

            AnnotationUseSiteTarget.PROPERTY_SETTER ->
                parent = (parentUnwrapped as? KtProperty)?.setter
                         ?: (parentUnwrapped as? KtParameter)?.toLightSetter()
                         ?: parent
            AnnotationUseSiteTarget.FIELD ->
                parent = (parentUnwrapped as? KtProperty)
                    ?: (parentUnwrapped as? KtParameter)
                        ?.takeIf { it.isPropertyParameter() }
                        ?.let(LightClassUtil::getLightClassBackingField)
                            ?: parent
            AnnotationUseSiteTarget.SETTER_PARAMETER ->
                parent = (parentUnwrapped as? KtParameter)
                    ?.toLightSetter()?.parameterList?.parameters?.firstOrNull() ?: parent
        }
    }
    if ((psi is UastKotlinPsiVariable || psi is UastKotlinPsiParameter) && parent != null) {
        parent = parent.parent
    }

    if (service.baseKotlinConverter.forceUInjectionHost()) {
        if (parent is KtBlockStringTemplateEntry) {
            parent = parent.parent
        }
    } else
        while (parent is KtStringTemplateEntryWithExpression || parent is KtStringTemplateExpression && parent.entries.size == 1) {
            parent = parent.parent
        }

    if (parent is KtWhenConditionWithExpression) {
        parent = parent.parent
    }

    if (parent is KtImportList) {
        parent = parent.parent
    }

    if (psi is KtFunctionLiteral && parent is KtLambdaExpression) {
        parent = parent.parent
    }

    if (parent is KtLambdaArgument) {
        parent = parent.parent
    }

    if (psi is KtSuperTypeCallEntry) {
        parent = parent?.parent
    }

    if (parent is KtPropertyDelegate) {
        parent = parent.parent
    }

    val result = convertParentImpl(service, uElement, parent)
    if (result == uElement) {
        throw KotlinExceptionWithAttachments("Loop in parent structure when converting a $psi of type ${psi?.javaClass} with parent $parent of type ${parent?.javaClass}")
            .withAttachment("text", parent?.text)
            .withAttachment("result", result)
    }

    return result
}

internal fun convertParentImpl(
    service: BaseKotlinUastResolveProviderService,
    element: UElement,
    parent: PsiElement?
): UElement? {
    val parentUnwrapped = service.baseKotlinConverter.unwrapElements(parent) ?: return null
    if (parent is KtValueArgument && parentUnwrapped is KtAnnotationEntry) {
        return (service.languagePlugin.convertElementWithParent(parentUnwrapped, null) as? KotlinUAnnotation)?.let {
            service.findAttributeValueExpression(it, parent)
        }
    }

    if (parent is KtParameter) {
        val annotationClass = findAnnotationClassFromConstructorParameter(service.languagePlugin, parent)
        if (annotationClass != null) {
            return annotationClass.methods.find { it.name == parent.name }
        }
    }

    if (parent is KtClassInitializer) {
        val containingClass = parent.containingClassOrObject
        if (containingClass != null) {
            val containingUClass = service.languagePlugin.convertElementWithParent(containingClass, null) as? KotlinUClass
            containingUClass?.methods?.filterIsInstance<KotlinConstructorUMethod>()?.firstOrNull { it.isPrimary }?.let {
                return it.uastBody
            }
        }
    }

    val result = service.languagePlugin.convertElementWithParent(parentUnwrapped, null)

    if (result is KotlinUBlockExpression && element is UClass) {
        return KotlinUDeclarationsExpression(result).apply {
            declarations = listOf(element)
        }
    }

    if (result is UEnumConstant && element is UDeclaration) {
        return result.initializingClass
    }

    if (result is UCallExpression && result.uastParent is UEnumConstant) {
        return result.uastParent
    }

    if (result is USwitchClauseExpressionWithBody && !isInConditionBranch(element, result)) {
        val uYieldExpression = result.body.expressions.lastOrNull().safeAs<UYieldExpression>()
        if (uYieldExpression != null && uYieldExpression.expression == element)
            return uYieldExpression

        return result.body
    }

    if (result is KotlinUDestructuringDeclarationExpression &&
        when (parent) {
            is KtDestructuringDeclaration -> parent.initializer?.let { it == element.psi } == true
            is KtDeclarationModifierList -> parent == element.sourcePsi?.parent
            else -> false
        }
    ) {
        return result.tempVarAssignment
    }

    if (result is KotlinUElvisExpression && parentUnwrapped is KtBinaryExpression) {
        val branch: Sequence<PsiElement?> = element.psi?.parentsWithSelf.orEmpty().takeWhile { it != parentUnwrapped }
        if (branch.contains(parentUnwrapped.left))
            return result.lhsDeclaration
        if (branch.contains(parentUnwrapped.right))
            return result.rhsIfExpression
    }

    if ((result is UMethod || result is KotlinLocalFunctionULambdaExpression)
        && result !is KotlinConstructorUMethod // no sense to wrap super calls with `return`
        && element is UExpression
        && element !is UBlockExpression
        && element !is UTypeReferenceExpression // when element is a type in extension methods
    ) {
        return KotlinLazyUBlockExpression(result) { block ->
            listOf(KotlinUImplicitReturnExpression(block).apply { returnExpression = element })
        }.expressions.single()
    }

    if (result is KotlinULambdaExpression.Body && element is UExpression && result.implicitReturn?.returnExpression == element) {
        return result.implicitReturn!!
    }

    return result
}

private fun isInConditionBranch(element: UElement, result: USwitchClauseExpressionWithBody) =
    element.psi?.parentsWithSelf?.takeWhile { it !== result.psi }?.any { it is KtWhenCondition } ?: false

private fun findAnnotationClassFromConstructorParameter(
    languagePlugin: UastLanguagePlugin,
    parameter: KtParameter
): UClass? {
    val primaryConstructor = parameter.getStrictParentOfType<KtPrimaryConstructor>() ?: return null
    val containingClass = primaryConstructor.getContainingClassOrObject()
    if (containingClass.isAnnotation()) {
        return languagePlugin.convertElementWithParent(containingClass, null) as? UClass
    }
    return null
}