forked from c-cube/qcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQCheck.ml
More file actions
2019 lines (1695 loc) · 65.5 KB
/
QCheck.ml
File metadata and controls
2019 lines (1695 loc) · 65.5 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
(*
QCheck: Random testing for OCaml
copyright (c) 2013-2017, Guillaume Bury, Simon Cruanes, Vincent Hugot, Jan Midtgaard
all rights reserved.
*)
(** {1 Quickcheck inspired property-based testing} *)
let poly_compare=compare
module RS = struct
(* Poor man's splitter for version < 5.0 *)
(* This definition is shadowed by the [include] on OCaml >=5.0 *)
(* For the record, this is a hack:
Seeding a child RNG based on the output of a parent RNG
does not create an independent RNG. As an added bonus,
performance is bad. *)
let split rs =
let bits = Random.State.bits rs in
let rs' = Random.State.make [|bits|] in
rs'
include Random.State
(* This is how OCaml 5.0 splits: *)
(* Split a new PRNG off the given PRNG *)
(*
let split s =
let i1 = bits64 s in let i2 = bits64 s in
let i3 = bits64 s in let i4 = bits64 s in
mk i1 i2 i3 i4
*)
end
let (|>) x f = f x
let rec foldn ~f ~init:acc i =
if i = 0 then acc else foldn ~f ~init:(f acc i) (i-1)
let _is_some = function Some _ -> true | None -> false
let _opt_map_or ~d ~f = function
| None -> d
| Some x -> f x
let _opt_or a b = match a with
| None -> b
| Some x -> x
let _opt_map ~f = function
| None -> None
| Some x -> Some (f x)
let _opt_map_2 ~f a b = match a, b with
| Some x, Some y -> Some (f x y)
| _ -> None
let _opt_map_3 ~f a b c = match a, b, c with
| Some x, Some y, Some z -> Some (f x y z)
| _ -> None
let _opt_map_4 ~f a b c d = match a, b, c, d with
| Some x, Some y, Some z, Some w -> Some (f x y z w)
| _ -> None
let _opt_map_5 ~f a b c d e = match a, b, c, d, e with
| Some x, Some y, Some z, Some u, Some v -> Some (f x y z u v)
| _ -> None
let _opt_map_6 ~f a b c d e g = match a, b, c, d, e, g with
| Some a, Some b, Some c, Some d, Some e, Some g -> Some (f a b c d e g)
| _ -> None
let _opt_map_7 ~f a b c d e g h = match a, b, c, d, e, g, h with
| Some a, Some b, Some c, Some d, Some e, Some g, Some h -> Some (f a b c d e g h)
| _ -> None
let _opt_map_8 ~f a b c d e g h i = match a, b, c, d, e, g, h, i with
| Some a, Some b, Some c, Some d, Some e, Some g, Some h, Some i ->
Some (f a b c d e g h i)
| _ -> None
let _opt_map_9 ~f a b c d e g h i j = match a, b, c, d, e, g, h, i, j with
| Some a, Some b, Some c, Some d, Some e, Some g, Some h, Some i, Some j ->
Some (f a b c d e g h i j)
| _ -> None
let _opt_sum a b = match a, b with
| Some _, _ -> a
| None, _ -> b
let sum_int = List.fold_left (+) 0
(* Included for backwards compatibility, pre 4.13 *)
let string_fold_right f s acc =
let len = String.length s in
let rec loop i acc =
if i<0
then acc
else loop (i-1) (f s.[i] acc) in
loop (len-1) acc
let cut_exp_zero s =
match String.split_on_char 'e' s with
| [signif;exponent] ->
(match exponent.[0] with (* int_of_string removes a leading '0' *)
| '+' -> Printf.sprintf "%se+%i" signif (int_of_string exponent) (* keep a leading '+' *)
| _ -> Printf.sprintf "%se%i" signif (int_of_string exponent)) (* keep a leading '-' *)
| _ -> s
exception No_example_found of string
(* raised if an example failed to be found *)
let assume = QCheck2.assume
let assume_fail = QCheck2.assume_fail
let (==>) = QCheck2.(==>)
module Gen = struct
type 'a t = RS.t -> 'a
type 'a sized = int -> Random.State.t -> 'a
let return x _st = x
let pure = return
let bind gen f st = f (gen st) st
let (>>=) = bind
let ap f x st = f st (x st)
let (<*>) = ap
let map f x st = f (x st)
let map2 f x y st = f (x st) (y st)
let map3 f x y z st = f (x st) (y st) (z st)
let map4 f x y z v st = f (x st) (y st) (z st) (v st)
let map5 f x y z v w st = f (x st) (y st) (z st) (v st) (w st)
let map_keep_input f gen st = let x = gen st in x, f x
let (>|=) x f st = f (x st)
let (<$>) f x st = f (x st)
let oneof l st = List.nth l (Random.State.int st (List.length l)) st
let oneofl xs st = List.nth xs (Random.State.int st (List.length xs))
let oneofa xs st = Array.get xs (Random.State.int st (Array.length xs))
let frequencyl l st =
let sums = sum_int (List.map fst l) in
let i = Random.State.int st sums in
let rec aux acc = function
| ((x,g)::xs) -> if i < acc+x then g else aux (acc+x) xs
| _ -> failwith "frequency"
in
aux 0 l
let frequencya a = frequencyl (Array.to_list a)
let frequency l st = frequencyl l st st
let int_pos_small st =
let p = RS.float st 1. in
if p < 0.75 then RS.int st 10 else RS.int st 100
let nat_small = int_pos_small
let small_nat = int_pos_small
(* natural number generator *)
let nat st =
let p = RS.float st 1. in
if p < 0.5 then RS.int st 10
else if p < 0.75 then RS.int st 100
else if p < 0.95 then RS.int st 1_000
else RS.int st 10_000
let int_pos_mid = nat
let big_nat st =
let p = RS.float st 1. in
if p < 0.75 then nat st
else RS.int st 1_000_000
let unit _st = ()
let bool st = RS.bool st
let float st = (* switch to [bits64] once lower bound reaches 4.14 *)
(* Technically we could write [15] but this is clearer *)
let four_bits_mask = 0b1111 in
(* Top 4 bits *)
let left = Int64.(shift_left (of_int (RS.bits st land four_bits_mask)) 60) in
(* Middle 30 bits *)
let middle = Int64.(shift_left (of_int (RS.bits st)) 30) in
(* Bottom 30 bits *)
let right = Int64.of_int (RS.bits st) in
Int64.(float_of_bits (logor left (logor middle right)))
let float_pos st = abs_float (float st)
let float_neg st = -.(float_pos st)
let pfloat = float_pos
let nfloat = float_neg
let float_bound_inclusive bound st = RS.float st bound
let float_bound_exclusive bound st =
match bound with
| 0. -> raise (Invalid_argument "Gen.float_bound_exclusive")
| b_pos when bound > 0. -> RS.float st (b_pos -. epsilon_float)
| b_neg -> RS.float st (b_neg +. epsilon_float)
let float_range low high =
if high < low || high -. low > max_float then invalid_arg "Gen.float_range";
fun st -> low +. (float_bound_inclusive (high -. low) st)
let (--.) = float_range
let float_exp mean =
if Float.is_nan mean then invalid_arg "Gen.float_exp";
let unit_gen = float_bound_inclusive 1.0 in
map (fun p -> -. mean *. (log p)) unit_gen
(* See https://en.wikipedia.org/wiki/Relationships_among_probability_distributions *)
let exponential = float_exp
let neg_int st = -(nat st)
let option ?(ratio = 0.85) f st =
let p = RS.float st 1. in
if p < (1.0 -. ratio) then None
else Some (f st)
let opt = option
let result ?(ratio = 0.75) vg eg st =
let p = RS.float st 1. in
if p < (1.0 -. ratio)
then Error (eg st)
else Ok (vg st)
(* Uniform random int generator *)
let int_pos =
if Sys.word_size = 32 then
fun st -> RS.bits st
else (* word size = 64 *)
fun st ->
(* Technically we could write [3] but this is clearer *)
let two_bits_mask = 0b11 in
(* Top 2 bits *)
let left = ((RS.bits st land two_bits_mask) lsl 60) in
(* Middle 30 bits *)
let middle = (RS.bits st lsl 30) in
(* Bottom 30 bits *)
let right = RS.bits st in
left lor middle lor right
let pint = int_pos
let int_neg st = -(int_pos st)-1
let int st = if RS.bool st then - (int_pos st) - 1 else int_pos st
let int_bound n =
if n < 0 then invalid_arg "Gen.int_bound";
if n <= (1 lsl 30) - 2
then fun st -> Random.State.int st (n + 1)
else fun st -> let r = int_pos st in r mod (n + 1)
let int_range a b =
if b < a then invalid_arg "Gen.int_range";
if a >= 0 || b < 0 then (
(* range smaller than max_int *)
assert (b-a >= 0);
fun st -> a + (int_bound (b-a) st)
) else (
(* range potentially bigger than max_int: we split on 0 and
choose the itv wrt to their size ratio *)
fun st ->
let f_a = float_of_int a in
let ratio = (-.f_a) /. (1. +. float_of_int b -. f_a) in
if Random.State.float st 1. <= ratio then - (int_bound (- (a+1)) st) - 1
else int_bound b st
)
let (--) = int_range
(* NOTE: we keep this alias to not break code that uses [small_int]
for sizes of strings, arrays, etc. *)
let small_int = small_nat
let int_small st =
if bool st
then nat_small st
else - (nat_small st)
let small_signed_int = int_small
let char_range a b = map Char.chr (Char.code a -- Char.code b)
let random_binary_string st length =
(* 0b011101... *)
let s = Bytes.create (length + 2) in
Bytes.set s 0 '0';
Bytes.set s 1 'b';
for i = 0 to length - 1 do
Bytes.set s (i+2) (if RS.bool st then '0' else '1')
done;
Bytes.unsafe_to_string s
let int32 st = Int32.of_string (random_binary_string st 32)
let int64 st = Int64.of_string (random_binary_string st 64)
let ui32 = int32
let ui64 = int64
let list_size size gen st =
foldn ~f:(fun acc _ -> (gen st)::acc) ~init:[] (size st)
let list gen st = list_size nat gen st
let list_repeat n g = list_size (return n) g
let array_size size gen st =
Array.init (size st) (fun _ -> gen st)
let array gen st = array_size nat gen st
let array_repeat n g = array_size (return n) g
let flatten_l l st = List.map (fun f->f st) l
let flatten_a a st = Array.map (fun f->f st) a
let flatten_opt o st =
match o with
| None -> None
| Some f -> Some (f st)
let flatten_res r st =
match r with
| Ok f -> Ok (f st)
| Error e -> Error e
let shuffle_a a st =
for i = Array.length a-1 downto 1 do
let j = Random.State.int st (i+1) in
let tmp = a.(i) in
a.(i) <- a.(j);
a.(j) <- tmp;
done
let shuffle_l l st =
let a = Array.of_list l in
shuffle_a a st;
Array.to_list a
let shuffle_w_l l st =
let sample (w, v) =
let fl_w = float_of_int w in
(float_bound_inclusive 1. st ** (1. /. fl_w), v)
in
let samples = List.rev_map sample l in
List.sort (fun (w1, _) (w2, _) -> poly_compare w1 w2) samples |> List.rev_map snd
let range_subset ~size low high st =
let range_size = high - low + 1 in
if not (0 <= size && size <= range_size) then
invalid_arg "Gen.range_subset";
(* The algorithm below is attributed to Floyd, see for example
https://eyalsch.wordpress.com/2010/04/01/random-sample/
https://math.stackexchange.com/questions/178690
Note: the code is easier to read when drawing from [0..range_size-1]
rather than [low..high]. We draw in [0..bound], and shift the
results by adding [low] when writing them to the result array.
*)
let module ISet = Set.Make(Int) in
let s = ref ISet.empty in
for i = range_size - size to range_size - 1 do
let pos = int_range 0 i st in
let choice = if ISet.mem pos !s then i else pos in
s := ISet.add choice !s;
done;
let arr = Array.make size 0 in
let idx = ref 0 in
ISet.iter (fun choice -> arr.(!idx) <- low + choice; incr idx) !s;
arr
let array_subset size arr st =
range_subset ~size 0 (Array.length arr - 1) st
|> Array.map (fun i -> arr.(i))
let pair g1 g2 st = (g1 st, g2 st)
let triple g1 g2 g3 st = (g1 st, g2 st, g3 st)
let quad g1 g2 g3 g4 st = (g1 st, g2 st, g3 st, g4 st)
let char st = char_of_int (RS.int st 256)
let tup2 = pair
let tup3 = triple
let tup4 = quad
let tup5 (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) (g5 : 'e t) : ('a * 'b * 'c * 'd * 'e) t =
(fun a b c d e -> (a, b, c, d, e)) <$> g1 <*> g2 <*> g3 <*> g4 <*> g5
let tup6 (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) (g5 : 'e t) (g6 : 'f t) : ('a * 'b * 'c * 'd * 'e * 'f) t =
(fun a b c d e f -> (a, b, c, d, e, f)) <$> g1 <*> g2 <*> g3 <*> g4 <*> g5 <*> g6
let tup7 (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) (g5 : 'e t) (g6 : 'f t) (g7 : 'g t) : ('a * 'b * 'c * 'd * 'e * 'f * 'g) t =
(fun a b c d e f g -> (a, b, c, d, e, f, g)) <$> g1 <*> g2 <*> g3 <*> g4 <*> g5 <*> g6 <*> g7
let tup8 (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) (g5 : 'e t) (g6 : 'f t) (g7 : 'g t) (g8 : 'h t) : ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h) t =
(fun a b c d e f g h -> (a, b, c, d, e, f, g, h)) <$> g1 <*> g2 <*> g3 <*> g4 <*> g5 <*> g6 <*> g7 <*> g8
let tup9 (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) (g5 : 'e t) (g6 : 'f t) (g7 : 'g t) (g8 : 'h t) (g9 : 'i t) : ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i) t =
(fun a b c d e f g h i -> (a, b, c, d, e, f, g, h, i)) <$> g1 <*> g2 <*> g3 <*> g4 <*> g5 <*> g6 <*> g7 <*> g8 <*> g9
let printable_chars =
let l = 126-32+1 in
let s = Bytes.create l in
for i = 0 to l-2 do
Bytes.set s i (char_of_int (32+i))
done;
Bytes.set s (l-1) '\n';
Bytes.unsafe_to_string s
let char_printable st = printable_chars.[RS.int st (String.length printable_chars)]
let printable = char_printable
let char_numeral st = char_of_int (48 + RS.int st 10)
let numeral = char_numeral
let bytes_size ?(gen = char) size st =
let s = Bytes.create (size st) in
for i = 0 to Bytes.length s - 1 do
Bytes.set s i (gen st)
done;
s
let bytes_size_of size gen = bytes_size ~gen size
let string_size ?(gen = char) size st =
let s = bytes_size ~gen size st in
Bytes.unsafe_to_string s
let string_size_of size gen = string_size ~gen size
let bytes st = bytes_size nat st
let string st = string_size nat st
let bytes_of gen = bytes_size ~gen nat
let string_of gen = string_size ~gen nat
let bytes_printable = bytes_size ~gen:char_printable nat
let string_printable = string_size ~gen:char_printable nat
let string_readable = string_printable
let bytes_small st = bytes_size nat_small st
let bytes_small_of gen st = bytes_size ~gen nat_small st
let small_string ?gen st = string_size ?gen nat_small st
let list_small gen = list_size nat_small gen
let small_list = list_small
let array_small gen = array_size nat_small gen
let small_array = array_small
let string_small st = string_size nat_small st
let string_small_of gen st = string_size ~gen nat_small st
let join g st = (g st) st
(* corner cases *)
let graft_corners gen corners () =
let cors = ref corners in fun st ->
match !cors with [] -> gen st
| e::l -> cors := l; e
let int_pos_corners = [0;1;2;max_int]
let int_corners = int_pos_corners @ [min_int;-2;-1]
let int_small_corners () = graft_corners int_small int_corners ()
let nng_corners () = graft_corners nat int_pos_corners ()
(* sized, fix *)
let sized_size s f st = f (s st) st
let sized f = sized_size nat f
let fix f =
let rec f' n st = f f' n st in
f'
(* nat splitting *)
let pos_split2 n st =
if (n < 2) then invalid_arg "pos_split2";
let n1 = int_range 1 (n - 1) st in
(n1, n - n1)
let nat_split2 n st =
if (n < 0) then invalid_arg "nat_split2";
let n1 = int_range 0 n st in
(n1, n - n1)
let pos_split ~size:k n st =
if (n < 0) then invalid_arg "pos_split";
if 0 = k && 0 = n then [||]
else begin
if not (0 < k && k <= n) then invalid_arg "pos_split";
(* To split n into n{0}+n{1}+..+n{k-1}, we draw distinct "boundaries"
b{-1}..b{k-1}, with b{-1}=0 and b{k-1} = n
and the k-1 intermediate boundaries b{0}..b{k-2}
chosen randomly distinct in [1;n-1].
Then each n{i} is defined as b{i}-b{i-1}. *)
let b = range_subset ~size:(k-1) 1 (n - 1) st in
if k = 1 then [|n|]
else Array.init k (fun i ->
if i = 0 then b.(0)
else if i = k-1 then n - b.(i-1)
else b.(i) - b.(i-1)
)
end
let nat_split ~size:k n st =
if not (0 <= k && 0 <= n) then invalid_arg "nat_split";
pos_split ~size:k (n+k) st
|> Array.map (fun v -> v - 1)
let generate ?(rand=Random.State.make_self_init()) ~n g =
list_repeat n g rand
let generate1 ?(rand=Random.State.make_self_init()) g = g rand
let delay f st = f () st
let (let+) = (>|=)
let (and+) = pair
let (let*) = (>>=)
let (and*) = pair
end
module Print = struct
type 'a t = 'a -> string
let unit _ = "()"
let int = string_of_int
let int32 i = Int32.to_string i ^ "l"
let int64 i = Int64.to_string i ^ "L"
let bool = string_of_bool
let float f = (* Workaround for Windows and macOS to print negative nans consistently as "-nan" *)
if Float.is_nan f && Float.sign_bit f
then "-nan"
else if Sys.win32 (* Windows workaround to avoid leading exponent zero such as "-1.00001604579e-010" *)
then string_of_float f |> cut_exp_zero
else string_of_float f
let string s = Printf.sprintf "%S" s
let bytes b = string (Bytes.to_string b)
let char c = Printf.sprintf "%C" c
let option f = function
| None -> "None"
| Some x -> "Some (" ^ f x ^ ")"
let result vp ep = function
| Error e -> "Error (" ^ ep e ^ ")"
| Ok v -> "Ok (" ^ vp v ^ ")"
let pair a b (x,y) = Printf.sprintf "(%s, %s)" (a x) (b y)
let triple a b c (x,y,z) = Printf.sprintf "(%s, %s, %s)" (a x) (b y) (c z)
let quad a b c d (x,y,z,w) =
Printf.sprintf "(%s, %s, %s, %s)" (a x) (b y) (c z) (d w)
let default = fun _ -> "<no printer>"
let tup2 p_a p_b (a, b) =
Printf.sprintf "(%s, %s)" (p_a a) (p_b b)
let tup2_opt p_a p_b (a, b) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
tup2 p_a p_b (a, b)
let tup3 p_a p_b (p_c) (a, b, c) =
Printf.sprintf "(%s, %s, %s)" (p_a a) (p_b b) (p_c c)
let tup3_opt p_a p_b p_c (a, b, c) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
tup3 p_a p_b p_c (a, b, c)
let tup4 p_a p_b p_c p_d (a, b, c, d) =
Printf.sprintf "(%s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
let tup4_opt p_a p_b p_c p_d (a, b, c, d) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
tup4 p_a p_b p_c p_d (a, b, c, d)
let tup5 p_a p_b p_c p_d p_e (a, b, c, d, e) =
Printf.sprintf "(%s, %s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
(p_e e)
let tup5_opt p_a p_b p_c p_d p_e (a, b, c, d, e) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
let p_e = Option.value ~default p_e in
tup5 p_a p_b p_c p_d p_e (a, b, c, d, e)
let tup6 p_a p_b p_c p_d p_e p_f (a, b, c, d, e, f) =
Printf.sprintf "(%s, %s, %s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
(p_e e) (p_f f)
let tup6_opt p_a p_b p_c p_d p_e p_f (a, b, c, d, e, f) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
let p_e = Option.value ~default p_e in
let p_f = Option.value ~default p_f in
tup6 p_a p_b p_c p_d p_e p_f (a, b, c, d, e, f)
let tup7 p_a p_b p_c p_d p_e p_f p_g (a, b, c, d, e, f, g) =
Printf.sprintf "(%s, %s, %s, %s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
(p_e e) (p_f f)
(p_g g)
let tup7_opt p_a p_b p_c p_d p_e p_f p_g (a, b, c, d, e, f, g) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
let p_e = Option.value ~default p_e in
let p_f = Option.value ~default p_f in
let p_g = Option.value ~default p_g in
tup7 p_a p_b p_c p_d p_e p_f p_g (a, b, c, d, e, f, g)
let tup8 p_a p_b p_c p_d p_e p_f p_g p_h (a, b, c, d, e, f, g, h) =
Printf.sprintf "(%s, %s, %s, %s, %s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
(p_e e) (p_f f)
(p_g g) (p_h h)
let tup8_opt p_a p_b p_c p_d p_e p_f p_g p_h (a, b, c, d, e, f, g, h) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
let p_e = Option.value ~default p_e in
let p_f = Option.value ~default p_f in
let p_g = Option.value ~default p_g in
let p_h = Option.value ~default p_h in
tup8 p_a p_b p_c p_d p_e p_f p_g p_h (a, b, c, d, e, f, g, h)
let tup9 p_a p_b p_c p_d p_e p_f p_g p_h p_i (a, b, c, d, e, f, g, h, i) =
Printf.sprintf "(%s, %s, %s, %s, %s, %s, %s, %s, %s)"
(p_a a) (p_b b)
(p_c c) (p_d d)
(p_e e) (p_f f)
(p_g g) (p_h h)
(p_i i)
let tup9_opt p_a p_b p_c p_d p_e p_f p_g p_h p_i (a, b, c, d, e, f, g, h, i) =
let p_a = Option.value ~default p_a in
let p_b = Option.value ~default p_b in
let p_c = Option.value ~default p_c in
let p_d = Option.value ~default p_d in
let p_e = Option.value ~default p_e in
let p_f = Option.value ~default p_f in
let p_g = Option.value ~default p_g in
let p_h = Option.value ~default p_h in
let p_i = Option.value ~default p_i in
tup9 p_a p_b p_c p_d p_e p_f p_g p_h p_i (a, b, c, d, e, f, g, h, i)
let list pp l =
let b = Buffer.create 25 in
Buffer.add_char b '[';
List.iteri (fun i x ->
if i > 0 then Buffer.add_string b "; ";
Buffer.add_string b (pp x))
l;
Buffer.add_char b ']';
Buffer.contents b
let array pp a =
let b = Buffer.create 25 in
Buffer.add_string b "[|";
Array.iteri (fun i x ->
if i > 0 then Buffer.add_string b "; ";
Buffer.add_string b (pp x))
a;
Buffer.add_string b "|]";
Buffer.contents b
let comap f p x = p (f x)
end
module Iter = struct
type 'a t = ('a -> unit) -> unit
let empty _ = ()
let return x yield = yield x
let (<*>) a b yield = a (fun f -> b (fun x -> yield (f x)))
let (>>=) a f yield = a (fun x -> f x yield)
let map f a yield = a (fun x -> yield (f x))
let map2 f a b yield = a (fun x -> b (fun y -> yield (f x y)))
let (>|=) a f = map f a
let append a b yield = a yield; b yield
let append_l l yield = List.iter (fun s->s yield) l
let flatten s yield = s (fun sub -> sub yield)
let filter f s yield = s (fun x -> if f x then yield x)
let (<+>) = append
let of_list l yield = List.iter yield l
let of_array a yield = Array.iter yield a
let pair a b yield = a (fun x -> b(fun y -> yield (x,y)))
let triple a b c yield = a (fun x -> b (fun y -> c (fun z -> yield (x,y,z))))
let quad a b c d yield =
a (fun x -> b (fun y -> c (fun z -> d (fun w -> yield (x,y,z,w)))))
exception IterExit
let find_map p iter =
let r = ref None in
(try iter (fun x -> match p x with Some _ as y -> r := y; raise IterExit | None -> ())
with IterExit -> ()
);
!r
let find p iter = find_map (fun x->if p x then Some x else None) iter
let (let+) = (>|=)
let (and+) = pair
let (let*) = (>>=)
let (and*) = pair
end
module Shrink = struct
type 'a t = 'a -> 'a Iter.t
let nil _ = Iter.empty
let unit = nil
let bool b =
if b then Iter.return false else Iter.empty
(* balanced shrinker for integers (non-exhaustive) *)
let int x yield =
let y = ref x in
(* try some divisors *)
while !y < -2 || !y >2 do y := !y / 2; yield (x - !y); done; (* fast path *)
if x = 1 || (x>0 && !y <> 1) then yield (x-1);
if x = -1 || (x<0 && !y <> -1) then yield (x+1);
()
let int32 x yield =
let open Int32 in
let y = ref x in
(* try some divisors *)
while !y < -2l || !y > 2l do y := div !y 2l; yield (sub x !y); done; (* fast path *)
if x = 1l || (x>0l && !y <> 1l) then yield (pred x);
if x = -1l || (x<0l && !y <> -1l) then yield (succ x);
()
let int64 x yield =
let open Int64 in
let y = ref x in
(* try some divisors *)
while !y < -2L || !y > 2L do y := div !y 2L; yield (sub x !y); done; (* fast path *)
if x = 1L || (x>0L && !y <> 1L) then yield (pred x);
if x = -1L || (x<0L && !y <> -1L) then yield (succ x);
()
(* aggressive shrinker for integers,
get from 0 to x, by dichotomy or just enumerating smaller values *)
let int_aggressive x yield =
let y = ref x in
while !y < -2 || !y >2 do y := !y / 2; yield (x - !y); done; (* fast path *)
if x>0 then for i=x-1 downto 0 do yield i done;
if x<0 then for i=x+1 to 0 do yield i done
let float_suff_different cand x =
let threshold = 1e-4 in (* candidate has to be at least 0.0001% different *)
Float.(abs cand < abs x) && Float.abs ((cand -. x) /. x) > threshold
(* [float_shrink_exponent 2.234 213] shrinks an exponent 213 from 2.234e213
and glues it back together with significand 2.234 *)
let float_shrink_exponent signif exponent yield =
int (int_of_string exponent)
(fun exponent -> Printf.sprintf "%se%i" signif exponent |> float_of_string |> yield)
(* [float_shrink_significand 2.234e213 "2.234" "213"] shrinks the significand 2.234 of
a floating point number in scientific notation 2.234e213 *)
let float_shrink_significand orig_x signif exponent yield =
let signif = float_of_string signif in
let exponent = float_of_string ("1e" ^ exponent) in
let recompose_float signif = signif *. exponent in
let recompose_and_yield signif =
let cand = recompose_float signif in
if String.length (Print.float cand) <= String.length (Print.float orig_x)
then yield cand in
(* [shrink_decimals 2.2345 1000] multiplies a significand 2.2345 with a
precision 1000 to get [2234], shrink it, and thus round off decimals *)
let shrink_decimals signif prec yield =
let tmp = signif *. float prec in (* use tmp to avoid i386 ocamlopt 4 weirdness https://github.com/ocaml/ocaml/issues/8018 *)
let multiple = int_of_float tmp in (* returns an unshrinkable 0 on overflow *)
if prec = 10 || multiple mod 100 <> 0 then (* first iteration or decimals to round *)
int multiple (fun i ->
let signif' = float i /. float prec in
if float_suff_different signif' signif
then yield signif') in
(* first try reducing the decimal digits with different precision *)
if signif > 1.0 || signif < -1.0 (* don't attempt to shrink 1.0 or -1.0 *)
then
begin
shrink_decimals signif 10 recompose_and_yield;
shrink_decimals signif 1000 recompose_and_yield;
shrink_decimals signif 100000 recompose_and_yield
end;
(* second try simple reductions of the significand's leading digit, in [1;9] *)
if signif > 2. then
(* shrink 2.234e213 to 1.234e213 by int shrinking the leading 2 *)
int (int_of_float signif)
(fun s -> if s != 0 then yield (recompose_float (signif -. floor signif +. float s)));
if signif < -2. then
(* shrink -2.234e213 to -1.234e213 by int shrinking the leading -2 *)
int (int_of_float signif)
(fun s -> if s != 0 then yield (recompose_float (signif -. ceil signif +. float s)))
let float x yield =
if not (Float.is_infinite x || Float.is_nan x) then
(* first try quick roundings and negation *)
(if x > 1. then let floor_x = floor x in
if float_suff_different floor_x x then yield floor_x);
(if x < -1. then let ceil_x = ceil x in
if float_suff_different ceil_x x then yield ceil_x);
if x < 0. then yield (-. x);
(* second proceed with simplification based on decimal, scientific notation 2.234e213 *)
match String.split_on_char 'e' (Printf.sprintf "%e" x) with
| [signif;exponent] ->
float_shrink_exponent signif exponent yield;
float_shrink_significand x signif exponent yield
| _ -> ()
let float_bound bound =
if bound > 0.
then
fun i ->
Iter.map (fun i -> i -. 1.) (float (i +. 1.)) (* towards 1. and subtract 1. afterwards *)
|> Iter.filter (fun i -> 0. <= i && i < bound)
else
fun i ->
Iter.map (fun i -> i +. 1.) (float (i -. 1.)) (* towards -1. and add 1. afterwards *)
|> Iter.filter (fun i -> bound < i && i <= 0.)
let float_range low high =
if high < low then invalid_arg "Shrink.float_range: invalid range";
let filter_range = Iter.filter (fun i -> low <= i && i <= high) in
if low >= 0. then
fun i -> (* move [low;high] to [1;high-low+1], shrink towards 1., and move back *)
Iter.map (fun i -> i +. low -. 1.) (float (i -. low +. 1.)) |> filter_range
else if high <= 0. then
fun i -> (* move [low;high] to [low-high-1;-1], shrink towards -1., and move back *)
Iter.map (fun i -> i +. high +. 1.) (float (i -. high -. 1.)) |> filter_range
else (* low < 0 && 0 < high, i.e., crosses 0. *)
fun i -> (* shrink towards 1. and subtract 1. afterwards *)
Iter.map (fun i -> i -. 1.) (float (i +. 1.)) |> filter_range
let filter f shrink x = Iter.filter f (shrink x)
let char_generic target c =
if c = target
then Iter.empty
else
let c_code = Char.code c in
let target_code = Char.code target in
Iter.map (fun diff -> Char.chr (target_code + diff)) (int (c_code - target_code))
let char = char_generic 'a'
let char_numeral = char_generic '0'
let char_printable = function
| '\n' -> char '~' (* treat '\n' (10) as '~' (126) to ensure a non-trivial, printable output *)
| c -> char c
let option s x = match x with
| None -> Iter.empty
| Some x -> Iter.(return None <+> map (fun y->Some y) (s x))
let result vs es x = match x with
| Error e -> Iter.map (fun e -> Error e) (es e)
| Ok v -> Iter.map (fun v -> Ok v) (vs v)
let array ?shrink a yield =
let n = Array.length a in
let chunk_size = ref n in
while !chunk_size > 0 do
for i=0 to n - !chunk_size do
(* remove elements in [i .. i+!chunk_size] *)
let a' = Array.init (n - !chunk_size)
(fun j -> if j< i then a.(j) else a.(j + !chunk_size))
in
yield a'
done;
chunk_size := !chunk_size / 2;
done;
match shrink with
| None -> ()
| Some f ->
(* try to shrink each element of the array *)
for i = 0 to Array.length a - 1 do
f a.(i) (fun x ->
let b = Array.copy a in
b.(i) <- x;
yield b
)
done
let rec list_spine l yield =
let rec split l len acc = match len,l with
| _,[]
| 0,_ -> List.rev acc, l
| _,x::xs -> split xs (len-1) (x::acc) in
match l with
| [] -> ()
| [_] -> yield []
| [x;y] -> yield []; yield [x]; if (try x <> y with Invalid_argument _ -> x != y) then yield [y]
| _::_ ->
let len = List.length l in
let xs,ys = split l ((1 + len) / 2) [] in
yield xs;
list_spine xs (fun xs' -> yield (xs'@ys))
let list_elems shrink l yield =
(* try to shrink each element of the list *)
let rec elem_loop rev_prefix suffix = match suffix with
| [] -> ()
| x::xs ->
shrink x (fun x' -> yield (List.rev_append rev_prefix (x'::xs)));
elem_loop (x::rev_prefix) xs
in
elem_loop [] l
let list ?shrink l yield =
list_spine l yield;
match shrink with
| None -> ()
| Some shrink -> list_elems shrink l yield
let string ?(shrink = char) s yield =
let buf = Buffer.create 42 in
list ~shrink
(string_fold_right (fun c acc -> c::acc) s [])
(fun cs ->
List.iter (fun c -> Buffer.add_char buf c) cs;
let s = Buffer.contents buf in
Buffer.clear buf;
yield s)
let bytes ?(shrink = char) b = Iter.map Bytes.of_string (string ~shrink (Bytes.to_string b))
let pair a b (x,y) yield =
a x (fun x' -> yield (x',y));
b y (fun y' -> yield (x,y'))
let triple a b c (x,y,z) yield =
a x (fun x' -> yield (x',y,z));
b y (fun y' -> yield (x,y',z));
c z (fun z' -> yield (x,y,z'))
let quad a b c d (x,y,z,w) yield =
a x (fun x' -> yield (x',y,z,w));
b y (fun y' -> yield (x,y',z,w));
c z (fun z' -> yield (x,y,z',w));
d w (fun w' -> yield (x,y,z,w'))
let default = nil
let tup2 = pair
let tup2_opt a b =
let a = Option.value ~default a in
let b = Option.value ~default b in
tup2 a b
let tup3 = triple
let tup3_opt a b c =
let a = Option.value ~default a in
let b = Option.value ~default b in
let c = Option.value ~default c in
tup3 a b c
let tup4 = quad
let tup4_opt a b c d =
let a = Option.value ~default a in
let b = Option.value ~default b in
let c = Option.value ~default c in
let d = Option.value ~default d in
tup4 a b c d