forked from google/ksp
/
ResolverImpl.kt
1562 lines (1427 loc) · 72.5 KB
/
ResolverImpl.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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 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.
*/
package com.google.devtools.ksp.processing.impl
import com.google.devtools.ksp.*
import com.google.devtools.ksp.processing.KSBuiltIns
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.Variance
import com.google.devtools.ksp.symbol.impl.binary.*
import com.google.devtools.ksp.symbol.impl.declarationsInSourceOrder
import com.google.devtools.ksp.symbol.impl.findParentAnnotated
import com.google.devtools.ksp.symbol.impl.getInstanceForCurrentRound
import com.google.devtools.ksp.symbol.impl.java.*
import com.google.devtools.ksp.symbol.impl.jvmAccessFlag
import com.google.devtools.ksp.symbol.impl.kotlin.*
import com.google.devtools.ksp.symbol.impl.resolveContainingClass
import com.google.devtools.ksp.symbol.impl.synthetic.*
import com.google.devtools.ksp.visitor.CollectAnnotatedSymbolsVisitor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.codegen.ClassBuilderMode
import org.jetbrains.kotlin.codegen.OwnerKind
import org.jetbrains.kotlin.codegen.state.JVM_SUPPRESS_WILDCARDS_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.codegen.state.JVM_WILDCARD_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.container.tryGetService
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.descriptors.JavaForKotlinOverridePropertyDescriptor
import org.jetbrains.kotlin.load.java.lazy.JavaResolverComponents
import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext
import org.jetbrains.kotlin.load.java.lazy.ModuleClassResolver
import org.jetbrains.kotlin.load.java.lazy.TypeParameterResolver
import org.jetbrains.kotlin.load.java.lazy.childForClassOrPackage
import org.jetbrains.kotlin.load.java.lazy.childForMethod
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaTypeParameterDescriptor
import org.jetbrains.kotlin.load.java.lazy.types.JavaTypeResolver
import org.jetbrains.kotlin.load.java.lazy.types.toAttributes
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.load.java.structure.JavaClassifierType
import org.jetbrains.kotlin.load.java.structure.classId
import org.jetbrains.kotlin.load.java.structure.impl.JavaArrayTypeImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaConstructorImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaFieldImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaMethodImpl
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.classFiles.BinaryJavaClass
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaMethod
import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaMethodBase
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass
import org.jetbrains.kotlin.load.kotlin.getContainingKotlinJvmBinaryClass
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.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.annotations.argumentValue
import org.jetbrains.kotlin.resolve.calls.inference.components.NewTypeSubstitutor
import org.jetbrains.kotlin.resolve.calls.inference.components.composeWith
import org.jetbrains.kotlin.resolve.calls.inference.substitute
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.constants.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperClassifiers
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.descriptorUtil.propertyIfAccessor
import org.jetbrains.kotlin.resolve.lazy.DeclarationScopeProvider
import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.multiplatform.findActuals
import org.jetbrains.kotlin.resolve.multiplatform.findExpects
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.SimpleClassicTypeSystemContext
import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections
import org.jetbrains.kotlin.types.typeUtil.substitute
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.util.containingNonLocalDeclaration
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
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
import org.jetbrains.org.objectweb.asm.Opcodes.API_VERSION
import java.io.File
import java.util.Stack
class ResolverImpl(
val module: ModuleDescriptor,
val allKSFiles: Collection<KSFile>,
val newKSFiles: Collection<KSFile>,
private val deferredSymbols: Map<SymbolProcessor, List<KSAnnotated>>,
val bindingTrace: BindingTrace,
val project: Project,
componentProvider: ComponentProvider,
val incrementalContext: IncrementalContext,
val options: KspOptions,
) : Resolver {
val psiDocumentManager = PsiDocumentManager.getInstance(project)
private val nameToKSMap: MutableMap<KSName, KSClassDeclaration>
/**
* Checking as member of is an expensive operation, hence we cache result values in this map.
*/
private val functionAsMemberOfCache: MutableMap<Pair<KSFunctionDeclaration, KSType>, KSFunction>
private val propertyAsMemberOfCache: MutableMap<Pair<KSPropertyDeclaration, KSType>, KSType>
private val typeMapper = KotlinTypeMapper(
BindingContext.EMPTY, ClassBuilderMode.LIGHT_CLASSES,
module.name.getNonSpecialIdentifier(),
KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT, // TODO use proper LanguageVersionSettings
true
)
private val qualifiedExpressionResolver = QualifiedExpressionResolver(LanguageVersionSettingsImpl.DEFAULT)
private val aliasingFqNs: MutableMap<String, KSTypeAlias> = mutableMapOf()
private val aliasingNames: MutableSet<String> = mutableSetOf()
private val topDownAnalysisContext by lazy {
TopDownAnalysisContext(TopDownAnalysisMode.TopLevelDeclarations, DataFlowInfo.EMPTY, declarationScopeProvider)
}
companion object {
lateinit var resolveSession: ResolveSession
lateinit var bodyResolver: BodyResolver
lateinit var constantExpressionEvaluator: ConstantExpressionEvaluator
lateinit var declarationScopeProvider: DeclarationScopeProvider
lateinit var topDownAnalyzer: LazyTopDownAnalyzer
lateinit var instance: ResolverImpl
lateinit var annotationResolver: AnnotationResolver
lateinit var moduleClassResolver: ModuleClassResolver
lateinit var javaTypeResolver: JavaTypeResolver
lateinit var lazyJavaResolverContext: LazyJavaResolverContext
lateinit var doubleColonExpressionResolver: DoubleColonExpressionResolver
}
init {
resolveSession = componentProvider.get()
bodyResolver = componentProvider.get()
declarationScopeProvider = componentProvider.get()
topDownAnalyzer = componentProvider.get()
constantExpressionEvaluator = componentProvider.get()
doubleColonExpressionResolver = componentProvider.get()
annotationResolver = resolveSession.annotationResolver
componentProvider.tryGetService(JavaResolverComponents::class.java)?.let {
lazyJavaResolverContext = LazyJavaResolverContext(it, TypeParameterResolver.EMPTY) { null }
javaTypeResolver = lazyJavaResolverContext.typeResolver
moduleClassResolver = lazyJavaResolverContext.components.moduleClassResolver
}
instance = this
nameToKSMap = mutableMapOf()
functionAsMemberOfCache = mutableMapOf()
propertyAsMemberOfCache = mutableMapOf()
val visitor = object : KSVisitorVoid() {
override fun visitFile(file: KSFile, data: Unit) {
file.declarations.forEach { it.accept(this, data) }
// TODO: evaluate with benchmarks: cost of getContainingFile v.s. name collision
// Import aliases are file-scoped. `aliasingNamesByFile` could be faster
file.safeAs<KSFileImpl>()?.file?.importDirectives?.forEach {
it.aliasName?.let { aliasingNames.add(it) }
}
}
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val qualifiedName = classDeclaration.qualifiedName
if (qualifiedName != null) {
nameToKSMap[qualifiedName] = classDeclaration
}
classDeclaration.declarations.forEach { it.accept(this, data) }
}
override fun visitTypeAlias(typeAlias: KSTypeAlias, data: Unit) {
typeAlias.qualifiedName?.asString()?.let { fqn ->
aliasingFqNs[fqn] = typeAlias
aliasingNames.add(fqn.substringAfterLast('.'))
}
}
}
// FIXME: reuse results from previous rounds and only loop through newKSFiles.
allKSFiles.forEach { it.accept(visitor, Unit) }
}
override fun getNewFiles(): Sequence<KSFile> {
return newKSFiles.asSequence()
}
override fun getAllFiles(): Sequence<KSFile> {
return allKSFiles.asSequence()
}
override fun getClassDeclarationByName(name: KSName): KSClassDeclaration? {
nameToKSMap[name]?.let { return it }
return module.resolveClassByFqName(FqName(name.asString()), NoLookupLocation.WHEN_FIND_BY_FQNAME)
?.let {
val psi = it.findPsi()
if (psi != null) {
when (psi) {
is KtClassOrObject -> KSClassDeclarationImpl.getCached(psi)
is PsiClass -> KSClassDeclarationJavaImpl.getCached(psi)
else -> throw IllegalStateException("unexpected psi: ${psi.javaClass}")
}
} else {
KSClassDeclarationDescriptorImpl.getCached(it)
}
}
}
override fun getFunctionDeclarationsByName(
name: KSName,
includeTopLevel: Boolean,
): Sequence<KSFunctionDeclaration> {
val qualifier = name.getQualifier()
val functionName = name.getShortName()
val nonTopLevelResult = this.getClassDeclarationByName(qualifier)?.getDeclaredFunctions()
?.filter { it.simpleName.asString() == functionName }?.asSequence() ?: emptySequence()
return if (!includeTopLevel) nonTopLevelResult else {
nonTopLevelResult.plus(
module.getPackage(FqName(qualifier))
.memberScope.getContributedDescriptors(DescriptorKindFilter.FUNCTIONS) {
it.asString() == functionName
}
.filterIsInstance<MemberDescriptor>().mapNotNull { it.toKSDeclaration() as? KSFunctionDeclaration }
)
}
}
override fun getPropertyDeclarationByName(name: KSName, includeTopLevel: Boolean): KSPropertyDeclaration? {
val qualifier = name.getQualifier()
val propertyName = name.getShortName()
val nonTopLevelResult = this.getClassDeclarationByName(qualifier)?.getDeclaredProperties()
?.singleOrNull { it.simpleName.asString() == propertyName }
return if (!includeTopLevel) nonTopLevelResult else {
val topLevelResult = (
module.getPackage(FqName(qualifier))
.memberScope.getContributedDescriptors(DescriptorKindFilter.VARIABLES) {
it.asString() == propertyName
}
.also {
if (it.size > 1) {
throw IllegalStateException("Found multiple properties with same qualified name")
}
}
.singleOrNull() as? MemberDescriptor
)?.toKSDeclaration() as? KSPropertyDeclaration
if (topLevelResult != null && nonTopLevelResult != null) {
throw IllegalStateException("Found multiple properties with same qualified name")
}
nonTopLevelResult ?: topLevelResult
}
}
internal fun checkAnnotation(annotation: KSAnnotation, ksName: KSName, shortName: String): Boolean {
val annotationType = annotation.annotationType
val referencedName = (annotationType.element as? KSClassifierReference)?.referencedName()
val simpleName = referencedName?.substringAfterLast('.')
return (simpleName == shortName || simpleName in aliasingNames) &&
annotationType.resolveToUnderlying().declaration.qualifiedName == ksName
}
override fun getSymbolsWithAnnotation(annotationName: String, inDepth: Boolean): Sequence<KSAnnotated> {
// If annotationName is a typealias, resolve to underlying type.
val realAnnotationName =
aliasingFqNs[annotationName]?.type?.resolveToUnderlying()?.declaration?.qualifiedName?.asString()
?: annotationName
val ksName = KSNameImpl.getCached(realAnnotationName)
val shortName = ksName.getShortName()
fun checkAnnotated(annotated: KSAnnotated): Boolean {
return annotated.annotations.any {
checkAnnotation(it, ksName, shortName)
}
}
val allAnnotated = if (inDepth) newAnnotatedSymbolsWithLocals else newAnnotatedSymbols
return allAnnotated.asSequence().filter(::checkAnnotated)
}
private fun collectAnnotatedSymbols(inDepth: Boolean): Collection<KSAnnotated> {
val visitor = CollectAnnotatedSymbolsVisitor(inDepth)
for (file in newKSFiles) {
file.accept(visitor, Unit)
}
return visitor.symbols
}
private val deferredSymbolsUpdated: Collection<KSAnnotated> by lazy {
deferredSymbols.values.flatten().mapNotNull { it.getInstanceForCurrentRound() }
}
private val newAnnotatedSymbols: Collection<KSAnnotated> by lazy {
collectAnnotatedSymbols(false) + deferredSymbolsUpdated
}
private val newAnnotatedSymbolsWithLocals: Collection<KSAnnotated> by lazy {
collectAnnotatedSymbols(true) + deferredSymbolsUpdated
}
override fun getKSNameFromString(name: String): KSName {
return KSNameImpl.getCached(name)
}
override fun createKSTypeReferenceFromKSType(type: KSType): KSTypeReference {
return KSTypeReferenceSyntheticImpl.getCached(type, null)
}
@KspExperimental
override fun mapToJvmSignature(declaration: KSDeclaration): String? = mapToJvmSignatureInternal(declaration)
internal fun mapToJvmSignatureInternal(declaration: KSDeclaration): String? = when (declaration) {
is KSClassDeclaration -> resolveClassDeclaration(declaration)?.let { typeMapper.mapType(it).descriptor }
is KSFunctionDeclaration -> resolveFunctionDeclaration(declaration)?.let {
when (it) {
is FunctionDescriptor -> typeMapper.mapAsmMethod(it).descriptor
is PropertyDescriptor -> typeMapper.mapFieldSignature(it.type, it) ?: typeMapper.mapType(it).descriptor
else -> throw IllegalStateException("Unexpected descriptor type for declaration: $declaration")
}
}
is KSPropertyDeclaration -> resolvePropertyDeclaration(declaration)?.let {
typeMapper.mapFieldSignature(it.type, it) ?: typeMapper.mapType(it).descriptor
}
else -> null
}
override fun overrides(overrider: KSDeclaration, overridee: KSDeclaration): Boolean {
fun resolveForOverride(declaration: KSDeclaration): DeclarationDescriptor? {
return when (declaration) {
is KSPropertyDeclaration -> resolvePropertyDeclaration(declaration)
is KSFunctionDeclarationJavaImpl -> resolveJavaDeclaration(declaration.psi)
is KSFunctionDeclaration -> resolveFunctionDeclaration(declaration)
else -> null
}
}
if (!overridee.isOpen())
return false
if (!overridee.isVisibleFrom(overrider))
return false
if (!(
overridee is KSFunctionDeclaration || overrider is KSFunctionDeclaration ||
(overridee is KSPropertyDeclaration && overrider is KSPropertyDeclaration)
)
)
return false
if (overrider is KSPropertyDeclarationJavaImpl)
return false
val superDescriptor = resolveForOverride(overridee) as? CallableMemberDescriptor ?: return false
val subDescriptor = resolveForOverride(overrider) as? CallableMemberDescriptor ?: return false
val subClassDescriptor = overrider.closestClassDeclaration()?.let {
resolveClassDeclaration(it)
} ?: return false
val superClassDescriptor = overridee.closestClassDeclaration()?.let {
resolveClassDeclaration(it)
} ?: return false
incrementalContext.recordLookupWithSupertypes(subClassDescriptor.defaultType)
val typeOverride = subClassDescriptor.getAllSuperClassifiers()
.filter { it != subClassDescriptor } // exclude subclass itself as it cannot override its own methods
.any {
it == superClassDescriptor
}
if (!typeOverride) return false
incrementalContext.recordLookupForDeclaration(overrider)
incrementalContext.recordLookupForDeclaration(overridee)
return OverridingUtil.overrides(subDescriptor, superDescriptor, true, true)
}
// check if the candidate is overridden from the original declaration.
private fun isOriginal(original: KSDeclaration, candidate: KSDeclaration): Boolean {
incrementalContext.recordLookupForDeclaration(original)
incrementalContext.recordLookupForDeclaration(candidate)
val originalDescriptor = when (original) {
is KSPropertyDeclaration -> resolvePropertyDeclaration(original)
is KSFunctionDeclaration ->
resolveFunctionDeclaration(original).safeAs<FunctionDescriptor>()?.propertyIfAccessor
else -> return false
}
val candidateDescriptors = when (candidate) {
is KSPropertyDeclaration -> resolvePropertyDeclaration(candidate)?.overriddenDescriptors
is KSFunctionDeclaration -> resolveFunctionDeclaration(candidate)?.overriddenDescriptors
else -> return false
}
return candidateDescriptors?.any { it == originalDescriptor } ?: false
}
override fun overrides(
overrider: KSDeclaration,
overridee: KSDeclaration,
containingClass: KSClassDeclaration
): Boolean {
incrementalContext.recordLookupForDeclaration(containingClass)
return when (overrider) {
is KSPropertyDeclaration -> containingClass.getAllProperties().singleOrNull {
it.simpleName.asString() == overrider.simpleName.asString() && isOriginal(overrider, it)
}?.let { overrides(it, overridee) } ?: false
is KSFunctionDeclaration -> {
val candidates = containingClass.getAllFunctions().filter {
it.simpleName.asString() == overridee.simpleName.asString()
}
if (overrider.simpleName.asString().startsWith("get") ||
overrider.simpleName.asString().startsWith("set")
) {
candidates.plus(
containingClass.getAllProperties().filter {
val overriderName = overrider.simpleName.asString().substring(3)
.replaceFirstChar { it.lowercase() }
it.simpleName.asString() == overriderName ||
it.simpleName.asString().replaceFirstChar { it.lowercase() } == overriderName
}
// TODO: It is currently not possible to do the overridden descriptor optimization for java overrides.
).any { overrides(it, overridee) }
} else {
candidates.singleOrNull { isOriginal(overrider, it) }?.let { overrides(it, overridee) } ?: false
}
}
else -> false
}
}
fun evaluateConstant(expression: KtExpression?, expectedType: KotlinType): ConstantValue<*>? {
return expression?.let {
if (it is KtClassLiteralExpression && it.receiverExpression != null) {
val parent = KtStubbedPsiUtil.getPsiOrStubParent(it, KtPrimaryConstructor::class.java, false)
val scope = resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(parent!!)
val result = qualifiedExpressionResolver
.resolveDescriptorForDoubleColonLHS(it.receiverExpression!!, scope, bindingTrace, false)
val classifier = result.classifierDescriptor ?: return null
val typeResolutionContext = TypeResolutionContext(scope, bindingTrace, true, true, false)
val possiblyBareType = resolveSession.typeResolver
.resolveTypeForClassifier(typeResolutionContext, classifier, result, it, Annotations.EMPTY)
var actualType = if (possiblyBareType.isBare)
possiblyBareType.bareTypeConstructor.declarationDescriptor!!.defaultType
else possiblyBareType.actualType
var arrayDimension = 0
while (KotlinBuiltIns.isArray(actualType)) {
actualType = actualType.arguments.single().type
arrayDimension += 1
}
KClassValue(actualType.constructor.declarationDescriptor.classId!!, arrayDimension)
} else {
constantExpressionEvaluator.evaluateExpression(it, bindingTrace)?.toConstantValue(expectedType) ?: run {
val parent = KtStubbedPsiUtil
.getPsiOrStubParent(expression, KtPrimaryConstructor::class.java, false)
val scope = resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(parent!!)
qualifiedExpressionResolver
.resolvePackageHeader(expression.containingKtFile.packageDirective!!, module, bindingTrace)
bodyResolver.resolveConstructorParameterDefaultValues(
topDownAnalysisContext.outerDataFlowInfo, bindingTrace,
parent, (scope.ownerDescriptor as ClassDescriptor).constructors.first(), scope,
resolveSession.inferenceSession
)
constantExpressionEvaluator.evaluateExpression(it, bindingTrace)?.toConstantValue(expectedType)
}
}
}
}
fun resolveDeclaration(declaration: KtDeclaration): DeclarationDescriptor? {
return if (KtPsiUtil.isLocal(declaration)) {
resolveDeclarationForLocal(declaration)
bindingTrace.bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration)
} else {
resolveSession.resolveToDescriptor(declaration)
}
}
// TODO: Resolve Java variables is not supported by this function. Not needed currently.
fun resolveJavaDeclaration(psi: PsiElement): DeclarationDescriptor? {
return when (psi) {
is PsiClass -> moduleClassResolver.resolveClass(JavaClassImpl(psi))
is PsiMethod -> {
// TODO: get rid of hardcoded check if possible.
val property = if (psi.name.startsWith("set") || psi.name.startsWith("get")) {
moduleClassResolver
.resolveContainingClass(psi)
?.findEnclosedDescriptor(
kindFilter = DescriptorKindFilter.CALLABLES
) {
(it as? PropertyDescriptor)?.getter?.findPsi() == psi ||
(it as? PropertyDescriptor)?.setter?.findPsi() == psi
}
} else null
property ?: moduleClassResolver
.resolveContainingClass(psi)?.let { containingClass ->
val filter = if (psi is SyntheticElement) {
{ declaration: DeclarationDescriptor -> declaration.name.asString() == psi.name }
} else {
{ declaration: DeclarationDescriptor -> declaration.findPsi() == psi }
}
containingClass.findEnclosedDescriptor(
kindFilter = DescriptorKindFilter.FUNCTIONS,
filter = filter
)
}
}
is PsiField -> {
moduleClassResolver
.resolveClass(JavaFieldImpl(psi).containingClass)
?.findEnclosedDescriptor(
kindFilter = DescriptorKindFilter.VARIABLES,
filter = { it.findPsi() == psi }
)
}
else -> throw IllegalStateException("unhandled psi element kind: ${psi.javaClass}")
}
}
fun resolveClassDeclaration(classDeclaration: KSClassDeclaration): ClassDescriptor? {
return when (classDeclaration) {
is KSClassDeclarationImpl -> resolveDeclaration(classDeclaration.ktClassOrObject)
is KSClassDeclarationDescriptorImpl -> classDeclaration.descriptor
is KSClassDeclarationJavaImpl -> resolveJavaDeclaration(classDeclaration.psi)
else -> throw IllegalStateException("unexpected class: ${classDeclaration.javaClass}")
} as ClassDescriptor?
}
fun resolveFunctionDeclaration(function: KSFunctionDeclaration): CallableDescriptor? {
return when (function) {
is KSFunctionDeclarationImpl -> resolveDeclaration(function.ktFunction)
is KSFunctionDeclarationDescriptorImpl -> function.descriptor
is KSFunctionDeclarationJavaImpl -> {
val descriptor = resolveJavaDeclaration(function.psi)
if (descriptor is JavaForKotlinOverridePropertyDescriptor) {
if (function.simpleName.asString().startsWith("set")) {
descriptor.setter
} else {
descriptor.getter
}
} else {
descriptor
}
}
is KSConstructorSyntheticImpl -> {
// we might create synthetic constructor when it is not declared in code
// it is either for kotlin, where we can use primary constructor, or for java
// where we can use the only available constructor
val resolved = resolveClassDeclaration(function.ksClassDeclaration)
resolved?.unsubstitutedPrimaryConstructor ?: resolved?.constructors?.singleOrNull()
}
else -> throw IllegalStateException("unexpected class: ${function.javaClass}")
} as? CallableDescriptor
}
fun resolvePropertyDeclaration(property: KSPropertyDeclaration): PropertyDescriptor? {
return when (property) {
is KSPropertyDeclarationImpl -> resolveDeclaration(property.ktProperty)
is KSPropertyDeclarationParameterImpl -> resolveDeclaration(property.ktParameter)
is KSPropertyDeclarationDescriptorImpl -> property.descriptor
is KSPropertyDeclarationJavaImpl -> resolveJavaDeclaration(property.psi)
else -> throw IllegalStateException("unexpected class: ${property.javaClass}")
} as PropertyDescriptor?
}
fun resolvePropertyAccessorDeclaration(accessor: KSPropertyAccessor): PropertyAccessorDescriptor? {
return when (accessor) {
is KSPropertyAccessorDescriptorImpl -> accessor.descriptor
is KSPropertyAccessorImpl -> resolveDeclaration(accessor.ktPropertyAccessor)
is KSPropertySetterSyntheticImpl -> resolvePropertyDeclaration(accessor.receiver)?.setter
is KSPropertyGetterSyntheticImpl -> resolvePropertyDeclaration(accessor.receiver)?.getter
else -> throw IllegalStateException("unexpected class: ${accessor.javaClass}")
} as PropertyAccessorDescriptor?
}
fun resolveJavaType(psi: PsiType, parentTypeReference: KSTypeReference? = null): KotlinType {
incrementalContext.recordLookup(psi)
val javaType = JavaTypeImpl.create(psi)
var parent: KSNode? = parentTypeReference
val stack = Stack<KSNode>()
while (parent != null) {
if (parent is KSFunctionDeclarationJavaImpl || parent is KSClassDeclarationJavaImpl) {
stack.push(parent)
}
parent = parent.parent
}
// Construct resolver context for the PsiType
var resolverContext = lazyJavaResolverContext
// TODO: fix in compiler.
// Temporary work around for https://github.com/google/ksp/issues/1034
// Force resolve outer most class for Java nested classes.
javaType.safeAs<JavaClassifierType>()?.classifier.safeAs<JavaClass>()?.let {
var outerMost = it.outerClass
while (outerMost?.outerClass != null) {
outerMost = outerMost.outerClass
}
outerMost?.classId?.let { lazyJavaResolverContext.components.finder.findClass(it) }
}
for (e in stack) {
when (e) {
is KSFunctionDeclarationJavaImpl -> {
// Non-physical methods have no interesting scope and may have no containing class
if (!e.psi.isPhysical || e.psi.containingClass == null)
continue
resolverContext = resolverContext
.childForMethod(
resolveJavaDeclaration(e.psi)!!,
if (e.psi.isConstructor) JavaConstructorImpl(e.psi) else JavaMethodImpl(e.psi)
)
}
is KSClassDeclarationJavaImpl -> {
resolverContext = resolverContext
.childForClassOrPackage(resolveJavaDeclaration(e.psi) as ClassDescriptor, JavaClassImpl(e.psi))
}
}
}
return if (javaType is JavaArrayTypeImpl)
resolverContext
.typeResolver.transformArrayType(javaType, TypeUsage.COMMON.toAttributes(), psi is PsiEllipsisType)
else
resolverContext.typeResolver.transformJavaType(javaType, TypeUsage.COMMON.toAttributes())
}
fun KotlinType.expandNonRecursively(): KotlinType =
(constructor.declarationDescriptor as? TypeAliasDescriptor)?.expandedType?.withAbbreviation(this as SimpleType)
?: this
fun TypeProjection.expand(): TypeProjection {
val expandedType = type.expand()
return if (expandedType == type) this else substitute { expandedType }
}
// TODO: Is this the most efficient way?
fun KotlinType.expand(): KotlinType =
replace(arguments.map { it.expand() }).expandNonRecursively()
fun KtTypeReference.lookup(): KotlinType? =
bindingTrace.get(BindingContext.ABBREVIATED_TYPE, this)?.expand() ?: bindingTrace.get(BindingContext.TYPE, this)
fun resolveUserType(type: KSTypeReference): KSType {
when (type) {
is KSTypeReferenceImpl -> {
val typeReference = type.ktTypeReference
typeReference.lookup()?.let {
return getKSTypeCached(it, type.element.typeArguments, type.annotations)
}
KtStubbedPsiUtil.getContainingDeclaration(typeReference)?.let { containingDeclaration ->
resolveDeclaration(containingDeclaration)?.let {
// TODO: only resolve relevant branch.
ForceResolveUtil.forceResolveAllContents(it)
}
// TODO: Fix resolution look up to avoid fallback to file scope.
typeReference.lookup()?.let {
return getKSTypeCached(it, type.element.typeArguments, type.annotations)
}
}
val scope = resolveSession.fileScopeProvider.getFileResolutionScope(typeReference.containingKtFile)
return resolveSession.typeResolver.resolveType(scope, typeReference, bindingTrace, false).let {
getKSTypeCached(it, type.element.typeArguments, type.annotations)
}
}
is KSTypeReferenceDescriptorImpl -> {
return getKSTypeCached(type.kotlinType)
}
is KSTypeReferenceJavaImpl -> {
val psi = (type.psi as? PsiClassReferenceType)?.resolve()
if (psi is PsiTypeParameter) {
(type.psi as PsiClassReferenceType).typeArguments().forEach {
if (it is PsiType) {
incrementalContext.recordLookup(it)
}
}
val containingDeclaration = if (psi.owner is PsiClass) {
moduleClassResolver.resolveClass(JavaClassImpl(psi.owner as PsiClass))
} else {
val owner = psi.owner
check(owner is PsiMethod) {
"unexpected owner type: $owner / ${owner?.javaClass}"
}
moduleClassResolver.resolveContainingClass(owner)
?.findEnclosedDescriptor(
kindFilter = DescriptorKindFilter.FUNCTIONS,
filter = { it.findPsi() == owner }
) as FunctionDescriptor
} as DeclarationDescriptor
return getKSTypeCached(
LazyJavaTypeParameterDescriptor(
lazyJavaResolverContext,
JavaTypeParameterImpl(psi),
psi.index,
containingDeclaration
).defaultType
)
} else {
return getKSTypeCached(
resolveJavaType(type.psi, type),
type.element.typeArguments, type.annotations
)
}
}
else -> throw IllegalStateException("Unable to resolve type for $type, $ExceptionMessage")
}
}
fun findDeclaration(kotlinType: KotlinType): KSDeclaration {
val descriptor = kotlinType.constructor.declarationDescriptor
val psi = descriptor?.findPsi()
return if (psi != null && psi !is KtTypeParameter) {
when (psi) {
is KtClassOrObject -> KSClassDeclarationImpl.getCached(psi)
is PsiClass -> KSClassDeclarationJavaImpl.getCached(psi)
is KtTypeAlias -> KSTypeAliasImpl.getCached(psi)
is PsiEnumConstant -> KSClassDeclarationJavaEnumEntryImpl.getCached(psi)
else -> throw IllegalStateException("Unexpected psi type: ${psi.javaClass}, $ExceptionMessage")
}
} else {
when (descriptor) {
is ClassDescriptor -> KSClassDeclarationDescriptorImpl.getCached(descriptor)
is TypeParameterDescriptor -> KSTypeParameterDescriptorImpl.getCached(descriptor)
is TypeAliasDescriptor -> KSTypeAliasDescriptorImpl.getCached(descriptor)
null -> throw IllegalStateException("Failed to resolve descriptor for $kotlinType")
else -> throw IllegalStateException(
"Unexpected descriptor type: ${descriptor.javaClass}, $ExceptionMessage"
)
}
}
}
// Finds closest non-local scope.
fun KtElement.findLexicalScope(): LexicalScope {
return containingNonLocalDeclaration()?.let {
resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(it)
} ?: resolveSession.fileScopeProvider.getFileResolutionScope(this.containingKtFile)
}
fun resolveAnnotationEntry(ktAnnotationEntry: KtAnnotationEntry): AnnotationDescriptor? {
bindingTrace.get(BindingContext.ANNOTATION, ktAnnotationEntry)?.let { return it }
KtStubbedPsiUtil.getContainingDeclaration(ktAnnotationEntry)?.let { containingDeclaration ->
if (KtPsiUtil.isLocal(containingDeclaration)) {
resolveDeclarationForLocal(containingDeclaration)
} else {
resolveSession.resolveToDescriptor(containingDeclaration).annotations.forEach {}
}
} ?: ktAnnotationEntry.containingKtFile.let {
resolveSession.getFileAnnotations(it).forEach {}
}
return bindingTrace.get(BindingContext.ANNOTATION, ktAnnotationEntry)
}
fun resolveDeclarationForLocal(localDeclaration: KtDeclaration) {
var declaration = KtStubbedPsiUtil.getContainingDeclaration(localDeclaration) ?: return
while (KtPsiUtil.isLocal(declaration))
declaration = KtStubbedPsiUtil.getContainingDeclaration(declaration)!!
val containingFD = resolveSession.resolveToDescriptor(declaration).also {
ForceResolveUtil.forceResolveAllContents(it)
}
if (declaration is KtNamedFunction) {
val dataFlowInfo = DataFlowInfo.EMPTY
val scope = resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(declaration)
bodyResolver.resolveFunctionBody(
dataFlowInfo,
bindingTrace,
declaration,
containingFD as FunctionDescriptor,
scope,
null
)
}
}
@KspExperimental
override fun getJvmName(accessor: KSPropertyAccessor): String? {
val descriptor = resolvePropertyAccessorDeclaration(accessor)
return descriptor?.let {
// KotlinTypeMapper.mapSignature always uses OwnerKind.IMPLEMENTATION
typeMapper.mapFunctionName(descriptor, OwnerKind.IMPLEMENTATION)
}
}
@KspExperimental
override fun getJvmName(declaration: KSFunctionDeclaration): String? {
// function names might be mangled if they receive inline class parameters or they are internal
val descriptor = resolveFunctionDeclaration(declaration)
return descriptor.safeAs<FunctionDescriptor>()?.let {
// KotlinTypeMapper.mapSignature always uses OwnerKind.IMPLEMENTATION
typeMapper.mapFunctionName(it, OwnerKind.IMPLEMENTATION)
}
}
@KspExperimental
override fun getOwnerJvmClassName(declaration: KSPropertyDeclaration): String? {
val descriptor = resolvePropertyDeclaration(declaration) ?: return null
return getJvmOwnerQualifiedName(descriptor)
}
@KspExperimental
override fun getOwnerJvmClassName(declaration: KSFunctionDeclaration): String? {
val descriptor = resolveFunctionDeclaration(declaration) ?: return null
return getJvmOwnerQualifiedName(descriptor)
}
private fun getJvmOwnerQualifiedName(descriptor: DeclarationDescriptor): String? {
return try {
typeMapper.mapImplementationOwner(descriptor).className
} catch (unsupported: UnsupportedOperationException) {
null
}
}
private fun extractThrowsFromClassFile(
virtualFileContent: ByteArray,
jvmDesc: String?,
simpleName: String?
): Sequence<KSType> {
val exceptionNames = mutableListOf<String>()
ClassReader(virtualFileContent).accept(
object : ClassVisitor(API_VERSION) {
override fun visitMethod(
access: Int,
name: String?,
descriptor: String?,
signature: String?,
exceptions: Array<out String>?,
): MethodVisitor {
if (name == simpleName && jvmDesc == descriptor) {
exceptions?.toList()?.let { exceptionNames.addAll(it) }
}
return object : MethodVisitor(API_VERSION) {
}
}
},
ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES
)
return exceptionNames.mapNotNull {
this@ResolverImpl.getClassDeclarationByName(it.replace("/", "."))?.asStarProjectedType()
}.asSequence()
}
@SuppressWarnings("UNCHECKED_CAST")
private fun extractThrowsAnnotation(annotated: KSAnnotated): Sequence<KSType> {
return annotated.annotations
.singleOrNull {
it.shortName.asString() == "Throws" &&
it.annotationType.resolve().declaration.qualifiedName?.asString() == "kotlin.Throws"
}?.arguments
?.singleOrNull()
?.let { it.value as? ArrayList<KSType> }
?.asSequence() ?: emptySequence()
}
// TODO: refactor and reuse BinaryClassInfoCache
@KspExperimental
override fun getJvmCheckedException(function: KSFunctionDeclaration): Sequence<KSType> {
return when (function.origin) {
Origin.JAVA -> {
val psi = (function as KSFunctionDeclarationJavaImpl).psi
psi.throwsList.referencedTypes.asSequence().map { getKSTypeCached(resolveJavaType(it)) }
}
Origin.KOTLIN -> {
extractThrowsAnnotation(function)
}
Origin.KOTLIN_LIB, Origin.JAVA_LIB -> {
val descriptor = (function as KSFunctionDeclarationDescriptorImpl).descriptor
val jvmDesc = this.mapToJvmSignature(function)
val virtualFileContent = if (function.origin == Origin.KOTLIN_LIB) {
(descriptor.getContainingKotlinJvmBinaryClass() as? VirtualFileKotlinClass)?.file
?.contentsToByteArray()
} else {
(
((descriptor.source as? JavaSourceElement)?.javaElement as? BinaryJavaMethodBase)
?.containingClass as? BinaryJavaClass
)?.virtualFile?.contentsToByteArray()
}
if (virtualFileContent == null) {
return emptySequence()
}
extractThrowsFromClassFile(virtualFileContent, jvmDesc, function.simpleName.asString())
}
else -> emptySequence()
}
}
@KspExperimental
override fun getJvmCheckedException(accessor: KSPropertyAccessor): Sequence<KSType> {
return when (accessor.origin) {
Origin.KOTLIN, Origin.SYNTHETIC -> {
extractThrowsAnnotation(accessor)
}
Origin.KOTLIN_LIB -> {
val descriptor = (accessor as KSPropertyAccessorDescriptorImpl).descriptor
val jvmDesc = typeMapper.mapAsmMethod(descriptor).descriptor
val virtualFileContent = if (accessor.origin == Origin.KOTLIN_LIB) {
(descriptor.correspondingProperty.getContainingKotlinJvmBinaryClass() as? VirtualFileKotlinClass)
?.file?.contentsToByteArray()
} else {
(
((descriptor.source as? JavaSourceElement)?.javaElement as? BinaryJavaMethod)?.containingClass
as? BinaryJavaClass
)?.virtualFile?.contentsToByteArray()
}
if (virtualFileContent == null) {
return emptySequence()
}
extractThrowsFromClassFile(virtualFileContent, jvmDesc, getJvmName(accessor))
}
else -> emptySequence()
}
}
private val javaPackageToClassMap: Map<String, List<KSDeclaration>> by lazy {
val packageToClassMapping = mutableMapOf<String, List<KSDeclaration>>()
allKSFiles
.filter { file ->
file.origin == Origin.JAVA &&
options.javaSourceRoots.any { root ->
file.filePath.startsWith(root.absolutePath) &&
file.filePath.substringAfter(root.absolutePath)
.dropLastWhile { c -> c != File.separatorChar }.dropLast(1).drop(1)
.replace(File.separatorChar, '.') == file.packageName.asString()
}
}
.forEach {
packageToClassMapping.put(
it.packageName.asString(),
packageToClassMapping.getOrDefault(it.packageName.asString(), emptyList())
.plus(
it.declarations.filterNot {
it.containingFile?.fileName?.split(".")?.first() == it.simpleName.asString()
}
)
)
}
packageToClassMapping
}
@KspExperimental
override fun getDeclarationsFromPackage(packageName: String): Sequence<KSDeclaration> {
val noPackageFilter = DescriptorKindFilter.ALL.withoutKinds(DescriptorKindFilter.PACKAGES_MASK)
return module.getPackage(FqName(packageName))
.memberScope.getContributedDescriptors(noPackageFilter)
.asSequence()
.mapNotNull { (it as? MemberDescriptor)?.toKSDeclaration() }
.plus(javaPackageToClassMap.getOrDefault(packageName, emptyList()).asSequence())
}
override fun getTypeArgument(typeRef: KSTypeReference, variance: Variance): KSTypeArgument {
return KSTypeArgumentLiteImpl.getCached(typeRef, variance)
}
internal fun asMemberOf(
property: KSPropertyDeclaration,
containing: KSType,
): KSType {
val key = property to containing
return propertyAsMemberOfCache.getOrPut(key) {