-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathKotlinUsesExtractor.kt
More file actions
2270 lines (2071 loc) · 95.8 KB
/
KotlinUsesExtractor.kt
File metadata and controls
2270 lines (2071 loc) · 95.8 KB
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
package com.github.codeql
import com.github.codeql.utils.*
import com.github.codeql.utils.versions.*
import com.semmle.extractor.java.OdasaOutput
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.ir.*
import org.jetbrains.kotlin.backend.jvm.ir.*
import org.jetbrains.kotlin.codegen.JvmCodegenUtil
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.addAnnotations
import org.jetbrains.kotlin.ir.types.classFqName
import org.jetbrains.kotlin.ir.types.classifierOrNull
import org.jetbrains.kotlin.ir.types.classOrNull
import org.jetbrains.kotlin.ir.types.isAny
import org.jetbrains.kotlin.ir.types.isNullableAny
import org.jetbrains.kotlin.ir.types.isPrimitiveType
import org.jetbrains.kotlin.ir.types.makeNullable
import org.jetbrains.kotlin.ir.types.typeOrNull
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.types.typeWithArguments
import org.jetbrains.kotlin.ir.types.IrDynamicType
import org.jetbrains.kotlin.ir.types.IrErrorType
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrStarProjection
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.IrTypeArgument
import org.jetbrains.kotlin.ir.types.IrTypeProjection
import org.jetbrains.kotlin.ir.types.impl.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.typeEnhancement.hasEnhancedNullability
import org.jetbrains.kotlin.load.kotlin.getJvmModuleNameForDeserializedDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.NameUtils
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.resolve.descriptorUtil.propertyIfAccessor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
open class KotlinUsesExtractor(
open val logger: Logger,
open val tw: TrapWriter,
val dependencyCollector: OdasaOutput.TrapFileManager?,
val externalClassExtractor: ExternalDeclExtractor,
val primitiveTypeMapping: PrimitiveTypeMapping,
val pluginContext: IrPluginContext,
val globalExtensionState: KotlinExtractorGlobalState
) {
fun referenceExternalClass(name: String) =
getClassByFqName(pluginContext, FqName(name))?.owner.also {
if (it == null) logger.warn("Unable to resolve external class $name")
else extractExternalClassLater(it)
}
val javaLangObject by lazy { referenceExternalClass("java.lang.Object") }
val javaLangObjectType by lazy { javaLangObject?.typeWith() }
private fun usePackage(pkg: String): Label<out DbPackage> {
return extractPackage(pkg)
}
fun extractPackage(pkg: String): Label<out DbPackage> {
val pkgLabel = "@\"package;$pkg\""
val id: Label<DbPackage> = tw.getLabelFor(pkgLabel, { tw.writePackages(it, pkg) })
return id
}
fun useFileClassType(f: IrFile) =
TypeResults(TypeResult(extractFileClass(f), "", ""), TypeResult(fakeKotlinType(), "", ""))
fun useFileClassType(fqName: FqName) =
TypeResults(
TypeResult(extractFileClass(fqName), "", ""),
TypeResult(fakeKotlinType(), "", "")
)
private fun useFileClassType(pkg: String, jvmName: String) =
TypeResults(
TypeResult(extractFileClass(pkg, jvmName), "", ""),
TypeResult(fakeKotlinType(), "", "")
)
fun extractFileClass(f: IrFile): Label<out DbClassorinterface> {
val pkg = f.packageFqName.asString()
val jvmName = getFileClassName(f)
val id = extractFileClass(pkg, jvmName)
if (tw.lm.fileClassLocationsExtracted.add(f)) {
val fileId = tw.mkFileId(f.path, false)
val locId = tw.getWholeFileLocation(fileId)
tw.writeHasLocation(id, locId)
}
return id
}
private fun extractFileClass(fqName: FqName): Label<out DbClassorinterface> {
val pkg = if (fqName.codeQlIsRoot()) "" else fqName.parent().asString()
val jvmName = fqName.shortName().asString()
return extractFileClass(pkg, jvmName)
}
private fun extractFileClass(pkg: String, jvmName: String): Label<out DbClassorinterface> {
val qualClassName = if (pkg.isEmpty()) jvmName else "$pkg.$jvmName"
val label = "@\"class;$qualClassName\""
val id: Label<DbClassorinterface> =
tw.getLabelFor(label) {
val pkgId = extractPackage(pkg)
tw.writeClasses_or_interfaces(it, jvmName, pkgId, it)
tw.writeFile_class(it)
addModifiers(it, "public", "final")
}
return id
}
data class UseClassInstanceResult(
val typeResult: TypeResult<DbClassorinterface>,
val javaClass: IrClass
)
fun useType(t: IrType, context: TypeContext = TypeContext.OTHER): TypeResults {
when (t) {
is IrSimpleType -> return useSimpleType(t, context)
else -> {
logger.error("Unrecognised IrType: " + t.javaClass)
return extractErrorType()
}
}
}
private fun extractJavaErrorType(): TypeResult<DbErrortype> {
val typeId = tw.getLabelFor<DbErrortype>("@\"errorType\"") { tw.writeError_type(it) }
return TypeResult(typeId, "<CodeQL error type>", "<CodeQL error type>")
}
private fun extractErrorType(): TypeResults {
val javaResult = extractJavaErrorType()
val kotlinTypeId =
tw.getLabelFor<DbKt_nullable_type>("@\"errorKotlinType\"") {
tw.writeKt_nullable_types(it, javaResult.id)
}
return TypeResults(
javaResult,
TypeResult(kotlinTypeId, "<CodeQL error type>", "<CodeQL error type>")
)
}
fun getJavaEquivalentClass(c: IrClass) =
getJavaEquivalentClassId(c)?.let { getClassByClassId(pluginContext, it) }?.owner
/**
* Gets a KotlinFileExtractor based on this one, except it attributes locations to the file that
* declares the given class.
*/
private fun withFileOfClass(cls: IrClass): KotlinFileExtractor {
val clsFile = cls.fileOrNull
if (this is KotlinFileExtractor && this.filePath == clsFile?.path) {
return this
}
val newDeclarationStack =
if (this is KotlinFileExtractor) this.declarationStack
else KotlinFileExtractor.DeclarationStack()
if (clsFile == null || isExternalDeclaration(cls)) {
val filePath = getIrClassBinaryPath(cls)
val newTrapWriter = tw.makeFileTrapWriter(filePath, true)
val newLoggerTrapWriter = logger.dtw.makeFileTrapWriter(filePath, false)
val newLogger = FileLogger(logger.loggerBase, newLoggerTrapWriter)
return KotlinFileExtractor(
newLogger,
newTrapWriter,
null,
filePath,
dependencyCollector,
externalClassExtractor,
primitiveTypeMapping,
pluginContext,
newDeclarationStack,
globalExtensionState
)
}
val newTrapWriter = tw.makeSourceFileTrapWriter(clsFile, true)
val newLoggerTrapWriter = logger.dtw.makeSourceFileTrapWriter(clsFile, false)
val newLogger = FileLogger(logger.loggerBase, newLoggerTrapWriter)
return KotlinFileExtractor(
newLogger,
newTrapWriter,
null,
clsFile.path,
dependencyCollector,
externalClassExtractor,
primitiveTypeMapping,
pluginContext,
newDeclarationStack,
globalExtensionState
)
}
// The Kotlin compiler internal representation of Outer<T>.Inner<S>.InnerInner<R> is
// InnerInner<R, S, T>. This function returns just `R`.
fun removeOuterClassTypeArgs(
c: IrClass,
argsIncludingOuterClasses: List<IrTypeArgument>?
): List<IrTypeArgument>? {
return argsIncludingOuterClasses?.let {
if (it.size > c.typeParameters.size) it.take(c.typeParameters.size) else null
} ?: argsIncludingOuterClasses
}
private fun isStaticClass(c: IrClass) =
c.visibility != DescriptorVisibilities.LOCAL && !c.isInner
// Gets nested inner classes starting at `c` and proceeding outwards to the innermost enclosing
// static class.
// For example, for (java syntax) `class A { static class B { class C { class D { } } } }`,
// `nonStaticParentsWithSelf(D)` = `[D, C, B]`.
private fun parentsWithTypeParametersInScope(c: IrClass): List<IrDeclarationParent> {
val parentsList = c.parentsWithSelf.toList()
val firstOuterClassIdx = parentsList.indexOfFirst { it is IrClass && isStaticClass(it) }
return if (firstOuterClassIdx == -1) parentsList
else parentsList.subList(0, firstOuterClassIdx + 1)
}
// Gets the type parameter symbols that are in scope for class `c` in Kotlin order (i.e. for
// `class NotInScope<T> { static class OutermostInScope<A, B> { class QueryClass<C, D> { } } }`,
// `getTypeParametersInScope(QueryClass)` = `[C, D, A, B]`.
private fun getTypeParametersInScope(c: IrClass) =
parentsWithTypeParametersInScope(c).mapNotNull({ getTypeParameters(it) }).flatten()
// Returns a map from `c`'s type variables in scope to type arguments
// `argsIncludingOuterClasses`.
// Hack for the time being: the substituted types are always nullable, to prevent downstream
// code
// from replacing a generic parameter by a primitive. As and when we extract Kotlin types we
// will
// need to track this information in more detail.
private fun makeTypeGenericSubstitutionMap(
c: IrClass,
argsIncludingOuterClasses: List<IrTypeArgument>
) =
getTypeParametersInScope(c)
.map({ it.symbol })
.zip(argsIncludingOuterClasses.map { it.withQuestionMark(true) })
.toMap()
fun makeGenericSubstitutionFunction(
c: IrClass,
argsIncludingOuterClasses: List<IrTypeArgument>
) =
makeTypeGenericSubstitutionMap(c, argsIncludingOuterClasses).let {
{ x: IrType, useContext: TypeContext, pluginContext: IrPluginContext ->
x.substituteTypeAndArguments(it, useContext, pluginContext)
}
}
// The Kotlin compiler internal representation of Outer<A, B>.Inner<C, D>.InnerInner<E,
// F>.someFunction<G, H>.LocalClass<I, J> is LocalClass<I, J, G, H, E, F, C, D, A, B>. This
// function returns [A, B, C, D, E, F, G, H, I, J].
private fun orderTypeArgsLeftToRight(
c: IrClass,
argsIncludingOuterClasses: List<IrTypeArgument>?
): List<IrTypeArgument>? {
if (argsIncludingOuterClasses.isNullOrEmpty()) return argsIncludingOuterClasses
val ret = ArrayList<IrTypeArgument>()
// Iterate over nested inner classes starting at `c`'s surrounding top-level or static
// nested class and ending at `c`, from the outermost inwards:
val truncatedParents = parentsWithTypeParametersInScope(c)
for (parent in truncatedParents.reversed()) {
val parentTypeParameters = getTypeParameters(parent)
val firstArgIdx =
argsIncludingOuterClasses.size - (ret.size + parentTypeParameters.size)
ret.addAll(
argsIncludingOuterClasses.subList(
firstArgIdx,
firstArgIdx + parentTypeParameters.size
)
)
}
return ret
}
// `typeArgs` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
fun useClassInstance(
c: IrClass,
typeArgs: List<IrTypeArgument>?,
inReceiverContext: Boolean = false
): UseClassInstanceResult {
val substituteClass = getJavaEquivalentClass(c)
val extractClass = substituteClass ?: c
// `KFunction1<T1,T2>` is substituted by `KFunction<T>`. The last type argument is the
// return type.
// Similarly Function23 and above get replaced by kotlin.jvm.functions.FunctionN with only
// one type arg, the result type.
// References to SomeGeneric<T1, T2, ...> where SomeGeneric is declared SomeGeneric<T1, T2,
// ...> are extracted
// as if they were references to the unbound type SomeGeneric.
val extractedTypeArgs =
when {
extractClass.symbol.isKFunction() && typeArgs != null && typeArgs.isNotEmpty() ->
listOf(typeArgs.last())
extractClass.fqNameWhenAvailable == FqName("kotlin.jvm.functions.FunctionN") &&
typeArgs != null &&
typeArgs.isNotEmpty() -> listOf(typeArgs.last())
typeArgs != null && isUnspecialised(c, typeArgs, logger) -> listOf()
else -> typeArgs
}
val classTypeResult = addClassLabel(extractClass, extractedTypeArgs, inReceiverContext)
// Extract both the Kotlin and equivalent Java classes, so that we have database entries
// for both even if all internal references to the Kotlin type are substituted.
if (c != extractClass) {
extractClassLaterIfExternal(c)
}
return UseClassInstanceResult(classTypeResult, extractClass)
}
private fun extractClassLaterIfExternal(c: IrClass) {
if (isExternalDeclaration(c)) {
extractExternalClassLater(c)
}
}
private fun extractExternalEnclosingClassLater(d: IrDeclaration) {
when (val parent = d.parent) {
is IrClass -> extractExternalClassLater(parent)
is IrFunction -> extractExternalEnclosingClassLater(parent)
is IrFile -> logger.error("extractExternalEnclosingClassLater but no enclosing class.")
is IrExternalPackageFragment -> {
// The parent is a (multi)file class. We don't need
// extract it separately.
}
else ->
logger.error(
"Unrecognised extractExternalEnclosingClassLater ${parent.javaClass} for ${d.javaClass}"
)
}
}
private fun propertySignature(p: IrProperty) =
((p.getter ?: p.setter)?.extensionReceiverParameter?.let {
useType(erase(it.type)).javaResult.signature
} ?: "")
fun getTrapFileSignature(d: IrDeclaration) =
when (d) {
is IrFunction ->
// Note we erase the parameter types before calling useType even though the
// signature should be the same
// in order to prevent an infinite loop through useTypeParameter ->
// useDeclarationParent -> useFunction
// -> extractFunctionLaterIfExternalFileMember, which would result for `fun <T> f(t:
// T) { ... }` for example.
(listOfNotNull(d.extensionReceiverParameter) + d.valueParameters)
.map { useType(erase(it.type)).javaResult.signature }
.joinToString(separator = ",", prefix = "(", postfix = ")")
is IrProperty -> propertySignature(d) + externalClassExtractor.propertySignature
is IrField ->
(d.correspondingPropertySymbol?.let { propertySignature(it.owner) } ?: "") +
externalClassExtractor.fieldSignature
else ->
"unknown signature"
.also { logger.warn("Trap file signature requested for unexpected element $d") }
}
private fun extractParentExternalClassLater(d: IrDeclaration) {
val p = d.parent
when (p) {
is IrClass -> extractExternalClassLater(p)
is IrExternalPackageFragment -> {
// The parent is a (multi)file class. We don't need to
// extract it separately.
}
else -> {
logger.warn("Unexpected parent type ${p.javaClass} for external file class member")
}
}
}
private fun extractPropertyLaterIfExternalFileMember(p: IrProperty) {
if (isExternalFileClassMember(p)) {
extractParentExternalClassLater(p)
val signature = getTrapFileSignature(p)
dependencyCollector?.addDependency(p, signature)
externalClassExtractor.extractLater(p, signature)
}
}
private fun extractFieldLaterIfExternalFileMember(f: IrField) {
if (isExternalFileClassMember(f)) {
extractParentExternalClassLater(f)
val signature = getTrapFileSignature(f)
dependencyCollector?.addDependency(f, signature)
externalClassExtractor.extractLater(f, signature)
}
}
private fun extractFunctionLaterIfExternalFileMember(f: IrFunction) {
if (isExternalFileClassMember(f)) {
extractParentExternalClassLater(f)
(f as? IrSimpleFunction)?.correspondingPropertySymbol?.let {
extractPropertyLaterIfExternalFileMember(it.owner)
// No need to extract the function specifically, as the property's
// getters and setters are extracted alongside it
return
}
val signature = getTrapFileSignature(f)
dependencyCollector?.addDependency(f, signature)
externalClassExtractor.extractLater(f, signature)
}
}
fun extractExternalClassLater(c: IrClass) {
dependencyCollector?.addDependency(c)
externalClassExtractor.extractLater(c)
}
private fun tryReplaceAndroidSyntheticClass(c: IrClass): IrClass {
// The Android Kotlin Extensions Gradle plugin introduces synthetic functions, fields and
// classes. The most
// obvious signature is that they lack any supertype information even though they are not
// root classes.
// If possible, replace them by a real version of the same class.
if (
c.superTypes.isNotEmpty() ||
c.origin != IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB ||
c.hasEqualFqName(FqName("java.lang.Object"))
)
return c
return globalExtensionState.syntheticToRealClassMap.getOrPut(c) {
val qualifiedName = c.fqNameWhenAvailable
if (qualifiedName == null) {
logger.warn(
"Failed to replace synthetic class ${c.name} because it has no fully qualified name"
)
return@getOrPut null
}
val result = getClassByFqName(pluginContext, qualifiedName)?.owner
if (result != null) {
logger.info("Replaced synthetic class ${c.name} with its real equivalent")
return@getOrPut result
}
// The above doesn't work for (some) generated nested classes, such as R$id, which
// should be R.id
val fqn = qualifiedName.asString()
if (fqn.indexOf('$') >= 0) {
val nested = getClassByFqName(pluginContext, fqn.replace('$', '.'))?.owner
if (nested != null) {
logger.info(
"Replaced synthetic nested class ${c.name} with its real equivalent"
)
return@getOrPut nested
}
}
logger.warn("Failed to replace synthetic class ${c.name}")
return@getOrPut null
} ?: c
}
private fun tryReplaceFunctionInSyntheticClass(
f: IrFunction,
getClassReplacement: (IrClass) -> IrClass
): IrFunction {
val parentClass = f.parent as? IrClass ?: return f
val replacementClass = getClassReplacement(parentClass)
if (replacementClass === parentClass) return f
return globalExtensionState.syntheticToRealFunctionMap.getOrPut(f) {
val result =
replacementClass.declarations.findSubType<IrSimpleFunction> { replacementDecl ->
replacementDecl.name == f.name &&
replacementDecl.valueParameters.size == f.valueParameters.size &&
replacementDecl.valueParameters.zip(f.valueParameters).all {
erase(it.first.type) == erase(it.second.type)
}
}
if (result == null) {
logger.warn("Failed to replace synthetic class function ${f.name}")
} else {
logger.info("Replaced synthetic class function ${f.name} with its real equivalent")
}
result
} ?: f
}
fun tryReplaceSyntheticFunction(f: IrFunction): IrFunction {
val androidReplacement =
tryReplaceFunctionInSyntheticClass(f) { tryReplaceAndroidSyntheticClass(it) }
return tryReplaceFunctionInSyntheticClass(androidReplacement) {
tryReplaceParcelizeRawType(it)?.first ?: it
}
}
fun tryReplaceAndroidSyntheticField(f: IrField): IrField {
val parentClass = f.parent as? IrClass ?: return f
val replacementClass = tryReplaceAndroidSyntheticClass(parentClass)
if (replacementClass === parentClass) return f
return globalExtensionState.syntheticToRealFieldMap.getOrPut(f) {
val result =
replacementClass.declarations.findSubType<IrField> { replacementDecl ->
replacementDecl.name == f.name
}
?: replacementClass.declarations
.findSubType<IrProperty> { it.backingField?.name == f.name }
?.backingField
if (result == null) {
logger.warn("Failed to replace synthetic class field ${f.name}")
} else {
logger.info("Replaced synthetic class field ${f.name} with its real equivalent")
}
result
} ?: f
}
private fun tryReplaceType(
cBeforeReplacement: IrClass,
argsIncludingOuterClassesBeforeReplacement: List<IrTypeArgument>?
): Pair<IrClass, List<IrTypeArgument>?> {
val c = tryReplaceAndroidSyntheticClass(cBeforeReplacement)
val p = tryReplaceParcelizeRawType(c)
return Pair(p?.first ?: c, p?.second ?: argsIncludingOuterClassesBeforeReplacement)
}
// `typeArgs` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
private fun addClassLabel(
cBeforeReplacement: IrClass,
argsIncludingOuterClassesBeforeReplacement: List<IrTypeArgument>?,
inReceiverContext: Boolean = false
): TypeResult<DbClassorinterface> {
val replaced =
tryReplaceType(cBeforeReplacement, argsIncludingOuterClassesBeforeReplacement)
val replacedClass = replaced.first
val replacedArgsIncludingOuterClasses = replaced.second
val classLabelResult = getClassLabel(replacedClass, replacedArgsIncludingOuterClasses)
var instanceSeenBefore = true
val classLabel: Label<out DbClassorinterface> =
tw.getLabelFor(classLabelResult.classLabel) {
instanceSeenBefore = false
extractClassLaterIfExternal(replacedClass)
}
if (
replacedArgsIncludingOuterClasses == null ||
replacedArgsIncludingOuterClasses.isNotEmpty()
) {
// If this is a generic type instantiation or a raw type then it has no
// source entity, so we need to extract it here
val shouldExtractClassDetails =
inReceiverContext &&
tw.lm.genericSpecialisationsExtracted.add(classLabelResult.classLabel)
if (!instanceSeenBefore || shouldExtractClassDetails) {
this.withFileOfClass(replacedClass)
.extractClassInstance(
classLabel,
replacedClass,
replacedArgsIncludingOuterClasses,
!instanceSeenBefore,
shouldExtractClassDetails
)
}
}
val fqName = replacedClass.fqNameWhenAvailable
val signature =
if (replacedClass.isAnonymousObject) {
null
} else if (fqName == null) {
logger.error("Unable to find signature/fqName for ${replacedClass.name}")
null
} else {
fqName.asString()
}
return TypeResult(classLabel, signature, classLabelResult.shortName)
}
private fun tryReplaceParcelizeRawType(c: IrClass): Pair<IrClass, List<IrTypeArgument>?>? {
if (
c.superTypes.isNotEmpty() ||
c.origin != IrDeclarationOrigin.DEFINED ||
c.hasEqualFqName(FqName("java.lang.Object"))
) {
return null
}
val fqName = c.fqNameWhenAvailable
if (fqName == null) {
return null
}
fun tryGetPair(arity: Int): Pair<IrClass, List<IrTypeArgument>?>? {
val replaced = getClassByFqName(pluginContext, fqName)?.owner ?: return null
return Pair(
replaced,
List(arity) {
makeTypeProjection(pluginContext.irBuiltIns.anyNType, Variance.INVARIANT)
}
)
}
// The list of types handled here match
// https://github.com/JetBrains/kotlin/blob/d7c7d1efd2c0983c13b175e9e4b1cda979521159/plugins/parcelize/parcelize-compiler/src/org/jetbrains/kotlin/parcelize/ir/AndroidSymbols.kt
// Specifically, types are added for generic types created in AndroidSymbols.kt.
// This replacement is from a raw type to its matching parameterized type with `Object` type
// arguments.
return when (fqName.asString()) {
"java.util.ArrayList" -> tryGetPair(1)
"java.util.LinkedHashMap" -> tryGetPair(2)
"java.util.LinkedHashSet" -> tryGetPair(1)
"java.util.List" -> tryGetPair(1)
"java.util.TreeMap" -> tryGetPair(2)
"java.util.TreeSet" -> tryGetPair(1)
"java.lang.Class" -> tryGetPair(1)
else -> null
}
}
private fun useAnonymousClass(c: IrClass) =
tw.lm.anonymousTypeMapping.getOrPut(c) {
TypeResults(
TypeResult(tw.getFreshIdLabel<DbClassorinterface>(), "", ""),
TypeResult(fakeKotlinType(), "TODO", "TODO")
)
}
fun fakeKotlinType(): Label<out DbKt_type> {
val fakeKotlinPackageId: Label<DbPackage> =
tw.getLabelFor("@\"FakeKotlinPackage\"", { tw.writePackages(it, "fake.kotlin") })
val fakeKotlinClassId: Label<DbClassorinterface> =
tw.getLabelFor(
"@\"FakeKotlinClass\"",
{ tw.writeClasses_or_interfaces(it, "FakeKotlinClass", fakeKotlinPackageId, it) }
)
val fakeKotlinTypeId: Label<DbKt_nullable_type> =
tw.getLabelFor(
"@\"FakeKotlinType\"",
{ tw.writeKt_nullable_types(it, fakeKotlinClassId) }
)
return fakeKotlinTypeId
}
// `args` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
fun useSimpleTypeClass(
c: IrClass,
args: List<IrTypeArgument>?,
hasQuestionMark: Boolean
): TypeResults {
val classInstanceResult = useClassInstance(c, args)
val javaClassId = classInstanceResult.typeResult.id
val kotlinQualClassName = getUnquotedClassLabel(c, args).classLabel
val javaResult = classInstanceResult.typeResult
val kotlinResult =
if (true) TypeResult(fakeKotlinType(), "TODO", "TODO")
else if (hasQuestionMark) {
val kotlinSignature = "$kotlinQualClassName?" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;nullable;$kotlinQualClassName\""
val kotlinId: Label<DbKt_nullable_type> =
tw.getLabelFor(kotlinLabel, { tw.writeKt_nullable_types(it, javaClassId) })
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature = kotlinQualClassName // TODO: Is this right?
val kotlinLabel = "@\"kt_type;notnull;$kotlinQualClassName\""
val kotlinId: Label<DbKt_notnull_type> =
tw.getLabelFor(kotlinLabel, { tw.writeKt_notnull_types(it, javaClassId) })
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
// Given either a primitive array or a boxed array, returns primitive arrays unchanged,
// but returns boxed arrays with a nullable, invariant component type, with any nested arrays
// similarly transformed. For example, Array<out Array<in E>> would become Array<Array<E?>?>
// Array<*> will become Array<Any?>.
private fun getInvariantNullableArrayType(arrayType: IrSimpleType): IrSimpleType =
if (arrayType.isPrimitiveArray()) arrayType
else {
val componentType = arrayType.getArrayElementTypeCodeQL(pluginContext.irBuiltIns)
val componentTypeBroadened =
when (componentType) {
is IrSimpleType ->
if (isArray(componentType)) getInvariantNullableArrayType(componentType)
else componentType
else -> componentType
}
val unchanged =
componentType == componentTypeBroadened &&
(arrayType.arguments[0] as? IrTypeProjection)?.variance == Variance.INVARIANT &&
componentType.isNullableCodeQL()
if (unchanged) arrayType
else
IrSimpleTypeImpl(
arrayType.classifier,
true,
listOf(makeTypeProjection(componentTypeBroadened, Variance.INVARIANT)),
listOf()
)
}
/*
Kotlin arrays can be broken down as:
isArray(t)
|- t.isBoxedArrayCodeQL
| |- t.isArray() e.g. Array<Boolean>, Array<Boolean?>
| |- t.isNullableArray() e.g. Array<Boolean>?, Array<Boolean?>?
|- t.isPrimitiveArray() e.g. BooleanArray
For the corresponding Java types:
Boxed arrays are represented as e.g. java.lang.Boolean[].
Primitive arrays are represented as e.g. boolean[].
*/
private fun isArray(t: IrType) = t.isBoxedArrayCodeQL || t.isPrimitiveArray()
data class ArrayInfo(
val elementTypeResults: TypeResults,
val componentTypeResults: TypeResults,
val dimensions: Int
)
/**
* `t` is somewhere in a stack of array types, or possibly the element type of the innermost
* array. For example, in `Array<Array<Int>>`, we will be called with `t` being
* `Array<Array<Int>>`, then `Array<Int>`, then `Int`. `isPrimitiveArray` is true if we are
* immediately nested inside a primitive array.
*/
private fun useArrayType(t: IrType, isPrimitiveArray: Boolean): ArrayInfo {
if (!isArray(t)) {
val nullableT = if (t.isPrimitiveType() && !isPrimitiveArray) t.makeNullable() else t
val typeResults = useType(nullableT)
return ArrayInfo(typeResults, typeResults, 0)
}
if (t !is IrSimpleType) {
logger.error("Unexpected non-simple array type: ${t.javaClass}")
return ArrayInfo(extractErrorType(), extractErrorType(), 0)
}
val arrayClass = t.classifier.owner
if (arrayClass !is IrClass) {
logger.error("Unexpected owner type for array type: ${arrayClass.javaClass}")
return ArrayInfo(extractErrorType(), extractErrorType(), 0)
}
// Because Java's arrays are covariant, Kotlin will render
// Array<in X> as Object[], Array<Array<in X>> as Object[][] etc.
val elementType =
if (
(t.arguments.singleOrNull() as? IrTypeProjection)?.variance == Variance.IN_VARIANCE
) {
pluginContext.irBuiltIns.anyType
} else {
t.getArrayElementTypeCodeQL(pluginContext.irBuiltIns)
}
val recInfo = useArrayType(elementType, t.isPrimitiveArray())
val javaShortName = recInfo.componentTypeResults.javaResult.shortName + "[]"
val kotlinShortName = recInfo.componentTypeResults.kotlinResult.shortName + "[]"
val elementTypeLabel = recInfo.elementTypeResults.javaResult.id
val componentTypeLabel = recInfo.componentTypeResults.javaResult.id
val dimensions = recInfo.dimensions + 1
val id =
tw.getLabelFor<DbArray>("@\"array;$dimensions;{$elementTypeLabel}\"") {
tw.writeArrays(it, javaShortName, elementTypeLabel, dimensions, componentTypeLabel)
extractClassSupertypes(
arrayClass,
it,
ExtractSupertypesMode.Specialised(t.arguments)
)
// array.length
val length = tw.getLabelFor<DbField>("@\"field;{$it};length\"")
val intTypeIds = useType(pluginContext.irBuiltIns.intType)
tw.writeFields(length, "length", intTypeIds.javaResult.id, it)
tw.writeFieldsKotlinType(length, intTypeIds.kotlinResult.id)
addModifiers(length, "public", "final")
// Note we will only emit one `clone()` method per Java array type, so we choose
// `Array<C?>` as its Kotlin
// return type, where C is the component type with any nested arrays themselves
// invariant and nullable.
val kotlinCloneReturnType = getInvariantNullableArrayType(t).makeNullable()
val kotlinCloneReturnTypeLabel = useType(kotlinCloneReturnType).kotlinResult.id
val clone = tw.getLabelFor<DbMethod>("@\"callable;{$it}.clone(){$it}\"")
tw.writeMethods(clone, "clone", "clone()", it, it, clone)
tw.writeMethodsKotlinType(clone, kotlinCloneReturnTypeLabel)
addModifiers(clone, "public")
}
val javaResult =
TypeResult(id, recInfo.componentTypeResults.javaResult.signature + "[]", javaShortName)
val kotlinResult =
TypeResult(
fakeKotlinType(),
recInfo.componentTypeResults.kotlinResult.signature + "[]",
kotlinShortName
)
val typeResults = TypeResults(javaResult, kotlinResult)
return ArrayInfo(recInfo.elementTypeResults, typeResults, dimensions)
}
enum class TypeContext {
RETURN,
GENERIC_ARGUMENT,
OTHER
}
private fun useSimpleType(s: IrSimpleType, context: TypeContext): TypeResults {
if (s.abbreviation != null) {
// TODO: Extract this information
}
// We use this when we don't actually have an IrClass for a class
// we want to refer to
// TODO: Eliminate the need for this if possible
fun makeClass(pkgName: String, className: String): Label<DbClassorinterface> {
val pkgId = extractPackage(pkgName)
val label = "@\"class;$pkgName.$className\""
val classId: Label<DbClassorinterface> =
tw.getLabelFor(label, { tw.writeClasses_or_interfaces(it, className, pkgId, it) })
return classId
}
fun primitiveType(
kotlinClass: IrClass,
primitiveName: String?,
otherIsPrimitive: Boolean,
javaClass: IrClass,
kotlinPackageName: String,
kotlinClassName: String
): TypeResults {
// Note the use of `hasEnhancedNullability` here covers cases like `@NotNull Integer`,
// which must be extracted as `Integer` not `int`.
val javaResult =
if (
(context == TypeContext.RETURN ||
(context == TypeContext.OTHER && otherIsPrimitive)) &&
!s.isNullableCodeQL() &&
getKotlinType(s)?.hasEnhancedNullability() != true &&
primitiveName != null
) {
val label: Label<DbPrimitive> =
tw.getLabelFor(
"@\"type;$primitiveName\"",
{ tw.writePrimitives(it, primitiveName) }
)
TypeResult(label, primitiveName, primitiveName)
} else {
addClassLabel(javaClass, listOf())
}
val kotlinClassId = useClassInstance(kotlinClass, listOf()).typeResult.id
val kotlinResult =
if (true) TypeResult(fakeKotlinType(), "TODO", "TODO")
else if (s.isNullableCodeQL()) {
val kotlinSignature =
"$kotlinPackageName.$kotlinClassName?" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;nullable;$kotlinPackageName.$kotlinClassName\""
val kotlinId: Label<DbKt_nullable_type> =
tw.getLabelFor(
kotlinLabel,
{ tw.writeKt_nullable_types(it, kotlinClassId) }
)
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature =
"$kotlinPackageName.$kotlinClassName" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;notnull;$kotlinPackageName.$kotlinClassName\""
val kotlinId: Label<DbKt_notnull_type> =
tw.getLabelFor(kotlinLabel, { tw.writeKt_notnull_types(it, kotlinClassId) })
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
val owner = s.classifier.owner
val primitiveInfo = primitiveTypeMapping.getPrimitiveInfo(s)
when {
primitiveInfo != null -> {
if (owner is IrClass) {
return primitiveType(
owner,
primitiveInfo.primitiveName,
primitiveInfo.otherIsPrimitive,
primitiveInfo.javaClass,
primitiveInfo.kotlinPackageName,
primitiveInfo.kotlinClassName
)
} else {
logger.error(
"Got primitive info for non-class (${owner.javaClass}) for ${s.render()}"
)
return extractErrorType()
}
}
(s.isBoxedArrayCodeQL && s.arguments.isNotEmpty()) || s.isPrimitiveArray() -> {
val arrayInfo = useArrayType(s, false)
return arrayInfo.componentTypeResults
}
owner is IrClass -> {
val args = if (s.codeQlIsRawType()) null else s.arguments
return useSimpleTypeClass(owner, args, s.isNullableCodeQL())
}
owner is IrTypeParameter -> {
val javaResult = useTypeParameter(owner)
val aClassId = makeClass("kotlin", "TypeParam") // TODO: Wrong
val kotlinResult =
if (true) TypeResult(fakeKotlinType(), "TODO", "TODO")
else if (s.isNullableCodeQL()) {
val kotlinSignature = "${javaResult.signature}?" // TODO: Wrong
val kotlinLabel = "@\"kt_type;nullable;type_param\"" // TODO: Wrong
val kotlinId: Label<DbKt_nullable_type> =
tw.getLabelFor(kotlinLabel, { tw.writeKt_nullable_types(it, aClassId) })
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature = javaResult.signature // TODO: Wrong
val kotlinLabel = "@\"kt_type;notnull;type_param\"" // TODO: Wrong
val kotlinId: Label<DbKt_notnull_type> =
tw.getLabelFor(kotlinLabel, { tw.writeKt_notnull_types(it, aClassId) })
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
else -> {
logger.error("Unrecognised IrSimpleType: " + s.javaClass + ": " + s.render())
return extractErrorType()
}
}
}
private fun parentOf(d: IrDeclaration): IrDeclarationParent {
if (d is IrField) {
return getFieldParent(d)
}
return d.parent
}
fun useDeclarationParentOf(
// The declaration
d: IrDeclaration,
// Whether the type of entity whose parent this is can be a
// top-level entity in the JVM's eyes. If so, then its parent may
// be a file; otherwise, if dp is a file foo.kt, then the parent
// is really the JVM class FooKt.
canBeTopLevel: Boolean,
classTypeArguments: List<IrTypeArgument>? = null,
inReceiverContext: Boolean = false
): Label<out DbElement>? {
val parent = parentOf(d)
if (parent is IrExternalPackageFragment) {
// This is in a file class.
val fqName = getFileClassFqName(d)
if (fqName == null) {
logger.error(
"Can't get FqName for declaration in external package fragment ${d.javaClass}"
)
return null
}
return extractFileClass(fqName)
}
return useDeclarationParent(parent, canBeTopLevel, classTypeArguments, inReceiverContext)
}
// Generally, useDeclarationParentOf should be used instead of
// calling this directly, as this cannot handle
// IrExternalPackageFragment
fun useDeclarationParent(
// The declaration parent according to Kotlin
dp: IrDeclarationParent,
// Whether the type of entity whose parent this is can be a
// top-level entity in the JVM's eyes. If so, then its parent may
// be a file; otherwise, if dp is a file foo.kt, then the parent