-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathCodeGenerators.swift
More file actions
3178 lines (2891 loc) · 128 KB
/
CodeGenerators.swift
File metadata and controls
3178 lines (2891 loc) · 128 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
// 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.
import Foundation
// Generator stubs for disposable and async-disposable object variables.
func disposableObjVariableGeneratorStubs(
inContext contextRequirement : Context,
withSymbol symbolProperty : String,
genDisposableVariable : @escaping (ProgramBuilder, Variable) -> Void) -> [GeneratorStub] {
return [
GeneratorStub(
"DisposableObjectLiteralBeginGenerator",
inContext: .single(contextRequirement),
provides: [.objectLiteral]
) { b in
// Ensure we have the desired symbol below.
let symbol = b.createSymbolProperty(symbolProperty)
b.hide(symbol)
b.runtimeData.push("symbol", symbol)
b.emit(BeginObjectLiteral())
},
GeneratorStub(
"DisposableObjectLiteralComputedMethodBeginGenerator",
inContext: .single(.objectLiteral),
provides: [.javascript, .subroutine, .method]
) { b in
let symbol = b.runtimeData.pop("symbol")
let parameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(parameters.parameterTypes)
b.emit(
BeginObjectLiteralComputedMethod(
parameters: parameters.parameters),
withInputs: [symbol])
},
GeneratorStub(
"DisposableObjectLiteralComputedMethodEndGenerator",
inContext: .single([.javascript, .subroutine, .method]),
provides: [.objectLiteral]
) { b in
b.maybeReturnRandomJsVariable(0.9)
b.emit(EndObjectLiteralComputedMethod())
},
GeneratorStub(
"DisposableObjectLiteralEndGenerator",
inContext: .single(.objectLiteral)
) { b in
let disposableVariable = b.emit(EndObjectLiteral()).output
genDisposableVariable(b, disposableVariable)
},
]
}
// Generator stubs for disposable and async-disposable class variables.
func disposableClassVariableGeneratorStubs(
inContext contextRequirement : Context,
withSymbol symbolProperty : String,
genDisposableVariable : @escaping (ProgramBuilder, Variable) -> Void) -> [GeneratorStub] {
return [
GeneratorStub(
"DisposableClassDefinitionBeginGenerator",
inContext: .single(contextRequirement),
provides: [.classDefinition]
) { b in
// Ensure we have the desired symbol below.
let symbol = b.createSymbolProperty(symbolProperty)
b.hide(symbol)
b.runtimeData.push("symbol", symbol)
// Possibly pick a superclass.
// The superclass must be a constructor (or null).
var superclass: Variable? = nil
if probability(0.5) && b.hasVisibleVariables {
superclass = b.randomVariable(ofType: .constructor())
}
let inputs = superclass != nil ? [superclass!] : []
let cls = b.emit(BeginClassDefinition(
hasSuperclass: superclass != nil,
isExpression: probability(0.3)),
withInputs: inputs).output
b.runtimeData.push("class", cls)
},
GeneratorStub(
"DisposableClassInstanceComputedMethodBeginGenerator",
inContext: .single(.classDefinition),
provides: [.javascript, .subroutine, .method, .classMethod]
) { b in
let symbol = b.runtimeData.pop("symbol")
let parameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(parameters.parameterTypes)
b.emit(
BeginClassInstanceComputedMethod(
parameters: parameters.parameters),
withInputs: [symbol])
},
GeneratorStub(
"DisposableClassInstanceComputedMethodEndGenerator",
inContext: .single([.javascript, .subroutine, .method, .classMethod]),
provides: [.classDefinition]
) { b in
b.maybeReturnRandomJsVariable(0.9)
b.emit(EndClassInstanceComputedMethod())
},
GeneratorStub(
"DisposableClassDefinitionEndGenerator",
inContext: .single(.classDefinition)
) { b in
b.emit(EndClassDefinition())
let cls = b.runtimeData.pop("class")
let disposableVariable = b.construct(
cls, withArgs: b.randomArguments(forCalling: cls))
genDisposableVariable(b, disposableVariable)
},
]
}
//
// 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, i.e. they have a `produces` annotation.
//
// 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.
//
CodeGenerator("IntegerGenerator", produces: [.integer]) { b in
b.loadInt(b.randomInt())
},
CodeGenerator("BigIntGenerator", produces: [.bigint]) { b in
b.loadBigInt(b.randomInt())
},
CodeGenerator("FloatGenerator", produces: [.float]) { b in
b.loadFloat(b.randomFloat())
},
CodeGenerator("StringGenerator", produces: [.string]) { b in
b.loadString(b.randomString())
},
CodeGenerator("ConcatenatedStringGenerator", inputs: .required(.string), produces: [.string]) { b, inputString in
// Emit a dynamically concatenated string, e.g. something like:
// let select = someVar ? "string a" : "string b";
// let result = select + "other string";
let selectLhs = inputString
let selectRhs = b.randomVariable(ofType: .string)!
let cond = b.randomJsVariable()
let select = b.ternary(cond, selectLhs, selectRhs)
let other = b.randomVariable(ofType: .string)!
if Bool.random() {
b.binary(select, other, with: .Add)
} else {
b.binary(other, select, with: .Add)
}
},
CodeGenerator("BooleanGenerator", produces: [.boolean]) { b in
// It's probably not too useful to generate multiple boolean values here.
b.loadBool(Bool.random())
},
CodeGenerator("UndefinedGenerator", produces: [.undefined]) { b in
// There is only one 'undefined' value, so don't generate it multiple times.
b.loadUndefined()
},
CodeGenerator("NullGenerator", produces: [.undefined]) { b in
// There is only one 'null' value, so don't generate it multiple times.
b.loadNull()
},
CodeGenerator("ArrayGenerator", produces: [.jsArray]) { b in
// If we can only generate empty arrays, then only create one such array.
if !b.hasVisibleVariables {
b.createArray(with: [])
} else {
let initialValues = (0..<Int.random(in: 1...5)).map({ _ in
b.randomJsVariable()
})
b.createArray(with: initialValues)
}
},
CodeGenerator("IntArrayGenerator", produces: [.jsArray]) { b in
let values = (0..<Int.random(in: 1...10)).map({ _ in b.randomInt() })
b.createIntArray(with: values)
},
CodeGenerator("FloatArrayGenerator", produces: [.jsArray]) { b in
let values = (0..<Int.random(in: 1...10)).map({ _ in b.randomFloat() })
b.createFloatArray(with: values)
},
CodeGenerator("HoleyArrayGenerator", inputs: .one, produces: [.jsArray]) { b, _ in
let undefined = b.loadUndefined()
// Hide 'undefined' so it is for sure inlined, allowing the lifter to produce holes [,,].
// NOTE: undefineds are lifted to holes
b.hide(undefined)
var size = Int.random(in: 1...7)
var elements = [Variable]()
// Randomly select the type of elements to surround the holes with.
let getElementOptions : [() -> Variable] = [
// Holey Smi (in most cases)
{b.randomVariable(ofType: .integer) ?? b.loadInt(b.randomInt())},
// Holey Double
{b.randomVariable(ofType: .float) ?? b.loadFloat(b.randomFloat())},
// Holey Elements
{b.randomJsVariable()}
]
let getElement = getElementOptions.randomElement()!
let guaranteeHole = Int.random(in: 0..<size) // One element is always a hole.
for i in 0..<size {
elements.append((probability(0.8) || i == guaranteeHole)
? undefined : getElement() )
}
let array = b.createArray(with: elements)
// 50% chance to access a random element, increasing the chance of hole usage.
if probability(0.5) {
b.getElement(Int64.random(in: 0..<Int64(size)), of: array)
}
},
CodeGenerator("ObjectIntegrityLevelGenerator", inputs: .one) { b, obj in
let Object = b.createNamedVariable(forBuiltin: "Object")
b.hide(Object)
let transitionMethod = chooseUniform(from: ["seal", "freeze", "preventExtensions"])
b.callMethod(transitionMethod, on: Object, withArgs: [obj])
},
CodeGenerator("BuiltinObjectInstanceGenerator", produces: [.object()]) {
b in
let builtin = chooseUniform(from: [
"Array", "Map", "WeakMap", "Set", "WeakSet", "Date",
])
let constructor = b.createNamedVariable(forBuiltin: 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)
}
},
CodeGenerator("BuiltinObjectPrototypeCallGenerator") { b in
// TODO: It would be nice to type more prototypes and extend this list.
let builtinName = chooseUniform(from: [
"Promise", "Date", "Array", "ArrayBuffer", "SharedArrayBuffer", "String"])
let builtin = b.createNamedVariable(forBuiltin: builtinName)
let prototype = b.getProperty("prototype", of: builtin)
let prototypeType = b.type(of: prototype)
let choiceCount = prototypeType.numProperties + prototypeType.numMethods
guard choiceCount != 0 else {
fatalError("\(builtinName).prototype has no known properties or methods (type: \(prototypeType))")
}
let useProperty = Int.random(in: 0..<choiceCount) < prototypeType.numProperties
let fctName = (useProperty ? prototypeType.properties : prototypeType.methods).randomElement()!
let fct = b.getProperty(fctName, of: prototype)
let fctType = b.type(of: fct)
let (arguments, matches) = b.randomArguments(forCallingGuardableFunction: fct)
let receiverType = fctType.receiver ?? prototypeType
let desiredReceiverType = fctType.receiver ?? prototypeType
let receiver = b.randomVariable(forUseAs: desiredReceiverType)
let needGuard = (!fctType.Is(.function()) && !fctType.Is(.unboundFunction()))
|| !b.type(of: receiver).Is(receiverType) || !matches
if Bool.random() {
b.callMethod("call", on: fct, withArgs: [receiver] + arguments, guard: needGuard)
} else {
b.callMethod("apply", on: fct, withArgs: [receiver, b.createArray(with: arguments)], guard: needGuard)
}
},
CodeGenerator("BuiltinTemporalGenerator") { b in
let _ = chooseUniform(from: [b.constructTemporalInstant, b.constructTemporalDuration,
b.constructTemporalTime, b.constructTemporalYearMonth, b.constructTemporalMonthDay,
b.constructTemporalDate, b.constructTemporalDateTime, b.constructTemporalZonedDateTime])()
},
CodeGenerator("TypedArrayGenerator", produces: [.object()]) { b in
let size = b.loadInt(b.randomSize(upTo: 0x1000))
let constructor = b.createNamedVariable(
forBuiltin: chooseUniform(
from: [
"Uint8Array", "Int8Array", "Uint16Array", "Int16Array",
"Uint32Array", "Int32Array", "Float32Array", "Float64Array",
"Uint8ClampedArray", "BigInt64Array", "BigUint64Array",
]
)
)
b.construct(constructor, withArgs: [size])
},
CodeGenerator("TypedArrayFromBufferGenerator",
inContext: .single(.javascript),
inputs: .required(.jsArrayBuffer | .jsSharedArrayBuffer)
) { b, buffer in
let constructor = b.createNamedVariable(
forBuiltin: chooseUniform(
from: JavaScriptEnvironment.typedArrayConstructors
)
)
b.construct(constructor, withArgs: [buffer])
// TODO(tacet): add Fixed length view. withArgs: [buffer, offset, length]
},
CodeGenerator("DataViewFromBufferGenerator",
inContext: .single(.javascript),
inputs: .required(.jsArrayBuffer | .jsSharedArrayBuffer),
produces: [.jsDataView]
) { b, buffer in
let constructor = b.createNamedVariable(forBuiltin: "DataView")
b.construct(constructor, withArgs: [buffer])
// TODO(tacet): add Fixed length view. withArgs: [buffer, offset, length]
},
CodeGenerator("TypedArrayLastIndexGenerator",
inContext: .single(.javascript),
inputs: .required(.object(withProperties: ["buffer", "length"]))
) { b, view in
let len = b.getProperty("length", of: view)
let index = b.binary(len, b.loadInt(1), with: .Sub)
b.getComputedProperty(index, of: view)
},
CodeGenerator("BuiltinIntlGenerator") { b in
let _ = chooseUniform(from: [
b.constructIntlDateTimeFormat,
b.constructIntlCollator,
b.constructIntlListFormat,
b.constructIntlLocale,
b.constructIntlNumberFormat,
b.constructIntlPluralRules,
b.constructIntlRelativeTimeFormat,
b.constructIntlSegmenter,
b.constructIntlDisplayNames,
{ // Fuzz Intl.DisplayNames.prototype.of()
let intl = b.createNamedVariable(forBuiltin: "Intl")
let ctor = b.getProperty("DisplayNames", of: intl)
let types =
b.fuzzer.environment.getEnum(ofName: "IntlDisplayNamesTypeEnum")!.enumValues
let type = types.randomElement()!
let locale = b.loadString(ProgramBuilder.constructIntlLocaleString())
let options = b.createOptionsBag(.jsIntlDisplayNamesSettings,
predefined: ["type": b.loadString(type)])
b.construct(ctor, withArgs: [locale, options])
let code = switch type {
case "language":
ProgramBuilder.constructIntlLanguageString()
case "region":
ProgramBuilder.constructIntlRegionString()
case "script":
ProgramBuilder.constructIntlScriptString()
case "currency":
Locale.commonISOCurrencyCodes.randomElement()!
case "calendar":
b.fuzzer.environment.getEnum(ofName: "temporalCalendar")!.enumValues
.randomElement()!
case "dateTimeField":
["era", "year", "quarter", "month", "weekOfYear", "weekday", "day",
"dayPeriod", "hour", "minute", "second", "timeZoneName"].randomElement()!
default:
String.random(ofLength: 4)
}
return b.callMethod("of", on: ctor, withArgs: [b.loadString(code)])
}
])()
},
CodeGenerator("HexGenerator") { b in
let hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]
let uint8ArrayBuiltin = b.createNamedVariable(forBuiltin: "Uint8Array")
withEqualProbability({
// Generate Uint8Array construction from hex string.
var s = ""
for _ in 0..<Int.random(in: 1...40) {
s += chooseUniform(from: hexValues)
s += chooseUniform(from: hexValues)
}
let hex = b.loadString(s)
if probability(0.5) {
b.callMethod("fromHex", on: uint8ArrayBuiltin, withArgs: [hex])
} else {
let target = b.construct(uint8ArrayBuiltin, withArgs: [b.loadInt(Int64.random(in: 0...0x100))])
b.callMethod("setFromHex", on: target, withArgs: [hex])
}
}, {
// Generate hex String construction from Uint8Array.
let values = (0..<Int.random(in: 1...20)).map {_ in b.loadInt(Int64.random(in: 0...0xFF))}
let bytes = b.callMethod("of", on: uint8ArrayBuiltin, withArgs: values)
b.callMethod("toHex", on: bytes, withArgs: [])
}
)
},
CodeGenerator("Base64Generator") { b in
let base64Alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"]
let base64URLAlphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_"]
let uint8ArrayBuiltin = b.createNamedVariable(forBuiltin: "Uint8Array")
withEqualProbability({
var options = [String: Variable]()
let alphabet = chooseUniform(from: [base64Alphabet, base64URLAlphabet])
options["alphabet"] = b.loadString((alphabet == base64Alphabet) ? "base64" : "base64url")
options["lastChunkHandling"] = b.loadString(
chooseUniform(
from: ["loose", "strict", "stop-before-partial"]
)
)
var s = ""
for _ in 0..<Int.random(in: 1...32) * 4 {
s += chooseUniform(from: alphabet)
}
// Extend by 0, 1, or 2 bytes.
switch (Int.random(in: 0...3)) {
case 1:
s += base64Alphabet[Int.random(in: 0...63)]
s += base64Alphabet[Int.random(in: 0...63) & 0x30]
s += "=="
break
case 2:
s += base64Alphabet[Int.random(in: 0...63)]
s += base64Alphabet[Int.random(in: 0...63)]
s += base64Alphabet[Int.random(in: 0...63) & 0x3C]
s += "="
break
default:
break
}
let base64 = b.loadString(s)
let optionsObject = b.createObject(with: options)
if probability(0.5) {
b.callMethod("fromBase64", on: uint8ArrayBuiltin, withArgs: [base64, optionsObject])
} else {
let target = b.construct(uint8ArrayBuiltin, withArgs: [b.loadInt(Int64.random(in: 0...0x100))])
b.callMethod("setFromBase64", on: target, withArgs: [base64, optionsObject])
}
}, {
let values = (0..<Int.random(in: 1...64)).map {_ in b.loadInt(Int64.random(in: 0...0xFF))}
let bytes = b.callMethod("of", on: uint8ArrayBuiltin, withArgs: values)
b.callMethod("toBase64", on: bytes, withArgs: [])
}
)
},
CodeGenerator("RegExpGenerator", produces: [.jsRegExp]) { b in
let (regexpPattern, flags) = b.randomRegExpPatternAndFlags()
b.loadRegExp(regexpPattern, flags)
},
// TODO(cffsmith): If we had a way to pass variables to elements of a list of CodeGenerators, we could pass the `o` and the `f` variables.
// We can pass the `f` variable right now with the `b.lastFunctionVariable` but we cannot pass `o`.
CodeGenerator("ObjectBuilderFunctionGenerator") {
b 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(n: Int.random(in: 0...10))
}
objType = b.type(of: o)
b.doReturn(o)
}
assert(b.type(of: f).signature != nil)
assert(b.type(of: f).signature!.outputType.Is(objType))
for _ in 0..<Int.random(in: 5...10) {
b.callFunction(f, withArgs: b.randomArguments(forCalling: f))
}
},
CodeGenerator("ObjectConstructorGenerator", produces: [.constructor()]) {
b 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.randomJsVariable() : 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..<Int.random(in: 1...4) {
b.construct(c, withArgs: b.randomArguments(forCalling: c))
}
},
CodeGenerator(
"ClassDefinitionGenerator",
[
GeneratorStub(
"ClassDefinitionBeginGenerator",
produces: [.constructor()],
provides: [.classDefinition]
) { b in
// Possibly pick a superclass.
// The superclass must be a constructor (or null).
var superclass: Variable? = nil
if probability(0.4) && b.hasVisibleVariables {
superclass = b.randomVariable(ofType: .constructor())
} else if probability(0.2) {
superclass = b.buildPlainFunction(with: .parameters(n: 1)) {
args in
b.doReturn(b.randomJsVariable())
}
}
let inputs = superclass != nil ? [superclass!] : []
let cls = b.emit(BeginClassDefinition(
hasSuperclass: superclass != nil,
isExpression: probability(0.3)),
withInputs: inputs).output
b.runtimeData.push("class", cls)
},
GeneratorStub(
"ClassDefinitionEndGenerator",
inContext: .single(.classDefinition)
) { b in
b.emit(EndClassDefinition())
// Construct a few instances of the class.
let cls = b.runtimeData.pop("class")
for _ in 0..<Int.random(in: 0...4) {
b.construct(cls, withArgs: b.randomArguments(forCalling: cls))
}
},
]
),
CodeGenerator("TrivialFunctionGenerator", produces: [.function()]) { b 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.randomJsVariable() : nil
b.buildPlainFunction(with: .parameters(n: 0)) { _ in
if let returnValue = maybeReturnValue {
b.doReturn(returnValue)
}
}
},
CodeGenerator("TimeZoneIdGenerator") { b in
if Bool.random() {
b.randomTimeZone()
} else {
b.randomUTCOffset(mayHaveSeconds: true)
}
},
//
// "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: .single(.subroutine)) { b in
b.loadArguments()
},
CodeGenerator("FunctionWithArgumentsAccessGenerator", [
GeneratorStub("FunctionWithArgumentsAccessBeginGenerator",
provides: [.subroutine, .javascript]) { b in
let randomParameters = probability(0.5) ? .parameters(n: 0) : b.randomParameters()
b.setParameterTypesForNextSubroutine(
randomParameters.parameterTypes)
let f = b.emit(
BeginPlainFunction(parameters: randomParameters.parameters, functionName: nil)).output
b.runtimeData.push("functionArgsAccess", f)
b.loadArguments()
},
GeneratorStub("FunctionWithArgumentsAccessEndGenerator", inContext: .single([.javascript, .subroutine])) { b in
// Ideally we would like to return the arguments Variable from above here.
b.doReturn(b.randomJsVariable())
b.emit(EndPlainFunction())
let f = b.runtimeData.pop("functionArgsAccess")
let args = b.randomJsVariables(n: Int.random(in: 0...5))
b.callFunction(f, withArgs: args)
},
]),
CodeGenerator(
"DisposableObjVariableGenerator",
disposableObjVariableGeneratorStubs(
inContext: .subroutine,
withSymbol: "dispose") { b, variable in
b.loadDisposableVariable(variable)
}),
CodeGenerator(
"AsyncDisposableObjVariableGenerator",
disposableObjVariableGeneratorStubs(
inContext: .asyncFunction,
withSymbol: "asyncDispose") { b, variable in
b.loadAsyncDisposableVariable(variable)
}),
CodeGenerator(
"DisposableClassVariableGenerator",
disposableClassVariableGeneratorStubs(
inContext: .subroutine,
withSymbol: "dispose") { b, variable in
b.loadDisposableVariable(variable)
}),
CodeGenerator(
"AsyncDisposableClassVariableGenerator",
disposableClassVariableGeneratorStubs(
inContext: .asyncFunction,
withSymbol: "asyncDispose") { b, variable in
b.loadAsyncDisposableVariable(variable)
}),
CodeGenerator(
"ObjectLiteralGenerator",
[
GeneratorStub(
"ObjectLiteralBeginGenerator", provides: [.objectLiteral]
) { b in
b.emit(BeginObjectLiteral())
},
GeneratorStub(
"ObjectLiteralEndGenerator", inContext: .single(.objectLiteral)
) { b in
b.emit(EndObjectLiteral())
},
]),
CodeGenerator("ObjectLiteralPropertyGenerator", inContext: .single(.objectLiteral)) {
b in
// Try to find a property that hasn't already been added to this literal.
let propertyName = b.generateString(b.randomCustomPropertyName,
notIn: b.currentObjectLiteral.properties)
b.currentObjectLiteral.addProperty(
propertyName, as: b.randomJsVariable())
},
CodeGenerator(
"ObjectLiteralElementGenerator", inContext: .single(.objectLiteral), inputs: .one
) { b, value in
// 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: .single(.objectLiteral),
inputs: .one
) { b, value in
// Try to find a computed property that hasn't already been added to this literal.
var propertyName: Variable
var attempts = 0
repeat {
if attempts >= 10 {
// Could not find anything.
// Since this CodeGenerator does not produce anything it is fine to bail.
return
}
propertyName = b.randomJsVariable()
attempts += 1
} while b.currentObjectLiteral.computedProperties.contains(propertyName)
b.currentObjectLiteral.addComputedProperty(propertyName, as: value)
},
CodeGenerator(
"ObjectLiteralCopyPropertiesGenerator", inContext: .single(.objectLiteral),
inputs: .preferred(.object())
) { b, object in
b.currentObjectLiteral.copyProperties(from: object)
},
CodeGenerator("ObjectLiteralPrototypeGenerator", inContext: .single(.objectLiteral))
{ b in
// 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)
},
CodeGenerator(
"ObjectLiteralMethodGenerator",
[
GeneratorStub(
"ObjectLiteralMethodBeginGenerator", inContext: .single(.objectLiteral),
provides: [.javascript, .subroutine, .method]
) { b in
// Try to find a method that hasn't already been added to this literal.
let methodName = b.generateString(b.randomCustomMethodName,
notIn: b.currentObjectLiteral.methods)
let randomParameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(
randomParameters.parameterTypes)
b.emit(
BeginObjectLiteralMethod(
methodName: methodName,
parameters: randomParameters.parameters))
},
GeneratorStub("ObjectLiteralMethodEndGenerator", inContext: .single([.javascript, .subroutine, .method])) { b in
b.emit(EndObjectLiteralMethod())
},
]),
CodeGenerator(
"ObjectLiteralComputedMethodGenerator",
[
GeneratorStub(
"ObjectLiteralComputedMethodBeginGenerator",
inContext: .single(.objectLiteral),
provides: [.javascript, .subroutine, .method]
) { b in
// Try to find a computed method name that hasn't already been added to this literal.
var methodName: Variable
var attempts = 0
repeat {
methodName = b.randomJsVariable()
if attempts >= 10 {
// This might lead to having two computed methods with the same name (so one
// will overwrite the other).
break
}
attempts += 1
} while b.currentObjectLiteral.computedMethods.contains(
methodName)
let parameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(parameters.parameterTypes)
b.emit(
BeginObjectLiteralComputedMethod(
parameters: parameters.parameters),
withInputs: [methodName])
},
GeneratorStub(
"ObjectLiteralComputedMethodEndGenerator",
inContext: .single([.javascript, .subroutine, .method]),
inputs: .one
) { b, inp in
b.doReturn(inp)
b.emit(EndObjectLiteralComputedMethod())
},
]),
CodeGenerator(
"ObjectLiteralGetterGenerator",
[
GeneratorStub(
"ObjectLiteralGetterBeginGenerator",
inContext: .single(.objectLiteral),
provides: [.javascript, .subroutine, .method]
) { b in
// Try to find a property that hasn't already been added and for which a getter has not yet been installed.
let propertyName = b.generateString(b.randomCustomPropertyName,
notIn: b.currentObjectLiteral.properties + b.currentObjectLiteral.getters)
b.emit(BeginObjectLiteralGetter(propertyName: propertyName))
},
GeneratorStub(
"ObjectLiteralGetterEndGenerator",
inContext: .single([.javascript, .subroutine, .method]),
inputs: .one
) { b, inp in
b.doReturn(inp)
b.emit(EndObjectLiteralGetter())
},
]),
CodeGenerator(
"ObjectLiteralSetterGenerator",
[
GeneratorStub(
"ObjectLiteralSetterBeginGenerator",
inContext: .single(.objectLiteral),
provides: [.javascript, .subroutine, .method]
) { b in
// Try to find a property that hasn't already been added and for which a setter has not yet been installed.
let propertyName = b.generateString(b.randomCustomPropertyName,
notIn: b.currentObjectLiteral.properties + b.currentObjectLiteral.setters)
b.emit(BeginObjectLiteralSetter(propertyName: propertyName))
},
GeneratorStub(
"ObjectLiteralSetterEndGenerator",
inContext: .single([.javascript, .subroutine, .method])
) { b in
b.emit(EndObjectLiteralSetter())
},
]),
CodeGenerator(
"ClassConstructorGenerator",
[
GeneratorStub(
"ClassConstructorBeginGenerator",
inContext: .single(.classDefinition),
provides: []
) { b in
guard !b.currentClassDefinition.hasConstructor else {
// There must only be one constructor
// If we bail here, we are *not* in .javaScript context so we cannot provide it here for other chains.
return
}
let randomParameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(
randomParameters.parameterTypes)
let args = b.emit(
BeginClassConstructor(
parameters: randomParameters.parameters)
).innerOutputs
if randomParameters.parameters.hasRestParameter && probability(0.2) {
b.getProperty("length", of: args.last!)
}
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)
}
},
GeneratorStub(
"ClassConstructorEndGenerator",
// This can run in either context and will do different things
// depending on if the previous generator succeeded.
inContext: .either([.javascript, .classDefinition])
) { b in
if b.context.contains(.javascript) {
b.emit(EndClassConstructor())
}
},
]),
CodeGenerator("ClassInstancePropertyGenerator", inContext: .single(.classDefinition))
{ b in
// Try to find a property that hasn't already been added to this literal.
let propertyName = b.generateString(b.randomCustomPropertyName,
notIn: b.currentClassDefinition.instanceProperties)
var value: Variable? = probability(0.5) ? b.randomJsVariable() : nil
b.currentClassDefinition.addInstanceProperty(propertyName, value: value)
},
CodeGenerator("ClassInstanceElementGenerator", inContext: .single(.classDefinition))
{ b in
// 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.randomJsVariable() : nil
b.currentClassDefinition.addInstanceElement(index, value: value)
},
CodeGenerator(
"ClassInstanceComputedPropertyGenerator", inContext: .single(.classDefinition)
) { b in
// 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.randomJsVariable()
attempts += 1
} while b.currentClassDefinition.instanceComputedProperties.contains(
propertyName)
let value = probability(0.5) ? b.randomJsVariable() : nil
b.currentClassDefinition.addInstanceComputedProperty(
propertyName, value: value)
},
CodeGenerator(
"ClassInstanceMethodGenerator",
[
GeneratorStub(
"ClassInstanceMethodBeginGenerator",
inContext: .single(.classDefinition),
provides: [.javascript, .subroutine, .method, .classMethod]
) { b in
// Try to find a method that hasn't already been added to this class.
let methodName = b.generateString(b.randomCustomMethodName,
notIn: b.currentClassDefinition.instanceMethods)
let parameters = b.randomParameters()
b.setParameterTypesForNextSubroutine(parameters.parameterTypes)
b.emit(
BeginClassInstanceMethod(
methodName: methodName,