forked from c-cube/qcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQCheck2.ml
More file actions
2198 lines (1784 loc) · 76 KB
/
QCheck2.ml
File metadata and controls
2198 lines (1784 loc) · 76 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, Julien Debon, Valentin Chaboche
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. *)
(* copy of 4.14 Random.State.t to create a record of the right shape *)
type rs = { st : int array; mutable idx : int } [@@warning "-69"]
let split rs : Random.State.t =
let rs' = { st = Array.init 55 (fun _i -> Random.State.bits rs); idx = 0 } in
for i = 0 to 54 do
rs'.st.(i) <- (rs'.st.(i) lxor rs'.st.((i+1) mod 55)) land 0x3FFFFFFF;
done;
Obj.magic rs' (* sorry! *)
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 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
let rec list_split l len acc = match len,l with
| _,[]
| 0,_ -> List.rev acc, l
| _,x::xs -> list_split xs (len-1) (x::acc)
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)
let rec force_drop n xs =
match xs() with
| Nil ->
Nil
| Cons (_, xs) ->
let n = n - 1 in
if n = 0 then
xs()
else
force_drop n xs
let drop n xs =
if n < 0 then invalid_arg "Seq.drop"
else if n = 0 then
xs
else
fun () ->
force_drop n xs
(* 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)
(** [drop_one l []] returns all versions of [l] with one element removed, for example
[drop_one [1;2;3] [] = [ [2;3]; [1;3]; [1;2] ]] *)
let rec drop_one (l : 'a list) (rev_prefix : 'a list) : 'a list list = match l with
| [] -> []
| x::xs -> (List.rev rev_prefix @ xs) :: drop_one xs (x::rev_prefix)
let rec build_list_shrink_tree (l : 'a t list) : 'a list t Seq.t = match l with
| [] -> Seq.empty
| _::_ ->
fun () ->
let len = List.length l in
if len < 4 then
let candidates = drop_one l [] in
List.fold_right (* try dropping each element in turn, starting with the list head *)
(fun cand acc -> Seq.cons (Tree (List.map root cand, build_list_shrink_tree cand)) acc)
candidates
(fun () -> children (sequence_list l) ()) () (* otherwise, reduce element(s) *)
else
let xs,ys = list_split l ((1 + len) / 2) [] in
let xs_roots = List.map root xs in
let ys_roots = List.map root ys in
(* Try reducing a list [1;2;3;4] in halves: [1;2] and [3;4] *)
Seq.cons (Tree (xs_roots, build_list_shrink_tree xs))
(Seq.cons (Tree (ys_roots, build_list_shrink_tree ys))
(fun () ->
(* Try dropping an element from either half: [2;3;4] and [1;2;4] *)
let rest = List.tl l in
let rest_roots = List.map root rest in
(Seq.cons (Tree (rest_roots, build_list_shrink_tree rest))
(Seq.cons (Tree (xs_roots@(List.tl ys_roots), build_list_shrink_tree (xs@(List.tl ys))))
(fun () -> children (sequence_list l) ()))) (* at bottom: reduce elements *)
() )) ()
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 ->
let st' = RS.split st in
let ftree = f st in
let xtree = x st' in
Tree.ap ftree xtree
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 ->
let st' = RS.split st in
let gentree = gen st in
Tree.bind gentree (fun a -> f a (RS.copy 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 exponential (mean : float) =
if Float.is_nan mean then invalid_arg "Gen.exponential";
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 neg_int : int t = nat >|= Int.neg
(** [option gen] shrinks towards [None] then towards shrinks of [gen]. *)
let option ?(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)
(** [opt] is an alias of {!val:option} for backward compatibility. *)
let opt = option
let result ?(ratio : float = 0.75) (ok_gen : 'a t) (err_gen : 'e t) : ('a, 'e) result t = fun st ->
let p = RS.float st 1. in
if p < (1. -. ratio)
then Tree.map (fun e -> Error e) (err_gen st)
else Tree.map (fun o -> Ok o) (ok_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 : RS.t -> int =
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 ?(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_bound (List.length l - 1) >>= List.nth l
let oneofl (l : 'a list) : 'a t =
int_bound (List.length l - 1) >|= List.nth l
let oneofa (a : 'a array) : 'a t =
int_bound (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
(* A tail-recursive implementation over Tree.t *)
let list_size (size : int t) (gen : 'a t) : 'a list t =
fun st ->
let st' = RS.split st in
Tree.bind (size st) @@ fun size ->
let st' = RS.copy st' in (* start each loop from same Random.State to recreate same element (prefix) *)
let rec loop n acc = (* phase 1: build a list of element trees, tail recursively *)
if n <= 0 (* phase 2: build a list shrink Tree of element trees, tail recursively *)
then List.fold_left (fun acc t -> Tree.liftA2 List.cons t acc) (Tree.pure []) acc
else (loop [@tailcall]) (n - 1) ((gen st')::acc)
in
loop size []
(** [list_ignore_size_tree] is a helper applying its own size shrinking heuristic,
and thus using only the root of [size]'s output shrink [Tree]. *)
let list_ignore_size_tree (size : int t) (gen : 'a t) : 'a list t = fun st ->
let st' = RS.split st in
let size = Tree.root (size st) in
let st' = RS.copy st' in (* start each loop from same Random.State to recreate same element (prefix) *)
let rec loop n acc = (* phase 1: build a list of element trees, tail recursively *)
if n <= 0 (* phase 2: build a list shrink Tree of element trees, tail recursively *)
then
let l = List.rev acc in
Tree.Tree (List.map Tree.root l, Tree.build_list_shrink_tree l)
else (loop [@tailcall]) (n - 1) ((gen st')::acc)
in
loop size []
let list (gen : 'a t) : 'a list t = list_ignore_size_tree 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 -> option 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
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
(** 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 + 1) (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
let st' = RS.split st 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 st' = RS.copy st' in (* start char generation from same Random.State to recreate same char prefix (when size shrinking) *)
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 bytes_of_char_list cs =
let b = Buffer.create (List.length cs) in
List.iter (fun c -> Buffer.add_char b c) cs;
let bytes = Buffer.to_bytes b in
Buffer.clear b;
bytes
let bytes : bytes t = list char >|= bytes_of_char_list
let bytes_of gen = list gen >|= bytes_of_char_list
let bytes_printable = list printable >|= bytes_of_char_list
let bytes_small = list_ignore_size_tree small_nat char >|= bytes_of_char_list
let bytes_small_of gen = list_ignore_size_tree small_nat gen >|= bytes_of_char_list
let string_of_char_list cs =
let b = Buffer.create (List.length cs) in
List.iter (fun c -> Buffer.add_char b c) cs;
let str = Buffer.contents b in
Buffer.clear b;
str
let string : string t = list char >|= string_of_char_list
let string_of gen = list gen >|= string_of_char_list
let string_printable = list printable >|= string_of_char_list
let string_small = list_ignore_size_tree small_nat char >|= string_of_char_list
let string_small_of gen = list_ignore_size_tree small_nat gen >|= string_of_char_list
let small_string ?(gen=char) = string_small_of gen
let small_list gen = list_ignore_size_tree small_nat gen
let small_array gen = list_ignore_size_tree small_nat gen >|= Array.of_list
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 set_shrink shrink gen =
make_primitive
~gen:(fun st -> gen st |> Tree.root)
~shrink
let no_shrink (gen: 'a t) : 'a t = set_shrink (fun _ -> Seq.empty) gen
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 = string_of_float
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 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
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)