-
Notifications
You must be signed in to change notification settings - Fork 321
/
Copy pathTypeSystem.swift
1378 lines (1172 loc) · 56.9 KB
/
TypeSystem.swift
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 2019 Google LLC
//
// 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
//
// https://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.
// A simple type system for the JavaScript language designed to be used for fuzzing.
//
// The goal of this type system is to be as simple as possible while still being able to express all the common
// operations that one can peform on values of the target language, e.g. calling a function or constructor,
// accessing properties, or calling methods.
// The type system is mainly used for two purposes:
//
// 1. to obtain a variable of a certain type when generating code. E.g. the method call code generator will want
// a variable of type .object() as input because only that can have methods. Also, when generating function
// calls it can be necessary to find variables of the types that the function expects as arguments. This task
// is solved by defining a "Is a" relationship between types which can then be used to find suitable variables.
// 2. to determine possible actions that can be performed on a value. E.g. when having a reference to something
// that is known to be a function, a function call can be performed. Also, the method call code generator will
// want to know the available methods that it can call on an object, which it can query from the type system.
//
// The following base types are defined:
// .undefined
// .integer
// .bigint
// .float
// .boolean
// .string
// .regexp
// .object(ofGroup: G, withProperties: [...], withMethods: [...])
// something that (potentially) has properties and methods. Can also have a "group", which is simply a string.
// Groups can e.g. be used to store property and method type information for related objects. See JavaScriptEnvironment.swift for examples.
// .function(signature: S)
// something that can be invoked as a function
// .constructor(signature: S)
// something that can be invoked as a constructor
// .iterable
// something that can be iterated over, e.g. in a for-of loop
//
// Besides the base types, types can be combined to form new types:
//
// A type can be a union, essentially stating that it is one of multiple types. Union types occur in many scenarios, e.g.
// when reassigning a variable, when computing type information following a conditionally executing piece of code, or due to
// imprecise modelling of the environment, e.g. the + operation in JavaScript or return values of various APIs.
//
// Further, a type can also be a merged type, essentially stating that it is *all* of the contained types at the same type.
// As an example of a merged type, think of regular JavaScript functions which can be called but also constructed. On the other hand,
// some JavaScript builtins can be used as a function but not as a constructor or vice versa. As such, it is necessary to be able to
// differentiate between functions and constructors. Strings are another example for merged types. On the one hand they are a primitive
// type expected by various APIs, on the other hand they can be used like an object by accessing properties on them or invoking methods.
// As such, a JavaScript string would be represented as a merge of .string and .object(properties: [...], methods: [...]).
//
// The operations that can be performed on types are then:
//
// 1. Unioning (|) : this operation on two types expresses that the result can either
// be the first or the second type.
//
// 2. Intersecting (&) : this operation computes the intersection, so the common type
// between the two argument types. This is used by the "MayBe" query,
// answering whether a value could potentially have the given type.
// In contrast to the other two operations, itersecting will not create
// new types.
//
// 3. Merging (+) : this operation merges the two argument types into a single type
// which is both types. Not all types can be merged, however.
//
// Finally, types define the "is a" (subsumption) relation (>=) which amounts to set inclusion. A type T1 subsumes
// another type T2 if all instances of T2 are also instances of T1. See the .subsumes method for the exact subsumption
// rules. Some examples:
//
// - .anything, the union of all types, subsumes every other type
// - .nothing, the empty type, is subsumed by all other types. .nothing occurs e.g. during intersection
// - .object() subsumes all other object type. I.e. objects with a property "foo" are sill objects
// e.g. .object() >= .object(withProperties: ["foo"]) and .object() >= .object(withMethods: ["bar"])
// - .object(withProperties: ["foo"]) subsumes all other object types that also have a property "foo"
// e.g. .object(withProperties: ["foo"]) >= .object(withProperties: ["foo", "bar"], withMethods: ["baz"])
// - .object(ofGroup: G) subsumes any other object of group G, but not of a different group
// - .function([.integer] => .integer) only subsumes other functions with the same signature
// - .primitive, the union of .integer, .float, and .string, subsumes its parts like every union
// - .functionAndConstructor(), the merge of .function() and .constructor(), is subsumed by each of its parts like every merged type
//
// Internally, types are implemented as bitsets, with each base type corresponding to one bit.
// Types are then implemented as two bitsets: the definite type, indicating what it definitely
// is, and the possible type, indicating what types it could potentially be.
// A union type is one where the possible type is larger than the definite one.
//
// Examples:
// .integer => definiteType = .integer, possibleType = .integer
// .integer | .float => definiteType = .nothing (0), possibleType = .integer | .float
// .string + .object => definiteType = .string | .object, possibleType = .string | .object
// .string | (.string + .object) => definiteType = .string, possibleType = .string | .object
//
// See also Tests/FuzzilliTests/TypeSystemTest.swift for examples of the various properties and features of this type system.
//
public struct ILType: Hashable {
//
// Types and type constructors
//
/// Corresponds to the undefined type in JavaScript
public static let undefined = ILType(definiteType: .undefined)
/// An integer type.
public static let integer = ILType(definiteType: .integer)
/// A bigInt type.
public static let bigint = ILType(definiteType: .bigint)
/// A floating point number.
public static let float = ILType(definiteType: .float)
/// A string.
public static let string = ILType(definiteType: .string)
/// A boolean.
public static let boolean = ILType(definiteType: .boolean)
/// A RegExp
public static let regexp = ILType(definiteType: .regexp)
/// A type that can be iterated over, such as an array or a generator.
public static let iterable = ILType(definiteType: .iterable)
/// The type that subsumes all others.
public static let anything = ILType(definiteType: .nothing, possibleType: .anything)
/// The type that is subsumed by all others.
public static let nothing = ILType(definiteType: .nothing, possibleType: .nothing)
/// A number: either an integer or a float.
public static let number: ILType = .integer | .float
/// A primitive: either a number, a string, a boolean, or a bigint.
public static let primitive: ILType = .integer | .float | .string | .boolean
/// A "nullish" type ('undefined' or 'null 'in JavaScript). Curently this is effectively an alias for .undefined since we also use .undefined for null.
public static let nullish: ILType = .undefined
/// Constructs an object type.
public static func object(ofGroup group: String? = nil, withProperties properties: [String] = [], withMethods methods: [String] = [], withWasmType wasmExt: WasmTypeExtension? = nil) -> ILType {
let ext = TypeExtension(group: group, properties: Set(properties), methods: Set(methods), signature: nil, wasmExt: wasmExt)
return ILType(definiteType: .object, ext: ext)
}
/// Constructs an enum type, which is a string with a limited set of allowed values.
public static func enumeration(ofName name: String, withValues values: [String]) -> ILType {
let ext = TypeExtension(group: name, properties: Set(values), methods: Set(), signature: nil, wasmExt: nil)
return ILType(definiteType: .string, ext: ext)
}
/// An object for which it is not known what properties or methods it has, if any.
public static let unknownObject: ILType = .object()
/// A function.
public static func function(_ signature: Signature? = nil) -> ILType {
let ext = TypeExtension(properties: Set(), methods: Set(), signature: signature)
return ILType(definiteType: [.function], ext: ext)
}
/// A constructor.
public static func constructor(_ signature: Signature? = nil) -> ILType {
let ext = TypeExtension(properties: Set(), methods: Set(), signature: signature)
return ILType(definiteType: [.constructor], ext: ext)
}
/// A function and constructor. Same as .function(signature) + .constructor(signature).
public static func functionAndConstructor(_ signature: Signature? = nil) -> ILType {
let ext = TypeExtension(properties: Set(), methods: Set(), signature: signature)
return ILType(definiteType: [.function, .constructor], ext: ext)
}
// Internal types
// This type is used to indicate block labels in wasm.
public static func label(_ parameterTypes: [ILType] = [], isCatch: Bool = false) -> ILType {
return ILType(definiteType: .label, ext: TypeExtension(group: "WasmLabel", properties: [], methods: [], signature: nil, wasmExt: WasmLabelType(parameterTypes, isCatch: isCatch)))
}
public static let anyLabel: ILType = ILType(definiteType: .label, ext: TypeExtension(group: "WasmLabel", properties: [], methods: [], signature: nil, wasmExt: nil))
/// A label that allows rethrowing the caught exception of a catch block.
public static let exceptionLabel: ILType = ILType(definiteType: .exceptionLabel)
public static func wasmMemory(limits: Limits, isShared: Bool = false, isMemory64: Bool = false) -> ILType {
let wasmMemExt = WasmMemoryType(limits: limits, isShared: isShared, isMemory64: isMemory64)
return .object(ofGroup: "WasmMemory", withProperties: ["buffer"], withMethods: ["grow"], withWasmType: wasmMemExt)
}
public static func wasmTable(wasmTableType: WasmTableType) -> ILType {
return .object(ofGroup: "WasmTable", withProperties: ["length"], withMethods: ["get", "grow", "set"], withWasmType: wasmTableType)
}
//
// Wasm Types
//
public static let wasmi32 = ILType(definiteType: .wasmi32)
public static let wasmi64 = ILType(definiteType: .wasmi64)
public static let wasmf32 = ILType(definiteType: .wasmf32)
public static let wasmf64 = ILType(definiteType: .wasmf64)
public static let wasmExternRef = ILType(definiteType: .wasmExternRef)
public static let wasmFuncRef = ILType(definiteType: .wasmFuncRef)
public static let wasmSimd128 = ILType(definiteType: .wasmSimd128)
// The union of all primitive wasm types
public static let wasmPrimitive = .wasmi32 | .wasmi64 | .wasmf32 | .wasmf64 | .wasmExternRef | .wasmFuncRef | .wasmSimd128
public static let wasmNumericalPrimitive = .wasmi32 | .wasmi64 | .wasmf32 | .wasmf64
//
// Type testing
//
// Whether it is a function or a constructor (or both).
public var isCallable: Bool {
return !definiteType.intersection([.function, .constructor]).isEmpty
}
/// Whether this type is a union, i.e can be one of multiple types.
public var isUnion: Bool {
return possibleType.isStrictSuperset(of: definiteType)
}
/// Whether this type is a merge of multiple base types.
public var isMerged: Bool {
return definiteType.rawValue.nonzeroBitCount > 1
}
/// The base type of this type.
/// The base type of objects is .object(), of functions is .function(), of constructors is .constructor() and of callables is .callable(). For unions it can be .nothing. Otherwise it is the type itself.
public var baseType: ILType {
return ILType(definiteType: definiteType)
}
public static func ==(lhs: ILType, rhs: ILType) -> Bool {
return lhs.definiteType == rhs.definiteType && lhs.possibleType == rhs.possibleType && lhs.ext == rhs.ext
}
public static func !=(lhs: ILType, rhs: ILType) -> Bool {
return !(lhs == rhs)
}
/// Returns true if this type subsumes the given type, i.e. every instance of other is also an instance of this type.
public func Is(_ other: ILType) -> Bool {
return other.subsumes(self)
}
/// Returns true if this type could be the given type, i.e. the intersection of the two is nonempty.
public func MayBe(_ other: ILType) -> Bool {
return self.intersection(with: other) != .nothing
}
/// Returns true if this type could be something other than the specified type.
public func MayNotBe(_ other: ILType) -> Bool {
return !self.Is(other)
}
/// Returns whether this type subsumes the other type.
///
/// A type T1 subsumes another type T2 if all instances of T2 are also instances of T1.
///
/// Subsumption rules:
///
/// - T >= T
/// - except for the above, there is no subsumption relationship between
/// primitive types (.undefined, .integer, .float, .string, .boolean)
/// - .object(ofGroup: G1, withProperties: P1, withMethods: M1) >= .object(ofGroup: G2, withProperties: P2, withMethods: M2)
/// iff (G1 == nil || G1 == G2) && P1 is a subset of P2 && M1 is a subset of M2
/// - for .object(..., withWasmType: W) the WasmTypeExtensions have to be equal
/// - .function(S1) >= .function(S2) iff S1 = nil || S1 == S2
/// - .constructor(S1) >= .constructor(S2) iff S1 = nil || S1 == S2
/// - T1 | T2 >= T1 && T1 | T2 >= T2
/// - T1 >= T1 + T2 && T2 >= T1 + T2
/// - T1 >= T1 & T2 && T2 >= T1 & T2
public func subsumes(_ other: ILType) -> Bool {
// Handle trivial cases
if self == other || other == .nothing {
return true
} else if self == .nothing {
return false
}
// A multitype subsumes only multitypes containing at least the same necessary types.
// E.g. every stringobject (a .string and .object) is a .string (.string subsumes stringobject), but not every .string
// is also a stringobject (stringobject does not subsume .string).
guard other.definiteType.isSuperset(of: self.definiteType) else {
return false
}
// If we are a union (so our possible type is larger than the definite type)
// then check that our possible type is larger than the other possible type.
// However, there are some special rules to consider:
// 1. If the other type is a merged type, it is enough if our possible
// type is a superset of one of the merged base types.
if isUnion {
// Verify that either the other definite type is empty or that there is some overlap between
// our possible type and the other definite type
guard other.definiteType.isEmpty || !other.definiteType.intersection(self.possibleType).isEmpty else {
return false
}
// Given the above, we can subtract the other's definite type here from its possible type so that
// e.g. StringObjects are correctly subsumed by both .string and .object.
guard self.possibleType.isSuperset(of: other.possibleType.subtracting(other.definiteType)) else {
return false
}
}
// Base types match. Check extension type now.
// Fast case.
if self.ext == nil || self.ext === other.ext {
return true
}
// The groups must either be identical or our group must be nil, in
// which case we subsume all objects regardless of their group if
// the properties and methods match (see below).
guard group == nil || group == other.group else {
return false
}
// Either our type must be a generic callable without a signature, or our signature must subsume the other type's signature.
guard signature == nil || (other.signature != nil && signature!.subsumes(other.signature!)) else {
return false
}
// The other object can have more properties/methods, but it must
// have at least the ones we have for us to be a supertype.
guard properties.isSubset(of: other.properties) else {
return false
}
guard methods.isSubset(of: other.methods) else {
return false
}
// Wasm type extension.
guard !self.hasWasmTypeInfo || self.wasmType == other.wasmType else {
return false
}
return true
}
public static func >=(lhs: ILType, rhs: ILType) -> Bool {
return lhs.subsumes(rhs)
}
public static func <=(lhs: ILType, rhs: ILType) -> Bool {
return rhs.subsumes(lhs)
}
//
// Access to extended type data
//
public var signature: Signature? {
return ext?.signature
}
public var functionSignature: Signature? {
return Is(.function()) ? ext?.signature : nil
}
public var constructorSignature: Signature? {
return Is(.constructor()) ? ext?.signature : nil
}
public var isEnumeration : Bool {
return Is(.string) && ext != nil
}
public var group: String? {
return ext?.group
}
public var hasWasmTypeInfo: Bool {
return ext?.wasmExt != nil
}
public var wasmType: WasmTypeExtension? {
return ext?.wasmExt
}
public var wasmGlobalType: WasmGlobalType? {
return ext?.wasmExt as? WasmGlobalType
}
public var isWasmGlobalType: Bool {
return wasmGlobalType != nil && ext?.group == "WasmGlobal"
}
public var wasmMemoryType: WasmMemoryType? {
return ext?.wasmExt as? WasmMemoryType
}
public var isWasmMemoryType: Bool {
return wasmMemoryType != nil && ext?.group == "WasmMemory"
}
public var wasmTableType: WasmTableType? {
return ext?.wasmExt as? WasmTableType
}
public var isWasmTableType: Bool {
return wasmTableType != nil && ext?.group == "WasmTable"
}
public var wasmTagType: WasmTagType? {
return wasmType as? WasmTagType
}
public var isWasmTagType: Bool {
return wasmTagType != nil && ext?.group == "WasmTag"
}
public var wasmLabelType: WasmLabelType? {
return wasmType as? WasmLabelType
}
public var isWasmLabelType: Bool {
return wasmTagType != nil
}
public var properties: Set<String> {
return ext?.properties ?? Set()
}
public var enumValues: Set<String> {
return properties
}
public var methods: Set<String> {
return ext?.methods ?? Set()
}
public var numProperties: Int {
return ext?.properties.count ?? 0
}
public var numMethods: Int {
return ext?.methods.count ?? 0
}
public func randomProperty() -> String? {
return ext?.properties.randomElement()
}
public func randomMethod() -> String? {
return ext?.methods.randomElement()
}
//
// Type operations
//
/// Forms the union of this and the other type.
///
/// The union of two types is the type that subsumes both: (T1 | T2) >= T1 && (T1 | T2) >= T2.
///
/// Unioning is imprecise (over-approximative). For example, constructing the following union
/// let r = .object(withProperties: ["a", "b"]) | .object(withProperties: ["a", "c"])
/// will result in r == .object(withProperties: ["a"]). Which is wider than it needs to be.
/// To have a WasmTypeExtension in the union, they have to be equal.
public func union(with other: ILType) -> ILType {
// Trivial cases.
if self == .anything || other == .anything {
return .anything
} else if self == .nothing {
return other
} else if other == .nothing {
return self
}
// Form a union: the intersection of both definiteTypes and the union of both possibleTypes.
// If the base types are the same, this will be a (cheap) Nop.
let definiteType = self.definiteType.intersection(other.definiteType)
let possibleType = self.possibleType.union(other.possibleType)
// Fast union case.
// Identity comparison avoids comparing each property of the class.
if self.ext === other.ext {
return ILType(definiteType: definiteType, possibleType: possibleType, ext: self.ext)
}
// Slow union case: need to union (or really widen) the extension. For properties and methods
// that means finding the set of shared properties and methods, which is imprecise but correct.
let commonProperties = self.properties.intersection(other.properties)
let commonMethods = self.methods.intersection(other.methods)
let signature = self.signature == other.signature ? self.signature : nil // TODO: this is overly coarse, we could also see if one signature subsumes the other, then take the subsuming one.
let group = self.group == other.group ? self.group : nil
let wasmExt = self.wasmType == other.wasmType ? self.wasmType : nil
return ILType(definiteType: definiteType, possibleType: possibleType, ext: TypeExtension(group: group, properties: commonProperties, methods: commonMethods, signature: signature, wasmExt: wasmExt))
}
public static func |(lhs: ILType, rhs: ILType) -> ILType {
return lhs.union(with: rhs)
}
public static func |=(lhs: inout ILType, rhs: ILType) {
lhs = lhs | rhs
}
/// Forms the intersection of the two types.
///
/// The intersection of T1 and T2 is the subtype that is contained in both T1 and T2.
/// The result of this can be .nothing.
public func intersection(with other: ILType) -> ILType {
// The definite types must have a subset relationship.
// E.g. a StringObject intersected with a String is a StringObject,
// but a StringObject intersected with an IntegerObject is .nothing.
let definiteType = self.definiteType.union(other.definiteType)
guard definiteType == self.definiteType || definiteType == other.definiteType else {
return .nothing
}
// Now intersect the possible type.
var possibleType = self.possibleType.intersection(other.possibleType)
guard !possibleType.isEmpty else {
return .nothing
}
// E.g. the intersection of a StringObject and a String is a StringObject. As such, here we have to
// "add back" the definite type to the possible type (which at this point would just be String).
possibleType.formUnion(definiteType)
// Fast intersection case.
// Identity comparison avoids comparing each property of the class.
if self.ext === other.ext {
return ILType(definiteType: definiteType, possibleType: possibleType, ext: self.ext)
}
// Slow intersection case: intersect the type extension.
//
// The intersection between an object with properties ["foo"] and an
// object with properties ["foo", "bar"] is an object with properties
// ["foo", "bar"], as that is the "smaller" type, subsumed by the first.
// The same rules apply for methods.
let properties = self.properties.union(other.properties)
guard properties.count == max(self.numProperties, other.numProperties) else {
return .nothing
}
let methods = self.methods.union(other.methods)
guard methods.count == max(self.numMethods, other.numMethods) else {
return .nothing
}
// Groups must either be equal or one of them must be nil, in which case
// the result will have the non-nil group as that is again the smaller type.
guard self.group == nil || other.group == nil || self.group == other.group else {
return .nothing
}
let group = self.group == nil ? other.group : self.group
// For signatures we take a shortcut: if one signature subsumes the other, then the intersection
// must be the subsumed signature. Additionally, we know that if there is an intersection, the
// return value must be the intersection of the return values, so we can compute that up-front.
let returnValue = (self.signature?.outputType ?? .anything) & (other.signature?.outputType ?? .anything)
guard returnValue != .nothing else {
return .nothing
}
let ourSignature = self.signature?.replacingOutputType(with: returnValue)
let otherSignature = other.signature?.replacingOutputType(with: returnValue)
let signature: Signature?
if ourSignature == nil || (otherSignature != nil && ourSignature!.subsumes(otherSignature!)) {
signature = otherSignature
} else if otherSignature == nil || (ourSignature != nil && otherSignature!.subsumes(ourSignature!)) {
signature = ourSignature
} else {
return .nothing
}
// Handling Wasm type extension.
var wasmExt: WasmTypeExtension?
if self.wasmType == other.wasmType {
wasmExt = self.wasmType
} else {
return .nothing
}
return ILType(definiteType: definiteType, possibleType: possibleType, ext: TypeExtension(group: group, properties: properties, methods: methods, signature: signature, wasmExt: wasmExt))
}
public static func &(lhs: ILType, rhs: ILType) -> ILType {
return lhs.intersection(with: rhs)
}
public static func &=(lhs: inout ILType, rhs: ILType) {
lhs = lhs & rhs
}
/// Returns whether this type can be merged with the other type.
public func canMerge(with other: ILType) -> Bool {
// Merging of unions is not allowed, mainly because it would be ambiguous in our internal representation and is not needed in practice.
guard !self.isUnion && !other.isUnion else {
return false
}
// Merging of callables with different signatures is not allowed.
guard self.signature == nil || other.signature == nil || self.signature == other.signature else {
return false
}
// Merging objects of different groups is not allowed.
guard self.group == nil || other.group == nil || self.group == other.group else {
return false
}
// Merging with .nothing is not supported as the result would have to be subsumed by .nothing but be != .nothing which is not allowed.
guard self != .nothing && other != .nothing else {
return false
}
return true
}
/// Merges this type with the other.
///
/// Merging two types results in a new type that is both of its parts at the same type (i.e. is subsumed by both).
/// Unlike intersection, this creates a new type if necessary and will never result in .nothing.
///
/// Not all types can be merged, see canMerge.
public func merging(with other: ILType) -> ILType {
assert(canMerge(with: other))
let definiteType = self.definiteType.union(other.definiteType)
let possibleType = self.possibleType.union(other.possibleType)
// Signatures must be equal here or one of them is nil (see canMerge)
let signature = self.signature ?? other.signature
// Same is true for the group name
let group = self.group ?? other.group
let ext = TypeExtension(group: group, properties: self.properties.union(other.properties), methods: self.methods.union(other.methods), signature: signature)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: ext)
}
public static func +(lhs: ILType, rhs: ILType) -> ILType {
return lhs.merging(with: rhs)
}
public static func +=(lhs: inout ILType, rhs: ILType) {
lhs = lhs.merging(with: rhs)
}
//
// Type transitioning
//
// TODO cache these in some kind of type transition table data structure?
//
/// Returns a new type that represents this type with the added property.
public func adding(property: String) -> ILType {
guard Is(.object()) else {
return self
}
var newProperties = properties
newProperties.insert(property)
let newExt = TypeExtension(group: group, properties: newProperties, methods: methods, signature: signature, wasmExt: wasmType)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: newExt)
}
/// Adds a property to this type.
public mutating func add(property: String) {
self = self.adding(property: property)
}
/// Returns a new ObjectType that represents this type without the removed property.
public func removing(property: String) -> ILType {
guard Is(.object()) else {
return self
}
var newProperties = properties
newProperties.remove(property)
let newExt = TypeExtension(group: group, properties: newProperties, methods: methods, signature: signature, wasmExt: wasmType)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: newExt)
}
/// Returns a new ObjectType that represents this type with the added property.
public func adding(method: String) -> ILType {
guard Is(.object()) else {
return self
}
var newMethods = methods
newMethods.insert(method)
let newExt = TypeExtension(group: group, properties: properties, methods: newMethods, signature: signature, wasmExt: wasmType)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: newExt)
}
/// Adds a method to this type.
public mutating func add(method: String) {
self = self.adding(method: method)
}
/// Returns a new ObjectType that represents this type without the removed property.
public func removing(method: String) -> ILType {
guard Is(.object()) else {
return self
}
var newMethods = methods
newMethods.remove(method)
let newExt = TypeExtension(group: group, properties: properties, methods: newMethods, signature: signature, wasmExt: wasmType)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: newExt)
}
public func settingSignature(to signature: Signature) -> ILType {
guard Is(.function() | .constructor()) else {
return self
}
let newExt = TypeExtension(group: group, properties: properties, methods: methods, signature: signature)
return ILType(definiteType: definiteType, possibleType: possibleType, ext: newExt)
}
//
// Type implementation internals
//
/// The base type is simply a bitset of (potentially multiple) basic types.
private let definiteType: BaseType
/// The possible type is always a superset of the necessary type.
private let possibleType: BaseType
/// The type extensions contains properties, methods, function signatures, etc.
private let ext: TypeExtension?
/// Types must be constructed through one of the public constructors.
private init(definiteType: BaseType, possibleType: BaseType? = nil, ext: TypeExtension? = nil) {
self.definiteType = definiteType
self.possibleType = possibleType ?? definiteType
self.ext = ext
assert(self.possibleType.contains(self.definiteType))
}
}
extension ILType: CustomStringConvertible {
public func format(abbreviate: Bool) -> String {
// Test for well-known union types and .nothing
if self == .anything {
return ".anything"
} else if self == .nothing {
return ".nothing"
} else if self == .primitive {
return ".primitive"
} else if self == .number {
return ".number"
}
if isUnion {
// Unions with non-zero necessary types can only
// occur if merged types are unioned.
var mergedTypes: [ILType] = []
for b in BaseType.allBaseTypes {
if self.definiteType.contains(b) {
let subtype = ILType(definiteType: b, ext: ext)
mergedTypes.append(subtype)
}
}
var parts: [String] = []
for b in BaseType.allBaseTypes {
if self.possibleType.contains(b) && !self.definiteType.contains(b) {
let subtype = ILType(definiteType: b, ext: ext)
parts.append(mergedTypes.reduce(subtype, +).format(abbreviate: abbreviate))
}
}
return parts.joined(separator: " | ")
}
// Must now either be a simple type or a merged type
// Handle simple types
switch definiteType {
case .undefined:
return ".undefined"
case .integer:
return ".integer"
case .bigint:
return ".bigint"
case .regexp:
return ".regexp"
case .float:
return ".float"
case .string:
return ".string"
case .boolean:
return ".boolean"
case .iterable:
return ".iterable"
case .object:
var params: [String] = []
if let group = group {
params.append("ofGroup: \(group)")
}
if !properties.isEmpty {
if abbreviate && properties.count > 5 {
let selection = properties.prefix(3).map { "\"\($0)\"" }
params.append("withProperties: [\(selection.joined(separator: ", ")), ...]")
} else {
params.append("withProperties: \(properties)")
}
}
if !methods.isEmpty {
if abbreviate && methods.count > 5 {
let selection = methods.prefix(3).map { "\"\($0)\"" }
params.append("withMethods: [\(selection.joined(separator: ", ")), ...]")
} else {
params.append("withMethods: \(methods)")
}
}
return ".object(\(params.joined(separator: ", ")))"
case .function:
if let signature = functionSignature {
return ".function(\(signature.format(abbreviate: abbreviate)))"
} else {
return ".function()"
}
case .constructor:
if let signature = constructorSignature {
return ".constructor(\(signature.format(abbreviate: abbreviate)))"
} else {
return ".constructor()"
}
case .wasmi32:
return ".wasmi32"
case .wasmi64:
return ".wasmi64"
case .wasmf32:
return ".wasmf32"
case .wasmf64:
return ".wasmf64"
case .wasmExternRef:
return ".wasmExternRef"
case .wasmFuncRef:
return ".wasmFuncRef"
case .wasmSimd128:
return ".wasmSimd128"
case .label:
return ".label"
default:
break
}
// Must be a merged type
if isMerged {
var parts: [String] = []
for b in BaseType.allBaseTypes {
if self.definiteType.contains(b) {
let subtype = ILType(definiteType: b, ext: ext)
parts.append(subtype.format(abbreviate: abbreviate))
}
}
return parts.joined(separator: " + ")
}
fatalError("Unhandled type")
}
public var description: String {
return format(abbreviate: false)
}
public var abbreviated: String {
return format(abbreviate: true)
}
}
struct BaseType: OptionSet, Hashable {
let rawValue: UInt32
// Base types
static let nothing = BaseType([])
static let undefined = BaseType(rawValue: 1 << 0)
static let integer = BaseType(rawValue: 1 << 1)
static let bigint = BaseType(rawValue: 1 << 2)
static let float = BaseType(rawValue: 1 << 3)
static let boolean = BaseType(rawValue: 1 << 4)
static let string = BaseType(rawValue: 1 << 5)
static let regexp = BaseType(rawValue: 1 << 6)
static let object = BaseType(rawValue: 1 << 7)
static let function = BaseType(rawValue: 1 << 8)
static let constructor = BaseType(rawValue: 1 << 9)
static let iterable = BaseType(rawValue: 1 << 10)
// Wasm Types
static let wasmi32 = BaseType(rawValue: 1 << 11)
static let wasmi64 = BaseType(rawValue: 1 << 12)
static let wasmf32 = BaseType(rawValue: 1 << 13)
static let wasmf64 = BaseType(rawValue: 1 << 14)
static let wasmExternRef = BaseType(rawValue: 1 << 15)
static let wasmFuncRef = BaseType(rawValue: 1 << 16)
// These are wasm internal types, these are never lifted as such and are only used to glue together dataflow in wasm.
static let label = BaseType(rawValue: 1 << 17)
// Any catch block exposes such a label now to rethrow the exception caught by that catch.
// Note that in wasm the label is actually the try block's label but as rethrows are only possible inside a catch
// block, semantically having a label on the catch makes more sense.
static let exceptionLabel = BaseType(rawValue: 1 << 18)
// This is a reference to a table, which can be passed around to table instructions
// The lifter will resolve this to the proper index when lifting.
static let wasmSimd128 = BaseType(rawValue: 1 << 19)
static let anything = BaseType([.undefined, .integer, .float, .string, .boolean, .object, .function, .constructor, .bigint, .regexp, .iterable])
static let allBaseTypes: [BaseType] = [.undefined, .integer, .float, .string, .boolean, .object, .function, .constructor, .bigint, .regexp, .iterable]
}
class TypeExtension: Hashable {
// Properties and methods. Will only be populated if MayBe(.object()) is true.
let properties: Set<String>
let methods: Set<String>
// The group name. Basically each group is its own sub type of the object type.
// (For now), there is no subtyping for group: if two objects have a different
// group then there is no subsumption relationship between them.
let group: String?
// The function signature. Will only be != nil if isFunction or isConstructor is true.
let signature: Signature?
// Wasm specific properties for Wasm types.
let wasmExt: WasmTypeExtension?
init?(group: String? = nil, properties: Set<String>, methods: Set<String>, signature: Signature?, wasmExt: WasmTypeExtension? = nil) {
if group == nil && properties.isEmpty && methods.isEmpty && signature == nil && wasmExt == nil {
return nil
}
self.properties = properties
self.methods = methods
self.group = group
self.signature = signature
self.wasmExt = wasmExt
}
static func ==(lhs: TypeExtension, rhs: TypeExtension) -> Bool {
return lhs.properties == rhs.properties && lhs.methods == rhs.methods && lhs.group == rhs.group && lhs.signature == rhs.signature && lhs.wasmExt == rhs.wasmExt
}
public func hash(into hasher: inout Hasher) {
hasher.combine(group)
hasher.combine(properties)
hasher.combine(methods)
hasher.combine(signature)
hasher.combine(wasmExt)
}
}
// Base class that all Wasm types wih TypeExtension should inherit from.
public class WasmTypeExtension: Hashable {
public static func ==(lhs: WasmTypeExtension, rhs: WasmTypeExtension) -> Bool {
lhs.isEqual(to: rhs)
}
func isEqual(to other: WasmTypeExtension) -> Bool {
fatalError("unreachable")
}
public func hash(into hasher: inout Hasher) {
fatalError("unreachable")
}
}
public class WasmGlobalType: WasmTypeExtension {
let valueType: ILType
let isMutable: Bool
override func isEqual(to other: WasmTypeExtension) -> Bool {
guard let other = other as? WasmGlobalType else { return false }
return self.valueType == other.valueType && self.isMutable == other.isMutable
}
override public func hash(into hasher: inout Hasher) {
hasher.combine(valueType)
hasher.combine(isMutable)
}
init(valueType: ILType, isMutable: Bool) {
self.valueType = valueType
self.isMutable = isMutable
}
}