-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathType.qll
More file actions
1398 lines (1221 loc) · 43.8 KB
/
Type.qll
File metadata and controls
1398 lines (1221 loc) · 43.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
/**
* Provides classes and predicates for working with Java types.
*
* Types can be primitive types (`PrimitiveType`), array types (`Array`), or reference
* types (`RefType`), where the latter are either classes (`Class`) or interfaces
* (`Interface`).
*
* Reference types can be at the top level (`TopLevelType`) or nested (`NestedType`).
* Classes and interfaces can also be local (`LocalClassOrInterface`, `LocalClass`) or anonymous (`AnonymousClass`).
* Enumerated types (`EnumType`) and records (`Record`) are special kinds of classes.
*/
overlay[local?]
module;
import Member
import Modifier
import JDK
private import semmle.code.java.Overlay
/**
* Holds if reference type `t` is an immediate super-type of `sub`.
*/
cached
predicate hasSubtype(RefType t, Type sub) {
// Direct subtype.
extendsReftype(sub, t) and t != sub
or
implInterface(sub, t)
or
// A parameterized type `T<A>` is a subtype of the corresponding raw type `T<>`.
parSubtypeRaw(t, sub) and t != sub
or
// Array subtyping is covariant.
arraySubtype(t, sub) and t != sub
or
// Type parameter containment for parameterized types.
parContainmentSubtype(t, sub)
or
// Type variables are subtypes of their upper bounds.
typeVarSubtypeBound(t, sub) and t != sub
}
/**
* Holds if reference type `anc` is a direct or indirect supertype of `sub`, including itself.
*/
cached
predicate hasDescendant(RefType anc, Type sub) {
anc = sub
or
exists(RefType mid | hasSubtype(anc, mid) and hasDescendant(mid, sub))
}
private predicate typeVarSubtypeBound(RefType t, TypeVariable tv) {
if tv.hasTypeBound() then t = tv.getATypeBound().getType() else t instanceof TypeObject
}
private predicate parSubtypeRaw(RefType t, ParameterizedType sub) {
t = sub.getErasure().(GenericType).getRawType()
}
private predicate arraySubtype(Array sup, Array sub) {
hasSubtype(sup.getComponentType(), sub.getComponentType())
}
/*
* `parContainmentSubtype(pt, psub)` is equivalent to:
* ```
* pt != psub and
* pt.getGenericType() = psub.getGenericType() and
* forex(int i | i in [0..pt.getNumberOfTypeArguments()-1] |
* typeArgumentContains(_, pt.getTypeArgument(i), psub.getTypeArgument(i), _)
* )
* ```
* For performance several transformations are made. First, the `forex` is
* written as a loop where `typePrefixContains(ppt, ppsub)` encode that
* `ppt` and `ppsub` are prefixes of `pt` and `ptsub` and that
* the `forex` holds for `i in [0..n-1]` where `n` is the length of the prefixes.
* Second, the recursive case that determines containment of length `n+1`
* prefixes is split into three cases depending on whether there is
* non-reflexive type parameter containment:
* - only in the length `n` prefix,
* - only in the `n`th position,
* - both in the length `n` prefix and the `n`th position.
*/
private predicate parContainmentSubtype(ParameterizedType pt, ParameterizedType psub) {
exists(ParameterizedPrefix ppt, ParameterizedPrefix ppsub |
typePrefixContains(ppt, ppsub) and
ppt.equals(pt) and
ppsub.equals(psub)
)
}
/**
* Gets the `index`-th type parameter of `t`, which is a parameterization of `g`.
*/
private RefType parameterisationTypeArgument(GenericType g, ParameterizedType t, int index) {
g = t.getGenericType() and
result = t.getTypeArgument(index)
}
private predicate varianceCandidate(ParameterizedType pt) {
pt.getATypeArgument() instanceof Wildcard
}
pragma[noinline]
private RefType parameterisationTypeArgumentVarianceCand(
GenericType g, ParameterizedType t, int index
) {
result = parameterisationTypeArgument(g, t, index) and
varianceCandidate(t)
}
private newtype TParameterizedPrefix =
TGenericType(GenericType g) or
TTypeParam(ParameterizedPrefix pp, RefType t) { prefixMatches(pp, t, _, _) }
/** Holds if `pp` is a length `n` prefix of `pt`. */
private predicate prefixMatches(ParameterizedPrefix pp, ParameterizedType pt, int n) {
pp = TGenericType(pt.getGenericType()) and n = 0
or
exists(ParameterizedPrefix pp0, RefType t |
pp = TTypeParam(pp0, t) and prefixMatches(pp0, t, pt, n - 1)
)
}
/**
* Holds if `pp` is a length `n` prefix of `pt` and `t` is the `n`th type
* argument of `pt`.
*/
private predicate prefixMatches(ParameterizedPrefix pp, RefType t, ParameterizedType pt, int n) {
prefixMatches(pp, pt, n) and
t = pt.getTypeArgument(n)
}
/**
* A prefix of a `ParameterizedType`. This encodes the corresponding
* `GenericType` and the first `n` type arguments where `n` is the prefix
* length.
*/
private class ParameterizedPrefix extends TParameterizedPrefix {
string toString() { result = "ParameterizedPrefix" }
predicate equals(ParameterizedType pt) { prefixMatches(this, pt, pt.getNumberOfTypeArguments()) }
/** Holds if this prefix has length `n`, applies to `g`, and equals `TTypeParam(pp, t)`. */
predicate split(GenericType g, ParameterizedPrefix pp, RefType t, int n) {
this = TTypeParam(pp, t) and
(
pp = TGenericType(g) and n = 0
or
pp.split(g, _, _, n - 1)
)
}
}
/**
* Holds if every type argument of `pps` contains the corresponding type
* argument of `ppt`. Both `pps` and `ppt` are constrained to be equal-length
* prefixes of parameterizations of the same `GenericType`.
*/
pragma[nomagic]
private predicate typePrefixContains(ParameterizedPrefix pps, ParameterizedPrefix ppt) {
// Let `pps = TTypeParam(pps0, s)` and `ppt = TTypeParam(ppt0, t)`.
// Case 1: pps0 = ppt0 and typeArgumentContains(_, s, t, _)
typePrefixContains_base(pps, ppt)
or
// Case 2: typePrefixContains(pps0, ppt0) and s = t
typePrefixContains_ext_eq(pps, ppt)
or
// Case 3: typePrefixContains(pps0, ppt0) and typeArgumentContains(_, s, t, _)
typePrefixContains_ext_neq(pps, ppt)
}
private predicate typePrefixContains_base(ParameterizedPrefix pps, ParameterizedPrefix ppt) {
exists(ParameterizedPrefix pp, RefType s |
pps = TTypeParam(pp, s) and
typePrefixContainsAux2(ppt, pp, s)
)
}
private predicate typePrefixContains_ext_eq(ParameterizedPrefix pps, ParameterizedPrefix ppt) {
exists(ParameterizedPrefix pps0, ParameterizedPrefix ppt0, RefType t |
typePrefixContains(pragma[only_bind_into](pps0), pragma[only_bind_into](ppt0)) and
pps = TTypeParam(pragma[only_bind_into](pps0), t) and
ppt = TTypeParam(ppt0, t)
)
}
private predicate typePrefixContains_ext_neq(ParameterizedPrefix pps, ParameterizedPrefix ppt) {
exists(ParameterizedPrefix ppt0, RefType s |
typePrefixContainsAux1(pps, ppt0, s) and
typePrefixContainsAux2(ppt, ppt0, s)
)
}
pragma[nomagic]
private TTypeParam parameterizedPrefixWithWildcard(ParameterizedPrefix pps0, Wildcard s) {
result = TTypeParam(pps0, s)
}
pragma[nomagic]
private predicate typePrefixContainsAux1(
ParameterizedPrefix pps, ParameterizedPrefix ppt0, RefType s
) {
exists(ParameterizedPrefix pps0 |
typePrefixContains(pps0, ppt0) and
// `s instanceof Wildcard` is manual magic, implied by `typeArgumentContains(_, s, t, _)`
pps = parameterizedPrefixWithWildcard(pps0, s)
)
}
pragma[nomagic]
private predicate typePrefixContainsAux2(
ParameterizedPrefix ppt, ParameterizedPrefix ppt0, RefType s
) {
exists(GenericType g, int n, RefType t |
// Implies `ppt = TTypeParam(ppt0, t)`
ppt.split(g, ppt0, t, n) and
typeArgumentContains(g, s, t, n)
)
}
/**
* Holds if the type argument `s` contains the type argument `t`, where both
* type arguments occur as index `n` in an instantiation of `g`.
*
* The case `s = t` is not included.
*/
pragma[noinline]
private predicate typeArgumentContains(GenericType g, RefType s, RefType t, int n) {
typeArgumentContainsAux2(g, s, t, n) and
s = parameterisationTypeArgumentVarianceCand(g, _, n)
}
pragma[nomagic]
private predicate typeArgumentContainsAux2(GenericType g, RefType s, RefType t, int n) {
typeArgumentContainsAux1(s, t, n) and
t = parameterisationTypeArgument(g, _, n)
}
/**
* Holds if the type argument `s` contains the type argument `t`, where both
* type arguments occur as index `n` in some parameterized types.
*
* The case `s = t` is not included.
*
* See JLS 4.5.1, Type Arguments of Parameterized Types.
*/
private predicate typeArgumentContainsAux1(RefType s, RefType t, int n) {
s = parameterisationTypeArgumentVarianceCand(_, _, pragma[only_bind_into](n)) and
t = parameterisationTypeArgument(_, _, pragma[only_bind_into](n)) and
s != t and
(
exists(RefType tUpperBound | tUpperBound = t.(Wildcard).getUpperBound().getType() |
// ? extends T <= ? extends S if T <: S
hasSubtypeStar1(s.(Wildcard).getUpperBound().getType(), tUpperBound)
or
// ? extends T <= ?
s.(Wildcard).isUnconstrained()
)
or
exists(RefType tLowerBound | tLowerBound = t.(Wildcard).getLowerBound().getType() |
// ? super T <= ? super S if s <: T
hasSubtypeStar2(tLowerBound, s.(Wildcard).getLowerBound().getType())
or
// ? super T <= ?
s.(Wildcard).isUnconstrained()
or
// ? super T <= ? extends Object
wildcardExtendsObject(s)
)
or
// T <= ? extends T
hasSubtypeStar1(s.(Wildcard).getUpperBound().getType(), t)
or
// T <= ? super T
hasSubtypeStar2(t, s.(Wildcard).getLowerBound().getType())
// or
// T <= T
// but this case is handled directly in `typePrefixContains`
)
}
pragma[noinline]
private predicate wildcardExtendsObject(Wildcard wc) {
wc.getUpperBound().getType() instanceof TypeObject
}
// manual magic for `hasSubtypeStar1`
private predicate getAWildcardUpperBound(RefType t) {
t = any(Wildcard w).getUpperBound().getType()
}
// manual magic for `hasSubtypeStar2`
private predicate getAWildcardLowerBound(RefType t) {
t = any(Wildcard w).getLowerBound().getType()
}
/**
* Holds if `hasSubtype*(t, sub)`, but manual-magic'ed with `getAWildcardUpperBound(t)`.
*/
pragma[nomagic]
private predicate hasSubtypeStar1(RefType t, RefType sub) {
sub = t and getAWildcardUpperBound(t)
or
hasSubtype(t, sub) and getAWildcardUpperBound(t)
or
exists(RefType mid | hasSubtypeStar1(t, mid) and hasSubtype(mid, sub))
}
/**
* Holds if `hasSubtype*(t, sub)`, but manual-magic'ed with `getAWildcardLowerBound(sub)`.
*/
pragma[nomagic]
private predicate hasSubtypeStar2(RefType t, RefType sub) {
sub = t and getAWildcardLowerBound(sub)
or
hasSubtype(t, sub) and getAWildcardLowerBound(sub)
or
exists(RefType mid | hasSubtype(t, mid) and hasSubtypeStar2(mid, sub))
}
/** Holds if type `t` declares member `m`. */
predicate declaresMember(Type t, @member m) {
methods(m, _, _, _, t, _)
or
constrs(m, _, _, _, t, _)
or
fields(m, _, _, t)
or
enclInReftype(m, t) and
// Since the type `@member` in the dbscheme includes all `@reftype`s,
// anonymous and local classes need to be excluded here.
not m instanceof AnonymousClass and
not m instanceof LocalClassOrInterface
}
/**
* A common abstraction for all Java types, including
* primitive, class, interface and array types.
*/
class Type extends Element, @type {
/**
* Gets the JVM descriptor for this type, as used in bytecode.
*/
string getTypeDescriptor() { none() }
/** Gets the erasure of this type. */
Type getErasure() { result = erase(this) }
}
/**
* An array type.
*
* Array types are implicitly declared when used; there is
* an array declaration for each array type used in the system.
*/
class Array extends RefType, @array {
/**
* Gets the type of the components of this array type.
*
* For example, the component type of `Object[][]` is `Object[]`.
*/
Type getComponentType() { arrays(this, _, _, _, result) }
/**
* Gets the type of the elements used to construct this array type.
*
* For example, the element type of `Object[][]` is `Object`.
*/
Type getElementType() { arrays(this, _, result, _, _) }
/**
* Gets the arity of this array type.
*
* For example, the dimension of `Object[][]` is 2.
*/
int getDimension() { arrays(this, _, _, result, _) }
/**
* Gets the JVM descriptor for this type, as used in bytecode.
*/
override string getTypeDescriptor() { result = "[" + this.getComponentType().getTypeDescriptor() }
override string getAPrimaryQlClass() { result = "Array" }
}
/**
* A common super-class for various kinds of reference types,
* including classes, interfaces, type parameters and arrays.
*/
class RefType extends Type, Annotatable, Modifiable, @reftype {
/** Gets the package in which this type is declared. */
Package getPackage() { classes_or_interfaces(this, _, result, _) }
/** Gets the type in which this reference type is enclosed, if any. */
RefType getEnclosingType() { enclInReftype(this, result) }
/** Gets the compilation unit in which this type is declared. */
override CompilationUnit getCompilationUnit() { result = this.getFile() }
/** Holds if `t` is an immediate supertype of this type. */
predicate hasSupertype(RefType t) { hasSubtype(t, this) }
/** Holds if `t` is an immediate subtype of this type. */
predicate hasSubtype(RefType t) { hasSubtype(this, t) }
/** Gets a direct subtype of this type. */
RefType getASubtype() { hasSubtype(this, result) }
/** Gets a direct or indirect descendant of this type, including itself. */
RefType getADescendant() { hasDescendant(this, result) }
/** Gets a direct supertype of this type. */
RefType getASupertype() { hasSubtype(result, this) }
/** Gets a direct or indirect supertype of this type, including itself. */
RefType getAnAncestor() { hasDescendant(result, this) }
/**
* Gets a direct or indirect supertype of this type.
* This does not include itself, unless this type is part of a cycle
* in the type hierarchy.
*/
overlay[caller?]
RefType getAStrictAncestor() { result = this.getASupertype().getAnAncestor() }
/**
* Gets the source declaration of a direct supertype of this type, excluding itself.
*
* Note, that a generic type is the source declaration of a direct supertype
* of itself, namely the corresponding raw type, and this case is thus
* explicitly excluded. See also `getSourceDeclaration()`.
*/
pragma[noinline]
RefType getASourceSupertype() {
result = this.getASupertype().getSourceDeclaration() and
result != this
}
/**
* Holds if `t` is an immediate super-type of this type using only the immediate
* `extends` or `implements` relationships. In particular, this excludes
* parameter containment sub-typing for parameterized types.
*/
predicate extendsOrImplements(RefType t) {
extendsReftype(this, t) or
implInterface(this, t) or
typeVarSubtypeBound(t, this)
}
/** Holds if this type declares any members. */
predicate hasMember() { exists(this.getAMember()) }
/** Gets a member declared in this type. */
Member getAMember() { this = result.getDeclaringType() }
/** Gets a method declared in this type. */
Method getAMethod() { this = result.getDeclaringType() }
/** Gets a constructor declared in this type. */
Constructor getAConstructor() { this = result.getDeclaringType() }
/** Gets a method or constructor declared in this type. */
Callable getACallable() { this = result.getDeclaringType() }
/** Gets a field declared in this type. */
Field getAField() { this = result.getDeclaringType() }
/** Holds if this type declares a method with the specified name. */
predicate declaresMethod(string name) { this.getAMethod().getName() = name }
/** Holds if this type declares a method with the specified name and number of parameters. */
predicate declaresMethod(string name, int n) {
exists(Method m | m = this.getAMethod() |
m.getName() = name and
m.getNumberOfParameters() = n
)
}
/** Holds if this type declares a field with the specified name. */
predicate declaresField(string name) { this.getAField().getName() = name }
/** Gets the number of methods declared in this type. */
int getNumberOfMethods() { result = count(Method m | m.getDeclaringType() = this) }
/**
* Holds if this type declares or inherits method `m`, which is declared
* in `declaringType`.
*/
predicate hasMethod(Method m, RefType declaringType) { this.hasMethod(m, declaringType, false) }
/**
* Holds if this type declares or inherits method `m`, which is declared
* in `declaringType`. Methods that would be inherited if they were public,
* but are not inherited due to being package protected, are also included
* and indicated by `hidden` being true.
*/
cached
predicate hasMethod(Method m, RefType declaringType, boolean hidden) {
this.hasNonInterfaceMethod(m, declaringType, hidden)
or
this.hasInterfaceMethod(m, declaringType) and hidden = false
}
private predicate hasNonInterfaceMethod(Method m, RefType declaringType, boolean hidden) {
m = this.getAMethod() and
this = declaringType and
not declaringType instanceof Interface and
hidden = false
or
exists(RefType sup, boolean h1, boolean h2 |
(
if m.isPackageProtected() and sup.getPackage() != this.getPackage()
then h1 = true
else h1 = false
) and
(not sup instanceof Interface or this instanceof Interface) and
this.extendsOrImplements(sup) and
sup.hasNonInterfaceMethod(m, declaringType, h2) and
hidden = h1.booleanOr(h2) and
exists(string signature |
methods(m, _, signature, _, _, _) and not methods(_, _, signature, _, this, _)
) and
m.isInheritable()
)
}
private predicate cannotInheritInterfaceMethod(string signature) {
methods(_, _, signature, _, this, _)
or
exists(Method m | this.hasNonInterfaceMethod(m, _, false) and methods(m, _, signature, _, _, _))
}
private predicate interfaceMethodCandidateWithSignature(
Method m, string signature, RefType declaringType
) {
m = this.getAMethod() and
this = declaringType and
declaringType instanceof Interface and
methods(m, _, signature, _, _, _)
or
exists(RefType sup |
sup.interfaceMethodCandidateWithSignature(m, signature, declaringType) and
not this.cannotInheritInterfaceMethod(signature) and
this.extendsOrImplements(sup) and
m.isInheritable()
)
}
pragma[nomagic]
private predicate overrideEquivalentInterfaceMethodCandidates(Method m1, Method m2) {
exists(string signature |
this.interfaceMethodCandidateWithSignature(m1, signature, _) and
this.interfaceMethodCandidateWithSignature(m2, signature, _) and
m1 != m2 and
m2.overrides(_) and
any(Method m).overrides(m1)
)
}
pragma[noinline]
private predicate overriddenInterfaceMethodCandidate(Method m) {
exists(Method m2 |
this.overrideEquivalentInterfaceMethodCandidates(m, m2) and
m2.overrides(m)
)
}
private predicate hasInterfaceMethod(Method m, RefType declaringType) {
this.interfaceMethodCandidateWithSignature(m, _, declaringType) and
not this.overriddenInterfaceMethodCandidate(m)
}
/** Holds if this type declares or inherits the specified member. */
predicate inherits(Member m) {
exists(Field f | f = m |
f = this.getAField()
or
not f.isPrivate() and not this.declaresField(f.getName()) and this.getASupertype().inherits(f)
or
this.getSourceDeclaration().inherits(f)
)
or
this.hasMethod(m, _)
}
/** Holds if this is a top-level type, which is not nested inside any other types. */
predicate isTopLevel() { this instanceof TopLevelType }
/**
* Holds if this type is declared in a specified package with the specified name.
*
* For nested types the name of the nested type is prefixed with a `$` and appended
* to the name of the enclosing type, which might be a nested type as well.
*/
predicate hasQualifiedName(string package, string type) {
this.getPackage().hasName(package) and type = this.getNestedName()
}
/**
* Gets the JVM descriptor for this type, as used in bytecode.
*/
override string getTypeDescriptor() {
result =
"L" + this.getPackage().getName().replaceAll(".", "/") + "/" +
this.getSourceDeclaration().getNestedName() + ";"
}
/**
* Gets the qualified name of this type, consisting of the package name followed by
* a `.` and the name of this type.
*
* For nested types the name of the nested type is prefixed with a `$` and appended
* to the name of the enclosing type, which might be a nested type as well. For example:
* `java.lang.Thread$State`.
*/
string getQualifiedName() {
exists(string pkgName | pkgName = this.getPackage().getName() |
if pkgName = ""
then result = this.getNestedName()
else result = pkgName + "." + this.getNestedName()
)
}
/**
* Gets the nested name of this type.
*
* If this type is not a nested type, the result is the same as `getName()`.
* Otherwise the name of the nested type is prefixed with a `$` and appended to
* the name of the enclosing type, which might be a nested type as well.
*/
string getNestedName() {
not this instanceof NestedType and result = this.getName()
or
this.(NestedType).getEnclosingType().getNestedName() + "$" + this.getName() = result
}
/** DEPRECATED: Alias for `getNestedName`. */
deprecated string nestedName() { result = this.getNestedName() }
/**
* Gets the source declaration of this type.
*
* For parameterized instances of generic types and raw types, the
* source declaration is the corresponding generic type.
*
* For non-parameterized types declared inside a parameterized
* instance of a generic type, the source declaration is the
* corresponding type in the generic type.
*
* For all other types, the source declaration is the type itself.
*/
RefType getSourceDeclaration() { result = this }
/** Holds if this type is the same as its source declaration. */
predicate isSourceDeclaration() { this.getSourceDeclaration() = this }
/** Cast this reference type to a class that provides access to metrics information. */
MetricRefType getMetrics() { result = this }
/**
* A common (reflexive, transitive) subtype of the erasures of
* types `t1` and `t2`, if it exists.
*
* If there is no such common subtype, then the two types are disjoint.
* However, the converse is not true; for example, the parameterized types
* `List<Integer>` and `Collection<String>` are disjoint,
* but their erasures (`List` and `Collection`, respectively)
* do have common subtypes (such as `List` itself).
*
* For the definition of the notion of *erasure* see JLS v8, section 4.6 (Type Erasure).
*/
overlay[caller?]
pragma[inline]
RefType commonSubtype(RefType other) {
result.getASourceSupertype*() = erase(this) and
result.getASourceSupertype*() = erase(other)
}
}
/**
* An `ErrorType` is generated when CodeQL is unable to correctly
* extract a type.
*/
class ErrorType extends RefType, @errortype {
override string getAPrimaryQlClass() { result = "ErrorType" }
}
/** A type that is the same as its source declaration. */
class SrcRefType extends RefType {
SrcRefType() { this.isSourceDeclaration() }
}
/** A class declaration. */
class Class extends ClassOrInterface {
Class() { not isInterface(this) }
/** Holds if this class is an anonymous class. */
predicate isAnonymous() { isAnonymClass(this.getSourceDeclaration(), _) }
/** Holds if this class is an implicit class (compact source file). */
predicate isImplicit() { isImplicitClass(this.getSourceDeclaration()) }
/** Holds if this is an auxiliary program element generated by the compiler. */
override predicate isCompilerGenerated() {
super.isCompilerGenerated() or
this.isImplicit()
}
/**
* Gets an annotation that applies to this class.
*
* Note that a class may inherit annotations from super-classes.
*/
override Annotation getAnAnnotation() {
result = ClassOrInterface.super.getAnAnnotation()
or
exists(AnnotationType tp | tp = result.getType() |
tp.isInherited() and
not exists(Annotation ann | ann = ClassOrInterface.super.getAnAnnotation() |
ann.getType() = tp
) and
result = this.getASupertype().(Class).getAnAnnotation()
)
}
/**
* Holds if this class is a Kotlin "file class", e.g. the class FooKt
* for top-level entities in Foo.kt.
*/
predicate isFileClass() { file_class(this) }
override string getAPrimaryQlClass() { result = "Class" }
}
/** A Kotlin `object`. */
class ClassObject extends Class {
ClassObject() { class_object(this, _) }
/** Gets the instance variable that implements this `object`. */
Field getInstance() { class_object(this, result) }
}
/** A Kotlin `companion object`. */
class CompanionObject extends Class {
CompanionObject() { type_companion_object(_, _, this) }
/** Gets the instance variable that implements this `companion object`. */
Field getInstance() { type_companion_object(_, result, this) }
}
/**
* A Kotlin data class declaration.
*/
class DataClass extends Class {
DataClass() { ktDataClasses(this) }
}
/**
* A record declaration.
*/
class Record extends Class {
Record() { isRecord(this) }
/**
* Gets the canonical constructor of this record.
*/
Constructor getCanonicalConstructor() {
result = this.getAConstructor() and isCanonicalConstr(result)
}
}
/** An intersection type. */
class IntersectionType extends RefType, @classorinterface {
IntersectionType() {
exists(string shortname |
classes_or_interfaces(this, shortname, _, _) and
shortname.matches("% & ...")
)
}
private RefType superType() { extendsReftype(this, result) }
private RefType superInterface() { implInterface(this, result) }
/** Gets a textual representation of this type that includes all the intersected types. */
string getLongName() {
result = this.superType().toString() + concat(" & " + this.superInterface().toString())
}
/** Gets the first bound of this intersection type. */
RefType getFirstBound() { extendsReftype(this, result) }
}
/** An anonymous class. */
class AnonymousClass extends NestedClass {
AnonymousClass() { this.isAnonymous() }
/**
* Utility method: an integer that is larger for classes that
* are defined textually later.
*/
private int rankInParent(RefType parent) {
this.getEnclosingType() = parent and
exists(Location myLocation, File f, int maxCol | myLocation = this.getLocation() |
f = myLocation.getFile() and
maxCol = max(Location loc | loc.getFile() = f | loc.getStartColumn()) and
result = myLocation.getStartLine() * maxCol + myLocation.getStartColumn()
)
}
/**
* Gets the JVM descriptor for this type, as used in bytecode.
*
* For an anonymous class, the type descriptor is the descriptor of the
* enclosing type followed by a (1-based) counter of anonymous classes
* declared within that type.
*/
override string getTypeDescriptor() {
exists(RefType parent | parent = this.getEnclosingType() |
exists(int num |
num =
1 + count(AnonymousClass other | other.rankInParent(parent) < this.rankInParent(parent))
|
exists(string parentWithSemi | parentWithSemi = parent.getTypeDescriptor() |
result = parentWithSemi.prefix(parentWithSemi.length() - 1) + "$" + num + ";"
)
)
)
}
/** Gets the class instance expression where this anonymous class occurs. */
ClassInstanceExpr getClassInstanceExpr() { isAnonymClass(this.getSourceDeclaration(), result) }
override string toString() {
// Include super.toString, i.e. the name given in the database, because for Kotlin anonymous
// classes we can get specialisations of anonymous generic types, and this will supply the
// trailing type arguments.
result =
"new " + pragma[only_bind_out](this.getClassInstanceExpr().getTypeName()).toString() +
"(...) { ... }" + super.toString()
}
/**
* Gets the qualified name of this type.
*
* Anonymous classes do not have qualified names, so we use
* the string `"<anonymous class>"` as a placeholder.
*/
override string getQualifiedName() { result = "<anonymous class>" }
override string getAPrimaryQlClass() { result = "AnonymousClass" }
}
/** A local class or interface. */
class LocalClassOrInterface extends NestedType, ClassOrInterface {
LocalClassOrInterface() { this.isLocal() }
/** Gets the statement that declares this local class. */
LocalTypeDeclStmt getLocalTypeDeclStmt() { isLocalClassOrInterface(this, result) }
override string getAPrimaryQlClass() { result = "LocalClassOrInterface" }
}
/** A local class. */
class LocalClass extends LocalClassOrInterface, NestedClass {
LocalClass() { this.isLocal() }
override string getAPrimaryQlClass() { result = "LocalClass" }
}
/** A top-level type. */
class TopLevelType extends RefType {
TopLevelType() {
not enclInReftype(this, _) and
this instanceof ClassOrInterface
}
}
/** A top-level class. */
class TopLevelClass extends TopLevelType, Class { }
/** A nested type is a type declared within another type. */
class NestedType extends RefType {
NestedType() { enclInReftype(this, _) }
/** Gets the type enclosing this nested type. */
override RefType getEnclosingType() { enclInReftype(this, result) }
/** Gets the nesting depth of this nested type. Top-level types have nesting depth 0. */
int getNestingDepth() {
if this.getEnclosingType() instanceof NestedType
then result = this.getEnclosingType().(NestedType).getNestingDepth() + 1
else result = 1
}
override predicate isPublic() {
super.isPublic()
or
// JLS 9.5: A member type declaration in an interface is implicitly public and static
exists(Interface i | this = i.getAMember())
}
override predicate isStrictfp() {
super.isStrictfp()
or
// JLS 8.1.1.3, JLS 9.1.1.2
this.getEnclosingType().isStrictfp()
}
override predicate isStatic() {
super.isStatic()
or
/*
* Note: The following is most likely redundant because `isStatic()` of the superclass
* holds for implicitly static types, but keep the special casing below for now to be
* on the safe side
*/
// JLS 8.5.1: A member interface is implicitly static.
this instanceof Interface
or
// JLS 8.9: A nested enum type is implicitly static.
this instanceof EnumType
or
// JLS 9.5: A member type declaration in an interface is implicitly public and static
exists(Interface i | this = i.getAMember())
}
}
/**
* A nested type which is a direct member of the enclosing type,
* that is, neither an anonymous nor local class.
*/
class MemberType extends NestedType, Member {
/**
* Gets the qualified name of this member type.
*
* The qualified name consists of the package name, a `.`, the name of the declaring
* type (which might be a nested or member type as well), followed by a `$` and the
* name of this member type. For example: `java.lang.Thread$State`.
*/
override string getQualifiedName() { result = NestedType.super.getQualifiedName() }
}
/**
* A class declared within another type.
*
* This includes (static and non-static) member classes,
* local classes and anonymous classes.
*/
class NestedClass extends NestedType, Class { }
/**
* An inner class is a nested class that is neither explicitly nor
* implicitly declared static. This includes anonymous and local
* classes.
*/
class InnerClass extends NestedClass {
InnerClass() { not this.isStatic() }
/**
* Holds if an instance of this inner class holds a reference to its
* enclosing class.
*/
predicate hasEnclosingInstance() {
// JLS 15.9.2. Determining Enclosing Instances
not this.(AnonymousClass).getClassInstanceExpr().isInStaticContext() and
not this.(LocalClass).getLocalTypeDeclStmt().getEnclosingCallable().isStatic()
}
}
/** An interface. */
class Interface extends ClassOrInterface {
Interface() { isInterface(this) }
override predicate isAbstract() {
// JLS 9.1.1.1: "Every interface is implicitly abstract"
any()
}
override string getAPrimaryQlClass() { result = "Interface" }
}
/** A class or interface. */
class ClassOrInterface extends RefType, @classorinterface {
override RefType getSourceDeclaration() { classes_or_interfaces(this, _, _, result) }
/** Holds if this class or interface is local. */
predicate isLocal() { isLocalClassOrInterface(this.getSourceDeclaration(), _) }
/** Holds if this class or interface is package protected, that is, neither public nor private nor protected. */
predicate isPackageProtected() {
not this.isPrivate() and
not this.isProtected() and
not this.isPublic()
}