-
Notifications
You must be signed in to change notification settings - Fork 249
/
util.kt
757 lines (713 loc) · 33 KB
/
util.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
/*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
@file:OptIn(KtAnalysisApiInternals::class, KtAnalysisApiInternals::class)
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.ExceptionMessage
import com.google.devtools.ksp.common.impl.KSNameImpl
import com.google.devtools.ksp.common.memoized
import com.google.devtools.ksp.impl.KSPCoreEnvironment
import com.google.devtools.ksp.impl.ResolverAAImpl
import com.google.devtools.ksp.impl.symbol.kotlin.resolved.KSClassifierParameterImpl
import com.google.devtools.ksp.impl.symbol.kotlin.resolved.KSClassifierReferenceResolvedImpl
import com.google.devtools.ksp.impl.symbol.util.getDocString
import com.google.devtools.ksp.symbol.*
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiJavaFile
import org.jetbrains.kotlin.analysis.api.KtAnalysisApiInternals
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.KtStarTypeProjection
import org.jetbrains.kotlin.analysis.api.KtTypeArgumentWithVariance
import org.jetbrains.kotlin.analysis.api.KtTypeProjection
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.annotations.*
import org.jetbrains.kotlin.analysis.api.components.KtSubstitutorBuilder
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.components.buildTypeParameterType
import org.jetbrains.kotlin.analysis.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.analysis.api.fir.evaluate.FirAnnotationValueConverter
import org.jetbrains.kotlin.analysis.api.fir.symbols.KtFirValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.fir.types.KtFirType
import org.jetbrains.kotlin.analysis.api.lifetime.KtAlwaysAccessibleLifetimeToken
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithMembers
import org.jetbrains.kotlin.analysis.api.types.*
import org.jetbrains.kotlin.analysis.project.structure.KtLibraryModule
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.java.JavaVisibilities
import org.jetbrains.kotlin.fir.declarations.getTargetType
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.expressions.FirArrayLiteral
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.FirGetClassCall
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.toFirExpression
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.symbols.SymbolInternals
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.ConeErrorType
import org.jetbrains.kotlin.fir.types.ConeFlexibleType
import org.jetbrains.kotlin.fir.types.ConeLookupTagBasedType
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.types.isAny
import org.jetbrains.kotlin.load.java.structure.JavaAnnotationArgument
import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryClassSignatureParser
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaAnnotationVisitor
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.ClassifierResolutionContext
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.JvmStandardClassIds.JVM_SUPPRESS_WILDCARDS_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.name.JvmStandardClassIds.JVM_WILDCARD_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.getEffectiveVariance
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
internal val ktSymbolOriginToOrigin = mapOf(
KtSymbolOrigin.JAVA to Origin.JAVA,
KtSymbolOrigin.SOURCE to Origin.KOTLIN,
KtSymbolOrigin.SAM_CONSTRUCTOR to Origin.SYNTHETIC,
KtSymbolOrigin.SOURCE_MEMBER_GENERATED to Origin.SYNTHETIC,
KtSymbolOrigin.DELEGATED to Origin.SYNTHETIC,
KtSymbolOrigin.PROPERTY_BACKING_FIELD to Origin.KOTLIN,
KtSymbolOrigin.JAVA_SYNTHETIC_PROPERTY to Origin.SYNTHETIC,
KtSymbolOrigin.INTERSECTION_OVERRIDE to Origin.KOTLIN,
// TODO: distinguish between kotlin library and java library.
KtSymbolOrigin.LIBRARY to Origin.KOTLIN_LIB,
KtSymbolOrigin.SUBSTITUTION_OVERRIDE to Origin.JAVA_LIB
)
internal fun mapAAOrigin(ktSymbol: KtSymbol): Origin {
val symbolOrigin = ktSymbolOriginToOrigin[ktSymbol.origin]
?: throw IllegalStateException("unhandled origin ${ktSymbol.origin.name}")
return if (symbolOrigin == Origin.JAVA && ktSymbol.psi?.containingFile?.fileType?.isBinary == true) {
Origin.JAVA_LIB
} else {
if (ktSymbol.psi == null && analyze { ktSymbol.getContainingModule() is KtLibraryModule }) {
Origin.KOTLIN_LIB
} else {
symbolOrigin
}
}
}
internal fun KtAnnotationApplicationWithArgumentsInfo.render(): String {
return buildString {
append("@")
if (this@render.useSiteTarget != null) {
append(this@render.useSiteTarget!!.renderName + ":")
}
append(this@render.classId!!.shortClassName.asString())
this@render.arguments.forEach {
append(it.expression.render())
}
}
}
internal fun KtAnnotationValue.render(): String {
return when (this) {
is KtAnnotationApplicationValue -> annotationValue.render()
is KtArrayAnnotationValue -> values.joinToString(",", "{", "}") { it.render() }
is KtConstantAnnotationValue -> constantValue.renderAsKotlinConstant()
is KtEnumEntryAnnotationValue -> callableId.toString()
// TODO: handle error classes.
is KtKClassAnnotationValue -> "$classId::class"
is KtUnsupportedAnnotationValue -> throw IllegalStateException("Unsupported annotation value: $this")
}
}
internal fun KtType.render(inFunctionType: Boolean = false): String {
return buildString {
annotations.forEach {
append("[${it.render()}] ")
}
append(
when (this@render) {
is KtNonErrorClassType -> buildString {
val symbol = this@render.classifierSymbol()
if (symbol is KtTypeAliasSymbol) {
if (!inFunctionType) {
append("[typealias ${symbol.name.asString()}]")
} else {
append(this@render.toAbbreviatedType().render(inFunctionType))
}
} else {
append(classSymbol.name?.asString())
if (typeArguments().isNotEmpty()) {
typeArguments().joinToString(separator = ", ", prefix = "<", postfix = ">") {
when (it) {
is KtStarTypeProjection -> "*"
is KtTypeArgumentWithVariance ->
"${it.variance}" +
(if (it.variance != Variance.INVARIANT) " " else "") +
it.type.render(this@render is KtFunctionalType)
}
}.also { append(it) }
}
}
}
is KtClassErrorType, is KtTypeErrorType -> "<ERROR TYPE>"
is KtCapturedType -> asStringForDebugging()
is KtDefinitelyNotNullType -> original.render(inFunctionType) + " & Any"
is KtDynamicType -> "<dynamic type>"
is KtFlexibleType -> "(${lowerBound.render(inFunctionType)}..${upperBound.render(inFunctionType)})"
is KtIntegerLiteralType -> "ILT: $value"
is KtIntersectionType ->
this@render.conjuncts
.joinToString(separator = " & ", prefix = "(", postfix = ")") { it.render(inFunctionType) }
is KtTypeParameterType -> name.asString()
} + if (nullability == KtTypeNullability.NULLABLE) "?" else ""
)
}
}
internal fun KtType.toClassifierReference(parent: KSTypeReference?): KSReferenceElement? {
return when (val ktType = this) {
is KtFunctionalType -> KSCallableReferenceImpl.getCached(ktType, parent)
is KtDynamicType -> KSDynamicReferenceImpl.getCached(parent!!)
is KtUsualClassType -> KSClassifierReferenceResolvedImpl.getCached(ktType, ktType.qualifiers.size - 1, parent)
is KtFlexibleType -> ktType.lowerBound.toClassifierReference(parent)
is KtErrorType -> null
is KtTypeParameterType -> KSClassifierParameterImpl.getCached(ktType, parent)
is KtDefinitelyNotNullType -> KSDefNonNullReferenceImpl.getCached(ktType, parent)
else -> throw IllegalStateException("Unexpected type element ${ktType.javaClass}, $ExceptionMessage")
}
}
internal fun KSTypeArgument.toKtTypeProjection(): KtTypeProjection {
val variance = when (this.variance) {
com.google.devtools.ksp.symbol.Variance.INVARIANT -> Variance.INVARIANT
com.google.devtools.ksp.symbol.Variance.COVARIANT -> Variance.OUT_VARIANCE
com.google.devtools.ksp.symbol.Variance.CONTRAVARIANT -> Variance.IN_VARIANCE
else -> null
}
val argType = (this.type?.resolve() as? KSTypeImpl)?.type
// TODO: maybe make a singleton of alwaysAccessibleLifetimeToken?
val alwaysAccessibleLifetimeToken = KtAlwaysAccessibleLifetimeToken(ResolverAAImpl.ktModule.project!!)
return if (argType == null || variance == null) {
KtStarTypeProjection(alwaysAccessibleLifetimeToken)
} else {
KtTypeArgumentWithVariance(argType, variance, alwaysAccessibleLifetimeToken)
}
}
internal fun PsiElement?.toLocation(): Location {
if (this == null) {
return NonExistLocation
}
val file = this.containingFile
val document = KSPCoreEnvironment.instance.psiDocumentManager.getDocument(file) ?: return NonExistLocation
return FileLocation(file.virtualFile.path, document.getLineNumber(this.textOffset) + 1)
}
internal fun KtSymbol.toContainingFile(): KSFile? {
return when (val psi = this.psi) {
is KtElement -> analyze {
KSFileImpl.getCached(psi.containingKtFile.getFileSymbol())
}
is PsiElement -> KSFileJavaImpl.getCached(psi.containingFile as PsiJavaFile)
else -> null
}
}
internal fun KtSymbol.toDocString(): String? = this.psi?.getDocString()
internal inline fun <R> analyze(crossinline action: KtAnalysisSession.() -> R): R {
return analyze(ResolverAAImpl.ktModule, action)
}
internal fun KtSymbolWithMembers.declarations(): Sequence<KSDeclaration> {
return analyze {
this@declarations.let {
it.getDeclaredMemberScope().getAllSymbols() + it.getStaticDeclaredMemberScope().getAllSymbols()
}.distinct().map { symbol ->
when (symbol) {
is KtNamedClassOrObjectSymbol -> KSClassDeclarationImpl.getCached(symbol)
is KtFunctionLikeSymbol -> KSFunctionDeclarationImpl.getCached(symbol)
is KtPropertySymbol -> KSPropertyDeclarationImpl.getCached(symbol)
is KtEnumEntrySymbol -> KSClassDeclarationEnumEntryImpl.getCached(symbol)
is KtJavaFieldSymbol -> KSPropertyDeclarationJavaImpl.getCached(symbol)
else -> throw IllegalStateException()
}
}.memoized()
}
}
internal fun KtSymbolWithMembers.getAllProperties(): Sequence<KSPropertyDeclaration> {
return analyze {
this@getAllProperties.getMemberScope().getCallableSymbols()
.filter {
it.isVisibleInClass(this@getAllProperties as KtClassOrObjectSymbol) ||
it.getContainingSymbol() == this@getAllProperties
}
.mapNotNull { callableSymbol ->
when (callableSymbol) {
is KtPropertySymbol -> KSPropertyDeclarationImpl.getCached(callableSymbol)
is KtJavaFieldSymbol -> KSPropertyDeclarationJavaImpl.getCached(callableSymbol)
else -> null
}
}
}
}
internal fun KtSymbolWithMembers.getAllFunctions(): Sequence<KSFunctionDeclaration> {
return analyze {
this@getAllFunctions.getMemberScope().let { it.getCallableSymbols() + it.getConstructors() }
.filter {
it.isVisibleInClass(this@getAllFunctions as KtClassOrObjectSymbol) ||
it.getContainingSymbol() == this@getAllFunctions
}
.mapNotNull { callableSymbol ->
// TODO: replace with single safe cast if no more implementations of KSFunctionDeclaration is added.
when (callableSymbol) {
is KtFunctionLikeSymbol -> KSFunctionDeclarationImpl.getCached(callableSymbol)
else -> null
}
}
}
}
internal fun KtAnnotated.annotations(parent: KSNode? = null): Sequence<KSAnnotation> {
return this.annotations.asSequence().map { KSAnnotationImpl.getCached(it, parent) }
}
internal fun KtSymbol.getContainingKSSymbol(): KSDeclaration? {
return analyze {
when (val containingSymbol = this@getContainingKSSymbol.getContainingSymbol()) {
is KtNamedClassOrObjectSymbol -> KSClassDeclarationImpl.getCached(containingSymbol)
is KtFunctionLikeSymbol -> KSFunctionDeclarationImpl.getCached(containingSymbol)
is KtPropertySymbol -> KSPropertyDeclarationImpl.getCached(containingSymbol)
else -> null
}
}
}
internal fun KtSymbol.toKSDeclaration(): KSDeclaration? = this.toKSNode() as? KSDeclaration
internal fun KtSymbol.toKSNode(): KSNode {
return when (this) {
is KtPropertySymbol -> KSPropertyDeclarationImpl.getCached(this)
is KtNamedClassOrObjectSymbol -> KSClassDeclarationImpl.getCached(this)
is KtFunctionLikeSymbol -> KSFunctionDeclarationImpl.getCached(this)
is KtTypeAliasSymbol -> KSTypeAliasImpl.getCached(this)
is KtJavaFieldSymbol -> KSPropertyDeclarationJavaImpl.getCached(this)
is KtFileSymbol -> KSFileImpl.getCached(this)
is KtEnumEntrySymbol -> KSClassDeclarationEnumEntryImpl.getCached(this)
is KtTypeParameterSymbol -> KSTypeParameterImpl.getCached(this)
is KtLocalVariableSymbol -> KSPropertyDeclarationLocalVariableImpl.getCached(this)
else -> throw IllegalStateException("Unexpected class for KtSymbol: ${this.javaClass}")
}
}
internal fun ClassId.toKtClassSymbol(): KtClassOrObjectSymbol? {
return analyze {
if (this@toKtClassSymbol.isLocal) {
this@toKtClassSymbol.outerClassId?.toKtClassSymbol()?.getDeclaredMemberScope()?.getClassifierSymbols {
it.asString() == this@toKtClassSymbol.shortClassName.asString()
}?.singleOrNull() as? KtClassOrObjectSymbol
} else {
getClassOrObjectSymbolByClassId(this@toKtClassSymbol)
}
}
}
internal fun KtType.classifierSymbol(): KtClassifierSymbol? {
return try {
when (this) {
is KtTypeParameterType -> this.symbol
// TODO: upstream is not exposing enough information for captured types.
is KtCapturedType -> TODO("fix in upstream")
is KtClassErrorType, is KtTypeErrorType -> null
is KtFunctionalType -> classSymbol
is KtUsualClassType -> classSymbol
is KtDefinitelyNotNullType -> original.classifierSymbol()
is KtDynamicType -> null
// flexible types have 2 bounds, using lower bound for a safer approximation.
// TODO: find a case where lower bound is not appropriate.
is KtFlexibleType -> lowerBound.classifierSymbol()
is KtIntegerLiteralType -> null
// TODO: KSP does not support intersection type.
is KtIntersectionType -> null
}
} catch (e: KotlinExceptionWithAttachments) {
// The implementation for getting symbols from a type throws an excpetion
// when it can't find the corresponding class symbol fot the given class ID.
null
}
}
internal fun KtType.typeArguments(): List<KtTypeProjection> {
return if (this is KtFlexibleType) {
this.lowerBound
} else {
this
}.let { (it as? KtNonErrorClassType)?.qualifiers?.reversed()?.flatMap { it.typeArguments } ?: emptyList() }
}
internal fun KSAnnotated.findAnnotationFromUseSiteTarget(): Sequence<KSAnnotation> {
return when (this) {
is KSPropertyGetter -> (this.receiver as? AbstractKSDeclarationImpl)?.let {
it.originalAnnotations.asSequence().filter { it.useSiteTarget == AnnotationUseSiteTarget.GET }
}
is KSPropertySetter -> (this.receiver as? AbstractKSDeclarationImpl)?.let {
it.originalAnnotations.asSequence().filter { it.useSiteTarget == AnnotationUseSiteTarget.SET }
}
is KSValueParameter -> {
var parent = this.parent
// TODO: eliminate annotationsFromParents to make this fully sequence.
val annotationsFromParents = mutableListOf<KSAnnotation>()
(parent as? KSPropertyAccessorImpl)?.let {
annotationsFromParents.addAll(
it.originalAnnotations.asSequence()
.filter { it.useSiteTarget == AnnotationUseSiteTarget.SETPARAM }
)
parent = (parent as KSPropertyAccessorImpl).receiver
}
(parent as? KSPropertyDeclarationImpl)?.let {
annotationsFromParents.addAll(
it.originalAnnotations.asSequence()
.filter { it.useSiteTarget == AnnotationUseSiteTarget.SETPARAM }
)
}
annotationsFromParents.asSequence()
}
else -> emptySequence()
} ?: emptySequence()
}
internal fun org.jetbrains.kotlin.descriptors.Visibility.toModifier(): Modifier {
return when (this) {
Visibilities.Public -> Modifier.PUBLIC
Visibilities.Private -> Modifier.PRIVATE
Visibilities.Internal -> Modifier.INTERNAL
Visibilities.Protected, JavaVisibilities.ProtectedAndPackage, JavaVisibilities.ProtectedStaticVisibility ->
Modifier.PROTECTED
else -> Modifier.PUBLIC
}
}
internal fun Modality.toModifier(): Modifier {
return when (this) {
Modality.FINAL -> Modifier.FINAL
Modality.ABSTRACT -> Modifier.ABSTRACT
Modality.OPEN -> Modifier.OPEN
Modality.SEALED -> Modifier.SEALED
}
}
internal inline fun <reified T : KSNode> KSNode.findParentOfType(): KSNode? {
var result = parent
while (!(result == null || result is T)) {
result = result.parent
}
return result
}
@OptIn(SymbolInternals::class)
internal fun KtValueParameterSymbol.getDefaultValue(): KtAnnotationValue? {
fun FirExpression.toValue(builder: KtSymbolByFirBuilder): KtAnnotationValue? {
if (this is FirAnnotation) {
return KtAnnotationApplicationValue(
KtAnnotationApplicationWithArgumentsInfo(
ClassId.fromString((annotationTypeRef.coneType as? ConeLookupTagBasedType)?.lookupTag.toString()),
null,
null,
emptyList(),
0,
null,
KtAlwaysAccessibleLifetimeToken(ResolverAAImpl.ktModule.project)
),
KtAlwaysAccessibleLifetimeToken(ResolverAAImpl.ktModule.project)
)
}
if (this is FirArrayLiteral) {
return KtArrayAnnotationValue(argumentList.arguments.mapNotNull { it.toValue(builder) }, null, token)
}
return if (this is FirGetClassCall) {
var coneType = this.getTargetType()?.fullyExpandedType(builder.rootSession)
// FirAnnotationValueConverter expects fir type, while the type parsed from libraries are modeled
// as flexible type, for it to be used in argument of KClass values, it needs to be unwrapped.
if (coneType is ConeFlexibleType) {
coneType = coneType.lowerBound
}
if (coneType is ConeClassLikeType && coneType !is ConeErrorType) {
val classId = coneType.lookupTag.classId
val type = builder.typeBuilder.buildKtType(coneType)
KtKClassAnnotationValue(type, classId, null, token)
} else {
null
}
} else {
FirAnnotationValueConverter.toConstantValue(this, builder)
}
}
return this.psi.let {
when (it) {
is KtParameter -> analyze {
it.defaultValue?.evaluateAsAnnotationValue()
}
null -> {
val fileManager = ResolverAAImpl.instance.javaFileManager
val parentClass = this.getContainingKSSymbol()!!.findParentOfType<KSClassDeclaration>()
val classId = (parentClass as KSClassDeclarationImpl).ktClassOrObjectSymbol.classIdIfNonLocal!!
val file = analyze {
(fileManager.findClass(classId, analysisScope) as JavaClassImpl).virtualFile!!.contentsToByteArray()
}
var defaultValue: JavaAnnotationArgument? = null
ClassReader(file).accept(
object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitMethod(
access: Int,
name: String?,
desc: String?,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
return if (name == this@getDefaultValue.name.asString()) {
object : MethodVisitor(Opcodes.API_VERSION) {
override fun visitAnnotationDefault(): AnnotationVisitor =
BinaryJavaAnnotationVisitor(
ClassifierResolutionContext { null },
BinaryClassSignatureParser()
) {
defaultValue = it
}
}
} else {
object : MethodVisitor(Opcodes.API_VERSION) {}
}
}
},
ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES
)
(this as? KtFirValueParameterSymbol)?.let {
val firSession = it.firSymbol.fir.moduleData.session
val symbolBuilder = it.builder
val expectedTypeRef = it.firSymbol.fir.returnTypeRef
val expression = defaultValue
?.toFirExpression(firSession, JavaTypeParameterStack.EMPTY, expectedTypeRef, null)
expression?.toValue(symbolBuilder)
}
}
else -> throw IllegalStateException("Unhandled default value type ${it.javaClass}")
}
}
}
internal fun fillInDeepSubstitutor(context: KtType, substitutorBuilder: KtSubstitutorBuilder) {
if (context !is KtNonErrorClassType) {
return
}
val parameters = context.classSymbol.typeParameters
val arguments = context.ownTypeArguments
if (parameters.size != arguments.size) {
throw IllegalStateException("invalid substitution for $context")
}
parameters.zip(arguments).forEach {
substitutorBuilder.substitution(it.first, it.second.type ?: it.first.upperBounds.first())
}
(context.classSymbol as? KtClassOrObjectSymbol)?.superTypes?.forEach {
fillInDeepSubstitutor(it, substitutorBuilder)
}
}
internal fun KtSymbol.psiIfSource(): PsiElement? {
return if (origin == KtSymbolOrigin.SOURCE || origin == KtSymbolOrigin.JAVA && toContainingFile() != null) {
psi
} else {
null
}
}
fun interface Restorable {
fun restore(): KSAnnotated?
}
fun interface Deferrable {
fun defer(): Restorable?
}
fun <T : KtSymbol> T.defer(restore: (T) -> KSAnnotated?): Restorable? {
val ptr = analyze { with(this) { this@defer.createPointer() } }
return Restorable {
analyze {
val restored = ptr.restoreSymbol() ?: return@analyze null
restore(restored as T)
}
}
}
fun ClassId.toKSName() = KSNameImpl.getCached(asSingleFqName().toString())
// Only need to map java types if type declaration has origin of java
// or kotlin functional type (in the case of Java functional type).
internal fun KtClassLikeSymbol.shouldMapToKotlinForAssignabilityCheck(): Boolean {
return this.origin == KtSymbolOrigin.JAVA ||
this.classIdIfNonLocal?.packageFqName?.asString() == "kotlin.jvm.functions"
}
// recursively replace type & type argument to map java types into kotlin types.
internal fun KtType.convertToKotlinType(): KtType {
if (this !is KtNonErrorClassType) {
return this
}
val declaration = this.classifierSymbol() as? KtClassLikeSymbol ?: return this
if (declaration.classIdIfNonLocal == null) {
return this
}
val base = if (declaration.classIdIfNonLocal != null && declaration.shouldMapToKotlinForAssignabilityCheck()) {
JavaToKotlinClassMap.mapJavaToKotlin(declaration.classIdIfNonLocal!!.asSingleFqName())?.toKtClassSymbol()
?: declaration
} else declaration
return analyze {
buildClassType(base) {
this@convertToKotlinType.typeArguments().forEach { typeProjection ->
if (typeProjection is KtTypeArgumentWithVariance) {
argument(typeProjection.type.convertToKotlinType(), typeProjection.variance)
} else {
argument(typeProjection)
}
}
nullability = this@convertToKotlinType.nullability
}
}
}
internal fun KtType.isAssignableFrom(that: KtType): Boolean {
return if (that is KtFlexibleType) {
this.isAssignableFrom(that.upperBound) || this.isAssignableFrom(that.lowerBound)
} else {
analyze {
that.convertToKotlinType().isSubTypeOf(this@isAssignableFrom.convertToKotlinType())
}
}
}
// TODO: fix flexible type creation once upstream available.
internal fun KtType.replace(newArgs: List<KtTypeProjection>): KtType? {
if (newArgs.isNotEmpty() && newArgs.size != this.typeArguments().size) {
return null
}
return analyze {
when (val symbol = classifierSymbol()) {
is KtClassLikeSymbol -> analysisSession.buildClassType(symbol) {
newArgs.forEach { arg -> argument(arg) }
}
is KtTypeParameterSymbol -> analysisSession.buildTypeParameterType(symbol)
else -> throw IllegalStateException("Unexpected type $this")
}
}
}
internal fun getVarianceForWildcard(
parameter: KtTypeParameterSymbol,
projection: KtTypeProjection,
mode: TypeMappingMode
): Variance {
val projectionKind = if (projection is KtTypeArgumentWithVariance) {
projection.variance
} else {
Variance.INVARIANT
}
val parameterVariance = parameter.variance
if (parameterVariance == Variance.INVARIANT) {
return projectionKind
}
if (mode.skipDeclarationSiteWildcards) {
return Variance.INVARIANT
}
if (projectionKind == Variance.INVARIANT || projectionKind == parameterVariance) {
if (mode.skipDeclarationSiteWildcardsIfPossible && projection !is KtStarTypeProjection) {
val coneType = (projection.type as KtFirType).coneType
// TODO: fix most precise covariant argument case.
if (parameterVariance == Variance.OUT_VARIANCE) {
return Variance.INVARIANT
}
if (parameterVariance == Variance.IN_VARIANCE && coneType.isAny) {
return Variance.INVARIANT
}
}
return parameterVariance
}
return Variance.OUT_VARIANCE
}
internal fun KtType.toWildcard(mode: TypeMappingMode): KtType {
val parameters = this.classifierSymbol()?.typeParameters ?: emptyList()
val args = this.typeArguments()
return analyze {
when (this@toWildcard) {
is KtClassType -> {
// TODO: missing annotations from original type.
buildClassType(this@toWildcard.expandedClassSymbol!!) {
parameters.zip(args).map { (param, arg) ->
val argMode = mode.updateFromAnnotations(arg.type)
val variance = getVarianceForWildcard(param, arg, argMode)
val genericMode = argMode.toGenericArgumentMode(
getEffectiveVariance(
param.variance,
(arg as? KtTypeArgumentWithVariance)?.variance ?: Variance.INVARIANT
)
)
val argType =
arg.type ?: analysisSession.builtinTypes.ANY.withNullability(KtTypeNullability.NULLABLE)
argument(argType.toWildcard(genericMode), variance)
}
nullability = this@toWildcard.nullability
}
}
is KtTypeParameterType -> {
buildTypeParameterType(this@toWildcard.symbol)
}
else -> throw IllegalStateException("Unexpected type ${this@toWildcard}")
}
}
}
internal fun TypeMappingMode.suppressJvmWildcards(
suppress: Boolean
): TypeMappingMode {
return TypeMappingMode.createWithConstantDeclarationSiteWildcardsMode(
skipDeclarationSiteWildcards = suppress,
isForAnnotationParameter = isForAnnotationParameter,
needInlineClassWrapping = needInlineClassWrapping,
mapTypeAliases = mapTypeAliases
)
}
internal fun TypeMappingMode.updateFromParents(
ref: KSTypeReference
): TypeMappingMode {
return ref.findJvmSuppressWildcards()?.let {
this.suppressJvmWildcards(it)
} ?: this
}
internal fun KSTypeReference.findJvmSuppressWildcards(): Boolean? {
var candidate: KSNode? = this
while (candidate != null) {
if ((candidate is KSTypeReference || candidate is KSDeclaration)) {
(candidate as KSAnnotated).annotations.singleOrNull {
it.annotationType.resolve().declaration.qualifiedName?.asString()?.equals(
JVM_SUPPRESS_WILDCARDS_ANNOTATION_FQ_NAME.asString()
) == true
}?.let { it.arguments.singleOrNull { it.name?.asString() == "suppress" } }?.let {
return it.value as? Boolean
}
}
candidate = candidate.parent
}
return null
}
internal fun TypeMappingMode.updateFromAnnotations(
type: KtType?
): TypeMappingMode {
if (type == null) {
return this
}
type.annotations().firstOrNull {
it.annotationType.resolve().declaration.qualifiedName?.asString()
?.equals(JVM_SUPPRESS_WILDCARDS_ANNOTATION_FQ_NAME.asString()) == true
}?.let {
it.arguments.firstOrNull { it.name?.asString() == "suppress" }?.let {
(it.value as? Boolean)?.let { return suppressJvmWildcards(it) } ?: return this
}
}
return if (type.annotations().any {
it.annotationType.resolve().declaration.qualifiedName?.asString()
?.equals(JVM_WILDCARD_ANNOTATION_FQ_NAME.asString()) == true
}
) {
TypeMappingMode.createWithConstantDeclarationSiteWildcardsMode(
skipDeclarationSiteWildcards = false,
isForAnnotationParameter = isForAnnotationParameter,
fallbackMode = this,
needInlineClassWrapping = needInlineClassWrapping,
mapTypeAliases = mapTypeAliases
)
} else {
this
}
}