summaryrefslogtreecommitdiff
path: root/plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/UastResolveApiTestBase.kt
blob: 3245418f400c4ad7da210072f750e8ea60de0c93 (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
// 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.test.common.kotlin

import com.intellij.psi.*
import junit.framework.TestCase
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.UastVisitor
import org.junit.Assert
import java.lang.IllegalStateException

interface UastResolveApiTestBase : UastPluginSelection {

    fun checkCallbackForDoWhile(filePath: String, uFile: UFile) {
        val facade = uFile.findFacade()
            ?: throw IllegalStateException("No facade found at ${uFile.asRefNames()}")
        val test = facade.methods.find { it.name == "test" }
            ?: throw IllegalStateException("Target function not found at ${uFile.asRefNames()}")
        val resolvedBinaryOperators: MutableList<PsiMethod> = mutableListOf()
        test.accept(object : UastVisitor {
            override fun visitElement(node: UElement): Boolean {
                return false
            }

            override fun visitBinaryExpression(node: UBinaryExpression): Boolean {
                node.resolveOperator()?.let { resolvedBinaryOperators.add(it) }
                return false
            }
        })
        Assert.assertEquals("Expect != (String.equals)", 1, resolvedBinaryOperators.size)
        val op = resolvedBinaryOperators.single()
        Assert.assertEquals("equals", op.name)

        val kt44412 = facade.methods.find { it.name == "kt44412" }
            ?: throw IllegalStateException("Target function not found at ${uFile.asRefNames()}")
        resolvedBinaryOperators.clear()
        val resolvedUnaryOperators: MutableList<PsiMethod> = mutableListOf()
        kt44412.accept(object : UastVisitor {
            override fun visitElement(node: UElement): Boolean {
                return false
            }

            override fun visitBinaryExpression(node: UBinaryExpression): Boolean {
                node.resolveOperator()?.let { resolvedBinaryOperators.add(it) }
                return false
            }

            override fun visitPrefixExpression(node: UPrefixExpression): Boolean {
                node.resolveOperator()?.let { resolvedUnaryOperators.add(it) }
                return false
            }
        })
        Assert.assertEquals("Kotlin built-in >= (int.compareTo) and == (int.equals) are invisible", 0, resolvedBinaryOperators.size)
        Assert.assertEquals("Kotlin built-in ++ (int.inc) is invisible", 0, resolvedUnaryOperators.size)
    }

    fun checkCallbackForIf(filePath: String, uFile: UFile) {
        val facade = uFile.findFacade()
            ?: throw IllegalStateException("No facade found at ${uFile.asRefNames()}")
        val test = facade.methods.find { it.name == "test" }
            ?: throw IllegalStateException("Target function not found at ${uFile.asRefNames()}")
        val resolvedOperators: MutableList<PsiMethod> = mutableListOf()
        test.accept(object : UastVisitor {
            override fun visitElement(node: UElement): Boolean {
                return false
            }

            override fun visitBinaryExpression(node: UBinaryExpression): Boolean {
                node.resolveOperator()?.let { resolvedOperators.add(it) }
                return false
            }
        })
        Assert.assertEquals("Kotlin built-in * (int.times) and + (int.plus) are invisible", 0, resolvedOperators.size)
    }

    fun checkCallbackForMethodReference(filePath: String, uFile: UFile) {
        val facade = uFile.findFacade()
            ?: throw IllegalStateException("No facade found at ${uFile.asRefNames()}")
        // val x = Foo::bar
        val x = facade.fields.single()
        var barReference: PsiElement? = null
        x.accept(object : UastVisitor {
            override fun visitElement(node: UElement): Boolean {
                return false
            }

            override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean {
                barReference = node.resolve()
                return false
            }
        })
        Assert.assertNotNull("Foo::bar is not resolved", barReference)
        val barReferenceOrigin = (barReference as KtLightMethod).kotlinOrigin
        Assert.assertTrue("Foo::bar is not a function", barReferenceOrigin is KtNamedFunction)
        Assert.assertEquals("Foo.bar", (barReferenceOrigin as KtNamedFunction).fqName?.asString())
    }

    fun checkCallbackForImports(filePath: String, uFile: UFile) {
        uFile.imports.forEach { uImport ->
            if ((uImport.sourcePsi as? KtImportDirective)?.text?.endsWith("sleep") == true) {
                // There are two static [sleep] in [java.lang.Thread], so the import (w/o knowing its usage) can't be resolved to
                // a single function, hence `null` (as [resolve] result).
                // TODO: make [UImportStatement] a subtype of [UMultiResolvable], instead of [UResolvable]?
                return@forEach
            }
            val resolvedImport = uImport.resolve()
                ?: throw IllegalStateException("Unresolved import: ${uImport.asRenderString()}")
            val expected = when (resolvedImport) {
                is PsiClass -> {
                    // import java.lang.Thread.*
                    resolvedImport.name == "Thread" || resolvedImport.name == "UncaughtExceptionHandler"
                }
                is PsiMethod -> {
                    // import java.lang.Thread.currentThread
                    resolvedImport.name == "currentThread" ||
                            // import kotlin.collections.emptyList
                            (!isFirUastPlugin && resolvedImport.name == "emptyList")
                }
                is PsiField -> {
                    // import java.lang.Thread.NORM_PRIORITY
                    resolvedImport.name == "NORM_PRIORITY" ||
                            // import kotlin.Int.Companion.SIZE_BYTES
                            (!isFirUastPlugin && resolvedImport.name == "SIZE_BYTES")
                }
                is KtNamedFunction -> {
                    // import kotlin.collections.emptyList
                    isFirUastPlugin && resolvedImport.isTopLevel && resolvedImport.name == "emptyList"
                }
                is KtProperty -> {
                    // import kotlin.Int.Companion.SIZE_BYTES
                    isFirUastPlugin && resolvedImport.name == "SIZE_BYTES"
                }
                else -> false
            }
            Assert.assertTrue("Unexpected import: $resolvedImport", expected)
        }
    }

    fun checkCallbackForReceiverFun(filePath: String, uFile: UFile) {
        val facade = uFile.findFacade()
            ?: throw IllegalStateException("No facade found at ${uFile.asRefNames()}")
        // ... String.foo() = this.length
        val foo = facade.methods.find { it.name == "foo" }
            ?: throw IllegalStateException("Target function not found at ${uFile.asRefNames()}")
        var thisReference: PsiElement? = foo
        foo.accept(object : UastVisitor {
            override fun visitElement(node: UElement): Boolean {
                return false
            }

            override fun visitThisExpression(node: UThisExpression): Boolean {
                thisReference = node.resolve()
                return false
            }
        })
        Assert.assertNull("plain `this` has `null` label", thisReference)
    }

    fun checkCallbackForRetention(uFilePath: String, uFile: UFile) {

        fun checkRetentionAndResolve(uAnnotation: UAnnotation) {
            if (uAnnotation.qualifiedName?.endsWith("Retention") == true) {
                val value = uAnnotation.findAttributeValue("value")
                val reference = value as? UReferenceExpression
                TestCase.assertNotNull("Can't find the reference to @Retention value", reference)
                // Resolve @Retention value
                val resolvedValue = reference!!.resolve()
                TestCase.assertNotNull("Can't resolve @Retention value", resolvedValue)
                TestCase.assertEquals("SOURCE", (resolvedValue as? PsiNamedElement)?.name)
            }
        }

        // Lookup @Anno directly from the source file
        val anno = uFile.classes.find { it.name == "Anno" }
            ?: throw IllegalStateException("Target class not found at ${uFile.asRefNames()}")
        TestCase.assertTrue("@Anno is not an annotation?!", anno.isAnnotationType)
        anno.uAnnotations.forEach(::checkRetentionAndResolve)

        // Lookup @Anno indirectly from an annotated test class
        val testClass = uFile.classes.find { it.name == "TestClass" }
            ?: throw IllegalStateException("Target class not found at ${uFile.asRefNames()}")
        val annoOnTestClass = testClass.uAnnotations.find { it.qualifiedName?.endsWith("Anno") == true }
            ?: throw IllegalStateException("Target annotation not found at ${testClass.asSourceString()}")
        // Resolve @Anno to PsiClass
        val resolvedAnno = annoOnTestClass.resolve()
        TestCase.assertNotNull("Can't resolve @Anno on TestClass", resolvedAnno)
        for (psi in resolvedAnno!!.annotations) {
            val uAnnotation = anno.uAnnotations.find { it.javaPsi == psi } ?: continue
            val rebuiltAnnotation = psi.toUElement(UAnnotation::class.java)
            TestCase.assertNotNull("Should be able to rebuild UAnnotation from $psi", rebuiltAnnotation)
            TestCase.assertEquals(uAnnotation.qualifiedName, rebuiltAnnotation!!.qualifiedName)
            // Check Retention on a rebuilt UAnnotation
            checkRetentionAndResolve(rebuiltAnnotation)
        }
    }
}