/
KtFirPsiTypeProvider.kt
406 lines (365 loc) · 18.6 KB
/
KtFirPsiTypeProvider.kt
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.components
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import com.intellij.psi.impl.cache.TypeInfo
import com.intellij.psi.impl.compiled.ClsTypeElementImpl
import com.intellij.psi.impl.compiled.SignatureParsing
import com.intellij.psi.impl.compiled.StubBuildingVisitor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.analysis.api.KtAnalysisNonPublicApi
import org.jetbrains.kotlin.analysis.api.components.KtPsiTypeProvider
import org.jetbrains.kotlin.analysis.api.fir.KtFirAnalysisSession
import org.jetbrains.kotlin.analysis.api.fir.findPsi
import org.jetbrains.kotlin.analysis.api.fir.types.KtFirType
import org.jetbrains.kotlin.analysis.api.fir.types.PublicTypeApproximator
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.types.KtTypeMappingMode
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightParameter
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.descriptors.java.JavaVisibilities
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.backend.jvm.jvmTypeMapper
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.java.MutableJavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.javaSymbolProvider
import org.jetbrains.kotlin.fir.java.resolveIfJavaType
import org.jetbrains.kotlin.fir.moduleData
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.resolve.substitution.AbstractConeSubstitutor
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.lazyResolveToPhase
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.types.jvm.buildJavaTypeRef
import org.jetbrains.kotlin.light.classes.symbol.annotations.annotateByKtType
import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaTypeImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaTypeParameterImpl
import org.jetbrains.kotlin.load.java.structure.impl.source.JavaElementSourceFactory
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.load.kotlin.getOptimalModeForReturnType
import org.jetbrains.kotlin.load.kotlin.getOptimalModeForValueParameter
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.platform.has
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.psi
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.types.model.SimpleTypeMarker
import org.jetbrains.kotlin.types.updateArgumentModeFromAnnotations
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.text.StringCharacterIterator
internal class KtFirPsiTypeProvider(
override val analysisSession: KtFirAnalysisSession,
override val token: KtLifetimeToken,
) : KtPsiTypeProvider(), KtFirAnalysisSessionComponent {
override fun asPsiType(
type: KtType,
useSitePosition: PsiElement,
allowErrorTypes: Boolean,
mode: KtTypeMappingMode,
isAnnotationMethod: Boolean,
suppressWildcards: Boolean?,
preserveAnnotations: Boolean,
): PsiType? {
val coneType = type.coneType
with(rootModuleSession.typeContext) {
if (!allowErrorTypes && coneType.contains { it.isError() }) {
return null
}
}
if (!rootModuleSession.moduleData.platform.has<JvmPlatform>()) return null
val typeElement = coneType.simplifyType(rootModuleSession, useSitePosition).asPsiTypeElement(
session = rootModuleSession,
mode = mode.toTypeMappingMode(type, isAnnotationMethod, suppressWildcards),
useSitePosition = useSitePosition,
allowErrorTypes = allowErrorTypes,
) ?: return null
val psiType = typeElement.type
if (!preserveAnnotations) return psiType
@OptIn(KtAnalysisNonPublicApi::class)
return with(analysisSession) {
annotateByKtType(
psiType = psiType,
ktType = type,
annotationParent = typeElement,
)
}
}
private fun KtTypeMappingMode.toTypeMappingMode(
type: KtType,
isAnnotationMethod: Boolean,
suppressWildcards: Boolean?,
): TypeMappingMode {
require(type is KtFirType)
val expandedType = type.coneType.fullyExpandedType(rootModuleSession)
return when (this) {
KtTypeMappingMode.DEFAULT -> TypeMappingMode.DEFAULT
KtTypeMappingMode.DEFAULT_UAST -> TypeMappingMode.DEFAULT_UAST
KtTypeMappingMode.GENERIC_ARGUMENT -> TypeMappingMode.GENERIC_ARGUMENT
KtTypeMappingMode.SUPER_TYPE -> TypeMappingMode.SUPER_TYPE
KtTypeMappingMode.SUPER_TYPE_KOTLIN_COLLECTIONS_AS_IS -> TypeMappingMode.SUPER_TYPE_KOTLIN_COLLECTIONS_AS_IS
KtTypeMappingMode.RETURN_TYPE_BOXED -> TypeMappingMode.RETURN_TYPE_BOXED
KtTypeMappingMode.RETURN_TYPE -> {
rootModuleSession.jvmTypeMapper.typeContext.getOptimalModeForReturnType(expandedType, isAnnotationMethod)
}
KtTypeMappingMode.VALUE_PARAMETER -> {
rootModuleSession.jvmTypeMapper.typeContext.getOptimalModeForValueParameter(expandedType)
}
}.let { typeMappingMode ->
// Otherwise, i.e., if we won't skip type with no type arguments, flag overriding might bother a case like:
// @JvmSuppressWildcards(false) Long -> java.lang.Long, not long, even though it should be no-op!
if (expandedType.typeArguments.isEmpty())
typeMappingMode
else
typeMappingMode.updateArgumentModeFromAnnotations(
expandedType,
rootModuleSession.jvmTypeMapper.typeContext,
suppressWildcards,
)
}
}
override fun asKtType(
psiType: PsiType,
useSitePosition: PsiElement,
): KtType? {
val javaElementSourceFactory = JavaElementSourceFactory.getInstance(project)
val javaType = JavaTypeImpl.create(psiType, javaElementSourceFactory.createTypeSource(psiType))
val javaTypeRef = buildJavaTypeRef {
// Annotations are unused during `resolveIfJavaType`, so there is no need to provide something
annotationBuilder = { emptyList() }
type = javaType
}
val javaTypeParameterStack = MutableJavaTypeParameterStack()
var psiClass = PsiTreeUtil.getContextOfType(useSitePosition, PsiClass::class.java, false)
while (psiClass != null && psiClass.name == null || psiClass is PsiTypeParameter) {
psiClass = PsiTreeUtil.getContextOfType(psiClass, PsiClass::class.java, true)
}
if (psiClass != null) {
val qualifiedName = psiClass.qualifiedName
val packageName = (psiClass.containingFile as? PsiJavaFile)?.packageName ?: ""
if (qualifiedName != null) {
val javaClass = JavaClassImpl(javaElementSourceFactory.createPsiSource(psiClass))
val relativeName = if (packageName.isEmpty()) qualifiedName else qualifiedName.substring(packageName.length + 1)
val containingClassSymbol = rootModuleSession.javaSymbolProvider?.getClassLikeSymbolByClassId(
ClassId(
FqName(packageName),
FqName(relativeName.takeIf { !relativeName.isEmpty() } ?: SpecialNames.NO_NAME_PROVIDED.asString()),
PsiUtil.isLocalClass(psiClass)
),
javaClass
)
if (containingClassSymbol != null) {
val member = useSitePosition.parentsWithSelf
.filterNot { it is PsiTypeParameter }
.takeWhile { it !is PsiClass }
.firstIsInstanceOrNull<PsiTypeParameterListOwner>()
if (member != null) {
val memberSymbol = containingClassSymbol.declarationSymbols.find { it.findPsi() == member } as? FirCallableSymbol<*>
if (memberSymbol != null) {
//typeParamSymbol.fir.source == null thus zip is required, see KT-62354
memberSymbol.typeParameterSymbols.zip(member.typeParameters).forEach { (typeParamSymbol, typeParam) ->
javaTypeParameterStack.addParameter(JavaTypeParameterImpl(typeParam), typeParamSymbol)
}
}
}
containingClassSymbol.typeParameterSymbols.zip(psiClass.typeParameters).forEach { (symbol, typeParameter) ->
javaTypeParameterStack.addParameter(JavaTypeParameterImpl(typeParameter), symbol)
}
}
}
}
val firTypeRef = javaTypeRef.resolveIfJavaType(analysisSession.useSiteSession, javaTypeParameterStack, source = null)
val coneKotlinType = (firTypeRef as? FirResolvedTypeRef)?.type ?: return null
return coneKotlinType.asKtType()
}
}
private fun ConeKotlinType.simplifyType(
session: FirSession,
useSitePosition: PsiElement,
visited: MutableSet<ConeKotlinType> = mutableSetOf(),
): ConeKotlinType {
// E.g., Wrapper<T> : Comparable<Wrapper<T>>
if (!visited.add(this)) return this
val substitutor = AnonymousTypesSubstitutor(session)
val visibilityForApproximation = useSitePosition.visibilityForApproximation
// TODO: See if the given [useSitePosition] is an `inline` method
val isInlineFunction = false
var currentType = this
do {
val oldType = currentType
currentType = currentType.fullyExpandedType(session)
if (currentType is ConeDynamicType) {
return currentType
}
currentType = currentType.upperBoundIfFlexible()
if (visibilityForApproximation != Visibilities.Local) {
currentType = substitutor.substituteOrSelf(currentType)
}
val needLocalTypeApproximation = needLocalTypeApproximation(visibilityForApproximation, isInlineFunction, session, useSitePosition)
// TODO: can we approximate local types in type arguments *selectively* ?
currentType = PublicTypeApproximator.approximateTypeToPublicDenotable(currentType, session, needLocalTypeApproximation)
?: currentType
} while (oldType !== currentType)
if (typeArguments.isNotEmpty()) {
currentType = currentType.withArguments { typeProjection ->
typeProjection.replaceType(
typeProjection.type?.simplifyType(session, useSitePosition, visited)
)
}
}
return currentType
}
private fun ConeKotlinType.needLocalTypeApproximation(
visibilityForApproximation: Visibility,
isInlineFunction: Boolean,
session: FirSession,
useSitePosition: PsiElement,
): Boolean {
if (!shouldApproximateAnonymousTypesOfNonLocalDeclaration(visibilityForApproximation, isInlineFunction)) return false
val localTypes: List<ConeKotlinType> = if (isLocal(session)) listOf(this) else {
typeArguments.mapNotNull {
if (it is ConeKotlinTypeProjection && it.type.isLocal(session)) {
it.type
} else null
}
}
val unavailableLocalTypes = localTypes.filterNot { it.isLocalButAvailableAtPosition(session, useSitePosition) }
// Need to approximate if there are local types that are not available in this scope
return localTypes.isNotEmpty() && unavailableLocalTypes.isNotEmpty()
}
// Mimic FirDeclaration.visibilityForApproximation
private val PsiElement.visibilityForApproximation: Visibility
get() {
if (this !is PsiMember) return Visibilities.Local
val containerVisibility =
if (parent is KtLightClassForFacade) Visibilities.Public
else (parent as? PsiClass)?.visibility ?: Visibilities.Local
val visibility = visibility
if (containerVisibility == Visibilities.Local || visibility == Visibilities.Local) return Visibilities.Local
if (containerVisibility == Visibilities.Private) return Visibilities.Private
return visibility
}
// Mimic JavaElementUtil#getVisibility
private val PsiModifierListOwner.visibility: Visibility
get() {
if (parents.any { it is PsiMethod }) return Visibilities.Local
if (hasModifierProperty(PsiModifier.PUBLIC)) {
return Visibilities.Public
}
if (hasModifierProperty(PsiModifier.PRIVATE) || hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
return Visibilities.Private
}
return if (language == JavaLanguage.INSTANCE) {
when {
hasModifierProperty(PsiModifier.PROTECTED) && hasModifierProperty(PsiModifier.STATIC) ->
JavaVisibilities.ProtectedStaticVisibility
hasModifierProperty(PsiModifier.PROTECTED) ->
JavaVisibilities.ProtectedAndPackage
else ->
JavaVisibilities.PackageVisibility
}
} else Visibilities.DEFAULT_VISIBILITY
}
private fun ConeKotlinType.isLocal(session: FirSession): Boolean {
return with(session.typeContext) {
this@isLocal.typeConstructor().isLocalType()
}
}
private fun ConeKotlinType.isLocalButAvailableAtPosition(
session: FirSession,
useSitePosition: PsiElement,
): Boolean {
val localClassSymbol = this.toRegularClassSymbol(session) ?: return false
val localPsi = localClassSymbol.source?.psi ?: return false
val context = (useSitePosition as? KtLightElement<*, *>)?.kotlinOrigin ?: useSitePosition
// Local type is available if it's inside the same context (containing declaration)
// or containing declaration is inside the local type, e.g., a member of the local class
return localPsi == context ||
localPsi.parents.any { it == context } ||
context.parents.any { it == localPsi }
}
private fun ConeKotlinType.asPsiTypeElement(
session: FirSession,
mode: TypeMappingMode,
useSitePosition: PsiElement,
allowErrorTypes: Boolean,
): PsiTypeElement? {
if (this !is SimpleTypeMarker) return null
if (!allowErrorTypes && (this is ConeErrorType)) return null
(this as? ConeClassLikeType)?.lookupTag?.toSymbol(session)?.lazyResolveToPhase(FirResolvePhase.STATUS)
val signatureWriter = BothSignatureWriter(BothSignatureWriter.Mode.SKIP_CHECKS)
//TODO Check thread safety
session.jvmTypeMapper.mapType(this, mode, signatureWriter) {
val containingFile = useSitePosition.containingKtFile
// parameters for default setters does not have kotlin origin, but setter has
?: (useSitePosition as? KtLightParameter)?.parent?.parent?.containingKtFile
?: return@mapType null
val correspondingImport = containingFile.findImportByAlias(it) ?: return@mapType null
correspondingImport.importPath?.pathStr
}
val canonicalSignature = signatureWriter.toString()
require(!canonicalSignature.contains(SpecialNames.ANONYMOUS_STRING))
if (canonicalSignature.contains("L<error>")) return null
if (canonicalSignature.contains(SpecialNames.NO_NAME_PROVIDED.asString())) return null
val signature = StringCharacterIterator(canonicalSignature)
val javaType = SignatureParsing.parseTypeString(signature, StubBuildingVisitor.GUESSING_MAPPER)
val typeInfo = TypeInfo.fromString(javaType, false)
val typeText = TypeInfo.createTypeText(typeInfo) ?: return null
return SyntheticTypeElement(useSitePosition, typeText)
}
private class SyntheticTypeElement(parent: PsiElement, typeText: String) : ClsTypeElementImpl(parent, typeText, '\u0000'), SyntheticElement
private val PsiElement.containingKtFile: KtFile?
get() = (this as? KtLightElement<*, *>)?.kotlinOrigin?.containingKtFile
private class AnonymousTypesSubstitutor(
private val session: FirSession,
) : AbstractConeSubstitutor(session.typeContext) {
override fun substituteType(type: ConeKotlinType): ConeKotlinType? {
if (type !is ConeClassLikeType) return null
val hasStableName = type.classId?.isLocal == true
if (!hasStableName) {
// Make sure we're not going to expand type argument over and over again.
// If so, i.e., if there is a recursive type argument, return the current, non-null [type]
// to prevent the following [substituteTypeOr*] from proceeding to its own (recursive) substitution.
if (type.hasRecursiveTypeArgument()) return type
// Return `null` means we will use [fir.resolve.substitution.Substitutors]'s [substituteRecursive]
// that literally substitutes type arguments recursively.
return null
}
val firClassNode = type.lookupTag.toSymbol(session) as? FirClassSymbol
if (firClassNode != null) {
firClassNode.resolvedSuperTypes.singleOrNull()?.let { return it }
}
return if (type.nullability.isNullable) session.builtinTypes.nullableAnyType.type
else session.builtinTypes.anyType.type
}
private fun ConeKotlinType.hasRecursiveTypeArgument(
visited: MutableSet<ConeKotlinType> = mutableSetOf(),
): Boolean {
if (typeArguments.isEmpty()) return false
if (!visited.add(this)) return true
for (projection in typeArguments) {
// E.g., Test : Comparable<Test>
val type = (projection as? ConeKotlinTypeProjection)?.type ?: continue
// E.g., Comparable<Test>
val newType = substituteOrNull(type) ?: continue
// Visit new type: e.g., Test, as a type argument, is substituted with Comparable<Test>, again.
if (newType.hasRecursiveTypeArgument(visited)) return true
}
return false
}
}