-
Notifications
You must be signed in to change notification settings - Fork 37
/
QCheck2.ml
1796 lines (1446 loc) · 59.9 KB
/
QCheck2.ml
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, Julien Debon, Valentin Chaboche
all rights reserved.
*)
(** {1 Quickcheck inspired property-based testing} *)
let poly_compare=compare
module RS = Random.State
let rec foldn ~f ~init:acc i =
if i = 0 then acc else foldn ~f ~init:(f acc i) (i-1)
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_sum a b = match a, b with
| Some _, _ -> a
| None, _ -> b
let sum_int = List.fold_left (+) 0
exception Failed_precondition
(* raised if precondition is false *)
exception No_example_found of string
(* raised if an example failed to be found *)
let assume b = if not b then raise Failed_precondition
let assume_fail () = raise Failed_precondition
let (==>) b1 b2 = if b1 then b2 else raise Failed_precondition
(** Enhancement of Stdlib [Seq] to backport some recent functions, and add a few useful others. *)
module Seq = struct
include Seq
(* The following functions are copied from https://github.com/ocaml/ocaml/blob/trunk/stdlib/seq.ml to support older OCaml versions. *)
let rec unfold f u () =
match f u with
| None -> Nil
| Some (x, u') -> Cons (x, unfold f u')
let rec append seq1 seq2 () =
match seq1() with
| Nil -> seq2()
| Cons (x, next) -> Cons (x, append next seq2)
let cons x next () = Cons (x, next)
(* End of copy of old functions. *)
let is_empty (seq : _ t) : bool = match seq () with
| Nil -> true
| _ -> false
(** Take at most [n] values. *)
let rec take (n : int) (seq : _ t) : _ t = fun () -> match (n, seq ()) with
| (0, _) | (_, Nil) -> Nil
| (n, Cons (a, rest)) -> Cons (a, take (n - 1) rest)
let hd (l : 'a t) : 'a option =
match l () with
| Nil -> None
| Cons (hd, _) -> Some hd
(** Useful to improve [Seq] code perf when chaining functions *)
let apply (l : 'a t) : 'a node = l ()
end
module Shrink = struct
module type Number = sig
type t
val equal : t -> t -> bool
val div : t -> t -> t
val add : t -> t -> t
val sub : t -> t -> t
val of_int : int -> t
end
let number_towards (type a) (module Number : Number with type t = a) ~(destination : a) (x : a) : a Seq.t = fun () ->
Seq.unfold (fun current_shrink ->
if Number.equal current_shrink x
then None
else (
(* Halve the operands before subtracting them so they don't overflow.
Consider [number_towards min_int max_int] *)
let half_diff = Number.sub (Number.div x (Number.of_int 2)) (Number.div current_shrink (Number.of_int 2)) in
if half_diff = Number.of_int 0
(* [current_shrink] is the last valid shrink candidate, put [x] as next step to make sure we stop *)
then Some (current_shrink, x)
else Some (current_shrink, Number.add current_shrink half_diff)
)) destination ()
let int_towards destination x = fun () ->
let module Int : Number with type t = int = struct
include Int
let of_int = Fun.id
end in
number_towards (module Int) ~destination x ()
let int32_towards destination x = fun () ->
number_towards (module Int32) ~destination x ()
let int64_towards destination x = fun () ->
number_towards (module Int64) ~destination x ()
(** Arbitrarily limit to 15 elements as dividing a [float] by 2 doesn't converge quickly
towards the destination. *)
let float_towards destination x = fun () ->
number_towards (module Float) ~destination x |> Seq.take 15 |> Seq.apply
let int_aggressive_towards (destination : int) (n : int) : int Seq.t = fun () ->
Seq.unfold (fun current ->
if current = n then None
else if current < n then let next = succ current in Some (next, next)
else let next = pred current in Some (next, next)
) destination ()
let int_aggressive n = fun () -> int_aggressive_towards 0 n ()
end
module Tree = struct
type 'a t = Tree of 'a * ('a t) Seq.t
let root (Tree (root, _) : 'a t) : 'a = root
let children (Tree (_, children) : 'a t) : ('a t) Seq.t = children
let rec pp ?(depth : int option) (inner_pp : Format.formatter -> 'a -> unit) (ppf : Format.formatter) (t : 'a t) : unit =
let Tree (x, xs) = t in
let wrapper_box ppf inner =
Format.fprintf ppf "@[<hv2>Tree(@,%a@]@,)" inner ()
in
let inner ppf () =
Format.fprintf ppf "@[<hv2>Node(@,%a@]@,),@ @[<hv>Shrinks(" inner_pp x;
if Option.fold depth ~none:false ~some:(fun depth -> depth <= 0) then (
Format.fprintf ppf "<max depth reached>@])")
else if Seq.is_empty xs then Format.fprintf ppf "@])"
else (
Format.fprintf ppf "@,%a@]@,)"
(Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf ",@ ")
(pp ?depth:(Option.map pred depth) inner_pp))
(List.of_seq xs);
)
in
wrapper_box ppf inner
let rec map (f : 'a -> 'b) (a : 'a t) : 'b t =
let Tree (x, xs) = a in
let y = f x in
let ys = fun () -> Seq.map (fun smaller_x -> map f smaller_x) xs () in
Tree (y, ys)
(** Note that parameter order is reversed. *)
let (>|=) a f = map f a
let rec ap (f : ('a -> 'b) t) (a : 'a t) : 'b t =
let Tree (x0, xs) = a in
let Tree (f0, fs) = f in
let y = f0 x0 in
let ys = fun () -> Seq.append (Seq.map (fun f' -> ap f' a) fs) (Seq.map (fun x' -> ap f x') xs) () in
Tree (y, ys)
let (<*>) = ap
let liftA2 (f : 'a -> 'b -> 'c) (a : 'a t) (b : 'b t) : 'c t =
(a >|= f) <*> b
let rec bind (a : 'a t) (f : 'a -> 'b t) : 'b t =
let Tree (x, xs) = a in
let Tree (y, ys_of_x) = f x in
let ys_of_xs = fun () -> Seq.map (fun smaller_x -> bind smaller_x f) xs () in
let ys = fun () -> Seq.append ys_of_xs ys_of_x () in
Tree (y, ys)
let (>>=) = bind
let pure x = Tree (x, Seq.empty)
let rec make_primitive (shrink : 'a -> 'a Seq.t) (x : 'a) : 'a t =
let shrink_trees = fun () -> shrink x |> Seq.map (make_primitive shrink) |> Seq.apply in
Tree (x, shrink_trees)
let rec opt (a : 'a t) : 'a option t =
let Tree (x, xs) = a in
let shrinks = fun () -> Seq.cons (pure None) (Seq.map opt xs) () in
Tree (Some x, shrinks)
let rec sequence_list (l : 'a t list) : 'a list t = match l with
| [] -> pure []
| hd :: tl -> liftA2 List.cons hd (sequence_list tl)
let rec add_shrink_invariant (p : 'a -> bool) (a : 'a t) : 'a t =
let Tree (x, xs) = a in
let xs' = fun () -> Seq.filter_map (fun (Tree (x', _) as t) -> if p x' then Some (add_shrink_invariant p t) else None) xs () in
Tree (x, xs')
(** [applicative_take n trees] returns a tree of lists with at most the [n] first elements of the input list. *)
let rec applicative_take (n : int) (l : 'a t list) : 'a list t = match (n, l) with
| (0, _) | (_, []) -> pure []
| (n, (tree :: trees)) -> liftA2 List.cons tree (applicative_take (pred n) trees)
end
module Gen = struct
type 'a t = RS.t -> 'a Tree.t
type 'a sized = int -> RS.t -> 'a Tree.t
let map f x = fun st -> Tree.map f (x st)
(** Note that parameter order is reversed. *)
let (>|=) x f = map f x
let (<$>) = map
let pure (a : 'a) : 'a t = fun _ -> Tree.pure a
let ap (f : ('a -> 'b) t) (x : 'a t) : 'b t = fun st -> Tree.ap (f st) (x st)
let (<*>) = ap
let liftA2 (f : 'a -> 'b -> 'c) (a : 'a t) (b : 'b t) : 'c t =
(a >|= f) <*> b
let liftA3 (f : 'a -> 'b -> 'c -> 'd) (a : 'a t) (b : 'b t) (c : 'c t) : 'd t =
(a >|= f) <*> b <*> c
let map2 = liftA2
let map3 = liftA3
let return = pure
let bind (gen : 'a t) (f : 'a -> ('b t)) : 'b t = fun st -> Tree.bind (gen st) (fun a -> f a st)
let (>>=) = bind
let sequence_list (l : 'a t list) : 'a list t = fun st -> List.map (fun gen -> gen st) l |> Tree.sequence_list
let make_primitive ~(gen : RS.t -> 'a) ~(shrink : 'a -> 'a Seq.t) : 'a t = fun st ->
Tree.make_primitive shrink (gen st)
let parse_origin (loc : string) (pp : Format.formatter -> 'a -> unit) ~(origin : 'a) ~(low : 'a) ~(high : 'a) : 'a =
if origin < low then invalid_arg Format.(asprintf "%s: origin value %a is lower than low value %a" loc pp origin pp low)
else if origin > high then invalid_arg Format.(asprintf "%s: origin value %a is greater than high value %a" loc pp origin pp high)
else origin
let small_nat : int t = fun st ->
let p = RS.float st 1. in
let x = if p < 0.75 then RS.int st 10 else RS.int st 100 in
let shrink a = fun () -> Shrink.int_towards 0 a () in
Tree.make_primitive shrink x
(** Natural number generator *)
let nat : int t = fun st ->
let p = RS.float st 1. in
let x =
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
in
let shrink a = fun () -> Shrink.int_towards 0 a () in
Tree.make_primitive shrink x
let big_nat : int t = fun st ->
let p = RS.float st 1. in
if p < 0.75
then nat st
else
let shrink a = fun () -> Shrink.int_towards 0 a () in
Tree.make_primitive shrink (RS.int st 1_000_000)
let unit : unit t = fun _st -> Tree.pure ()
let bool : bool t = fun st ->
let false_gen = Tree.pure false in
if RS.bool st
then Tree.Tree (true, Seq.return false_gen)
else false_gen
let float : float t = fun st ->
let x = exp (RS.float st 15. *. (if RS.bool st then 1. else -1.))
*. (if RS.bool st then 1. else -1.)
in
let shrink a = fun () -> Shrink.float_towards 0. a () in
Tree.make_primitive shrink x
let pfloat : float t = float >|= abs_float
let nfloat : float t = pfloat >|= Float.neg
let float_bound_inclusive ?(origin : float = 0.) (bound : float) : float t = fun st ->
let (low, high) = Float.min_max_num 0. bound in
let shrink a = fun () ->
let origin = parse_origin "Gen.float_bound_inclusive" Format.pp_print_float ~origin ~low ~high in
Shrink.float_towards origin a ()
in
let x = RS.float st bound in
Tree.make_primitive shrink x
let float_bound_exclusive ?(origin : float = 0.) (bound : float) : float t =
if bound = 0. then invalid_arg "Gen.float_bound_exclusive";
fun st ->
let (low, high) = Float.min_max_num 0. bound in
let shrink a = fun () ->
let origin = parse_origin "Gen.float_bound_exclusive" Format.pp_print_float ~origin ~low ~high in
Shrink.float_towards origin a ()
in
let bound =
if bound > 0.
then bound -. epsilon_float
else bound +. epsilon_float
in
let x = RS.float st bound in
Tree.make_primitive shrink x
let pick_origin_within_range ~low ~high ~goal =
if low > goal then low
else if high < goal then high
else goal
let float_range ?(origin : float option) (low : float) (high : float) : float t =
if high < low then invalid_arg "Gen.float_range: high < low"
else if high -. low > max_float then invalid_arg "Gen.float_range: high -. low > max_float";
let origin = parse_origin "Gen.float_range" Format.pp_print_float
~origin:(Option.value ~default:(pick_origin_within_range ~low ~high ~goal:0.) origin)
~low
~high in
(float_bound_inclusive ~origin (high -. low))
>|= (fun x -> low +. x)
let (--.) low high = float_range ?origin:None low high
let neg_int : int t = nat >|= Int.neg
(** [opt gen] shrinks towards [None] then towards shrinks of [gen]. *)
let opt ?(ratio : float = 0.85) (gen : 'a t) : 'a option t = fun st ->
let p = RS.float st 1. in
if p < (1. -. ratio)
then Tree.pure None
else Tree.opt (gen st)
(* Uniform positive random int generator.
We can't use {!RS.int} because the upper bound must be positive and is excluded,
so {!Int.max_int} would never be reached. We have to manipulate bits directly.
Note that the leftmost bit is used for negative numbers, so it must be [0].
{!RS.bits} only generates 30 bits, which is exactly enough on
32-bits architectures (i.e. {!Sys.int_size} = 31, i.e. 30 bits for positive numbers)
but not on 64-bits ones.
That's why for 64-bits, 3 30-bits segments are generated and shifted to craft a
62-bits number (i.e. {!Sys.int_size} = 63). The leftmost segment is masked to keep
only the last 2 bits.
The current implementation hard-codes 30/32/62/64 values, but technically we should
rely on {!Sys.int_size} to find the number of bits.
Note that we could also further generalize this function to merge it with [random_binary_string].
Technically this function is a special case of [random_binary_string] where the size is
{!Sys.int_size}.
*)
let pint_raw (st : RS.t) : int =
if Sys.word_size = 32
then RS.bits st
else (* word size = 64 *)
(* Bottom 30 bits *)
let right = RS.bits st in
(* Middle 30 bits *)
let middle = (RS.bits st lsl 30) in
(* 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
left lor middle lor right
let pint ?(origin : int = 0) : int t = fun st ->
let x = pint_raw st in
let shrink a = fun () ->
let origin = parse_origin "Gen.pint" Format.pp_print_int ~origin ~low:0 ~high:max_int in
Shrink.int_towards origin a ()
in
Tree.make_primitive shrink x
let number_towards = Shrink.number_towards
let int_towards = Shrink.int_towards
let int64_towards = Shrink.int64_towards
let int32_towards = Shrink.int32_towards
let float_towards = Shrink.float_towards
let int : int t =
bool >>= fun b ->
if b
then pint ~origin:0 >|= (fun n -> - n - 1)
else pint ~origin:0
let int_bound (n : int) : int t =
if n < 0 then invalid_arg "Gen.int_bound";
fun st ->
if n <= (1 lsl 30) - 2
then Tree.make_primitive (fun a () -> Shrink.int_towards 0 a ()) (RS.int st (n + 1))
else Tree.map (fun r -> r mod (n + 1)) (pint st)
(** To support ranges wider than [Int.max_int], the general idea is to find the center,
and generate a random half-difference number as well as whether we add or
subtract that number from the center. *)
let int_range ?(origin : int option) (low : int) (high : int) : int t =
if high < low then invalid_arg "Gen.int_range: high < low";
fun st ->
let Tree.Tree(n, _shrinks) = if low >= 0 || high < 0 then (
(* range smaller than max_int *)
Tree.map (fun n -> low + n) (int_bound (high - low) st)
) else (
(* range potentially bigger than max_int: we split on 0 and
choose the interval with regard to their size ratio *)
let f_low = float_of_int low in
let f_high = float_of_int high in
let ratio = (-.f_low) /. (1. +. f_high -. f_low) in
if RS.float st 1. <= ratio
then Tree.map (fun n -> -n - 1) (int_bound (- (low + 1)) st)
else int_bound high st
) in
let shrink a = fun () ->
let origin = match origin with
| None -> pick_origin_within_range ~low ~high ~goal:0
| Some origin ->
if origin < low
then invalid_arg "Gen.int_range: origin < low"
else if origin > high then invalid_arg "Gen.int_range: origin > high"
else origin
in
Shrink.int_towards origin a ()
in
Tree.make_primitive shrink n
let (--) low high = int_range ?origin:None low high
let oneof (l : 'a t list) : 'a t =
int_range 0 (List.length l - 1) >>= List.nth l
let oneofl (l : 'a list) : 'a t =
int_range 0 (List.length l - 1) >|= List.nth l
let oneofa (a : 'a array) : 'a t =
int_range 0 (Array.length a - 1) >|= Array.get a
(* 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 small_signed_int : int t = fun st ->
if RS.bool st
then small_nat st
else (small_nat >|= Int.neg) st
(** Shrink towards the first element of the list *)
let frequency (l : (int * 'a t) list) : 'a t =
if l = [] then failwith "QCheck2.frequency called with an empty list";
let sums = sum_int (List.map fst l) in
if sums < 1 then failwith "QCheck2.frequency called with weight sum < 1";
int_bound (sums - 1)
>>= fun i ->
let rec aux acc = function
| ((x, g) :: xs) -> if i < acc + x then g else aux (acc + x) xs
| _ -> assert false
in
aux 0 l
let frequencyl (l : (int * 'a) list) : 'a t =
List.map (fun (weight, value) -> (weight, pure value)) l
|> frequency
let frequencya a = frequencyl (Array.to_list a)
let char_range ?(origin : char option) (a : char) (b : char) : char t =
(int_range ~origin:(Char.code (Option.value ~default:a origin)) (Char.code a) (Char.code b)) >|= Char.chr
let random_binary_string (length : int) (st : RS.t) : string =
(* 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 : int32 t = fun st ->
let x = random_binary_string 32 st |> Int32.of_string in
let shrink a = fun () -> Shrink.int32_towards 0l a () in
Tree.make_primitive shrink x
let ui32 : int32 t = map Int32.abs int32
let int64 : int64 t = fun st ->
let x = random_binary_string 64 st |> Int64.of_string in
let shrink a = fun () -> Shrink.int64_towards 0L a () in
Tree.make_primitive shrink x
let ui64 : int64 t = map Int64.abs int64
let list_size (size : int t) (gen : 'a t) : 'a list t =
size >>= fun size ->
let rec loop n =
if n <= 0
then pure []
else liftA2 List.cons gen (loop (n - 1))
in
loop size
let list (gen : 'a t) : 'a list t = list_size nat gen
let list_repeat (n : int) (gen : 'a t) : 'a list t = list_size (pure n) gen
let array_size (size : int t) (gen : 'a t) : 'a array t =
(list_size size gen) >|= Array.of_list
let array (gen : 'a t) : 'a array t = list gen >|= Array.of_list
let array_repeat (n : int) (gen : 'a t) : 'a array t = list_repeat n gen >|= Array.of_list
let rec flatten_l (l : 'a t list) : 'a list t =
match l with
| [] -> pure []
| gen :: gens -> liftA2 List.cons gen (flatten_l gens)
let flatten_a (a : 'a t array) : 'a array t =
Array.to_list a |> flatten_l >|= Array.of_list
let flatten_opt (o : 'a t option) : 'a option t =
match o with
| None -> pure None
| Some gen -> opt gen
let flatten_res (res : ('a t, 'e) result) : ('a, 'e) result t =
match res with
| Ok gen -> gen >|= Result.ok
| Error e -> pure (Error e)
let shuffle_a (a : 'a array) : 'a array t = fun st ->
let a = Array.copy a in
for i = Array.length a - 1 downto 1 do
let j = RS.int st (i + 1) in
let tmp = a.(i) in
a.(i) <- a.(j);
a.(j) <- tmp;
done;
Tree.pure a
let shuffle_l (l : 'a list) : 'a list t =
Array.of_list l |> shuffle_a >|= Array.to_list
let shuffle_w_l (l : ((int * 'a) list)) : 'a list t = fun st ->
let sample (w, v) =
let Tree.Tree (p, _) = float_bound_inclusive 1. st in
let fl_w = float_of_int w in
(p ** (1. /. fl_w), v)
in
let samples = List.rev_map sample l in
samples
|> List.sort (fun (w1, _) (w2, _) -> poly_compare w1 w2)
|> List.rev_map snd
|> Tree.pure
let pair (g1 : 'a t) (g2 : 'b t) : ('a * 'b) t = liftA2 (fun a b -> (a, b)) g1 g2
let triple (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) : ('a * 'b * 'c) t = (fun a b c -> (a, b, c)) <$> g1 <*> g2 <*> g3
let quad (g1 : 'a t) (g2 : 'b t) (g3 : 'c t) (g4 : 'd t) : ('a * 'b * 'c * 'd) t =
(fun a b c d -> (a, b, c, d)) <$> g1 <*> g2 <*> g3 <*> g4
(** Don't reuse {!int_range} which is much less performant (many more checks because of the possible range and origins). As a [string] generator may call this hundreds or even thousands of times for a single value, it's worth optimizing. *)
let char : char t = fun st ->
let c = RS.int st 256 in
let shrink a = fun () -> Shrink.int_towards (int_of_char 'a') a |> Seq.apply in
Tree.map char_of_int (Tree.make_primitive shrink c)
(** The first characters are the usual lower case alphabetical letters to help shrinking. *)
let printable_chars : char list =
(* Left and right inclusive *)
let range min max = List.init (max - min) (fun i -> char_of_int (i + min)) in
let a = 97 in
let z = 122 in
let lower_alphabet = range a z in
(* ' ' *)
let first_printable_char = 32 in
let before_lower_alphabet = range first_printable_char (a - 1) in
(* '~' *)
let last_printable_char = 126 in
let after_lower_alphabet = range (z + 1) last_printable_char in
let newline = ['\n'] in
(* Put alphabet first for shrinking *)
List.flatten [lower_alphabet; before_lower_alphabet; after_lower_alphabet; newline]
let printable : char t =
int_range ~origin:0 0 (List.length printable_chars - 1)
>|= List.nth printable_chars
let numeral : char t =
let zero = 48 in
let nine = 57 in
int_range ~origin:zero zero nine >|= char_of_int
let bytes_size ?(gen = char) (size : int t) : bytes t = fun st ->
let open Tree in
size st >>= fun size ->
(* Adding char shrinks to a mutable list is expensive: ~20-30% cost increase *)
(* Adding char shrinks to a mutable lazy list is less expensive: ~15% cost increase *)
let char_trees_rev = ref [] in
let bytes = Bytes.init size (fun _ ->
let char_tree = gen st in
char_trees_rev := char_tree :: !char_trees_rev ;
(* Performance: return the root right now, the heavy processing of shrinks can wait until/if there is a need to shrink *)
root char_tree) in
let shrink = fun () ->
let char_trees = List.rev !char_trees_rev in
let char_list_tree = sequence_list char_trees in
let bytes_tree = char_list_tree >|= (fun char_list ->
let bytes = Bytes.create size in
List.iteri (Bytes.set bytes) char_list ;
bytes) in
(* Technically [bytes_tree] is the whole tree, but for perf reasons we eagerly created the root above *)
children bytes_tree ()
in
Tree (bytes, shrink)
let string_size ?(gen = char) (size : int t) : string t =
bytes_size ~gen size >|= Bytes.unsafe_to_string
let string : string t = string_size nat
let string_of gen = string_size ~gen nat
let string_readable = string_size ~gen:char nat
let small_string ?gen st = string_size ?gen small_nat st
let small_list gen = list_size small_nat gen
let small_array gen = array_size small_nat gen
let join (gen : 'a t t) : 'a t = gen >>= Fun.id
(* corner cases *)
let graft_corners (gen : 'a t) (corners : 'a list) () : 'a t =
let cors = ref corners in fun st ->
match !cors with [] -> gen st
| e::l -> cors := l; Tree.pure e
let int_pos_corners = [0; 1; 2; max_int]
let int_corners = int_pos_corners @ [min_int]
let small_int_corners () : int t = graft_corners nat int_pos_corners ()
(* sized, fix *)
let sized_size (size : int t) (gen : 'a sized) : 'a t =
size >>= gen
let sized (gen : 'a sized) : 'a t = sized_size nat gen
let fix f =
let rec f' n st = f f' n st in
f'
let generate ?(rand=RS.make_self_init()) ~(n : int) (gen : 'a t) : 'a list =
list_repeat n gen rand |> Tree.root
let generate1 ?(rand=RS.make_self_init()) (gen : 'a t) : 'a =
gen rand |> Tree.root
let generate_tree ?(rand=RS.make_self_init()) (gen : 'a t) : 'a Tree.t =
gen rand
let delay (f : unit -> 'a t) : 'a t = fun st -> f () st
let add_shrink_invariant (p : 'a -> bool) (gen : 'a t) : 'a t =
fun st -> gen st |> Tree.add_shrink_invariant p
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 bool = string_of_bool
let float = string_of_float
let string s = Printf.sprintf "%S" s
let char c = Printf.sprintf "%C" c
let option f = function
| None -> "None"
| Some x -> "Some (" ^ f x ^ ")"
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 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 contramap f p x = p (f x)
let comap = contramap
end
(** {2 Observe Values} *)
module Observable = struct
(** An observable is a (random) predicate on ['a] *)
type -'a t = {
print: 'a Print.t;
eq: ('a -> 'a -> bool);
hash: ('a -> int);
}
let hash o x = o.hash x
let equal o x y = o.eq x y
let print o x = o.print x
let make ?(eq=(=)) ?(hash=Hashtbl.hash) print =
{print; eq; hash; }
module H = struct
let combine a b = Hashtbl.seeded_hash a b
let combine_f f s x = Hashtbl.seeded_hash s (f x)
let int i = i land max_int
let bool b = if b then 1 else 2
let char x = Char.code x
let string (x:string) = Hashtbl.hash x
let opt f = function
| None -> 42
| Some x -> combine 43 (f x)
let list f l = List.fold_left (combine_f f) 0x42 l
let array f l = Array.fold_left (combine_f f) 0x42 l
let pair f g (x,y) = combine (f x) (g y)
end
module Eq = struct
type 'a t = 'a -> 'a -> bool
let int : int t = (=)
let string : string t = (=)
let bool : bool t = (=)
let float : float t = (=)
let unit () () = true
let char : char t = (=)
let rec list f l1 l2 = match l1, l2 with
| [], [] -> true
| [], _ | _, [] -> false
| x1::l1', x2::l2' -> f x1 x2 && list f l1' l2'
let array eq a b =
let rec aux i =
if i = Array.length a then true
else eq a.(i) b.(i) && aux (i+1)
in
Array.length a = Array.length b
&&
aux 0
let option f o1 o2 = match o1, o2 with
| None, None -> true
| Some _, None
| None, Some _ -> false
| Some x, Some y -> f x y
let pair f g (x1,y1)(x2,y2) = f x1 x2 && g y1 y2
end
let unit : unit t = make ~hash:(fun _ -> 1) ~eq:Eq.unit Print.unit
let bool : bool t = make ~hash:H.bool ~eq:Eq.bool Print.bool
let int : int t = make ~hash:H.int ~eq:Eq.int Print.int
let float : float t = make ~eq:Eq.float Print.float
let string = make ~hash:H.string ~eq:Eq.string Print.string
let char = make ~hash:H.char ~eq:Eq.char Print.char
let option p =
make ~hash:(H.opt p.hash) ~eq:(Eq.option p.eq)
(Print.option p.print)
let array p =
make ~hash:(H.array p.hash) ~eq:(Eq.array p.eq) (Print.array p.print)
let list p =
make ~hash:(H.list p.hash) ~eq:(Eq.list p.eq) (Print.list p.print)
let contramap f p =
make ~hash:(fun x -> p.hash (f x)) ~eq:(fun x y -> p.eq (f x)(f y))
(fun x -> p.print (f x))
let map = contramap
let pair a b =
make ~hash:(H.pair a.hash b.hash) ~eq:(Eq.pair a.eq b.eq) (Print.pair a.print b.print)
let triple a b c =
contramap (fun (x,y,z) -> x,(y,z)) (pair a (pair b c))
let quad a b c d =
contramap (fun (x,y,z,u) -> x,(y,z,u)) (pair a (triple b c d))
end
type 'a stat = string * ('a -> int)
(** A statistic on a distribution of values of type ['a] *)
(** Internal module taking care of storing generated function bindings.
In essence, a generated function of type ['a -> 'b] is a map (table) where
keys are input values of type ['a] and values are output values of
type ['b], plus a default value of type ['b].
This module provides the "map of input/output" part.
*)
module Poly_tbl : sig
type ('key, 'value) t
val create: 'key Observable.t -> ?v_print:'value Print.t -> 'value Gen.t -> int -> ('key, 'value) t Gen.t
val get : ('key, 'value) t -> 'key -> 'value option
val size : ('value -> int) -> ('key, 'value) t -> int
val print : ('key, 'value) t Print.t
end = struct
type ('key, 'value) t = {
get : 'key -> 'value option; (** Don't be fooled by its name and signature: this function mutates the table during test execution by adding entries (key is the value on which the function is applied in the test, and the value is generated on the fly). *)
p_size: ('value -> int) -> int;
p_print: unit -> string;
p_tree_bindings_rev : ('key * 'value Tree.t) list ref;
}
let create (type k) (type v) (k_obs : k Observable.t) ?(v_print: v Print.t option) (v_gen : v Gen.t) (size : int) : (k, v) t Gen.t =
fun st ->
let module T = Hashtbl.Make(struct
type t = k
let equal = k_obs.Observable.eq
let hash = k_obs.Observable.hash
end) in
(* make a table
@param extend if [true], extend table [tbl] on the fly (during test execution, to "record" input values and generate an associated output value). [false] during shrinking (use the default value if the input value is not in the table). *)
let make ~extend tbl =
let initial_tree_bindings_rev = T.to_seq tbl |> List.of_seq |> List.rev_map (fun (k, v) -> k, Tree.pure v) in
let p_tree_bindings_rev = ref initial_tree_bindings_rev in
let get = (fun key ->
try Some (T.find tbl key)
with Not_found ->
if extend then (
(* Generate a new value and "record" the binding for potential future display/shrinking *)
let value_tree = v_gen st in
p_tree_bindings_rev := (key, value_tree) :: !p_tree_bindings_rev;
let v = Tree.root value_tree in
T.add tbl key v;
Some v
) else None)
in
let p_print = (fun () ->
let pp_v = Option.value ~default:(fun _ -> "<opaque>") v_print in
let b = Buffer.create 64 in
let to_b = Format.formatter_of_buffer b in
T.iter
(fun key value ->
Format.fprintf to_b "%s -> %s; "
(k_obs.Observable.print key) (pp_v value))
tbl;
Format.pp_print_flush to_b ();
Buffer.contents b)
in
let p_size=(fun size_v -> T.fold (fun _ v n -> n + size_v v) tbl 0) in
{get; p_print; p_size; p_tree_bindings_rev}
in
let root_tbl = T.create size in
(* During initial running of the test, record bindings, hence [~extend:true]. *)
let root = make ~extend:true root_tbl in
(* Build the (lazy!) shrink tree of tables here *)
let shrinks : (k, v) t Tree.t Seq.t = fun () ->
(* This only gets evaluated *after* the test was run for [tbl], meaning it is correctly
populated with bindings recorded during the test already *)
let current_bindings : (k * v Tree.t) list = List.rev !(root.p_tree_bindings_rev) in
let take_at_most_tree : int Tree.t = Tree.make_primitive (Shrink.int_towards 0) (List.length current_bindings) in
let current_tree_bindings : (k * v) Tree.t list = List.map (fun (k, tree) -> Tree.map (fun v -> (k, v)) tree) current_bindings in
let shrunk_bindings_tree : (k * v) list Tree.t = Tree.bind take_at_most_tree (fun take_at_most -> Tree.applicative_take take_at_most current_tree_bindings) in
(* During shrinking, we don't want to record/add bindings, so [~extend:false]. *)
let shrunk_poly_tbl_tree : (k, v) t Tree.t = Tree.map (fun bindings -> List.to_seq bindings |> T.of_seq |> make ~extend:false) shrunk_bindings_tree in
(* [shrunk_poly_tbl_tree] is a bit misleading: its root *should* be the same as [root] but because of the required laziness
induced by the mutation of bindings, we don't use it, only graft its children to the original [root]. *)
Tree.children shrunk_poly_tbl_tree ()
in
Tree.Tree (root, shrinks)
let get t x = t.get x
let print t = t.p_print ()
let size p t = t.p_size p
end
(** Internal representation of functions, used for shrinking and printing (in case of error). *)
type ('a, 'b) fun_repr_tbl = {
fun_tbl: ('a, 'b) Poly_tbl.t; (** Input-output bindings *)
fun_gen: 'b Gen.t; (** How to generate output values *)
fun_print: 'b Print.t option; (** How to print output values *)
fun_default: 'b; (** Default value for all inputs not explicitly mapped in {!fun_tbl} *)
}
type 'f fun_repr =
| Fun_tbl : ('a, 'ret) fun_repr_tbl -> ('a -> 'ret) fun_repr (** Input-output list of bindings *)
| Fun_map : ('f1 -> 'f2) * 'f1 fun_repr -> 'f2 fun_repr (** Mapped from another function (typically used for currying) *)
(** A QCheck function, as in Koen Claessen's paper "Shrinking and showing functions".
Such a function is a pair of the function representation (used for shrinking and
printing the function) and a "real" function, which can be seen as an input-output
map + a default value for all other inputs.
- Test developers will only use the "real" function inside their tests (and ignore the function representation).
- During shrinking/printing, QCheck will ignore the "real" function and only use its representation.
*)
type 'f fun_ = Fun of 'f fun_repr * 'f