forked from googleprojectzero/fuzzilli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodeGenerators.swift
1992 lines (1708 loc) · 85.8 KB
/
CodeGenerators.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 2020 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.
//
// Code generators.
//
// These insert one or more instructions into a program.
//
public let CodeGenerators: [CodeGenerator] = [
//
// Value Generators: Code Generators that generate one or more new values.
//
// These behave like any other CodeGenerator in that they will be randomly chosen to generate code
// and have a weight assigned to them to determine how frequently they are selected, but in addition
// ValueGenerators are also used to "bootstrap" code generation by creating some initial variables
// that following code can then operate on.
//
// These:
// - Must be able to run when there are no visible variables.
// - Together should cover all "interesting" types that generated programs should operate on.
// - Must only generate values whose types can be inferred statically.
// - Should generate |n| different values of the same type, but may generate fewer.
// - May be recursive, for example to fill bodies of newly created blocks.
//
ValueGenerator("IntegerGenerator") { b, n in
for _ in 0..<n {
b.loadInt(b.randomInt())
}
},
ValueGenerator("BigIntGenerator") { b, n in
for _ in 0..<n {
b.loadBigInt(b.randomInt())
}
},
ValueGenerator("FloatGenerator") { b, n in
for _ in 0..<n {
b.loadFloat(b.randomFloat())
}
},
ValueGenerator("StringGenerator") { b, n in
for _ in 0..<n {
b.loadString(b.randomString())
}
},
ValueGenerator("BooleanGenerator") { b, n in
// It's probably not too useful to generate multiple boolean values here.
b.loadBool(Bool.random())
},
ValueGenerator("UndefinedGenerator") { b, n in
// There is only one 'undefined' value, so don't generate it multiple times.
b.loadUndefined()
},
ValueGenerator("NullGenerator") { b, n in
// There is only one 'null' value, so don't generate it multiple times.
b.loadNull()
},
ValueGenerator("ArrayGenerator") { b, n in
// If we can only generate empty arrays, then only create one such array.
if !b.hasVisibleVariables {
b.createArray(with: [])
} else {
for _ in 0..<n {
let initialValues = (0..<Int.random(in: 1...5)).map({ _ in b.randomVariable() })
b.createArray(with: initialValues)
}
}
},
ValueGenerator("IntArrayGenerator") { b, n in
for _ in 0..<n {
let values = (0..<Int.random(in: 1...10)).map({ _ in b.randomInt() })
b.createIntArray(with: values)
}
},
ValueGenerator("FloatArrayGenerator") { b, n in
for _ in 0..<n {
let values = (0..<Int.random(in: 1...10)).map({ _ in b.randomFloat() })
b.createFloatArray(with: values)
}
},
ValueGenerator("BuiltinObjectInstanceGenerator") { b, n in
let builtin = chooseUniform(from: ["Array", "Map", "WeakMap", "Set", "WeakSet", "Date"])
let constructor = b.loadBuiltin(builtin)
if builtin == "Array" {
let size = b.loadInt(b.randomSize(upTo: 0x1000))
b.construct(constructor, withArgs: [size])
} else {
// TODO could add arguments here if possible. Until then, just generate a single value.
b.construct(constructor)
}
},
ValueGenerator("TypedArrayGenerator") { b, n in
for _ in 0..<n {
let size = b.loadInt(b.randomSize(upTo: 0x1000))
let constructor = b.loadBuiltin(
chooseUniform(
from: ["Uint8Array", "Int8Array", "Uint16Array", "Int16Array", "Uint32Array", "Int32Array", "Float32Array", "Float64Array", "Uint8ClampedArray", "BigInt64Array", "BigUint64Array"]
)
)
b.construct(constructor, withArgs: [size])
}
},
ValueGenerator("RegExpGenerator") { b, n in
// TODO: this could be a ValueGenerator but currently has a fairly high failure rate.
for _ in 0..<n {
let (regexpPattern, flags) = b.randomRegExpPatternAndFlags()
b.loadRegExp(regexpPattern, flags)
}
},
RecursiveValueGenerator("ObjectBuilderFunctionGenerator") { b, n in
var objType = ILType.object()
let f = b.buildPlainFunction(with: b.randomParameters()) { args in
if !b.hasVisibleVariables {
// Just create some random number- or string values for the object to use.
for _ in 0..<3 {
withEqualProbability({
b.loadInt(b.randomInt())
}, {
b.loadFloat(b.randomFloat())
}, {
b.loadString(b.randomString())
})
}
}
let o = b.buildObjectLiteral() { obj in
b.buildRecursive()
// TODO: it would be nice if our type inference could figure out getters/setters as well.
objType = .object(withProperties: obj.properties, withMethods: obj.methods)
}
b.doReturn(o)
}
assert(b.type(of: f).signature != nil)
assert(b.type(of: f).signature!.outputType.Is(objType))
for _ in 0..<n {
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
}
},
ValueGenerator("ObjectConstructorGenerator") { b, n in
let maxProperties = 3
assert(b.fuzzer.environment.customProperties.count >= maxProperties)
let properties = Array(b.fuzzer.environment.customProperties.shuffled().prefix(Int.random(in: 1...maxProperties)))
// Define a constructor function...
let c = b.buildConstructor(with: b.randomParameters()) { args in
let this = args[0]
// We don't want |this| to be used as property value, so hide it.
b.hide(this)
// Add a few random properties to the |this| object.
for property in properties {
let value = b.hasVisibleVariables ? b.randomVariable() : b.loadInt(b.randomInt())
b.setProperty(property, of: this, to: value)
}
}
assert(b.type(of: c).signature != nil)
assert(b.type(of: c).signature!.outputType.Is(.object(withProperties: properties)))
// and create a few instances with it.
for _ in 0..<n {
b.construct(c, withArgs: b.randomArguments(forCalling: c))
}
},
RecursiveValueGenerator("ClassDefinitionGenerator") { b, n in
// Possibly pick a superclass. The superclass must be a constructor (or null), otherwise a type error will be raised at runtime.
var superclass: Variable? = nil
if probability(0.5) && b.hasVisibleVariables {
superclass = b.randomVariable(ofType: .constructor())
}
// If there are no visible variables, create some random number- or string values first, so they can be used for example as property values.
if !b.hasVisibleVariables {
for _ in 0..<3 {
withEqualProbability({
b.loadInt(b.randomInt())
}, {
b.loadFloat(b.randomFloat())
}, {
b.loadString(b.randomString())
})
}
}
// Create the class.
let c = b.buildClassDefinition(withSuperclass: superclass) { cls in
b.buildRecursive()
}
// And construct a few instances of it.
for _ in 0..<n {
b.construct(c, withArgs: b.randomArguments(forCalling: c))
}
},
ValueGenerator("TrivialFunctionGenerator") { b, n in
// Generating more than one function has a fairly high probability of generating
// essentially identical functions, so we just generate one.
let maybeReturnValue = b.hasVisibleVariables ? b.randomVariable() : nil
b.buildPlainFunction(with: .parameters(n: 0)) { _ in
if let returnValue = maybeReturnValue {
b.doReturn(returnValue)
}
}
},
//
// "Regular" Code Generators.
//
// These are used to generate all sorts of code constructs, from simple values to
// complex control-flow. They can also perform recursive code generation, for
// example to generate code to fill the bodies of generated blocks. Further, these
// generators may fail and produce no code at all.
//
// Regular code generators can assume that there are visible variables that can
// be used as inputs, and they can request to receive input variables of particular
// types. These input types should be chosen in a way that leads to the generation
// of "meaningful" code, but the generators should still be able to produce correct
// code (i.e. code that doesn't result in a runtime exception) if they receive
// input values of different types.
// For example, when generating a property load, the input type should be .object()
// (so that the property load is meaningful), but if the input type may be null or
// undefined, the property load should be guarded (i.e. use `?.` instead of `.`) to
// avoid raising an exception at runtime.
//
CodeGenerator("ThisGenerator") { b in
b.loadThis()
},
CodeGenerator("ArgumentsAccessGenerator", inContext: .subroutine) { b in
assert(b.context.contains(.subroutine))
b.loadArguments()
},
RecursiveCodeGenerator("FunctionWithArgumentsAccessGenerator") { b in
let parameterCount = probability(0.5) ? 0 : Int.random(in: 1...4)
let f = b.buildPlainFunction(with: .parameters(n: parameterCount)) { args in
let arguments = b.loadArguments()
b.buildRecursive()
b.doReturn(arguments)
}
let args = b.randomVariables(n: Int.random(in: 0...5))
b.callFunction(f, withArgs: args)
},
RecursiveCodeGenerator("ObjectLiteralGenerator") { b in
b.buildObjectLiteral() { obj in
b.buildRecursive()
}
},
CodeGenerator("ObjectLiteralPropertyGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added to this literal.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentObjectLiteral.properties.contains(propertyName)
b.currentObjectLiteral.addProperty(propertyName, as: b.randomVariable())
},
CodeGenerator("ObjectLiteralElementGenerator", inContext: .objectLiteral, inputs: .one) { b, value in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Select an element that hasn't already been added to this literal.
var index = b.randomIndex()
while b.currentObjectLiteral.elements.contains(index) {
// We allow integer overflows here since we could get Int64.max as index, and its not clear what should happen instead in that case.
index &+= 1
}
b.currentObjectLiteral.addElement(index, as: value)
},
CodeGenerator("ObjectLiteralComputedPropertyGenerator", inContext: .objectLiteral, inputs: .one) { b, value in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a computed property that hasn't already been added to this literal.
var propertyName: Variable
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomVariable()
attempts += 1
} while b.currentObjectLiteral.computedProperties.contains(propertyName)
b.currentObjectLiteral.addComputedProperty(propertyName, as: value)
},
CodeGenerator("ObjectLiteralCopyPropertiesGenerator", inContext: .objectLiteral, inputs: .preferred(.object())) { b, object in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
b.currentObjectLiteral.copyProperties(from: object)
},
CodeGenerator("ObjectLiteralPrototypeGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// There should only be one __proto__ field in an object literal.
guard !b.currentObjectLiteral.hasPrototype else { return }
let proto = b.randomVariable(forUseAs: .object())
b.currentObjectLiteral.setPrototype(to: proto)
},
RecursiveCodeGenerator("ObjectLiteralMethodGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a method that hasn't already been added to this literal.
var methodName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomCustomMethodName()
attempts += 1
} while b.currentObjectLiteral.methods.contains(methodName)
b.currentObjectLiteral.addMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ObjectLiteralComputedMethodGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a computed method name that hasn't already been added to this literal.
var methodName: Variable
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomVariable()
attempts += 1
} while b.currentObjectLiteral.computedMethods.contains(methodName)
b.currentObjectLiteral.addComputedMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ObjectLiteralGetterGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a getter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentObjectLiteral.properties.contains(propertyName) || b.currentObjectLiteral.getters.contains(propertyName)
b.currentObjectLiteral.addGetter(for: propertyName) { this in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ObjectLiteralSetterGenerator", inContext: .objectLiteral) { b in
assert(b.context.contains(.objectLiteral) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentObjectLiteral.properties.contains(propertyName) || b.currentObjectLiteral.setters.contains(propertyName)
b.currentObjectLiteral.addSetter(for: propertyName) { this, v in
b.buildRecursive()
}
},
RecursiveCodeGenerator("ClassConstructorGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
guard !b.currentClassDefinition.hasConstructor else {
// There must only be one constructor
return
}
b.currentClassDefinition.addConstructor(with: b.randomParameters()) { args in
let this = args[0]
// Derived classes must call `super()` before accessing this, but non-derived classes must not call `super()`.
if b.currentClassDefinition.isDerivedClass {
b.hide(this) // We need to hide |this| so it isn't used as argument for `super()`
let signature = b.currentSuperConstructorType().signature ?? Signature.forUnknownFunction
let args = b.randomArguments(forCallingFunctionWithSignature: signature)
b.callSuperConstructor(withArgs: args)
b.unhide(this)
}
b.buildRecursive()
}
},
CodeGenerator("ClassInstancePropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added to this literal.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.instanceProperties.contains(propertyName)
var value: Variable? = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addInstanceProperty(propertyName, value: value)
},
CodeGenerator("ClassInstanceElementGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Select an element that hasn't already been added to this literal.
var index = b.randomIndex()
while b.currentClassDefinition.instanceElements.contains(index) {
// We allow integer overflows here since we could get Int64.max as index, and its not clear what should happen instead in that case.
index &+= 1
}
let value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addInstanceElement(index, value: value)
},
CodeGenerator("ClassInstanceComputedPropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a computed property that hasn't already been added to this literal.
var propertyName: Variable
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomVariable()
attempts += 1
} while b.currentClassDefinition.instanceComputedProperties.contains(propertyName)
let value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addInstanceComputedProperty(propertyName, value: value)
},
RecursiveCodeGenerator("ClassInstanceMethodGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a method that hasn't already been added to this class.
var methodName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomCustomMethodName()
attempts += 1
} while b.currentClassDefinition.instanceMethods.contains(methodName)
b.currentClassDefinition.addInstanceMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassInstanceGetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a getter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.instanceProperties.contains(propertyName) || b.currentClassDefinition.instanceGetters.contains(propertyName)
b.currentClassDefinition.addInstanceGetter(for: propertyName) { this in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassPrivateInstanceGetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName) ||
b.currentClassDefinition.privateInstanceGetters.contains(propertyName)
b.currentClassDefinition.addPrivateInstanceGetter(for: propertyName) { this in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassInstanceSetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.instanceProperties.contains(propertyName) || b.currentClassDefinition.instanceSetters.contains(propertyName)
b.currentClassDefinition.addInstanceSetter(for: propertyName) { this, v in
b.buildRecursive()
}
},
RecursiveCodeGenerator("ClassPrivateInstanceSetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName) ||
b.currentClassDefinition.privateInstanceSetters.contains(propertyName)
b.currentClassDefinition.addPrivateInstanceSetter(for: propertyName) { this, v in
b.buildRecursive()
}
},
CodeGenerator("ClassStaticPropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added to this literal.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.staticProperties.contains(propertyName)
var value: Variable? = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addStaticProperty(propertyName, value: value)
},
CodeGenerator("ClassStaticElementGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Select an element that hasn't already been added to this literal.
var index = b.randomIndex()
while b.currentClassDefinition.staticElements.contains(index) {
// We allow integer overflows here since we could get Int64.max as index, and its not clear what should happen instead in that case.
index &+= 1
}
let value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addStaticElement(index, value: value)
},
CodeGenerator("ClassStaticComputedPropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a computed property that hasn't already been added to this literal.
var propertyName: Variable
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomVariable()
attempts += 1
} while b.currentClassDefinition.staticComputedProperties.contains(propertyName)
let value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addStaticComputedProperty(propertyName, value: value)
},
RecursiveCodeGenerator("ClassStaticInitializerGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
b.currentClassDefinition.addStaticInitializer { this in
b.buildRecursive()
}
},
RecursiveCodeGenerator("ClassStaticMethodGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a method that hasn't already been added to this class.
var methodName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomCustomMethodName()
attempts += 1
} while b.currentClassDefinition.staticMethods.contains(methodName)
b.currentClassDefinition.addStaticMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassStaticGetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a getter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.staticProperties.contains(propertyName) || b.currentClassDefinition.staticGetters.contains(propertyName)
b.currentClassDefinition.addStaticGetter(for: propertyName) { this in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassPrivateStaticGetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a getter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName) ||
b.currentClassDefinition.privateStaticGetters.contains(propertyName)
b.currentClassDefinition.addPrivateStaticGetter(for: propertyName) { this in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
RecursiveCodeGenerator("ClassStaticSetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.staticProperties.contains(propertyName) || b.currentClassDefinition.staticSetters.contains(propertyName)
b.currentClassDefinition.addStaticSetter(for: propertyName) { this, v in
b.buildRecursive()
}
},
RecursiveCodeGenerator("ClassPrivateStaticSetterGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName) ||
b.currentClassDefinition.privateStaticSetters.contains(propertyName)
b.currentClassDefinition.addPrivateStaticSetter(for: propertyName) { this, v in
b.buildRecursive()
}
},
CodeGenerator("ClassPrivateInstancePropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a private field that hasn't already been added to this literal.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName)
var value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addPrivateInstanceProperty(propertyName, value: value)
},
RecursiveCodeGenerator("ClassPrivateInstanceMethodGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a private field that hasn't already been added to this class.
var methodName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomCustomMethodName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(methodName)
b.currentClassDefinition.addPrivateInstanceMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
CodeGenerator("ClassPrivateStaticPropertyGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a private field that hasn't already been added to this literal.
var propertyName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
propertyName = b.randomCustomPropertyName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(propertyName)
var value = probability(0.5) ? b.randomVariable() : nil
b.currentClassDefinition.addPrivateStaticProperty(propertyName, value: value)
},
RecursiveCodeGenerator("ClassPrivateStaticMethodGenerator", inContext: .classDefinition) { b in
assert(b.context.contains(.classDefinition) && !b.context.contains(.javascript))
// Try to find a private field that hasn't already been added to this class.
var methodName: String
var attempts = 0
repeat {
guard attempts < 10 else { return }
methodName = b.randomCustomMethodName()
attempts += 1
} while b.currentClassDefinition.privateFields.contains(methodName)
b.currentClassDefinition.addPrivateStaticMethod(methodName, with: b.randomParameters()) { args in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
},
CodeGenerator("ArrayWithSpreadGenerator") { b in
var initialValues = [Variable]()
for _ in 0..<Int.random(in: 0...5) {
initialValues.append(b.randomVariable())
}
// Pick some random inputs to spread.
let spreads = initialValues.map({ el in
probability(0.75) && b.type(of: el).Is(.iterable)
})
b.createArray(with: initialValues, spreading: spreads)
},
CodeGenerator("TemplateStringGenerator") { b in
var interpolatedValues = [Variable]()
for _ in 1..<Int.random(in: 1...5) {
interpolatedValues.append(b.randomVariable())
}
var parts = [String]()
for _ in 0...interpolatedValues.count {
// For now we generate random strings
parts.append(b.randomString())
}
b.createTemplateString(from: parts, interpolating: interpolatedValues)
},
CodeGenerator("StringNormalizeGenerator") { b in
let form = b.loadString(
chooseUniform(
from: ["NFC", "NFD", "NFKC", "NFKD"]
)
)
let string = b.loadString(b.randomString())
b.callMethod("normalize", on: string, withArgs: [form])
},
// We don't treat this as a ValueGenerator since it doesn't create a new value, it only accesses an existing one.
CodeGenerator("BuiltinGenerator") { b in
b.loadBuiltin(b.randomBuiltin())
},
CodeGenerator("BuiltinOverwriteGenerator", inputs: .one) { b, value in
b.storeNamedVariable(b.randomBuiltin(), value)
},
RecursiveCodeGenerator("PlainFunctionGenerator") { b in
let f = b.buildPlainFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
},
RecursiveCodeGenerator("ArrowFunctionGenerator") { b in
b.buildArrowFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
b.doReturn(b.randomVariable())
}
// These are "typically" used as arguments, so we don't directly generate a call operation here.
},
RecursiveCodeGenerator("GeneratorFunctionGenerator") { b in
let f = b.buildGeneratorFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
if probability(0.5) {
b.yield(b.randomVariable())
} else {
let randomVariables = b.randomVariables(n: Int.random(in: 1...5))
let array = b.createArray(with: randomVariables)
b.yieldEach(array)
}
b.doReturn(b.randomVariable())
}
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
},
RecursiveCodeGenerator("AsyncFunctionGenerator") { b in
let f = b.buildAsyncFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
b.await(b.randomVariable())
b.doReturn(b.randomVariable())
}
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
},
RecursiveCodeGenerator("AsyncArrowFunctionGenerator") { b in
b.buildAsyncArrowFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
b.await(b.randomVariable())
b.doReturn(b.randomVariable())
}
// These are "typically" used as arguments, so we don't directly generate a call operation here.
},
RecursiveCodeGenerator("AsyncGeneratorFunctionGenerator") { b in
let f = b.buildAsyncGeneratorFunction(with: b.randomParameters(), isStrict: probability(0.1)) { _ in
b.buildRecursive()
b.await(b.randomVariable())
if probability(0.5) {
b.yield(b.randomVariable())
} else {
let randomVariables = b.randomVariables(n: Int.random(in: 1...5))
let array = b.createArray(with: randomVariables)
b.yieldEach(array)
}
b.doReturn(b.randomVariable())
}
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
},
CodeGenerator("PropertyRetrievalGenerator", inputs: .preferred(.object())) { b, obj in
let propertyName = b.type(of: obj).randomProperty() ?? b.randomCustomPropertyName()
let needGuard = b.type(of: obj).MayBe(.nullish)
b.getProperty(propertyName, of: obj, guard: needGuard)
},
CodeGenerator("PropertyAssignmentGenerator", inputs: .preferred(.object())) { b, obj in
let propertyName: String
// Either change an existing property or define a new one
if probability(0.5) {
propertyName = b.type(of: obj).randomProperty() ?? b.randomCustomPropertyName()
} else {
propertyName = b.randomCustomPropertyName()
}
// If this is an existing property with a specific type, try to find a variable with a matching type.
var propertyType = b.type(ofProperty: propertyName, on: obj)
assert(propertyType == .anything || b.type(of: obj).properties.contains(propertyName))
let value = b.randomVariable(forUseAs: propertyType)
// TODO: (here and below) maybe wrap in try catch if obj may be nullish?
b.setProperty(propertyName, of: obj, to: value)
},
CodeGenerator("PropertyUpdateGenerator", inputs: .preferred(.object())) { b, obj in
let propertyName: String
// Change an existing property
propertyName = b.type(of: obj).randomProperty() ?? b.randomCustomPropertyName()
// TODO: for now we simply look for numbers, since those probably make the most sense for binary operations. But we may also want BigInts or strings sometimes.
let rhs = b.randomVariable(forUseAs: .number)
b.updateProperty(propertyName, of: obj, with: rhs, using: chooseUniform(from: BinaryOperator.allCases))
},
CodeGenerator("PropertyRemovalGenerator", inputs: .preferred(.object())) { b, obj in
let propertyName = b.type(of: obj).randomProperty() ?? b.randomCustomPropertyName()
let needGuard = b.type(of: obj).MayBe(.nullish)
b.deleteProperty(propertyName, of: obj, guard: true)
},
CodeGenerator("PropertyConfigurationGenerator", inputs: .preferred(.object())) { b, obj in
let propertyName: String
// Either change an existing property or define a new one
if probability(0.25) {
propertyName = b.type(of: obj).randomProperty() ?? b.randomCustomPropertyName()
} else {
propertyName = b.randomCustomPropertyName()
}
// Getter/Setters must be functions or else a runtime exception will be raised.
withEqualProbability({
b.configureProperty(propertyName, of: obj, usingFlags: PropertyFlags.random(), as: .value(b.randomVariable()))
}, {
guard let getterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureProperty(propertyName, of: obj, usingFlags: PropertyFlags.random(), as: .getter(getterFunc))
}, {
guard let setterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureProperty(propertyName, of: obj, usingFlags: PropertyFlags.random(), as: .setter(setterFunc))
}, {
guard let getterFunc = b.randomVariable(ofType: .function()) else { return }
guard let setterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureProperty(propertyName, of: obj, usingFlags: PropertyFlags.random(), as: .getterSetter(getterFunc, setterFunc))
})
},
CodeGenerator("ElementRetrievalGenerator", inputs: .preferred(.object())) { b, obj in
let index = b.randomIndex()
let needGuard = b.type(of: obj).MayBe(.nullish)
b.getElement(index, of: obj, guard: needGuard)
},
CodeGenerator("ElementAssignmentGenerator", inputs: .preferred(.object())) { b, obj in
let index = b.randomIndex()
let value = b.randomVariable()
b.setElement(index, of: obj, to: value)
},
CodeGenerator("ElementUpdateGenerator", inputs: .preferred(.object())) { b, obj in
let index = b.randomIndex()
// TODO: for now we simply look for numbers, since those probably make the most sense for binary operations. But we may also want BigInts or strings sometimes.
let rhs = b.randomVariable(forUseAs: .number)
b.updateElement(index, of: obj, with: rhs, using: chooseUniform(from: BinaryOperator.allCases))
},
CodeGenerator("ElementRemovalGenerator", inputs: .preferred(.object())) { b, obj in
let index = b.randomIndex()
let needGuard = b.type(of: obj).MayBe(.nullish)
b.deleteElement(index, of: obj, guard: needGuard)
},
CodeGenerator("ElementConfigurationGenerator", inputs: .preferred(.object())) { b, obj in
let index = b.randomIndex()
withEqualProbability({
b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: .value(b.randomVariable()))
}, {
guard let getterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: .getter(getterFunc))
}, {
guard let setterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: .setter(setterFunc))
}, {
guard let getterFunc = b.randomVariable(ofType: .function()) else { return }
guard let setterFunc = b.randomVariable(ofType: .function()) else { return }
b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: .getterSetter(getterFunc, setterFunc))
})
},