summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt
blob: dbf8dc528ea9832df6c9a364ad4d5c403eb4bcd0 (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
302
303
304
305
306
307
308
309
310
311
312
313
314
// 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.kotlin.idea.quickfix.createFromUsage.callableBuilder

import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.getResolvableApproximations
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*

/**
 * Represents a concrete type or a set of types yet to be inferred from an expression.
 */
abstract class TypeInfo(val variance: Variance) {
    object Empty : TypeInfo(Variance.INVARIANT) {
        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = Collections.emptyList()
    }

    class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) {
        override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> {
            return KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray()
        }

        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = expression.guessTypes(
            context = builder.currentFileContext,
            module = builder.currentFileModule,
            pseudocode = try {
                builder.pseudocode
            } catch (stackException: EmptyStackException) {
                val originalElement = builder.config.originalElement
                val containingDeclarationForPseudocode = originalElement.containingDeclarationForPseudocode

                // copy-pasted from org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt.getContainingPseudocode
                val enclosingPseudocodeDeclaration = (containingDeclarationForPseudocode as? KtFunctionLiteral)?.let { functionLiteral ->
                    functionLiteral.parents.firstOrNull { it is KtDeclaration && it !is KtFunctionLiteral } as? KtDeclaration
                } ?: containingDeclarationForPseudocode

                throw KotlinExceptionWithAttachments(stackException.message, stackException)
                    .withPsiAttachment("original_expression.txt", originalElement)
                    .withPsiAttachment("containing_declaration.txt", containingDeclarationForPseudocode)
                    .withPsiAttachment("enclosing_declaration.txt", enclosingPseudocodeDeclaration)
            }
        ).flatMap { it.getPossibleSupertypes(variance, builder) }
    }

    class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) {
        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
            builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder)
    }

    class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) {
        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
            theType.getPossibleSupertypes(variance, builder)
    }

    class ByReceiverType(variance: Variance) : TypeInfo(variance) {
        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
            (builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder)
    }

    class ByExplicitCandidateTypes(val types: List<KotlinType>) : TypeInfo(Variance.INVARIANT) {
        override fun getPossibleTypes(builder: CallableBuilder) = types
    }

    abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) {
        override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed
        override fun getPossibleNamesFromExpression(bindingContext: BindingContext) =
            delegate.getPossibleNamesFromExpression(bindingContext)

        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = delegate.getPossibleTypes(builder)
    }

    class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
        override val substitutionsAllowed: Boolean = false
    }

    class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
        override val staticContextRequired: Boolean = true
    }

    class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate)

    val isOfThis: Boolean
        get() = when (this) {
            is OfThis -> true
            is DelegatingTypeInfo -> delegate.isOfThis
            else -> false
        }

    open val substitutionsAllowed: Boolean = true
    open val staticContextRequired: Boolean = false
    open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> = ArrayUtil.EMPTY_STRING_ARRAY
    abstract fun getPossibleTypes(builder: CallableBuilder): List<KotlinType>

    private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? {
        if (placement == null) return config.originalElement.getResolutionScope()

        val containingElement = when (placement) {
            is CallablePlacement.NoReceiver -> {
                placement.containingElement
            }
            is CallablePlacement.WithReceiver -> {
                val receiverClassDescriptor =
                    placement.receiverTypeCandidate.theType.constructor.declarationDescriptor
                val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
                if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
            }
        }
        return when (containingElement) {
            is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution
            is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope()
            is KtElement -> containingElement.containingKtFile.getResolutionScope()
            else -> null
        }
    }

    protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List<KotlinType> {
        if (this == null || ErrorUtils.containsErrorType(this)) {
            return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType)
        }
        val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement)
        val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true)
        return when (variance) {
            Variance.IN_VARIANCE -> approximations.toList()
            else -> listOf(approximations.firstOrNull() ?: this)
        }
    }
}

fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance)
fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance)
fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance)

fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this)

fun TypeInfo.forceNotNull(): TypeInfo {
    class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) {
        override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
            super.getPossibleTypes(builder).map { it.makeNotNullable() }
    }

    return (this as? ForcedNotNull) ?: ForcedNotNull(this)
}

fun TypeInfo.ofThis() = TypeInfo.OfThis(this)

/**
 * Encapsulates information about a function parameter that is going to be created.
 */
class ParameterInfo(
    val typeInfo: TypeInfo,
    val nameSuggestions: List<String>
) {
    constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName))
}

enum class CallableKind {
    FUNCTION,
    CLASS_WITH_PRIMARY_CONSTRUCTOR,
    CONSTRUCTOR,
    PROPERTY
}

abstract class CallableInfo(
    val name: String,
    val receiverTypeInfo: TypeInfo,
    val returnTypeInfo: TypeInfo,
    val possibleContainers: List<KtElement>,
    val typeParameterInfos: List<TypeInfo>,
    val isForCompanion: Boolean = false,
    val modifierList: KtModifierList? = null
) {
    abstract val kind: CallableKind
    abstract val parameterInfos: List<ParameterInfo>

    val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true

    abstract fun copy(
        receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
        possibleContainers: List<KtElement> = this.possibleContainers,
        modifierList: KtModifierList? = this.modifierList
    ): CallableInfo
}

class FunctionInfo(
    name: String,
    receiverTypeInfo: TypeInfo,
    returnTypeInfo: TypeInfo,
    possibleContainers: List<KtElement> = Collections.emptyList(),
    override val parameterInfos: List<ParameterInfo> = Collections.emptyList(),
    typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
    isForCompanion: Boolean = false,
    modifierList: KtModifierList? = null,
    val preferEmptyBody: Boolean = false
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
    override val kind: CallableKind get() = CallableKind.FUNCTION

    override fun copy(
        receiverTypeInfo: TypeInfo,
        possibleContainers: List<KtElement>,
        modifierList: KtModifierList?
    ) = FunctionInfo(
        name,
        receiverTypeInfo,
        returnTypeInfo,
        possibleContainers,
        parameterInfos,
        typeParameterInfos,
        isForCompanion,
        modifierList
    )
}

class ClassWithPrimaryConstructorInfo(
    val classInfo: ClassInfo,
    expectedTypeInfo: TypeInfo,
    modifierList: KtModifierList? = null,
    val primaryConstructorVisibility: DescriptorVisibility? = null
) : CallableInfo(
    classInfo.name,
    TypeInfo.Empty,
    expectedTypeInfo.forceNotNull(),
    Collections.emptyList(),
    classInfo.typeArguments,
    false,
    modifierList = modifierList
) {
    override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR
    override val parameterInfos: List<ParameterInfo> get() = classInfo.parameterInfos

    override fun copy(
        receiverTypeInfo: TypeInfo,
        possibleContainers: List<KtElement>,
        modifierList: KtModifierList?
    ) = throw UnsupportedOperationException()
}

class ConstructorInfo(
    override val parameterInfos: List<ParameterInfo>,
    val targetClass: PsiElement,
    val isPrimary: Boolean = false,
    modifierList: KtModifierList? = null,
    val withBody: Boolean = false
) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) {
    override val kind: CallableKind get() = CallableKind.CONSTRUCTOR

    override fun copy(
        receiverTypeInfo: TypeInfo,
        possibleContainers: List<KtElement>,
        modifierList: KtModifierList?
    ) = throw UnsupportedOperationException()
}

class PropertyInfo(
    name: String,
    receiverTypeInfo: TypeInfo,
    returnTypeInfo: TypeInfo,
    val writable: Boolean,
    possibleContainers: List<KtElement> = Collections.emptyList(),
    typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
    val isLateinitPreferred: Boolean = false,
    val isConst: Boolean = false,
    isForCompanion: Boolean = false,
    val annotations: List<KtAnnotationEntry> = emptyList(),
    modifierList: KtModifierList? = null,
    val initializer: KtExpression? = null
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
    override val kind: CallableKind get() = CallableKind.PROPERTY
    override val parameterInfos: List<ParameterInfo> get() = Collections.emptyList()

    override fun copy(
        receiverTypeInfo: TypeInfo,
        possibleContainers: List<KtElement>,
        modifierList: KtModifierList?
    ) = copyProperty(receiverTypeInfo, possibleContainers, modifierList)

    fun copyProperty(
        receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
        possibleContainers: List<KtElement> = this.possibleContainers,
        modifierList: KtModifierList? = this.modifierList,
        isLateinitPreferred: Boolean = this.isLateinitPreferred
    ) = PropertyInfo(
        name,
        receiverTypeInfo,
        returnTypeInfo,
        writable,
        possibleContainers,
        typeParameterInfos,
        isConst,
        isLateinitPreferred,
        isForCompanion,
        annotations,
        modifierList,
        initializer
    )
}