filename
stringlengths 3
67
| data
stringlengths 0
58.3M
| license
stringlengths 0
19.5k
|
---|---|---|
unit_slicing_fancy.ml | (** Unit test for Owl_stats module *)
open Owl
open Owl_types
(* some test input *)
let x0 = Arr.sequential [| 10 |]
let x1 = Arr.sequential [| 10; 10 |]
let x2 = Arr.sequential [| 10; 10; 10 |]
let x3 = Arr.sequential [| 5; 5; 5; 5 |]
(* a module with functions to test *)
module To_test = struct
let test_01 () =
let s = [ R [] ] in
let y = Arr.get_fancy s x0 in
Arr.(y = x0)
let test_02 () =
let s = [ L [ 1 ] ] in
let y = Arr.get_fancy s x0 in
let z = Arr.of_array [| 1. |] [| 1 |] in
Arr.(y = z)
let test_03 () =
let s = [ L [ 5; 1; 2 ] ] in
let y = Arr.get_fancy s x0 in
let z = Arr.of_array [| 5.; 1.; 2. |] [| 3 |] in
Arr.(y = z)
let test_04 () =
let s = [ R []; L [ 1 ] ] in
let y = Arr.get_fancy s x1 in
let z =
Arr.of_array [| 1.; 11.; 21.; 31.; 41.; 51.; 61.; 71.; 81.; 91. |] [| 10; 1 |]
in
Arr.(y = z)
let test_05 () =
let s = [ R [ 2 ]; L [ 1 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 21. |] [| 1; 1 |] in
Arr.(y = z)
let test_06 () =
let s = [ R [ 2; 3 ]; L [ 5; 4 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 25.; 24.; 35.; 34. |] [| 2; 2 |] in
Arr.(y = z)
let test_07 () =
let s = [ L [ 3; 2 ]; R [ 5; 4 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 35.; 34.; 25.; 24. |] [| 2; 2 |] in
Arr.(y = z)
let test_08 () =
let s = [ L [ -1; -2 ]; L [ 5; 4 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 95.; 94.; 85.; 84. |] [| 2; 2 |] in
Arr.(y = z)
let test_09 () =
let s = [ I 5; L [ 5; 4 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 55.; 54. |] [| 1; 2 |] in
Arr.(y = z)
let test_10 () =
let s = [ L [ 5; 4 ]; I (-4) ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 56.; 46. |] [| 2; 1 |] in
Arr.(y = z)
let test_11 () =
let s = [ I 5; I (-4) ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 56. |] [| 1; 1 |] in
Arr.(y = z)
let test_12 () =
let s = [ I 1; L [ 5 ]; L [ -4 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 156. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_13 () =
let s = [ I 1; I 5; I (-4) ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 156. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_14 () =
let s = [ R [ 5; 5 ]; L [ 6 ]; L [ -4 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 566. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_15 () =
let s = [ L [ 5 ]; L [ 6 ]; L [ -4 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 566. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_16 () =
let s = [ L [ 5 ]; L [ 6; -1 ]; L [ -4 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 566.; 596. |] [| 1; 2; 1 |] in
Arr.(y = z)
let test_17 () =
let s = [ L [ 8; 5 ]; L [ 6; -1 ]; L [ -4 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 866.; 896.; 566.; 596. |] [| 2; 2; 1 |] in
Arr.(y = z)
let test_18 () =
let s = [ L [ 2 ]; L [ 3 ]; L [ -1 ]; L [ 1 ] ] in
let y = Arr.get_fancy s x3 in
let z = Arr.of_array [| 346. |] [| 1; 1; 1; 1 |] in
Arr.(y = z)
let test_19 () =
let s = [ I 2; I 3; L [ -1; 2 ]; L [ 3; 1; 0 ] ] in
let y = Arr.get_fancy s x3 in
let z = Arr.of_array [| 348.; 346.; 345.; 338.; 336.; 335. |] [| 1; 1; 2; 3 |] in
Arr.(y = z)
let test_20 () =
let s = [ L [ 2 ]; R [ 3; 3 ]; L [ -1; 2 ]; L [ 3; 1; 0 ] ] in
let y = Arr.get_fancy s x3 in
let z = Arr.of_array [| 348.; 346.; 345.; 338.; 336.; 335. |] [| 1; 1; 2; 3 |] in
Arr.(y = z)
let test_21 () =
let s = [ I 1; I 2; I 3 ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 123. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_22 () =
let s = [ I 1; I (-2); I 3 ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 183. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_23 () =
let s = [ I 1; I (-2); I (-3) ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 187. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_24 () =
let s = [ I (-1); I (-2); I (-3) ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 987. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_25 () =
let s = [ L [ -1 ]; I 2; L [ -3 ] ] in
let y = Arr.get_fancy s x2 in
let z = Arr.of_array [| 927. |] [| 1; 1; 1 |] in
Arr.(y = z)
let test_26 () =
let s = [ R [ 3; 2 ]; L [ 5; 4 ] ] in
let y = Arr.get_fancy s x1 in
let z = Arr.of_array [| 35.; 34.; 25.; 24. |] [| 2; 2 |] in
Arr.(y = z)
let test_27 () =
let s = [ L [ 0; 1; 2 ] ] in
let x = Arr.copy x0 in
let y = Arr.of_array [| 2.; 3.; 5. |] [| 3 |] in
Arr.set_fancy s x y;
let z = Arr.of_array [| 2.; 3.; 5.; 3.; 4.; 5.; 6.; 7.; 8.; 9. |] [| 10 |] in
Arr.(x = z)
let test_28 () =
let s = [ L [ 5; 4; 3 ] ] in
let x = Arr.copy x0 in
let y = Arr.of_array [| 2.; 3.; 5. |] [| 3 |] in
Arr.set_fancy s x y;
let z = Arr.of_array [| 0.; 1.; 2.; 5.; 3.; 2.; 6.; 7.; 8.; 9. |] [| 10 |] in
Arr.(x = z)
let test_29 () =
let s = [ R [ 2; 8; 3 ] ] in
let x = Arr.copy x0 in
let y = Arr.of_array [| 2.; 3.; 5. |] [| 3 |] in
Arr.set_fancy s x y;
let z = Arr.of_array [| 0.; 1.; 2.; 3.; 4.; 3.; 6.; 7.; 5.; 9. |] [| 10 |] in
Arr.(x = z)
let test_30 () =
let s = [ L [ -1 ]; R [ -1 ] ] in
let x = Arr.copy x1 in
let y = Arr.of_array [| 0. |] [| 1; 1 |] in
Arr.set_fancy s x y;
let z = Arr.copy x1 in
Arr.set z [| 9; 9 |] 0.;
Arr.(x = z)
let test_31 () =
let s = [ R [ 0; 9; 9 ]; R [ 0; 9; 9 ] ] in
let x = Arr.copy x1 in
let y = Arr.of_array [| 5.; 6.; 7.; 8. |] [| 2; 2 |] in
Arr.set_fancy s x y;
let z = Arr.copy x1 in
Arr.set z [| 0; 0 |] 5.;
Arr.set z [| 0; 9 |] 6.;
Arr.set z [| 9; 0 |] 7.;
Arr.set z [| 9; 9 |] 8.;
Arr.(x = z)
let test_32 () =
let s = [ R [ -1; 0; -9 ]; R [ -1; 0; -9 ] ] in
let x = Arr.copy x1 in
let y = Arr.of_array [| 5.; 6.; 7.; 8. |] [| 2; 2 |] in
Arr.set_fancy s x y;
let z = Arr.copy x1 in
Arr.set z [| 0; 0 |] 8.;
Arr.set z [| 0; 9 |] 7.;
Arr.set z [| 9; 0 |] 6.;
Arr.set z [| 9; 9 |] 5.;
Arr.(x = z)
let test_33 () =
let s = [ I (-1); L [ -1 ]; R [ -2 ] ] in
let x = Arr.copy x2 in
let y = Arr.of_array [| 5. |] [| 1; 1; 1 |] in
Arr.set_fancy s x y;
let z = Arr.copy x2 in
Arr.set z [| 9; 9; 8 |] 5.;
Arr.(x = z)
let test_34 () =
let s = [ I (-1); L [ 5; 6 ]; L [ 0 ] ] in
let x = Arr.copy x2 in
let y = Arr.of_array [| 1.; 2. |] [| 1; 2; 1 |] in
Arr.set_fancy s x y;
let z = Arr.copy x2 in
Arr.set z [| 9; 5; 0 |] 1.;
Arr.set z [| 9; 6; 0 |] 2.;
Arr.(x = z)
let test_35 () =
(* This just checks that the extended accessor syntax compiles *)
let open Arr in
let x = of_array [| 0.5; 0.7 |] [| 2 |] in
let y = of_array [| 0.8; 0.9; 1.1; 1.2 |] [| 2; 2 |] in
let v1 = l2norm' (x.${[ 1 ]} - of_array [| 0.7 |] [| 1 |]) in
let v2 = abs_float (x.%{1} -. 0.7) in
let v3 = abs_float (y.%{0; 1} -. 0.9) in
let v4 = l2norm' (y.${[ 0 ]; [ 0; -1 ]} - of_array [| 0.8; 0.9 |] [| 2 |]) in
Stdlib.(v1 < 1e-10 && v2 < 1e-10 && v3 < 1e-10 && v4 < 1e-10)
let test_36 () =
(* This just checks that the extended accessor syntax compiles *)
let open Mat in
let x = gaussian 2 2 in
Stdlib.(x.%{0; 1} = x.%{0, 1})
end
(* the tests *)
let test_01 () = Alcotest.(check bool) "test 01" true (To_test.test_01 ())
let test_02 () = Alcotest.(check bool) "test 02" true (To_test.test_02 ())
let test_03 () = Alcotest.(check bool) "test 03" true (To_test.test_03 ())
let test_04 () = Alcotest.(check bool) "test 04" true (To_test.test_04 ())
let test_05 () = Alcotest.(check bool) "test 05" true (To_test.test_05 ())
let test_06 () = Alcotest.(check bool) "test 06" true (To_test.test_06 ())
let test_07 () = Alcotest.(check bool) "test 07" true (To_test.test_07 ())
let test_08 () = Alcotest.(check bool) "test 08" true (To_test.test_08 ())
let test_09 () = Alcotest.(check bool) "test 09" true (To_test.test_09 ())
let test_10 () = Alcotest.(check bool) "test 10" true (To_test.test_10 ())
let test_11 () = Alcotest.(check bool) "test 11" true (To_test.test_11 ())
let test_12 () = Alcotest.(check bool) "test 12" true (To_test.test_12 ())
let test_13 () = Alcotest.(check bool) "test 13" true (To_test.test_13 ())
let test_14 () = Alcotest.(check bool) "test 14" true (To_test.test_14 ())
let test_15 () = Alcotest.(check bool) "test 15" true (To_test.test_15 ())
let test_16 () = Alcotest.(check bool) "test 16" true (To_test.test_16 ())
let test_17 () = Alcotest.(check bool) "test 17" true (To_test.test_17 ())
let test_18 () = Alcotest.(check bool) "test 18" true (To_test.test_18 ())
let test_19 () = Alcotest.(check bool) "test 19" true (To_test.test_19 ())
let test_20 () = Alcotest.(check bool) "test 20" true (To_test.test_20 ())
let test_21 () = Alcotest.(check bool) "test 21" true (To_test.test_21 ())
let test_22 () = Alcotest.(check bool) "test 22" true (To_test.test_22 ())
let test_23 () = Alcotest.(check bool) "test 23" true (To_test.test_23 ())
let test_24 () = Alcotest.(check bool) "test 24" true (To_test.test_24 ())
let test_25 () = Alcotest.(check bool) "test 25" true (To_test.test_25 ())
let test_26 () = Alcotest.(check bool) "test 26" true (To_test.test_26 ())
let test_27 () = Alcotest.(check bool) "test 27" true (To_test.test_27 ())
let test_28 () = Alcotest.(check bool) "test 28" true (To_test.test_28 ())
let test_29 () = Alcotest.(check bool) "test 29" true (To_test.test_29 ())
let test_30 () = Alcotest.(check bool) "test 30" true (To_test.test_30 ())
let test_31 () = Alcotest.(check bool) "test 31" true (To_test.test_31 ())
let test_32 () = Alcotest.(check bool) "test 32" true (To_test.test_32 ())
let test_33 () = Alcotest.(check bool) "test 33" true (To_test.test_33 ())
let test_34 () = Alcotest.(check bool) "test 34" true (To_test.test_34 ())
let test_35 () = Alcotest.(check bool) "test 35" true (To_test.test_35 ())
let test_36 () = Alcotest.(check bool) "test 36" true (To_test.test_36 ())
let test_set =
[ "test 01", `Slow, test_01; "test 02", `Slow, test_02; "test 03", `Slow, test_03
; "test 04", `Slow, test_04; "test 05", `Slow, test_05; "test 06", `Slow, test_06
; "test 07", `Slow, test_07; "test 08", `Slow, test_08; "test 09", `Slow, test_09
; "test 10", `Slow, test_10; "test 11", `Slow, test_11; "test 12", `Slow, test_12
; "test 13", `Slow, test_13; "test 14", `Slow, test_14; "test 15", `Slow, test_15
; "test 16", `Slow, test_16; "test 17", `Slow, test_17; "test 18", `Slow, test_18
; "test 19", `Slow, test_19; "test 20", `Slow, test_20; "test 21", `Slow, test_21
; "test 22", `Slow, test_22; "test 23", `Slow, test_23; "test 24", `Slow, test_24
; "test 25", `Slow, test_25; "test 26", `Slow, test_26; "test 27", `Slow, test_27
; "test 28", `Slow, test_28; "test 29", `Slow, test_29; "test 30", `Slow, test_30
; "test 31", `Slow, test_31; "test 32", `Slow, test_32; "test 33", `Slow, test_33
; "test 34", `Slow, test_34; "test 35", `Slow, test_35; "test 36", `Slow, test_36 ]
| (** Unit test for Owl_stats module *)
|
disableTransitGatewayRouteTablePropagation.mli |
open Types
type input = DisableTransitGatewayRouteTablePropagationRequest.t
type output = DisableTransitGatewayRouteTablePropagationResult.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type
error := error | |
dune |
(executable
(name foo))
| |
Common.ml |
let logger = Logging.get_logger [ __MODULE__ ]
(*###########################################################################*)
(* Prelude *)
(*###########################################################################*)
(* if set, certain functions like unwind_protect will not
* do a try and finalize and instead just call the function, which
* helps in ocamldebug and also in getting better backtraces.
* This is also useful to set in a js_of_ocaml (jsoo) context to
* again get better backtraces.
*)
let debugger = ref false
(* You should set this to true when you run code compiled by js_of_ocaml
* so some functions can change their implementation and rely
* less on non-portable API like Unix which does not work well under
* node or in the browser.
*)
let jsoo = ref false
(*****************************************************************************)
(* Circular dependencies *)
(*****************************************************************************)
(* The following functions should be in their respective sections but
* because some functions in some sections use functions in other
* sections, and because I don't want to take care of the order of
* those sections (of those dependencies), I put the functions causing
* dependency problem here. C is better than OCaml on this with the
* ability to declare prototypes, enabling some form of forward
* references.
*)
let spf = Printf.sprintf
exception UnixExit of int
(*****************************************************************************)
(* Equality *)
(*****************************************************************************)
let ( =|= ) : int -> int -> bool = ( = )
let ( =$= ) : char -> char -> bool = ( = )
let ( =:= ) : bool -> bool -> bool = ( = )
(* dangerous, do not use, see the comment in Common.mli *)
let ( =*= ) = ( = )
(* To forbid people to use the polymorphic '='.
* See https://blog.janestreet.com/the-perils-of-polymorphic-compare/
*)
let ( = ) = String.equal
(*****************************************************************************)
(* Debugging/logging *)
(*****************************************************************************)
let pr s =
print_string s;
print_string "\n";
flush stdout
let pr2 s =
prerr_string s;
prerr_string "\n";
flush stderr
let _already_printed = Hashtbl.create 101
let disable_pr2_once = ref false
let xxx_once f s =
if !disable_pr2_once then pr2 s
else if not (Hashtbl.mem _already_printed s) then (
Hashtbl.add _already_printed s true;
f ("(ONCE) " ^ s))
let pr2_once s = xxx_once pr2 s
let pr2_gen x = pr2 (Dumper.dump x)
(* to be used in pipe operations *)
let before_return f v =
f v;
v
(*****************************************************************************)
(* Profiling *)
(*****************************************************************************)
(* see also profiling/Profiling.ml now *)
(* Report the time a function takes. *)
let with_time f =
let t1 = Unix.gettimeofday () in
let res = f () in
let t2 = Unix.gettimeofday () in
(res, t2 -. t1)
let pr_time name f =
let t1 = Unix.gettimeofday () in
Fun.protect f ~finally:(fun () ->
let t2 = Unix.gettimeofday () in
pr (spf "%s: %.6f s" name (t2 -. t1)))
let pr2_time name f =
let t1 = Unix.gettimeofday () in
Fun.protect f ~finally:(fun () ->
let t2 = Unix.gettimeofday () in
pr2 (spf "%s: %.6f s" name (t2 -. t1)))
(*###########################################################################*)
(* List functions *)
(*###########################################################################*)
(*****************************************************************************)
(* List.map *)
(*****************************************************************************)
(*
Custom list type used to store intermediate lists, while minimizing
the number of allocated blocks.
*)
type 'a list5 =
| Elt of 'a * 'a list5
| Tuple of 'a * 'a * 'a * 'a * 'a * 'a list5
| Empty
let rev5 l =
let rec aux acc l =
match l with
| Tuple (e, d, c, b, a, l) ->
(* common case *)
aux (a :: b :: c :: d :: e :: acc) l
| Elt (a, l) -> aux (a :: acc) l
| Empty -> acc
in
aux [] l
let rec slow_map acc f l =
match l with
| [] -> rev5 acc
| [ a ] -> rev5 (Elt (f a, acc))
| [ a; b ] ->
let a = f a in
let b = f b in
rev5 (Elt (b, Elt (a, acc)))
| [ a; b; c ] ->
let a = f a in
let b = f b in
let c = f c in
rev5 (Elt (c, Elt (b, Elt (a, acc))))
| [ a; b; c; d ] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
rev5 (Elt (d, Elt (c, Elt (b, Elt (a, acc)))))
| [ a; b; c; d; e ] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
rev5 (Elt (e, Elt (d, Elt (c, Elt (b, Elt (a, acc))))))
| a :: b :: c :: d :: e :: l ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
slow_map (Tuple (e, d, c, b, a, acc)) f l
let rec fast_map rec_calls_remaining f l =
if rec_calls_remaining <= 0 then slow_map Empty f l
else
match l with
| [] -> []
| [ a ] -> [ f a ]
| [ a; b ] ->
let a = f a in
let b = f b in
[ a; b ]
| [ a; b; c ] ->
let a = f a in
let b = f b in
let c = f c in
[ a; b; c ]
| [ a; b; c; d ] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
[ a; b; c; d ]
| [ a; b; c; d; e ] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
[ a; b; c; d; e ]
| a :: b :: c :: d :: e :: l ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
a :: b :: c :: d :: e :: fast_map (rec_calls_remaining - 1) f l
(*
This implementation of List.map makes at most 1000 non-tailrec calls
before switching to a slower tailrec implementation.
Additionally, this implementation guarantees left-to-right evaluation.
*)
let map f l = fast_map 1000 f l
(*****************************************************************************)
(* Other list functions *)
(*****************************************************************************)
(* Tail-recursive to prevent stack overflows. *)
let flatten xss =
xss |> List.fold_left (fun acc xs -> List.rev_append xs acc) [] |> List.rev
let rec drop n xs =
match (n, xs) with
| 0, _ -> xs
| _, [] -> failwith "drop: not enough"
| n, _x :: xs -> drop (n - 1) xs
let take n xs =
let rec next n xs acc =
match (n, xs) with
| 0, _ -> List.rev acc
| _, [] -> failwith "Common.take: not enough"
| n, x :: xs -> next (n - 1) xs (x :: acc)
in
next n xs []
let enum x n =
if not (x <= n) then
failwith (Printf.sprintf "bad values in enum, expect %d <= %d" x n);
let rec enum_aux acc x n =
if x =|= n then n :: acc else enum_aux (x :: acc) (x + 1) n
in
List.rev (enum_aux [] x n)
let exclude p xs = List.filter (fun x -> not (p x)) xs
let rec (span : ('a -> bool) -> 'a list -> 'a list * 'a list) =
fun p -> function
| [] -> ([], [])
| x :: xs ->
if p x then
let l1, l2 = span p xs in
(x :: l1, l2)
else ([], x :: xs)
let rec take_safe n xs =
match (n, xs) with
| 0, _ -> []
| _, [] -> []
| n, x :: xs -> x :: take_safe (n - 1) xs
let group_by f xs =
(* use Hashtbl.find_all property *)
let h = Hashtbl.create 101 in
(* could use Set *)
let hkeys = Hashtbl.create 101 in
xs
|> List.iter (fun x ->
let k = f x in
Hashtbl.replace hkeys k true;
Hashtbl.add h k x);
Hashtbl.fold (fun k _ acc -> (k, Hashtbl.find_all h k) :: acc) hkeys []
let group_by_multi fkeys xs =
(* use Hashtbl.find_all property *)
let h = Hashtbl.create 101 in
(* could use Set *)
let hkeys = Hashtbl.create 101 in
xs
|> List.iter (fun x ->
let ks = fkeys x in
ks
|> List.iter (fun k ->
Hashtbl.replace hkeys k true;
Hashtbl.add h k x));
Hashtbl.fold (fun k _ acc -> (k, Hashtbl.find_all h k) :: acc) hkeys []
(* you should really use group_assoc_bykey_eff *)
let rec group_by_mapped_key fkey l =
match l with
| [] -> []
| x :: xs ->
let k = fkey x in
let xs1, xs2 =
List.partition
(fun x' ->
let k2 = fkey x' in
k =*= k2)
xs
in
(k, x :: xs1) :: group_by_mapped_key fkey xs2
let rec zip xs ys =
match (xs, ys) with
| [], [] -> []
| [], _ -> failwith "zip: not same length"
| _, [] -> failwith "zip: not same length"
| x :: xs, y :: ys -> (x, y) :: zip xs ys
let null xs =
match xs with
| [] -> true
| _ -> false
let index_list xs =
if null xs then [] (* enum 0 (-1) generate an exception *)
else zip xs (enum 0 (List.length xs - 1))
let index_list_0 xs = index_list xs
let index_list_1 xs = xs |> index_list |> map (fun (x, i) -> (x, i + 1))
let sort_prof a b = List.sort a b
let sort_by_val_highfirst xs =
sort_prof (fun (_k1, v1) (_k2, v2) -> compare v2 v1) xs
let sort_by_val_lowfirst xs =
sort_prof (fun (_k1, v1) (_k2, v2) -> compare v1 v2) xs
let sort_by_key_highfirst xs =
sort_prof (fun (k1, _v1) (k2, _v2) -> compare k2 k1) xs
let sort_by_key_lowfirst xs =
sort_prof (fun (k1, _v1) (k2, _v2) -> compare k1 k2) xs
let push v l = l := v :: !l
(*###########################################################################*)
(* Exn *)
(*###########################################################################*)
let unwind_protect f cleanup =
if !debugger then f ()
else
try f () with
| exn ->
let e = Exception.catch exn in
cleanup e;
Exception.reraise e
(* TODO: remove and use Fun.protect instead? but then it will not have the
* !debugger goodies *)
let finalize f cleanup =
(* Does this debugger mode changes the semantic of the program too much?
* Is it ok in a debugging context to not call certain cleanup()
* and let the exn bubble up?
* TODO: maybe I should not use save_excursion/finalize so much? maybe
* -debugger can help to see code that I should refactor?
*)
if !debugger then (
let res = f () in
cleanup ();
res)
else Fun.protect f ~finally:cleanup
let save_excursion reference newv f =
let old = !reference in
reference := newv;
finalize f (fun _ -> reference := old)
let memoized ?(use_cache = true) h k f =
if not use_cache then f ()
else
try Hashtbl.find h k with
| Not_found ->
let v = f () in
Hashtbl.add h k v;
v
exception Todo
exception Impossible
exception Multi_found (* to be consistent with Not_found *)
let exn_to_s exn = Printexc.to_string exn
(*###########################################################################*)
(* Basic features *)
(*###########################################################################*)
(*****************************************************************************)
(* Test *)
(*****************************************************************************)
(* See Testutil *)
(*****************************************************************************)
(* Persistence *)
(*****************************************************************************)
let get_value filename =
let chan = open_in_bin filename in
let x = input_value chan in
(* <=> Marshal.from_channel *)
close_in chan;
x
let write_value valu filename =
let chan = open_out_bin filename in
output_value chan valu;
(* <=> Marshal.to_channel *)
(* Marshal.to_channel chan valu [Marshal.Closures]; *)
close_out chan
(*****************************************************************************)
(* Composition/Control *)
(*****************************************************************************)
(*****************************************************************************)
(* Error management *)
(*****************************************************************************)
(*****************************************************************************)
(* Arguments/options and command line *)
(*****************************************************************************)
(* use Cmdliner, or Arg_helpers if you really have to *)
(*###########################################################################*)
(* Basic types *)
(*###########################################################################*)
(*****************************************************************************)
(* Bool *)
(*****************************************************************************)
(*****************************************************************************)
(* Char *)
(*****************************************************************************)
(*****************************************************************************)
(* Num *)
(*****************************************************************************)
(*****************************************************************************)
(* Tuples *)
(*****************************************************************************)
(*****************************************************************************)
(* Option/Either *)
(*****************************************************************************)
let ( let* ) = Option.bind
(* type 'a maybe = Just of 'a | None *)
let ( >>= ) m1 m2 =
match m1 with
| None -> None
| Some x -> m2 x
(*
(*http://roscidus.com/blog/blog/2013/10/13/ocaml-tips/#handling-option-types*)
let (|?) maybe default =
match maybe with
| Some v -> v
| None -> Lazy.force default
*)
(* deprecated: use Option.map
let map_opt f = function
| None -> None
| Some x -> Some (f x)
*)
(* deprecated: use Option.iter
let do_option f = function
| None -> ()
| Some x -> f x
*)
(* deprecated: use Option.to_list
let opt_to_list : 'a option -> 'a list = function
| None -> []
| Some x -> [x]
*)
(* often used in grammar actions in menhir *)
let optlist_to_list = function
| None -> []
| Some xs -> xs
(* not sure why but can't use let (?:) a b = ... then at use time ocaml yells*)
let ( ||| ) a b =
match a with
| Some x -> x
| None -> b
type ('a, 'b) either = Left of 'a | Right of 'b [@@deriving eq, show]
(* with sexp *)
type ('a, 'b, 'c) either3 = Left3 of 'a | Middle3 of 'b | Right3 of 'c
[@@deriving eq, show]
(* with sexp *)
(* If you don't want to use [@@deriving eq, show] above, you
* can copy-paste manually the generated code by getting the
* result of ocamlfind ocamlc -dsource ... on this code
* type ('a, 'b) either =
* | Left of 'a
* | Right of 'b
* [@@deriving show]
*
* which should look like this:
* let pp_either = fun poly_a -> fun poly_b -> fun fmt -> function
* | Left a0 ->
* (Format.fprintf fmt "(@[<2>Left@ ";
* (poly_a fmt) a0;
* Format.fprintf fmt "@])")
* | Right a0 ->
* (Format.fprintf fmt "(@[<2>Right@ ";
* (poly_b fmt) a0;
* Format.fprintf fmt "@])")
*
* let pp_either3 = fun poly_a -> fun poly_b -> fun poly_c -> fun fmt -> function
* | Left3 a0 ->
* (Format.fprintf fmt "(@[<2>Left3@ ";
* (poly_a fmt) a0;
* Format.fprintf fmt "@])")
* | Middle3 a0 ->
* (Format.fprintf fmt "(@[<2>Middle3@ ";
* (poly_b fmt) a0;
* Format.fprintf fmt "@])")
* | Right3 a0 ->
* (Format.fprintf fmt "(@[<2>Right3@ ";
* (poly_c fmt) a0;
* Format.fprintf fmt "@])")
*)
let partition_either f l =
let rec part_either left right = function
| [] -> (List.rev left, List.rev right)
| x :: l -> (
match f x with
| Left e -> part_either (e :: left) right l
| Right e -> part_either left (e :: right) l)
in
part_either [] [] l
let partition_either3 f l =
let rec part_either left middle right = function
| [] -> (List.rev left, List.rev middle, List.rev right)
| x :: l -> (
match f x with
| Left3 e -> part_either (e :: left) middle right l
| Middle3 e -> part_either left (e :: middle) right l
| Right3 e -> part_either left middle (e :: right) l)
in
part_either [] [] [] l
let partition_result f l =
let rec aux left right = function
| [] -> (List.rev left, List.rev right)
| x :: l -> (
match f x with
| Ok x -> aux (x :: left) right l
| Error x -> aux left (x :: right) l)
in
aux [] [] l
let rec filter_some = function
| [] -> []
| None :: l -> filter_some l
| Some e :: l -> e :: filter_some l
(* Tail-recursive to prevent stack overflows. *)
let map_filter f xs =
List.fold_left
(fun acc x ->
match f x with
| None -> acc
| Some y -> y :: acc)
[] xs
|> List.rev
let rec find_some_opt p = function
| [] -> None
| x :: l -> (
match p x with
| Some v -> Some v
| None -> find_some_opt p l)
let find_some p xs =
match find_some_opt p xs with
| None -> raise Not_found
| Some x -> x
(*****************************************************************************)
(* Regexp, can also use PCRE *)
(*****************************************************************************)
let (matched : int -> string -> string) = fun i s -> Str.matched_group i s
let matched1 s = matched 1 s
let matched2 s = (matched 1 s, matched 2 s)
let matched3 s = (matched 1 s, matched 2 s, matched 3 s)
let matched4 s = (matched 1 s, matched 2 s, matched 3 s, matched 4 s)
let matched5 s =
(matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s)
let matched6 s =
(matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s, matched 6 s)
let matched7 s =
( matched 1 s,
matched 2 s,
matched 3 s,
matched 4 s,
matched 5 s,
matched 6 s,
matched 7 s )
let _memo_compiled_regexp = Hashtbl.create 101
let candidate_match_func s re =
(* old: Str.string_match (Str.regexp re) s 0 *)
let compile_re =
memoized _memo_compiled_regexp re (fun () -> Str.regexp re)
in
Str.string_match compile_re s 0
let match_func s re = candidate_match_func s re
let ( =~ ) s re = match_func s re
let split sep s = Str.split (Str.regexp sep) s
let join sep xs = String.concat sep xs
(*****************************************************************************)
(* Strings *)
(*****************************************************************************)
(* ruby *)
let i_to_s = string_of_int
let s_to_i = int_of_string
let null_string s = s = ""
(*****************************************************************************)
(* Filenames *)
(*****************************************************************************)
(* TODO: we should use strong types like in Li Haoyi filename Scala library! *)
type filename = string (* TODO could check that exist :) type sux *)
[@@deriving show, eq]
(* with sexp *)
type dirname = string
(* TODO could check that exist :) type sux *)
(* with sexp *)
(* file or dir *)
type path = string
let chop_dirsymbol = function
| s when s =~ "\\(.*\\)/$" -> matched1 s
| s -> s
(* pre: prj_path must not contain regexp symbol *)
let filename_without_leading_path prj_path s =
let prj_path = chop_dirsymbol prj_path in
if s = prj_path then "."
else if
(* Note that we should handle multiple consecutive '/' as in 'path/to//file' *)
s =~ "^" ^ prj_path ^ "/+\\(.*\\)$"
then matched1 s
else
failwith (spf "cant find filename_without_project_path: %s %s" prj_path s)
(* TODO: we should use strong types like in Li Haoyi filename Scala library! *)
let readable ~root s =
match root with
| "/" -> s
| "." -> (
match s with
| s when s =~ "^/" ->
failwith (spf "file %s shouldn't start with / when root is ." s)
| s when s =~ "^\\./\\(.*\\)" -> matched1 s
| _ -> s)
| _ -> filename_without_leading_path root s
let is_directory file =
(* old: (Unix.stat file).Unix.st_kind =*= Unix.S_DIR *)
Sys.is_directory file
(*****************************************************************************)
(* Dates *)
(*****************************************************************************)
(*****************************************************************************)
(* Lines/words/strings *)
(*****************************************************************************)
(*****************************************************************************)
(* Process/Files *)
(*****************************************************************************)
exception CmdError of Unix.process_status * string
let process_output_to_list2 ?(verbose = false) command =
let chan = Unix.open_process_in command in
let res = ref ([] : string list) in
let rec process_otl_aux () =
let e = input_line chan in
res := e :: !res;
if verbose then pr2 e;
process_otl_aux ()
in
try process_otl_aux () with
| End_of_file ->
let stat = Unix.close_process_in chan in
(List.rev !res, stat)
let cmd_to_list ?verbose command =
let l, exit_status = process_output_to_list2 ?verbose command in
match exit_status with
| Unix.WEXITED 0 -> l
| _ ->
raise
(CmdError
( exit_status,
spf "CMD = %s, RESULT = %s" command (String.concat "\n" l) ))
let cmd_to_list_and_status = process_output_to_list2
(*
Input a line of text from a file in a way that works for Windows files
or Unix files in any mode on any platform. Line terminators are eaten
up.
Known bug: CR characters preceding a CRLF sequence are eaten up anyway
in text mode on Windows. Workaround: open the file in binary mode.
Unix file on Unix: "a\nb" -> "a"
Windows file on Unix: "a\r\nb" -> "a" (* input_line returns "a\r" *)
Unix file on Windows text mode: "a\nb" -> "a"
Unix file on Windows binary mode: "a\nb" -> "a"
Windows file on Windows text mode: "a\r\nb" -> "a"
Windows file on Windows binary mode: "a\r\nb" -> "a"
What you need to know about Windows vs. Unix line endings
=========================================================
CR designates the byte '\r', LF designates '\n'.
CRLF designates the sequence "\r\n".
On Windows, there are two modes for opening a file for reading or writing:
- binary mode, which is the same as on Unix.
- text mode, which is special.
A file opened in text mode on Windows causes the reads and the writes
to translate line endings:
- read from text file: CRLF -> LF
- write to text file: LF -> CRLF
To avoid these translations when running on Windows, the file must be
opened in binary mode.
Q: When must a file be opened in text mode?
A: Never. Only stdin, stdout, and stderr connected to a console should
be in text mode but the OS takes care of this for us.
Q: Really never?
A: Never for reading. For writing, maybe some Windows applications behave
so badly that they can't recognize single LFs, in which case local logs
and such might have to be opened in text mode. See next question.
Q: Do all text processing applications on Windows support LF line endings
in input files?
A: Hopefully. They really should. The only way they don't support single LFs
is if they open files in binary mode and then search for CRLF
sequences as line terminators exclusively, which would be strange.
Q: Do the parsers in pfff support all line endings?
A: Yes unless there's a bug. All parsers for real programming languages
should use the pattern '\r'?'\n' to match line endings.
*)
let input_text_line ic =
let s = input_line ic in
let len = String.length s in
if len > 0 && s.[len - 1] =$= '\r' then String.sub s 0 (len - 1) else s
let cat file =
let acc = ref [] in
let chan = open_in_bin file in
try
while true do
acc := input_text_line chan :: !acc
done;
assert false
with
| End_of_file ->
close_in chan;
List.rev !acc
(*
This implementation works even with Linux files like /dev/fd/63
created by bash's process substitution e.g.
my-ocaml-program <(echo contents)
See https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html
In bash, '<(echo contents)' is replaced by something like
'/dev/fd/63' which is a special file of apparent size 0 (as
reported by `Unix.stat`) but contains data (here,
"contents\n"). So we can't use 'Unix.stat' or 'in_channel_length'
to obtain the length of the file contents. Instead, we read the file
chunk by chunk until there's nothing left to read.
Why such a function is not provided by the ocaml standard library is
unclear.
*)
let read_file ?(max_len = max_int) path =
let buf_len = 4096 in
let extbuf = Buffer.create 4096 in
let buf = Bytes.create buf_len in
let rec loop fd =
match Unix.read fd buf 0 buf_len with
| 0 -> Buffer.contents extbuf
| num_bytes ->
assert (num_bytes > 0);
assert (num_bytes <= buf_len);
Buffer.add_subbytes extbuf buf 0 num_bytes;
if Buffer.length extbuf >= max_len then Buffer.sub extbuf 0 max_len
else loop fd
in
let fd = Unix.openfile path [ Unix.O_RDONLY ] 0 in
Fun.protect ~finally:(fun () -> Unix.close fd) (fun () -> loop fd)
let write_file ~file s =
let chan = open_out_bin file in
output_string chan s;
close_out chan
(* could be in control section too *)
let filemtime file =
if !jsoo then failwith "JSOO: Common.filemtime"
else (Unix.stat file).Unix.st_mtime
(*
Using an external C functions complicates the linking process of
programs using commons/. Thus, I replaced realpath() with an OCaml-only
similar functions fullpath().
external c_realpath: string -> string option = "caml_realpath"
let realpath2 path =
match c_realpath path with
| Some s -> s
| None -> failwith (spf "problem with realpath on %s" path)
let realpath2 path =
let stat = Unix.stat path in
let dir, suffix =
match stat.Unix.st_kind with
| Unix.S_DIR -> path, ""
| _ -> Filename.dirname path, Filename.basename path
in
let oldpwd = Sys.getcwd () in
Sys.chdir dir;
let realpath_dir = Sys.getcwd () in
Sys.chdir oldpwd;
Filename.concat realpath_dir suffix
let realpath path =
profile_code "Common.realpath" (fun () -> realpath2 path)
*)
let fullpath file =
if not (Sys.file_exists file) then
failwith (spf "fullpath: file (or directory) %s does not exist" file);
let dir, base =
if Sys.is_directory file then (file, None)
else (Filename.dirname file, Some (Filename.basename file))
in
(* save *)
let old = Sys.getcwd () in
Sys.chdir dir;
let here = Sys.getcwd () in
(* restore *)
Sys.chdir old;
match base with
| None -> here
| Some x -> Filename.concat here x
(* Why a use_cache argument ? because sometimes want disable it but dont
* want put the cache_computation funcall in comment, so just easier to
* pass this extra option.
*)
let cache_computation ?(use_cache = true) file ext_cache f =
if not use_cache then f ()
else if not (Sys.file_exists file) then (
logger#error "WARNING: cache_computation: can't find %s" file;
logger#error "defaulting to calling the function";
f ())
else
let file_cache = file ^ ext_cache in
if Sys.file_exists file_cache && filemtime file_cache >= filemtime file then (
logger#info "using cache: %s" file_cache;
get_value file_cache)
else
let res = f () in
write_value res file_cache;
res
(* emacs/lisp inspiration (eric cooper and yaron minsky use that too) *)
let (with_open_outfile :
filename -> ((string -> unit) * out_channel -> 'a) -> 'a) =
fun file f ->
let chan = open_out_bin file in
let pr s = output_string chan s in
unwind_protect
(fun () ->
let res = f (pr, chan) in
close_out chan;
res)
(fun _e -> close_out chan)
let (with_open_infile : filename -> (in_channel -> 'a) -> 'a) =
fun file f ->
let chan = open_in_bin file in
unwind_protect
(fun () ->
let res = f chan in
close_in chan;
res)
(fun _e -> close_in chan)
(* creation of tmp files, a la gcc *)
let _temp_files_created = Hashtbl.create 101
(* ex: new_temp_file "cocci" ".c" will give "/tmp/cocci-3252-434465.c" *)
let new_temp_file prefix suffix =
let pid = if !jsoo then 42 else Unix.getpid () in
let processid = i_to_s pid in
let tmp_file = Filename.temp_file (prefix ^ "-" ^ processid ^ "-") suffix in
Hashtbl.add _temp_files_created tmp_file ();
tmp_file
let save_tmp_files = ref false
let erase_temp_files () =
if not !save_tmp_files then (
_temp_files_created
|> Hashtbl.iter (fun s () ->
logger#info "erasing: %s" s;
Sys.remove s);
Hashtbl.clear _temp_files_created)
let erase_this_temp_file f =
if not !save_tmp_files then (
Hashtbl.remove _temp_files_created f;
logger#info "erasing: %s" f;
Sys.remove f)
(*###########################################################################*)
(* Collection-like types other than List *)
(*###########################################################################*)
(*****************************************************************************)
(* Assoc *)
(*****************************************************************************)
type ('a, 'b) assoc = ('a * 'b) list
(*****************************************************************************)
(* Arrays *)
(*****************************************************************************)
(*****************************************************************************)
(* Matrix *)
(*****************************************************************************)
(*****************************************************************************)
(* Set. Have a look too at set*.mli *)
(*****************************************************************************)
(*****************************************************************************)
(* Hash *)
(*****************************************************************************)
let hash_to_list h =
Hashtbl.fold (fun k v acc -> (k, v) :: acc) h [] |> List.sort compare
let hash_of_list xs =
let h = Hashtbl.create 101 in
xs |> List.iter (fun (k, v) -> Hashtbl.replace h k v);
h
(*****************************************************************************)
(* Hash sets *)
(*****************************************************************************)
type 'a hashset = ('a, bool) Hashtbl.t
(* with sexp *)
let hashset_to_list h = hash_to_list h |> map fst
(* old: slightly slower?
* let hashset_of_list xs =
* xs +> map (fun x -> x, true) +> hash_of_list
*)
let hashset_of_list (xs : 'a list) : ('a, bool) Hashtbl.t =
let h = Hashtbl.create (List.length xs) in
xs |> List.iter (fun k -> Hashtbl.replace h k true);
h
let hkeys h =
let hkey = Hashtbl.create 101 in
h |> Hashtbl.iter (fun k _v -> Hashtbl.replace hkey k true);
hashset_to_list hkey
let group_assoc_bykey_eff xs =
let h = Hashtbl.create 101 in
xs |> List.iter (fun (k, v) -> Hashtbl.add h k v);
let keys = hkeys h in
keys |> map (fun k -> (k, Hashtbl.find_all h k))
(*****************************************************************************)
(* Stack *)
(*****************************************************************************)
type 'a stack = 'a list
(* with sexp *)
(*****************************************************************************)
(* Tree *)
(*****************************************************************************)
(*****************************************************************************)
(* Graph. Have a look too at Ograph_*.mli *)
(*****************************************************************************)
(*****************************************************************************)
(* Generic op *)
(*****************************************************************************)
let sort xs = List.sort compare xs
(* maybe too slow? use an hash instead to first group, and then in
* that group remove duplicates? *)
let rec uniq_by eq xs =
match xs with
| [] -> []
| x :: xs -> (
match List.find_opt (fun y -> eq x y) xs with
| Some _ -> uniq_by eq xs
| None -> x :: uniq_by eq xs)
(*###########################################################################*)
(* Misc functions *)
(*###########################################################################*)
(*###########################################################################*)
(* Postlude *)
(*###########################################################################*)
(*****************************************************************************)
(* Flags and actions *)
(*****************************************************************************)
(*****************************************************************************)
(* Postlude *)
(*****************************************************************************)
(*****************************************************************************)
(* Misc *)
(*****************************************************************************)
(* now in prelude: exception UnixExit of int *)
let exn_to_real_unixexit f =
try f () with
| UnixExit x -> exit x
let pp_do_in_zero_box f =
Format.open_box 0;
f ();
Format.close_box ()
let before_exit = ref []
let main_boilerplate f =
if not !Sys.interactive then
exn_to_real_unixexit (fun () ->
Sys.set_signal Sys.sigint
(Sys.Signal_handle
(fun _ ->
pr2 "C-c intercepted, will do some cleaning before exiting";
(* But if do some try ... with e -> and if do not reraise the exn,
* the bubble never goes at top and so I cant really C-c.
*
* A solution would be to not raise, but do the erase_temp_file in the
* syshandler, here, and then exit.
* The current solution is to not do some wild try ... with e
* by having in the exn handler a case: UnixExit x -> raise ... | e ->
*)
Sys.set_signal Sys.sigint Sys.Signal_default;
raise (UnixExit (-1))));
(* The finalize() below makes it tedious to go back from exns when we use
* 'back' in ocamldebug. Hence the special code in finalize() to
* run differently when in "debugger mode". However the
* Common.debugger global will be set in main(), so too late, so
* we have to be quicker here and set it for the finalize() below.
*)
if
Sys.argv |> Array.to_list
|> List.exists (fun x -> x = "-debugger" || x = "--debugger")
then debugger := true;
finalize
(fun () ->
pp_do_in_zero_box (fun () ->
try f () with
(* <---- here it is *)
| Unix.Unix_error (e, fm, argm) ->
pr2
(spf "exn Unix_error: %s %s %s\n" (Unix.error_message e)
fm argm);
raise (Unix.Unix_error (e, fm, argm))))
(fun () ->
!before_exit |> List.iter (fun f -> f ());
erase_temp_files ()))
(* let _ = if not !Sys.interactive then (main ()) *)
let follow_symlinks = ref false
let arg_symlink () = if !follow_symlinks then " -L " else ""
let grep_dash_v_str =
"| grep -v /.hg/ |grep -v /CVS/ | grep -v /.git/ |grep -v /_darcs/"
^ "| grep -v /.svn/ | grep -v .git_annot | grep -v .marshall"
let files_of_dir_or_files_no_vcs_nofilter xs =
xs
|> map (fun x ->
if is_directory x then
(* todo: should escape x *)
let cmd =
spf "find %s '%s' -type f %s"
(* -noleaf *) (arg_symlink ())
x grep_dash_v_str
in
let xs, status = cmd_to_list_and_status cmd in
match status with
| Unix.WEXITED 0 -> xs
(* bugfix: 'find -type f' does not like empty directories, but it's ok *)
| Unix.WEXITED 1 when Array.length (Sys.readdir x) =|= 0 -> []
| _ ->
raise
(CmdError
( status,
spf "CMD = %s, RESULT = %s" cmd (String.concat "\n" xs) ))
else [ x ])
|> flatten
(*****************************************************************************)
(* Maps *)
(*****************************************************************************)
module SMap = Map.Make (String)
type 'a smap = 'a SMap.t
| (* Yoann Padioleau
*
* Copyright (C) 1998-2023 Yoann Padioleau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*) |
owl_heavyhitters_sketch.ml | (* functor to make a heavy hitters sketch based on CountMin. *)
module Make (CM : Owl_countmin_sketch_sig.Sig) : Owl_heavyhitters_sketch_sig.Sig = struct
type ('a, 'b) inner =
{ s : (module Set.S with type elt = 'a * int and type t = 'b)
; sketch : 'a CM.sketch
; mutable queue : 'b
; mutable size : int
; k : float
}
type 'a t = E : ('a, 'b) inner -> 'a t
let init ~k ~epsilon ~delta (type a) =
let module PQPair = struct
type t = a * int
let compare (_, p0) (_, p1) = Stdlib.compare p0 p1
end
in
let module S = Set.Make (PQPair) in
E { s = (module S); sketch = CM.init ~epsilon ~delta; queue = S.empty; size = 0; k }
let add (type a) (E h : a t) v =
let module PQSet = (val h.s) in
CM.incr h.sketch v;
h.size <- h.size + 1;
let v_count = CM.count h.sketch v in
let threshold = float_of_int h.size /. h.k in
if v_count |> float_of_int > threshold
then
h.queue
<- h.queue
|> PQSet.partition (fun (x, _) -> x = v)
|> snd
|> PQSet.add (v, v_count)
else ();
let rec clean_queue queue =
match PQSet.min_elt_opt queue with
| Some (x, c) ->
if float_of_int c < threshold
then clean_queue (PQSet.remove (x, c) queue)
else queue
| None -> queue
in
h.queue <- clean_queue h.queue
let get (type a) (E h : a t) =
let module PQSet = (val h.s) in
PQSet.elements h.queue |> List.rev
end
module Native = Make (Owl_countmin_sketch.Native)
module Owl = Make (Owl_countmin_sketch.Owl)
| (* functor to make a heavy hitters sketch based on CountMin. *)
module Make (CM : Owl_countmin_sketch_sig.Sig) : Owl_heavyhitters_sketch_sig.Sig = struct |
test_pat.ml |
open Testing
open Astring
open Bos
let eqp = eq ~eq:Pat.equal ~pp:Pat.pp
let v = Fpath.v
let string_conv = test "Pat.{v,of_string,to_string}" @@ fun () ->
let trip p = eq_str p Pat.(to_string (v p)) in
app_invalid ~pp:Pat.pp Pat.v "$(";
app_invalid ~pp:Pat.pp Pat.v "$(a";
app_invalid ~pp:Pat.pp Pat.v "$$$(";
app_invalid ~pp:Pat.pp Pat.v "$$$";
app_invalid ~pp:Pat.pp Pat.v "$(bla,)";
app_invalid ~pp:Pat.pp Pat.v "$(b,la)";
trip "Hey $(ho)";
trip "Hey $(ho) $(hu)";
trip "Hey $(ho) $(h$u)";
trip "Hey mo $$(hu)";
trip "Hey mo $$30";
trip "Hey mo $$$$";
()
let dom = test "Pat.dom" @@ fun () ->
let eq s l =
eq ~eq:String.Set.equal ~pp:String.Set.dump
(Pat.(dom @@ v s)) (String.Set.of_list l)
in
eq "bla" [];
eq "bla ha $$" [];
eq "hey $(bla)" ["bla"];
eq "hey $(bla) $()" ["bla"; ""];
eq "hey $(bla) $$(ha) $()" ["bla"; ""];
eq "hey $(bla) $(bli) $()" ["bla"; "bli"; ""];
()
let subst = test "Pat.subst" @@ fun () ->
let eq ?undef defs p s =
eq_str Pat.(to_string @@ subst ?undef defs (v p)) s
in
let defs = String.Map.of_list ["bli", "bla"] in
let undef = function "blu" -> Some "bla$" | _ -> None in
eq ~undef defs "hey $$ $(bli) $(bla) $(blu)" "hey $$ bla $(bla) bla$$";
eq defs "hey $(blo) $(bla) $(blu)" "hey $(blo) $(bla) $(blu)";
()
let format = test "Pat.format" @@ fun () ->
let eq ?undef defs p s = eq_str (Pat.(format ?undef defs (v p))) s in
let defs = String.Map.of_list ["hey", "ho"; "hi", "ha$"] in
let undef = fun _ -> "undef" in
eq ~undef defs "a $$ $(hu)" "a $ undef";
eq ~undef defs "a $(hey) $(hi)" "a ho ha$";
eq defs "a $$(hey) $$(hi) $(ha)" "a $(hey) $(hi) ";
()
let matches = test "Pat.matches" @@ fun () ->
let m p s = Pat.(matches (v p) s) in
eq_bool (m "$(mod).mli" "string.mli") true;
eq_bool (m "$(mod).mli" "string.mli ") false;
eq_bool (m "$(mod).mli" ".mli") true;
eq_bool (m "$(mod).mli" ".mli ") false;
eq_bool (m "$(mod).$(suff)" "string.mli") true;
eq_bool (m "$(mod).$(suff)" "string.mli ") true;
eq_bool (m "$()aaa" "aaa") true;
eq_bool (m "aaa$()" "aaa") true;
eq_bool (m "$()a$()aa$()" "aaa") true;
()
let query = test "Pat.query" @@ fun () ->
let u ?init p s = Pat.(query ?init (v p) s) in
let eq = eq_option
~eq:(String.Map.equal String.equal) ~pp:(String.Map.dump String.dump)
in
let eq ?init p s = function
| None -> eq (u ?init p s) None
| Some l -> eq (u ?init p s) (Some (String.Map.of_list l))
in
let init = String.Map.of_list ["hey", "ho"] in
eq "$(mod).mli" "string.mli" (Some ["mod", "string"]);
eq ~init "$(mod).mli" "string.mli" (Some ["mod", "string"; "hey", "ho"]);
eq "$(mod).mli" "string.mli " None;
eq ~init "$(mod).mli" "string.mli " None;
eq "$(mod).mli" "string.mli " None;
eq "$(mod).$(suff)" "string.mli" (Some ["mod", "string"; "suff", "mli"]);
eq "$(mod).$(suff)" "string.mli" (Some ["mod", "string"; "suff", "mli"]);
eq "$(m).$(m)" "string.mli" (Some ["m", "string"]);
()
let suite = suite "Pat module"
[ string_conv;
dom;
subst;
format;
matches;
query; ]
(*---------------------------------------------------------------------------
Copyright (c) 2015 The bos programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| (*---------------------------------------------------------------------------
Copyright (c) 2015 The bos programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*) |
Loc.ml |
(* This file is free software, copyright Simon Cruanes. See file "LICENSE" for more details. *)
(** {1 Locations} *)
type t = {
file : string;
start_line : int;
start_column : int;
stop_line : int;
stop_column : int;
}
let mk file start_line start_column stop_line stop_column =
{ file; start_line; start_column; stop_line; stop_column; }
let mk_pair file (a,b)(c,d) = mk file a b c d
let mk_pos start stop =
let open Lexing in
mk
start.pos_fname
start.pos_lnum (start.pos_cnum - start.pos_bol)
stop.pos_lnum (stop.pos_cnum - stop.pos_bol)
let equal = (=)
let pp out pos =
if pos.start_line = pos.stop_line
then
Format.fprintf out "file '%s': line %d, col %d to %d"
pos.file pos.start_line pos.start_column pos.stop_column
else
Format.fprintf out "file '%s': line %d, col %d to line %d, col %d"
pos.file
pos.start_line pos.start_column
pos.stop_line pos.stop_column
let pp_opt out = function
| None -> Format.fprintf out "<no location>"
| Some pos -> pp out pos
let pp_to_string pp x =
let buf = Buffer.create 64 in
let fmt = Format.formatter_of_buffer buf in
pp fmt x;
Format.pp_print_flush fmt ();
Buffer.contents buf
let to_string_opt = pp_to_string pp_opt
(** {2 Lexbuf} *)
let set_file buf filename =
let open Lexing in
buf.lex_curr_p <- {buf.lex_curr_p with pos_fname=filename;};
()
let get_file buf =
let open Lexing in
buf.lex_curr_p.pos_fname
let of_lexbuf lexbuf =
let start = Lexing.lexeme_start_p lexbuf in
let end_ = Lexing.lexeme_end_p lexbuf in
let s_l = start.Lexing.pos_lnum in
let s_c = start.Lexing.pos_cnum - start.Lexing.pos_bol in
let e_l = end_.Lexing.pos_lnum in
let e_c = end_.Lexing.pos_cnum - end_.Lexing.pos_bol in
let file = get_file lexbuf in
mk file s_l s_c e_l e_c
| |
t-get_set_den.c | /*=============================================================================
This file is part of Antic.
Antic is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
=============================================================================*/
/******************************************************************************
Copyright (C) 2013 William Hart
2020 Julian Rüth
******************************************************************************/
#include <stdio.h>
#include "nf.h"
#include "nf_elem.h"
int
main(void)
{
int i, result;
flint_rand_t state;
flint_printf("get/set den....");
fflush(stdout);
flint_randinit(state);
for (i = 0; i < 100 * antic_test_multiplier(); i++)
{
nf_t nf;
nf_elem_t a;
fmpz_t d, d2;
nf_init_randtest(nf, state, 40, 200);
fmpz_init(d);
fmpz_init(d2);
nf_elem_init(a, nf);
nf_elem_randtest(a, state, 200, nf);
fmpz_randtest_not_zero(d, state, 200);
nf_elem_set_den(a, d, nf);
nf_elem_get_den(d2, a, nf);
result = fmpz_equal(d, d2);
if (!result)
{
flint_printf("FAIL:\n");
flint_printf("d = "); fmpz_print(d); printf("\n");
flint_printf("d2 = "); fmpz_print(d2); printf("\n");
flint_printf("a = "); nf_elem_print_pretty(a, nf, "x");
abort();
}
nf_elem_clear(a, nf);
nf_clear(nf);
fmpz_clear(d);
fmpz_clear(d2);
}
flint_randclear(state);
flint_cleanup();
flint_printf("PASS\n");
return 0;
}
| /*=============================================================================
This file is part of Antic.
Antic is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
=============================================================================*/ |
evar.ml | type t = int
let repr x = x
let unsafe_of_int x = x
let compare = Int.compare
let equal = Int.equal
let hash = Int.hash
let print x = Pp.(str "?X" ++ int x)
module Set = Int.Set
module Map = Int.Map
| (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
|
dune |
(library
(public_name ppx_pyformat)
(kind ppx_rewriter)
(preprocess
(pps ppxlib.metaquot ppx_make))
(libraries ppxlib)
(ppx_runtime_libraries ppx_pyformat_runtime))
(menhir
(modules parser))
(ocamllex lexer)
| |
period_repr.mli | type t
type period = t
include Compare.S with type t := t
val encoding : period Data_encoding.t
val rpc_arg : period RPC_arg.t
val pp: Format.formatter -> period -> unit
val to_seconds : period -> int64
(** [of_second period] fails if period is not positive *)
val of_seconds : int64 -> period tzresult
(** [of_second period] fails if period is not positive.
It should only be used at toplevel for constants. *)
val of_seconds_exn : int64 -> period
val mult : int32 -> period -> period tzresult
val zero : period
val one_second : period
val one_minute : period
val one_hour : period
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
minilib.ml | let rec print_list print fmt = function
| [] -> ()
| [x] -> print fmt x
| x :: r -> print fmt x; print_list print fmt r
type level = [
| `DEBUG
| `INFO
| `NOTICE
| `WARNING
| `ERROR
| `FATAL ]
(** Some excerpt of Util and similar files to avoid loading the whole
module and its dependencies (and hence Compat and Camlp5) *)
let debug = ref false
(* On a Win32 application with no console, writing to stderr raise
a Sys_error "bad file descriptor", hence the "try" below.
Ideally, we should re-route message to a log file somewhere, or
print in the response buffer.
*)
let log_pp ?(level = `DEBUG) msg =
let prefix = match level with
| `DEBUG -> "DEBUG"
| `INFO -> "INFO"
| `NOTICE -> "NOTICE"
| `WARNING -> "WARNING"
| `ERROR -> "ERROR"
| `FATAL -> "FATAL"
in
if !debug then begin
try Format.eprintf "[%s] @[%a@]\n%!" prefix Pp.pp_with msg
with _ -> ()
end
let log ?level str = log_pp ?level (Pp.str str)
let coqify d = Filename.concat d "coq"
let coqide_config_home () =
coqify (Glib.get_user_config_dir ())
let coqide_data_dirs () =
coqify (Glib.get_user_data_dir ())
:: List.map coqify (Glib.get_system_data_dirs ())
@ [Envars.datadir ()]
let coqide_system_config_dirs () =
List.map coqify (Glib.get_system_config_dirs ())
let coqide_default_config_dir () =
Envars.configdir ()
let coqide_config_dirs () =
coqide_config_home () ::
coqide_system_config_dirs () @
[coqide_default_config_dir ()]
| (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
|
discover.mli | (*_ This signature is deliberately empty. *)
| (*_ This signature is deliberately empty. *)
|
reference.ml |
open Lwt.Infix
let src = Logs.Src.create "git.refs" ~doc:"Git references"
module Log = (val Logs.src_log src : Logs.LOG)
type t = string
let of_string x = x
let to_string x = x
let sep = "/"
module P = struct
type partial = string
type branch = string
let ( // ) partial0 partial1 : partial =
String.concat sep [partial0; partial1]
let ( / ) partial branch : t = String.concat sep [partial; branch]
let refs : partial = "refs"
let heads : partial = "refs/heads"
let remotes : partial = "refs/remotes"
let origin : partial = "refs/remotes/origin"
let master : branch = "master"
end
let head = "HEAD"
let is_head = String.equal head
let master = "refs/heads/master"
let to_path = function "HEAD" -> Path.v "HEAD" | refs -> Path.v refs
let of_path path =
match Path.segs path with
| [] -> Fmt.invalid_arg "Reference.of_path: empty path"
| ["HEAD"] -> head
| "HEAD" :: _ ->
Fmt.invalid_arg "Reference.of_path: HEAD can not be followed by values"
| "refs" :: _ as refs -> String.concat sep refs
| _ :: _ ->
invalid_arg "Reference.of_path: bad path (need to be prefixed by refs)"
let pp ppf x = Fmt.pf ppf "%s" (String.escaped x)
module type S = sig
module Hash : S.HASH
type nonrec t = t
module P : sig
type partial
type branch = string
val ( // ) : partial -> partial -> partial
val ( / ) : partial -> branch -> t
val refs : partial
val heads : partial
val remotes : partial
val origin : partial
val master : branch
end
val head : t
val master : t
val is_head : t -> bool
val of_string : string -> t
val to_string : t -> string
val of_path : Path.t -> t
val to_path : t -> Path.t
include S.BASE with type t := t
type head_contents = Hash of Hash.t | Ref of t
val pp_head_contents : head_contents Fmt.t
val equal_head_contents : head_contents -> head_contents -> bool
val compare_head_contents : head_contents -> head_contents -> int
module A : S.DESC with type 'a t = 'a Angstrom.t and type e = head_contents
module M :
S.DESC with type 'a t = 'a Encore.Encoder.t and type e = head_contents
module D :
S.DECODER
with type t = head_contents
and type init = Cstruct.t
and type error = Error.Decoder.t
module E :
S.ENCODER
with type t = head_contents
and type init = Cstruct.t * head_contents
and type error = Error.never
end
module type IO = sig
module FS : S.FS
include S
type error = [Error.Decoder.t | FS.error Error.FS.t]
val pp_error : error Fmt.t
val mem : fs:FS.t -> root:Fpath.t -> t -> bool Lwt.t
val read :
fs:FS.t
-> root:Fpath.t
-> t
-> dtmp:Cstruct.t
-> raw:Cstruct.t
-> (head_contents, error) result Lwt.t
val write :
fs:FS.t
-> root:Fpath.t
-> temp_dir:Fpath.t
-> etmp:Cstruct.t
-> raw:Cstruct.t
-> t
-> head_contents
-> (unit, error) result Lwt.t
val remove : fs:FS.t -> root:Fpath.t -> t -> (unit, error) result Lwt.t
end
module Make (Hash : S.HASH) = struct
type nonrec t = t
module P = P
let master = master
let head = head
let is_head = is_head
let of_string = of_string
let to_string = to_string
let to_path = Path.v
let of_path path =
let segs = Path.segs path in
String.concat sep segs
(* XXX(dinosaure): doublon with [Path.to_string] but this function uses
[Fmt.to_to_string] and I don't trust this function. *)
let pp = pp
let equal = String.equal
let hash = Hashtbl.hash
let compare x y =
match x, y with
| "HEAD", "HEAD" -> 0
| "HEAD", _ -> -1
| _, "HEAD" -> 1
| _, _ -> compare x y
module Set = Set.Make (struct type nonrec t = t
let compare = compare end)
module Map = Map.Make (struct type nonrec t = t
let compare = compare end)
type head_contents = Hash of Hash.t | Ref of t
let pp_head_contents ppf = function
| Hash hash -> Fmt.pf ppf "(Hash %a)" Hash.pp hash
| Ref t -> Fmt.pf ppf "(Ref %a)" pp t
let equal_head_contents a b =
match a, b with
| Ref a', Ref b' -> equal a' b'
| Hash a', Hash b' -> Hash.equal a' b'
| _, _ -> false
let compare_head_contents a b =
match a, b with
| Ref a', Ref b' -> compare a' b'
| Hash a', Hash b' -> Hash.unsafe_compare a' b'
| Ref _, Hash _ -> 1
| Hash _, Ref _ -> -1
module MakeMeta (Meta : Encore.Meta.S) = struct
type e = head_contents
open Helper.BaseIso
module Iso = struct
open Encore.Bijection
let hex =
make_exn
~fwd:(Exn.safe_exn Hash.of_hex)
~bwd:(Exn.safe_exn Hash.to_hex)
let refname =
make_exn
~fwd:(Exn.safe_exn of_string)
~bwd:(Exn.safe_exn to_string)
let hash =
make_exn
~fwd:(fun hash -> Hash hash)
~bwd:(function
| Hash hash -> hash | _ -> Exn.fail ())
let reference =
make_exn
~fwd:(fun reference -> Ref reference)
~bwd:(function
| Ref r -> r | _ -> Exn.fail ())
end
type 'a t = 'a Meta.t
module Meta = Encore.Meta.Make (Meta)
open Meta
let is_not_lf = ( <> ) '\n'
let hash =
Iso.hex <$> take (Hash.digest_size * 2) <* (char_elt '\n' <$> any)
let reference =
(string_elt "ref: " <$> const "ref: ")
*> (Iso.refname <$> while1 is_not_lf)
<* (char_elt '\n' <$> any)
let p = Iso.reference <$> reference <|> (Iso.hash <$> hash)
end
module A = MakeMeta (Encore.Proxy_decoder.Impl)
module M = MakeMeta (Encore.Proxy_encoder.Impl)
module D = Helper.MakeDecoder (A)
module E = Helper.MakeEncoder (M)
end
module IO (H : S.HASH) (FS : S.FS) = struct
module FS = Helper.FS (FS)
include Make (H)
module Encoder = struct
module E = struct
type state = E.encoder
type result = int
type error = E.error
type rest = [`Flush of state | `End of state * result]
let used = E.used
let flush = E.flush
let eval raw state =
match E.eval raw state with
| `Error err -> Lwt.return (`Error (state, err))
| #rest as rest -> Lwt.return rest
end
include Helper.Encoder (E) (FS)
end
module Decoder = Helper.Decoder (D) (FS)
type fs_error = FS.error Error.FS.t
type error = [Error.Decoder.t | fs_error]
let pp_error ppf = function
| #Error.Decoder.t as err -> Error.Decoder.pp_error ppf err
| #fs_error as err -> Error.FS.pp_error FS.pp_error ppf err
let[@warning "-32"] normalize path =
let segs = Path.segs path in
List.fold_left
(fun (stop, acc) ->
if stop then fun x -> true, x :: acc
else function
| "HEAD" as x -> true, x :: acc
(* XXX(dinosaure): special case, HEAD can be stored in a refs
sub-directory or can be in root of dotgit (so, without refs). *)
| "refs" as x -> true, [x]
| _ -> false, [] )
(false, []) segs
|> fun (_, refs) -> List.rev refs |> String.concat "/" |> of_string
let mem ~fs ~root:dotgit reference =
let path = Path.(dotgit + to_path reference) in
FS.File.exists fs path >|= function Ok v -> v | Error _ -> false
let read ~fs ~root:dotgit reference ~dtmp ~raw : (_, error) result Lwt.t =
let state = D.default dtmp in
let path = Path.(dotgit + to_path reference) in
Decoder.of_file fs path raw state
>|= function
| Ok v -> Ok v
| Error (`Decoder err) -> Error.(v @@ Error.Decoder.with_path path err)
| Error #fs_error as err -> err
let write ~fs ~root:dotgit ~temp_dir ~etmp ~raw reference value
=
let state = E.default (etmp, value) in
let path = Path.(dotgit + to_path reference) in
FS.Dir.create fs (Fpath.parent path)
>>= function
| Error err ->
Lwt.return Error.(v @@ FS.err_create (Fpath.parent path) err)
| Ok (true | false) -> (
Encoder.to_file fs ~temp_dir path raw state
>|= function
| Ok _ -> Ok ()
| Error #fs_error as err -> err
| Error (`Encoder #Error.never) -> assert false )
let remove ~fs ~root:dotgit reference =
let path = Path.(dotgit + to_path reference) in
FS.File.delete fs path
>|= function
| Ok _ as v -> v | Error err -> Error.(v @@ FS.err_delete path err)
end
| (*
* Copyright (c) 2013-2017 Thomas Gazagnaire <[email protected]>
* and Romain Calascibetta <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*) |
owl_linalg_c.ml |
open Bigarray
type elt = Complex.t
type mat = Owl_dense_matrix_c.mat
type complex_mat = Owl_dense_matrix_c.mat
type int32_mat = (int32, int32_elt) Owl_dense_matrix_generic.t
include Owl_linalg_generic
let schur = schur ~otyp:complex32
let ordschur = ordschur ~otyp:complex32
let qz = qz ~otyp:complex32
let ordqz = ordqz ~otyp:complex32
let qzvals = qzvals ~otyp:complex32
let eig = eig ~otyp:complex32
let eigvals = eigvals ~otyp:complex32
| (*
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <[email protected]>
*) |
script_big_map.ml | open Script_typed_ir
open Script_ir_translator
let empty key_type value_type =
Big_map
{
id = None;
diff = {map = Big_map_overlay.empty; size = 0};
key_type;
value_type;
}
let mem ctxt key (Big_map {id; diff; key_type; _}) =
hash_comparable_data ctxt key_type key >>=? fun (key_hash, ctxt) ->
match (Big_map_overlay.find key_hash diff.map, id) with
| None, None -> return (false, ctxt)
| None, Some id ->
Alpha_context.Big_map.mem ctxt id key_hash >|=? fun (ctxt, res) ->
(res, ctxt)
| Some (_, None), _ -> return (false, ctxt)
| Some (_, Some _), _ -> return (true, ctxt)
let get_by_hash ctxt key (Big_map {id; diff; value_type; _}) =
match (Big_map_overlay.find key diff.map, id) with
| Some (_, x), _ -> return (x, ctxt)
| None, None -> return (None, ctxt)
| None, Some id -> (
Alpha_context.Big_map.get_opt ctxt id key >>=? function
| ctxt, None -> return (None, ctxt)
| ctxt, Some value ->
parse_data
ctxt
~elab_conf:Script_ir_translator_config.(make ~legacy:true ())
~allow_forged:true
value_type
(Micheline.root value)
>|=? fun (x, ctxt) -> (Some x, ctxt))
let get ctxt key (Big_map {key_type; _} as map) =
hash_comparable_data ctxt key_type key >>=? fun (key_hash, ctxt) ->
get_by_hash ctxt key_hash map
let update_by_hash key_hash key value (Big_map map) =
let contains = Big_map_overlay.mem key_hash map.diff.map in
Big_map
{
map with
diff =
{
map = Big_map_overlay.add key_hash (key, value) map.diff.map;
size = (if contains then map.diff.size else map.diff.size + 1);
};
}
let update ctxt key value (Big_map {key_type; _} as map) =
hash_comparable_data ctxt key_type key >>=? fun (key_hash, ctxt) ->
let map = update_by_hash key_hash key value map in
return (map, ctxt)
let get_and_update ctxt key value (Big_map {key_type; _} as map) =
hash_comparable_data ctxt key_type key >>=? fun (key_hash, ctxt) ->
let new_map = update_by_hash key_hash key value map in
get_by_hash ctxt key_hash map >>=? fun (old_value, ctxt) ->
return ((old_value, new_map), ctxt)
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* Copyright (c) 2021-2022 Nomadic Labs <[email protected]> *)
(* Copyright (c) 2022 Trili Tech <[email protected]> *)
(* Copyright (c) 2022 Marigold <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
abs_path_set.ml |
include Set.Make (Abs_path)
| |
dune |
(library
(name boulangerie)
(libraries yojson core str fileutils))
| |
test_dal_slot_proof.ml | (** Testing
-------
Component: Protocol (dal slot proof)
Invocation: dune exec src/proto_alpha/lib_protocol/test/unit/main.exe \
-- test "^\[Unit\] dal slot proof$"
Subject: These unit tests check proof-related functions of Dal slots.
*)
open Protocol
module S = Dal_slot_repr
module H = S.Header
module P = S.Page
module Hist = S.History
module Make (Parameters : sig
val name : string
val dal_parameters : Alpha_context.Constants.Parametric.dal
end) =
struct
open Dal_helpers.Make (struct
include Parameters
let cryptobox =
WithExceptions.Result.get_ok ~loc:__LOC__
@@ Dal_helpers.mk_cryptobox Parameters.dal_parameters.cryptobox_parameters
end)
(* Tests to check insertion of slots in a dal skip list. *)
(** Check insertion of a new slot in the given skip list. *)
let skip_list_ordering skip_list ~mk_level ~mk_slot_index ~check_result =
let open Lwt_result_syntax in
let {S.Header.id; _} = Hist.Internal_for_tests.content skip_list in
let level = mk_level id in
let index = mk_slot_index id in
let*? _data, _poly, slot = mk_slot ~level ~index () in
Hist.add_confirmed_slot_headers_no_cache skip_list [slot]
|> Environment.wrap_tzresult |> check_result
(** This test attempts to add a slot on top of genesis cell zero which would
break the ordering. In fact, confirmed slots' skip list is ordered by slots
ID: the slots' level should increase or the level is equal in which case the
slots' index should increase. In the test below, we attempt to insert a slot
where (published_level, slot_index) doesn't increase (is the same as the
genesis cell). *)
let insertion_breaks_skip_list_ordering () =
skip_list_ordering
genesis_history
~mk_level:(fun id -> id.H.published_level)
~mk_slot_index:(fun id -> id.H.index)
~check_result:(fun res ->
Assert.proto_error ~loc:__LOC__ res (function
| Hist.Add_element_in_slots_skip_list_violates_ordering -> true
| _ -> false))
(** This test attempts to add a slot on top of genesis cell zero which satisfies
the ordering. *)
let correct_insertion_in_skip_list_ordering_1 () =
let open Lwt_result_syntax in
skip_list_ordering
genesis_history
~mk_level:(fun id -> Raw_level_repr.succ id.H.published_level)
~mk_slot_index:(fun id -> id.H.index)
~check_result:(fun res ->
let* (_skip_list : Hist.t) = Assert.get_ok ~__LOC__ res in
return_unit)
(** This test attempts to add a slot on top of genesis cell zero which satisfies
the ordering. *)
let correct_insertion_in_skip_list_ordering_2 () =
let open Lwt_result_syntax in
skip_list_ordering
genesis_history
~mk_level:(fun id -> id.H.published_level)
~mk_slot_index:(fun id -> succ_slot_index id.H.index)
~check_result:(fun res ->
let* (_skip_list : Hist.t) = Assert.get_ok ~__LOC__ res in
return_unit)
(** This test attempts to add two slots on top of genesis cell zero which satisfies
the ordering. *)
let correct_insertion_in_skip_list_ordering_3 () =
let open Lwt_result_syntax in
skip_list_ordering
genesis_history
~mk_level:(fun id -> id.H.published_level)
~mk_slot_index:(fun id -> succ_slot_index id.H.index)
~check_result:(fun res ->
let* skip_list = Assert.get_ok ~__LOC__ res in
skip_list_ordering
skip_list
~mk_level:(fun id ->
Raw_level_repr.(succ (succ id.H.published_level)))
~mk_slot_index:(fun id -> id.H.index)
~check_result:(fun res ->
let* (_skip_list : Hist.t) = Assert.get_ok ~__LOC__ res in
return_unit))
(* Tests of construct/verify proofs that confirm/unconfirm pages on top of
genesis skip list (whose unique cell is slot zero). *)
(** This test attempts to construct a proof to confirm a slot page from the
genesis skip list. Proof production is expected to fail. *)
let confirmed_page_on_genesis () =
let {H.id = {published_level; index}; _} =
Hist.Internal_for_tests.content genesis_history
in
let page_id = mk_page_id published_level index P.Index.zero in
produce_and_verify_proof
genesis_history
~get_history:(get_history genesis_history_cache)
(* values of level and slot index are equal to slot zero. We would get a
page confirmation proof. But, no proof that confirms the existence of a page
in slot [zero] is possible. *)
~page_info:None
~page_id
~check_produce:(slot_confirmed_but_page_data_not_provided ~__LOC__)
(** This test attempts to construct a proof to unconfirm a slot page from the
genesis skip list. Proof production is expected to succeed. *)
let unconfirmed_page_on_genesis incr_level =
let {H.id = {published_level; index}; _} =
Hist.Internal_for_tests.content genesis_history
in
let level, sindex =
if incr_level then (Raw_level_repr.succ published_level, index)
else (published_level, succ_slot_index index)
in
let page_id = mk_page_id level sindex P.Index.zero in
produce_and_verify_proof
genesis_history
~get_history:(get_history genesis_history_cache)
~page_info:None
~page_id
~check_produce:(successful_check_produce_result ~__LOC__ `Unconfirmed)
~check_verify:(successful_check_verify_result ~__LOC__ `Unconfirmed)
(* Tests of construct/verify proofs that attempt to confirm pages on top of a
(confirmed) slot added in genesis_history skip list. *)
(** Helper function that adds a slot a top of the genesis skip list. *)
let helper_confirmed_slot_on_genesis ~level ~mk_page_info ~check_produce
?check_verify () =
let open Lwt_result_syntax in
let*? _slot_data, polynomial, slot = mk_slot ~level () in
let*? skip_list, cache =
Hist.add_confirmed_slot_headers
genesis_history
genesis_history_cache
[slot]
|> Environment.wrap_tzresult
in
let*? page_info, page_id = mk_page_info slot polynomial in
produce_and_verify_proof
skip_list
~get_history:(get_history cache)
~page_info
~page_id
?check_verify
~check_produce
(** Test where a slot is confirmed, requesting a proof for a confirmed page,
where the correct data and page proof are provided. *)
let confirmed_slot_on_genesis_confirmed_page_good_data =
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info
~check_produce:(successful_check_produce_result ~__LOC__ `Confirmed)
~check_verify:(successful_check_verify_result ~__LOC__ `Confirmed)
(** Test where a slot is confirmed, requesting a proof for a confirmed page,
where the page data and proof are not given. *)
let confirmed_slot_on_genesis_confirmed_page_no_data =
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info:(mk_page_info ~custom_data:no_data)
~check_produce:(slot_confirmed_but_page_data_not_provided ~__LOC__)
(** Test where a slot is confirmed, requesting a proof for a confirmed page,
where correct data are provided, but the given page proof is wrong. *)
let confirmed_slot_on_genesis_confirmed_page_bad_page_proof =
let open Result_syntax in
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info:(fun slot poly ->
let* page_info1, _page_id1 = mk_page_info ~page_index:1 slot poly in
let* page_info2, page_id2 = mk_page_info ~page_index:2 slot poly in
assert (
match (page_info1, page_info2) with
| Some (_d1, p1), Some (_d2, p2) -> not (eq_page_proof p1 p2)
| _ -> false) ;
return (page_info1, page_id2))
~check_produce:
(failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"Wrong page content for the given page index and slot \
commitment (page id=(published_level: 11, slot_index: 0, \
page_index: 2))."))
(** Test where a slot is confirmed, requesting a proof for a confirmed page,
where correct page proof is provided, but given page data is altered. *)
let confirmed_slot_on_genesis_confirmed_page_bad_data_right_length =
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info:
(mk_page_info
~custom_data:
(Some
(fun ~default_char page_size ->
Some
(Bytes.init page_size (fun i ->
if i = 0 then next_char default_char else default_char)))))
~check_produce:
(failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"Wrong page content for the given page index and slot \
commitment (page id=(published_level: 11, slot_index: 0, \
page_index: 0))."))
(** Same as {!confirmed_slot_on_genesis_confirmed_page_bad_data_right_length}
but the data is too short. *)
let confirmed_slot_on_genesis_confirmed_page_bad_data_short =
let page_size = Parameters.dal_parameters.cryptobox_parameters.page_size in
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info:
(mk_page_info
~custom_data:
(Some
(fun ~default_char page_size ->
Some (Bytes.make (page_size - 1) default_char))))
~check_produce:
(failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Unexpected_page_size
{expected_size = page_size; page_size = page_size - 1}))
(** Same as {!confirmed_slot_on_genesis_confirmed_page_bad_data_right_length}
but the data is too long. *)
let confirmed_slot_on_genesis_confirmed_page_bad_data_long =
let page_size = Parameters.dal_parameters.cryptobox_parameters.page_size in
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ level_ten)
~mk_page_info:
(mk_page_info
~custom_data:
(Some
(fun ~default_char page_size ->
Some (Bytes.make (page_size + 1) default_char))))
~check_produce:
(failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Unexpected_page_size
{expected_size = page_size; page_size = page_size + 1}))
(* Variants of the tests above: Construct/verify proofs that attempt to
unconfirm pages on top of a (confirmed) slot added in genesis_history skip
list.
All the tests are somehow equivalent when building "Unconfirmed page" proof,
because the page's data & page's proof are ignored in this case.
*)
(** Specialisation of helper {!helper_confirmed_slot_on_genesis}, where some
parameters are fixed. *)
let helper_confirmed_slot_on_genesis_unconfirmed_page ~check_produce
?check_verify ~page_level ~mk_page_info =
helper_confirmed_slot_on_genesis
~level:(Raw_level_repr.succ page_level)
~mk_page_info
~check_produce
?check_verify
(** Unconfirmation proof for a page with good data. *)
let confirmed_slot_on_genesis_unconfirmed_page_good_data =
helper_confirmed_slot_on_genesis_unconfirmed_page
~page_level:level_ten
~mk_page_info:(mk_page_info ~level:level_ten)
~check_produce:(slot_not_confirmed_but_page_data_provided ~__LOC__)
(** Unconfirmation proof for a page with no data. *)
let confirmed_slot_on_genesis_unconfirmed_page_no_data =
helper_confirmed_slot_on_genesis_unconfirmed_page
~page_level:level_ten
~mk_page_info:(mk_page_info ~custom_data:no_data ~level:level_ten)
~check_produce:(successful_check_produce_result ~__LOC__ `Unconfirmed)
(** Unconfirmation proof for a page with bad page proof. *)
let confirmed_slot_on_genesis_unconfirmed_page_bad_proof =
let open Result_syntax in
let level = level_ten in
helper_confirmed_slot_on_genesis_unconfirmed_page
~page_level:level
~mk_page_info:(fun slot poly ->
let* page_info1, _page_id1 =
mk_page_info ~level:level_ten ~page_index:1 slot poly
in
let* _page_info2, page_id2 =
mk_page_info ~level:level_ten ~page_index:2 slot poly
in
assert (
match (page_info1, _page_info2) with
| Some (_d1, p1), Some (_d2, p2) -> not (eq_page_proof p1 p2)
| _ -> false) ;
return (page_info1, page_id2))
~check_produce:(slot_not_confirmed_but_page_data_provided ~__LOC__)
(** Unconfirmation proof for a page with bad data. *)
let confirmed_slot_on_genesis_unconfirmed_page_bad_data =
let level = level_ten in
helper_confirmed_slot_on_genesis_unconfirmed_page
~page_level:level
~mk_page_info:
(mk_page_info
~level:level_ten
~custom_data:
(Some
(fun ~default_char page_size ->
Some
(Bytes.init page_size (fun i ->
if i = 0 then next_char default_char else default_char)))))
~check_produce:(slot_not_confirmed_but_page_data_provided ~__LOC__)
(* The list of tests. *)
let tests =
let mk_title = Format.sprintf "[%s] %s" Parameters.name in
let tztest title test_function =
Tztest.tztest (mk_title title) `Quick test_function
in
let qcheck2 title gen test =
Tztest.tztest_qcheck2 ~name:(mk_title title) ~count:2 gen test
in
let bool = QCheck2.Gen.bool in
let ordering_tests =
[
tztest
"add a slot on top of genesis that breaks ordering"
insertion_breaks_skip_list_ordering;
tztest
"add a slot on top of genesis that satisfies ordering (1/2)"
correct_insertion_in_skip_list_ordering_1;
tztest
"add a slot on top of genesis that satisfies ordering (2/2)"
correct_insertion_in_skip_list_ordering_2;
tztest
"add two slots on top of genesis that satisfy ordering"
correct_insertion_in_skip_list_ordering_3;
]
in
let proofs_tests_on_genesis =
[
tztest "Confirmed page on genesis" confirmed_page_on_genesis;
qcheck2 "Unconfirmed page on genesis" bool unconfirmed_page_on_genesis;
]
in
let confirmed_slot_on_genesis_confirmed_page_tests =
[
tztest
"Confirmed slot on top of genesis: confirmed page with good data"
confirmed_slot_on_genesis_confirmed_page_good_data;
tztest
"Confirmed slot on top of genesis: confirmed page with no data"
confirmed_slot_on_genesis_confirmed_page_no_data;
tztest
"Confirmed slot on top of genesis: confirmed page with bad proof"
confirmed_slot_on_genesis_confirmed_page_bad_page_proof;
tztest
"Confirmed slot on top of genesis: confirmed page with bad data"
confirmed_slot_on_genesis_confirmed_page_bad_data_right_length;
tztest
"Confirmed slot on top of genesis: confirmed page with too short data"
confirmed_slot_on_genesis_confirmed_page_bad_data_short;
tztest
"Confirmed slot on top of genesis: confirmed page with too long data"
confirmed_slot_on_genesis_confirmed_page_bad_data_long;
]
in
let confirmed_slot_on_genesis_unconfirmed_page_tests =
[
tztest
"Confirmed slot on top of genesis: unconfirmed page with good data"
confirmed_slot_on_genesis_unconfirmed_page_good_data;
tztest
"Confirmed slot on top of genesis: unconfirmed page with no data"
confirmed_slot_on_genesis_unconfirmed_page_no_data;
tztest
"Confirmed slot on top of genesis: unconfirmed page with bad proof"
confirmed_slot_on_genesis_unconfirmed_page_bad_proof;
tztest
"Confirmed slot on top of genesis: unconfirmed page with bad data \
(altered)"
confirmed_slot_on_genesis_unconfirmed_page_bad_data;
]
in
ordering_tests @ proofs_tests_on_genesis
@ confirmed_slot_on_genesis_confirmed_page_tests
@ confirmed_slot_on_genesis_unconfirmed_page_tests
end
let tests =
let open Tezos_protocol_alpha_parameters.Default_parameters in
let module Test = Make (struct
let name = "test"
let dal_parameters = constants_test.dal
end) in
Test.tests
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
sqrtpos.c |
#include "arb.h"
void
arb_sqrtpos(arb_t z, const arb_t x, slong prec)
{
if (!arb_is_finite(x))
{
if (mag_is_zero(arb_radref(x)) && arf_is_pos_inf(arb_midref(x)))
arb_pos_inf(z);
else
arb_zero_pm_inf(z);
}
else if (arb_contains_nonpositive(x))
{
arf_t t;
arf_init(t);
arf_set_mag(t, arb_radref(x));
arf_add(t, arb_midref(x), t, MAG_BITS, ARF_RND_CEIL);
if (arf_sgn(t) <= 0)
{
arb_zero(z);
}
else
{
arf_sqrt(t, t, MAG_BITS, ARF_RND_CEIL);
arf_mul_2exp_si(t, t, -1);
arf_set(arb_midref(z), t);
arf_get_mag(arb_radref(z), t);
}
arf_clear(t);
}
else
{
arb_sqrt(z, x, prec);
}
arb_nonnegative_part(z, z);
}
| /*
Copyright (C) 2012 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/ |
tactical.h | #pragma once
#include "tactic/tactic.h"
#include "tactic/probe.h"
tactic * and_then(unsigned num, tactic * const * ts);
tactic * and_then(tactic * t1, tactic * t2);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8, tactic * t9);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8, tactic * t9, tactic * t10);
tactic * and_then(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8, tactic * t9, tactic * t10, tactic * t11);
tactic * or_else(unsigned num, tactic * const * ts);
tactic * or_else(tactic * t1, tactic * t2);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8, tactic * t9);
tactic * or_else(tactic * t1, tactic * t2, tactic * t3, tactic * t4, tactic * t5, tactic * t6, tactic * t7, tactic * t8, tactic * t9, tactic * t10);
tactic * repeat(tactic * t, unsigned max = UINT_MAX);
/**
\brief Fails if \c t produces more than \c threshold subgoals.
Otherwise, it behaves like \c t.
*/
tactic * fail_if_branching(tactic * t, unsigned threshold = 1);
tactic * par(unsigned num, tactic * const * ts);
tactic * par(tactic * t1, tactic * t2);
tactic * par(tactic * t1, tactic * t2, tactic * t3);
tactic * par(tactic * t1, tactic * t2, tactic * t3, tactic * t4);
tactic * par_and_then(unsigned num, tactic * const * ts);
tactic * par_and_then(tactic * t1, tactic * t2);
tactic * try_for(tactic * t, unsigned msecs);
tactic * clean(tactic * t);
tactic * using_params(tactic * t, params_ref const & p);
tactic * annotate_tactic(char const* name, tactic * t);
// Create a tactic that fails if the result returned by probe p is true.
tactic * fail_if(probe * p);
tactic * fail_if_not(probe * p);
// Execute t1 if p returns true, and t2 otherwise
tactic * cond(probe * p, tactic * t1, tactic * t2);
// Alias for cond(p, t, mk_skip_tactic())
tactic * when(probe * p, tactic * t);
// alias for (or-else t skip)
tactic * skip_if_failed(tactic * t);
// Execute the given tactic only if proof production is not enabled.
// If proof production is enabled it is a skip
tactic * if_no_proofs(tactic * t);
tactic * if_no_unsat_cores(tactic * t);
tactic * if_no_models(tactic * t);
| /*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
tactical.h
Abstract:
Basic combinators
Author:
Leonardo (leonardo) 2011-10-13
Notes:
--*/ |
voting_period_repr.ml | type t = int32
type voting_period = t
include (Compare.Int32 : Compare.S with type t := t)
let encoding = Data_encoding.int32
let pp ppf level = Format.fprintf ppf "%ld" level
let rpc_arg =
let construct voting_period = Int32.to_string voting_period in
let destruct str =
match Int32.of_string str with
| exception _ -> Error "Cannot parse voting period"
| voting_period -> Ok voting_period in
RPC_arg.make
~descr:"A voting period"
~name: "voting_period"
~construct
~destruct
()
let root = 0l
let succ = Int32.succ
let to_int32 l = l
let of_int32_exn l =
if Compare.Int32.(l >= 0l)
then l
else invalid_arg "Voting_period_repr.of_int32"
type kind =
| Proposal
| Testing_vote
| Testing
| Promotion_vote
let kind_encoding =
let open Data_encoding in
union ~tag_size:`Uint8 [
case (Tag 0)
~title:"Proposal"
(constant "proposal")
(function Proposal -> Some () | _ -> None)
(fun () -> Proposal) ;
case (Tag 1)
~title:"Testing_vote"
(constant "testing_vote")
(function Testing_vote -> Some () | _ -> None)
(fun () -> Testing_vote) ;
case (Tag 2)
~title:"Testing"
(constant "testing")
(function Testing -> Some () | _ -> None)
(fun () -> Testing) ;
case (Tag 3)
~title:"Promotion_vote"
(constant "promotion_vote")
(function Promotion_vote -> Some () | _ -> None)
(fun () -> Promotion_vote) ;
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
baking_lib.ml | open Protocol
open Alpha_context
open Baking_state
let create_state cctxt ?synchronize ?monitor_node_mempool ~config
~current_proposal delegates =
let open Lwt_result_syntax in
let chain = cctxt#chain in
let monitor_node_operations = monitor_node_mempool in
let*! operation_worker =
Operation_worker.create ?monitor_node_operations cctxt
in
Baking_scheduling.create_initial_state
cctxt
?synchronize
~chain
config
operation_worker
~current_proposal
delegates
let get_current_proposal cctxt ?cache () =
let open Lwt_result_syntax in
let* block_stream, _block_stream_stopper =
Node_rpc.monitor_heads cctxt ?cache ~chain:cctxt#chain ()
in
Lwt_stream.peek block_stream >>= function
| Some current_head -> return (block_stream, current_head)
| None -> failwith "head stream unexpectedly ended"
module Events = Baking_events.Lib
let preendorse (cctxt : Protocol_client_context.full) ?(force = false) delegates
=
let open State_transitions in
let open Lwt_result_syntax in
let cache = Baking_cache.Block_cache.create 10 in
let* _, current_proposal = get_current_proposal cctxt ~cache () in
let config = Baking_configuration.make ~force () in
let* state = create_state cctxt ~config ~current_proposal delegates in
let proposal = state.level_state.latest_proposal in
let*! () =
Events.(
emit attempting_preendorse_proposal state.level_state.latest_proposal)
in
let* () =
if force then return_unit
else
is_acceptable_proposal_for_current_level state proposal >>= function
| Invalid -> cctxt#error "Cannot preendorse an invalid proposal"
| Outdated_proposal ->
cctxt#error "Cannot preendorse an outdated proposal"
| Valid_proposal -> return_unit
in
let consensus_list = make_consensus_list state proposal in
let*! () =
cctxt#message
"@[<v 2>Preendorsing for:@ %a@]"
Format.(
pp_print_list
~pp_sep:pp_print_space
Baking_state.pp_consensus_key_and_delegate)
(List.map fst consensus_list)
in
Baking_actions.inject_preendorsements state ~preendorsements:consensus_list
>>=? fun (_ignored_state : state) -> return_unit
let endorse (cctxt : Protocol_client_context.full) ?(force = false) delegates =
let open State_transitions in
let open Lwt_result_syntax in
let cache = Baking_cache.Block_cache.create 10 in
let* _, current_proposal = get_current_proposal cctxt ~cache () in
let config = Baking_configuration.make ~force () in
create_state cctxt ~config ~current_proposal delegates >>=? fun state ->
let proposal = state.level_state.latest_proposal in
let*! () =
Events.(emit attempting_endorse_proposal state.level_state.latest_proposal)
in
let* () =
if force then return_unit
else
is_acceptable_proposal_for_current_level state proposal >>= function
| Invalid -> cctxt#error "Cannot endorse an invalid proposal"
| Outdated_proposal -> cctxt#error "Cannot endorse an outdated proposal"
| Valid_proposal -> return_unit
in
let consensus_list = make_consensus_list state proposal in
let*! () =
cctxt#message
"@[<v 2>Endorsing for:@ %a@]"
Format.(
pp_print_list
~pp_sep:pp_print_space
Baking_state.pp_consensus_key_and_delegate)
(List.map fst consensus_list)
in
let* () =
Baking_state.may_record_new_state ~previous_state:state ~new_state:state
in
Baking_actions.inject_endorsements state ~endorsements:consensus_list
let bake_at_next_level state =
let open Lwt_result_syntax in
let cctxt = state.global_state.cctxt in
Baking_scheduling.compute_next_potential_baking_time_at_next_level state
>>= function
| None -> cctxt#error "No baking slot found for the delegates"
| Some (timestamp, round) ->
let*! () =
cctxt#message
"Waiting until %a for round %a"
Timestamp.pp
timestamp
Round.pp
round
in
let*! () =
Option.value
~default:Lwt.return_unit
(Baking_scheduling.sleep_until timestamp)
in
return (Baking_state.Timeout (Time_to_bake_next_level {at_round = round}))
(* Simulate the end of the current round to bootstrap the automaton
or endorse the block if necessary *)
let first_automaton_event state =
match state.level_state.elected_block with
| None -> Lwt.return (Baking_scheduling.compute_bootstrap_event state)
| Some _elected_block ->
(* If there is an elected block we can directly bake at next
level after waiting its date *)
bake_at_next_level state
let endorsements_endorsing_power state endorsements =
let get_endorsement_voting_power {slot; _} =
match
SlotMap.find slot state.level_state.delegate_slots.all_delegate_slots
with
| None -> assert false
| Some {endorsing_power; _} -> endorsing_power
in
List.sort_uniq compare endorsements
|> List.fold_left
(fun power endorsement ->
power + get_endorsement_voting_power endorsement)
0
let generic_endorsing_power (filter : packed_operation list -> 'a list)
(extract : 'a -> consensus_content) state =
let current_mempool =
Operation_worker.get_current_operations state.global_state.operation_worker
in
let latest_proposal = state.level_state.latest_proposal in
let block_round = latest_proposal.block.round in
let shell_level = latest_proposal.block.shell.level in
let endorsements =
filter (Operation_pool.Operation_set.elements current_mempool.consensus)
in
let endorsements_in_mempool =
List.filter_map
(fun v ->
let consensus_content = extract v in
if
Round.(consensus_content.round = block_round)
&& Compare.Int32.(
Raw_level.to_int32 consensus_content.level = shell_level)
then Some consensus_content
else None)
endorsements
in
let power = endorsements_endorsing_power state endorsements_in_mempool in
(power, endorsements)
let state_endorsing_power =
generic_endorsing_power
Operation_pool.filter_endorsements
(fun
({
protocol_data = {contents = Single (Endorsement consensus_content); _};
_;
} :
Kind.endorsement operation)
-> consensus_content)
let do_action (state, action) =
let state_recorder ~new_state =
Baking_state.may_record_new_state ~previous_state:state ~new_state
in
Baking_actions.perform_action ~state_recorder state action
let propose_at_next_level ~minimal_timestamp state =
let open Lwt_result_syntax in
let cctxt = state.global_state.cctxt in
assert (Option.is_some state.level_state.elected_block) ;
if minimal_timestamp then
let* minimal_round, delegate =
match
Baking_scheduling.first_potential_round_at_next_level
state
~earliest_round:Round.zero
with
| None -> cctxt#error "No potential baking slot for the given delegates."
| Some first_potential_round -> return first_potential_round
in
let pool =
Operation_worker.get_current_operations
state.global_state.operation_worker
in
let kind = Baking_actions.Fresh pool in
let block_to_bake : Baking_actions.block_to_bake =
{
Baking_actions.predecessor = state.level_state.latest_proposal.block;
round = minimal_round;
delegate;
kind;
force_apply = state.global_state.config.force_apply;
}
in
let state_recorder ~new_state =
Baking_state.may_record_new_state ~previous_state:state ~new_state
in
let* state =
Baking_actions.perform_action
~state_recorder
state
(Inject_block {block_to_bake; updated_state = state})
in
let*! () =
cctxt#message
"Proposed block at round %a on top of %a "
Round.pp
block_to_bake.round
Block_hash.pp
block_to_bake.predecessor.hash
in
return state
else
let* event = bake_at_next_level state in
let* state = State_transitions.step state event >>= do_action in
cctxt#message "Proposal injected" >>= fun () -> return state
let endorsement_quorum state =
let power, endorsements = state_endorsing_power state in
if
Compare.Int.(
power >= state.global_state.constants.parametric.consensus_threshold)
then Some (power, endorsements)
else None
(* Here's the sketch of the algorithm:
Do I have an endorsement quorum for the current block or an elected block?
- Yes :: wait and propose at next level
- No ::
Is the current proposal at the right round?
- Yes :: fail propose
- No ::
Is there a preendorsement quorum or does the last proposal contain a prequorum?
- Yes :: repropose block with right payload and preendorsements for current round
- No :: repropose fresh block for current round *)
let propose (cctxt : Protocol_client_context.full) ?minimal_fees
?minimal_nanotez_per_gas_unit ?minimal_nanotez_per_byte ?force_apply ?force
?(minimal_timestamp = false) ?extra_operations ?context_path delegates =
let open Lwt_result_syntax in
let cache = Baking_cache.Block_cache.create 10 in
let* _block_stream, current_proposal = get_current_proposal cctxt ~cache () in
let config =
Baking_configuration.make
?minimal_fees
?minimal_nanotez_per_gas_unit
?minimal_nanotez_per_byte
?context_path
?force_apply
?force
?extra_operations
()
in
let* state = create_state cctxt ~config ~current_proposal delegates in
let* _ =
match state.level_state.elected_block with
| Some _ -> propose_at_next_level ~minimal_timestamp state
| None -> (
match endorsement_quorum state with
| Some (_voting_power, endorsement_qc) ->
let state =
{
state with
round_state =
{
state.round_state with
current_phase = Baking_state.Awaiting_endorsements;
};
}
in
let latest_proposal = state.level_state.latest_proposal.block in
let candidate =
{
Operation_worker.hash = latest_proposal.hash;
round_watched = latest_proposal.round;
payload_hash_watched = latest_proposal.payload_hash;
}
in
let* state =
State_transitions.step
state
(Baking_state.Quorum_reached (candidate, endorsement_qc))
>>= do_action
(* this will register the elected block *)
in
propose_at_next_level ~minimal_timestamp state
| None -> (
Baking_scheduling.compute_bootstrap_event state >>?= fun event ->
let*! state, _action = State_transitions.step state event in
let latest_proposal = state.level_state.latest_proposal in
let open State_transitions in
let round = state.round_state.current_round in
is_acceptable_proposal_for_current_level state latest_proposal
>>= function
| Invalid | Outdated_proposal -> (
let slotmap =
state.level_state.delegate_slots.own_delegate_slots
in
match State_transitions.round_proposer state slotmap round with
| Some (delegate, _) ->
let*! action =
State_transitions.propose_block_action
state
delegate
round
state.level_state.latest_proposal
in
do_action (state, action) >>=? fun state ->
let*! () =
cctxt#message
"Reproposed block at level %ld on round %a"
state.level_state.current_level
Round.pp
state.round_state.current_round
in
return state
| None -> cctxt#error "No slots for current round")
| Valid_proposal ->
cctxt#error
"Cannot propose: there's already a valid proposal for the \
current round %a"
Round.pp
round))
in
return_unit
let bake_using_automaton config state heads_stream =
let open Lwt_result_syntax in
let cctxt = state.global_state.cctxt in
let* initial_event = first_automaton_event state in
let current_level = state.level_state.latest_proposal.block.shell.level in
let loop_state =
Baking_scheduling.create_loop_state
~heads_stream
state.global_state.operation_worker
in
let stop_on_next_level_block = function
| New_head_proposal proposal ->
Compare.Int32.(proposal.block.shell.level >= Int32.succ current_level)
| _ -> false
in
Baking_scheduling.automaton_loop
~stop_on_event:stop_on_next_level_block
~config
~on_error:(fun err -> Lwt.return (Error err))
loop_state
state
initial_event
>>=? function
| Some (New_head_proposal proposal) ->
let*! () =
cctxt#message
"Block %a (%ld) injected"
Block_hash.pp
proposal.block.hash
proposal.block.shell.level
in
return_unit
| _ -> cctxt#error "Baking loop unexpectedly ended"
(* endorse the latest proposal and bake with it *)
let baking_minimal_timestamp state =
let open Lwt_result_syntax in
let cctxt = state.global_state.cctxt in
let latest_proposal = state.level_state.latest_proposal in
let own_endorsements =
State_transitions.make_consensus_list state latest_proposal
in
let current_mempool =
Operation_worker.get_current_operations state.global_state.operation_worker
in
let endorsements_in_mempool =
Operation_pool.(
filter_endorsements (Operation_set.elements current_mempool.consensus))
|> List.filter_map
(fun
({
protocol_data =
{contents = Single (Endorsement consensus_content); _};
_;
} :
Kind.endorsement operation)
->
if
Round.(consensus_content.round = latest_proposal.block.round)
&& Compare.Int32.(
Raw_level.to_int32 consensus_content.level
= latest_proposal.block.shell.level)
then Some consensus_content
else None)
in
let total_voting_power =
List.fold_left
(fun endorsements own -> snd own :: endorsements)
endorsements_in_mempool
own_endorsements
|> endorsements_endorsing_power state
in
let consensus_threshold =
state.global_state.constants.parametric.consensus_threshold
in
let* () =
if Compare.Int.(total_voting_power < consensus_threshold) then
cctxt#error
"Delegates do not have enough voting power. Only %d is available while \
%d is required."
total_voting_power
consensus_threshold
else return_unit
in
let* minimal_round, delegate =
match
Baking_scheduling.first_potential_round_at_next_level
state
~earliest_round:Round.zero
with
| None -> cctxt#error "No potential baking slot for the given delegates."
| Some first_potential_round -> return first_potential_round
in
let* signed_endorsements =
Baking_actions.sign_endorsements state own_endorsements
in
let pool =
Operation_pool.add_operations
current_mempool
(List.map snd signed_endorsements)
in
let kind = Baking_actions.Fresh pool in
let block_to_bake : Baking_actions.block_to_bake =
{
Baking_actions.predecessor = latest_proposal.block;
round = minimal_round;
delegate;
kind;
force_apply = state.global_state.config.force_apply;
}
in
let state_recorder ~new_state =
Baking_state.may_record_new_state ~previous_state:state ~new_state
in
let* _ =
Baking_actions.perform_action
~state_recorder
state
(Inject_block {block_to_bake; updated_state = state})
in
let*! () = cctxt#message "Injected block at minimal timestamp" in
return_unit
let bake (cctxt : Protocol_client_context.full) ?minimal_fees
?minimal_nanotez_per_gas_unit ?minimal_nanotez_per_byte ?force_apply ?force
?(minimal_timestamp = false) ?extra_operations
?(monitor_node_mempool = true) ?context_path delegates =
let open Lwt_result_syntax in
let config =
Baking_configuration.make
?minimal_fees
?minimal_nanotez_per_gas_unit
?minimal_nanotez_per_byte
?context_path
?force_apply
?force
?extra_operations
()
in
let cache = Baking_cache.Block_cache.create 10 in
let* block_stream, current_proposal = get_current_proposal cctxt ~cache () in
let* state =
create_state
cctxt
~monitor_node_mempool
~synchronize:(not minimal_timestamp)
~config
~current_proposal
delegates
in
let* () =
when_ monitor_node_mempool (fun () ->
(* Make sure the operation worker is populated to avoid empty
blocks being baked *)
Operation_worker.retrieve_pending_operations
cctxt
state.global_state.operation_worker)
in
if not minimal_timestamp then bake_using_automaton config state block_stream
else baking_minimal_timestamp state
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
fees_storage.mli | type error += Cannot_pay_storage_fee (* `Temporary *)
type error += Operation_quota_exceeded (* `Temporary *)
type error += Storage_limit_too_high (* `Permanent *)
(** Does not burn, only adds the burn to storage space to be paid *)
val origination_burn:
Raw_context.t -> (Raw_context.t * Tez_repr.t) tzresult Lwt.t
(** The returned Tez quantity is for logging purpose only *)
val record_paid_storage_space:
Raw_context.t -> Contract_repr.t ->
(Raw_context.t * Z.t * Z.t * Tez_repr.t) tzresult Lwt.t
val check_storage_limit:
Raw_context.t -> storage_limit:Z.t -> unit tzresult
val start_counting_storage_fees :
Raw_context.t -> Raw_context.t
val burn_storage_fees:
Raw_context.t -> storage_limit:Z.t -> payer:Contract_repr.t -> Raw_context.t tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
liquidity_baking_cpmm.ml |
let script_hex : Hex.t =
`Hex
"02000011c405000764076407640865046e00000006256f776e6572076504620000000d256d696e4c71744d696e7465640765046200000013256d6178546f6b656e734465706f7369746564046b0000000925646561646c696e650000000d256164644c6971756964697479046c000000082564656661756c7407640865046e0000000325746f076504620000000a256c71744275726e65640765046a00000010256d696e58747a57697468647261776e0765046200000013256d696e546f6b656e7357697468647261776e046b0000000925646561646c696e65000000102572656d6f76654c69717569646974790865046e00000015256f7574707574446578746572436f6e74726163740765046200000010256d696e546f6b656e73426f756768740765046e0000000325746f076504620000000b25746f6b656e73536f6c64046b0000000925646561646c696e650000000d25746f6b656e546f546f6b656e07640865046e0000000325746f076504620000000b25746f6b656e73536f6c640765046a0000000d256d696e58747a426f75676874046b0000000925646561646c696e650000000b25746f6b656e546f58747a0865046e0000000325746f0765046200000010256d696e546f6b656e73426f75676874046b0000000925646561646c696e650000000b2578747a546f546f6b656e0501076504620000000a25746f6b656e506f6f6c0765046a000000082578747a506f6f6c0765046200000009256c7174546f74616c0765046e0000000d25746f6b656e41646472657373046e0000000b256c71744164647265737305020200000f7203210317034c0316072e02000009d1072e020000035a072e020000032603210317034c0316034c03210317034c0316034c03210317034c0316034c034003190328072c020000000c05200004074303620003032702000002ea0743036a000105700004032105710005031703160322072f0200000013074303680100000008444956206279203003270200000000031603130743036a0001034c0322072f02000000130743036801000000084449562062792030032702000000000316034c0321057100020570000603210571000703170317031605700002032105710003033a0322072f020000001307430368010000000844495620627920300327020000000003160570000205700006032105710007031605700003033a0322072f020000001307430368010000000844495620627920300327020000002a03210317034c03160743036200000570000203190325072c02000000000200000008074303620001031205700002034c0321057100020319032a072c020000000c05200005074303620004032702000001b60571000203210571000303190337072c020000000c0520000407430362000503270200000190057000030321057100040317031703170570000203210571000305700005032105710006031703170316031203420570000403210571000503170316034205700004032105710005031603420317034c032105710002057000050321057100060316031203420321031703170313057000060317031603120342034c03160342034c03490354034203480342034c032105710002034c03210317034c0316034c03210317034c031605700003031703170317031606550765036e0765036e036200000009257472616e73666572072f0200000008074303620000032702000000000743036a000005700003057000030342057000030342034d05700002033005700003034205700002032105710003034c03210317034c031605700002031703170317031706550765045b00000009257175616e74697479046e00000007257461726765740000000b256d696e744f724275726e072f020000000807430362000c032702000000000743036a000005700002057000030342034d05700002053d036d05700002031b05700002031b0342020000002803200321031703170313057000020321057100030317031603120342034c03160342053d036d0342020000066b072e020000038d03210317034c0316034c03210317034c0316034c03210317034c0316034c03210317034c0316034c034003190328072c020000000c05200005074303620003032702000003470743036a000003130319032a072c020000000c0520000507430362000a03270200000323057000040321057100050317031703160743036a000105700006032105710007031703160322072f0200000013074303680100000008444956206279203003270200000000031605700004032105710005033a0322072f020000001307430368010000000844495620627920300327020000000003160743036a0001034c033a0570000503210571000603170317031605700006032105710007031605700005032105710006033a0322072f02000000130743036801000000084449562062792030032702000000000316057000030570000203210571000303190337072c020000000c0520000607430362000b0327020000022e05700002034c03210571000203190337072c020000000c0520000507430362000d032702000002060570000203210571000305700005032105710006031703170316034b0356072f020000000807430362000e03270200000000034c032105710002057000060321057100070316034b0356072f020000000807430362000f03270200000000057000040743035b0000034b0348034205700006032105710007034c03210317034c031605700002031703170317031706550765045b00000009257175616e74697479046e00000007257461726765740000000b256d696e744f724275726e072f020000000807430362000c032702000000000743036a000005700002057000030342034d0570000305700005032105710006034203490354034205700006032105710007034c03210317034c0316034c03210317034c031605700003031703170317031606550765036e0765036e036200000009257472616e73666572072f0200000008074303620000032702000000000743036a000005700003057000030342057000030342034d05700004032105710005057000060555036c072f020000000807430362000903270200000000034c0743036c030b034d0570000603210571000703170317057000060570000703210571000803170316034b034205700006031603420321031703170317057000060342034c032105710002031703160342034c031603420317057000040342053d036d05700002031b05700002031b05700002031b034202000002d203210317034c0316034c03210317034c0316034c03210317034c0316034c03210317034c03160570000406550765046e0000000325746f0765046200000010256d696e546f6b656e73426f75676874046b0000000925646561646c696e650000000b2578747a546f546f6b656e072f020000000807430362001f032702000000000743036a000003130319032a072c020000000c0520000607430362000a0327020000022d05700002032105710003034003190328072c020000000c05200006074303620003032702000002050743036200a70f05700002032105710003033a0743036200a80f057000070321057100080316033a031205700006032105710007031703160743036200a70f05700004032105710005033a033a0322072f020000001307430368010000000844495620627920300327020000000003160743036200a80f0743036200a70f05700002032105710003033a0322072f02000000130743036801000000084449562062792030032702000000000316057000070321057100080317057000040321057100050570000903210571000a031603120342032103170317057000030321057100040570000a03170316034b0342034c031603420570000403490354034203480342034c032105710002034c03210317034c0316034c03210317034c031605700003031703170317031606550765036e0765036e036200000009257472616e73666572072f0200000008074303620000032702000000000743036a000005700003057000030342057000030342034d057000040570000303210571000405700006057000080342057000070342034d0570000305700004034b0743036e0100000024747a314b65326837734464616b484a5168385758345a3337326475314b4368736b7379550555036c072f020000000807430362000903270200000000034c0743036c030b034d05700003053d036d05700002031b05700002031b05700002031b0342020000058d072e02000002cc03210317034c0316034c03210317034c0316034c03210317034c0316034c034003190328072c020000000c05200004074303620003032702000002900743036a000003130319032a072c020000000c0520000407430362000a0327020000026c0743036200a70f05700002032105710003033a0743036200a80f057000050321057100060316033a03120743036a000105700005032105710006031703160322072f020000001307430368010000000844495620627920300327020000000003160743036200a70f05700004032105710005033a033a0322072f020000001307430368010000000844495620627920300327020000000003160743036a0001034c033a0743036200a80f0743036200a70f05700002032105710003033a0322072f0200000013074303680100000008444956206279203003270200000000031605700002034c03210571000203190337072c020000000a032007430362000803270200000000057000020321057100030349035403420348034205700005032105710006034c03210317034c0316034c03210317034c031605700003031703170317031606550765036e0765036e036200000009257472616e73666572072f0200000008074303620000032702000000000743036a000005700003057000030342057000030342034d034c032105710002057000050555036c072f020000000807430362000903270200000000034c0743036c030b034d0570000503210571000603170570000505700006032105710007031603120342032103170317057000050321057100060570000703170316034b0342034c031603420570000305700004034b0743036e0100000024747a314b65326837734464616b484a5168385758345a3337326475314b4368736b7379550555036c072f020000000807430362000903270200000000034c0743036c030b034d034c053d036d05700002031b05700002031b05700002031b034202000002b503210317034c0316034c03210317034c0316034c034003190328072c020000000c05200003074303620003032702000002830743036a000105700003032105710004031703160322072f0200000013074303680100000008444956206279203003270200000000031603130743036a0001034c0322072f020000001307430368010000000844495620627920300327020000000003160743036200a80f0743036200a70f05700002032105710003033a0322072f02000000130743036801000000084449562062792030032702000000000316032105700002034b03110743036200a70f05700002032105710003033a0743036200a80f05700004033a03120570000503210571000603160743036200a70f05700004032105710005033a033a0322072f0200000013074303680100000008444956206279203003270200000000031605700003034c03210571000203190337072c020000000a0320074303620012032702000000000321057000050321057100060316034b0356072f02000000080743036200130327020000000005700005032105710006031703170743036a000105700005033a05700006032105710007031703160312034205700005031603420317034c0342034c057000030342034903540342034c032105710002034c03210317034c0316034c03210317034c031605700003031703170317031606550765036e0765036e036200000009257472616e73666572072f0200000008074303620000032702000000000743036a000005700003057000030342057000030342034d0743036a000105700003033a0743036e0100000024747a314b65326837734464616b484a5168385758345a3337326475314b4368736b7379550555036c072f020000000807430362000903270200000000034c0743036c030b034d05700002053d036d05700002031b05700002031b0342"
let script_bytes : Bytes.t option = Hex.to_bytes script_hex
let script_opt : Script_repr.expr option =
Option.bind
script_bytes
(Data_encoding.Binary.of_bytes_opt Script_repr.expr_encoding)
let script : Script_repr.expr =
Option.value_f ~default:(fun () -> assert false) script_opt
| |
reflection.ml | open Term
open Ty
open Decl
open Ident
open Task
open Args_wrapper
open Generic_arg_trans_utils
exception NoReification
let debug_reification = Debug.register_info_flag
~desc:"Reification"
"reification"
let debug_refl = Debug.register_info_flag
~desc:"Reflection transformations"
"reflection"
let expl_reification_check = Ident.create_attribute "expl:reification check"
let meta_decision_procedure =
Theory.register_meta
~desc:"Declare a decision procedure, used for reflection."
"reflection"
[ Theory.MTid ]
type reify_env = { kn: known_map;
store: (vsymbol * int) Mterm.t;
fr: int;
subst: term Mvs.t;
lv: vsymbol list;
var_maps: ty Mvs.t; (* type of values pointed by each map*)
crc_map: Coercion.t;
ty_to_map: vsymbol Mty.t;
env: Env.env;
interps: Sls.t; (* functions that were inverted*)
task: Task.task;
bound_vars: Svs.t; (* bound variables, do not map them in a var map*)
bound_fr: int; (* separate, negative index for bound vars*)
}
let init_renv kn crc lv env task =
{ kn=kn;
store = Mterm.empty;
fr = 0;
subst = Mvs.empty;
lv = lv;
var_maps = Mvs.empty;
crc_map = crc;
ty_to_map = Mty.empty;
env = env;
interps = Sls.empty;
task = task;
bound_vars = Svs.empty;
bound_fr = -1;
}
let rec reify_term renv t rt =
let is_pvar p = match p.pat_node with Pvar _ -> true | _ -> false in
let rec use_interp t =
let r = match t.t_node with
| Tconst _ -> true
| Tvar _ -> false
| Tapp (ls, []) ->
begin match find_logic_definition renv.kn ls with
| None -> false
| Some ld ->
let _,t = open_ls_defn ld in
use_interp t
end
| Tapp (_, _) -> true
| _ -> false in
Debug.dprintf debug_reification "use_interp %a: %b@." Pretty.print_term t r;
r in
let add_to_maps renv vyl =
let var_maps, ty_to_map =
List.fold_left
(fun (var_maps, ty_to_map) vy ->
if Mty.mem vy.vs_ty ty_to_map
then (Mvs.add vy vy.vs_ty var_maps, ty_to_map)
else (Mvs.add vy vy.vs_ty var_maps,
Mty.add vy.vs_ty vy ty_to_map))
(renv.var_maps, renv.ty_to_map)
(List.map
(fun t -> match t.t_node with Tvar vy -> vy | _ -> assert false)
vyl)
in
{ renv with var_maps = var_maps; ty_to_map = ty_to_map }
in
let open Theory in
let th_list = Env.read_theory renv.env ["list"] "List" in
let ty_list = ns_find_ts th_list.th_export ["list"] in
let compat_h t rt =
match t.t_node, rt.t_node with
| Tapp (ls1,_), Tapp(ls2, _) -> ls_equal ls1 ls2
| Tquant (Tforall, _), Tquant (Tforall, _)
| Tquant (Texists, _), Tquant (Texists, _)-> true
| _ -> false in
let is_eq_true t = match t.t_node with
| Tapp (eq, [_; tr])
when ls_equal eq ps_equ && t_equal tr t_bool_true -> true
| _ -> false in
let lhs_eq_true t = match t.t_node with
| Tapp (eq, [t; tr])
when ls_equal eq ps_equ && t_equal tr t_bool_true -> t
| _ -> assert false in
let rec invert_nonvar_pat vl (renv:reify_env) (p,f) t =
Debug.dprintf debug_reification
"invert_nonvar_pat p %a f %a t %a@."
Pretty.print_pat p Pretty.print_term f Pretty.print_term t;
if is_eq_true f && not (is_eq_true t)
then invert_nonvar_pat vl renv (p, lhs_eq_true f) t else
match p.pat_node, f.t_node, t.t_node with
| Pwild , _, _ | Pvar _,_,_ when t_equal f t ->
Debug.dprintf debug_reification "case equal@.";
renv, t
| Papp (cs, pl), _,_
when compat_h f t
&& Svs.for_all (fun v -> t_v_occurs v f = 1) p.pat_vars
&& List.for_all is_pvar pl
(* could remove this with a bit more work in term reconstruction *)
->
Debug.dprintf debug_reification "case app@.";
let rec rt_of_var svs f t v (renv, acc) =
assert (not (Mvs.mem v acc));
Debug.dprintf debug_reification "rt_of_var %a %a@."
Pretty.print_vs v Pretty.print_term f;
if t_v_occurs v f = 1
&& Svs.for_all (fun v' -> vs_equal v v' || t_v_occurs v' f = 0) svs
then let renv, rt = invert_pat vl renv (pat_var v, f) t in
renv, Mvs.add v rt acc
else
match f.t_node, t.t_node with
| Tapp(ls1, la1), Tapp(ls2, la2) when ls_equal ls1 ls2 ->
let rec aux la1 la2 =
match la1, la2 with
| f'::l1, t'::l2 ->
if t_v_occurs v f' = 1 then rt_of_var svs f' t' v (renv, acc)
else aux l1 l2
| _ -> assert false in
aux la1 la2
| Tquant (Tforall, tq1), Tquant (Tforall, tq2)
| Tquant (Texists, tq1), Tquant (Texists, tq2) ->
let _, _, t1 = t_open_quant tq1 in
let vl, _, t2 = t_open_quant tq2 in
let bv = List.fold_left Svs.add_left renv.bound_vars vl in
let renv = { renv with bound_vars = bv } in
rt_of_var svs t1 t2 v (renv, acc)
| _ -> raise NoReification
in
let rec check_nonvar f t =
match f.t_node, t.t_node with
| Tapp (ls1, la1), Tapp (ls2, la2) ->
if Svs.for_all (fun v -> t_v_occurs v f = 0) p.pat_vars
then (if not (ls_equal ls1 ls2)
then raise NoReification);
if ls_equal ls1 ls2 then List.iter2 check_nonvar la1 la2;
| Tapp (ls,_), Tconst _ ->
(* reject constants that do not match the
definitions of logic constants*)
if Svs.for_all (fun v -> t_v_occurs v f = 0) p.pat_vars
then
match find_logic_definition renv.kn ls with
| None -> raise NoReification
| Some ld -> let v,f = open_ls_defn ld in
assert (v = []);
check_nonvar f t
else ()
| Tconst (Constant.ConstInt c1), Tconst (Constant.ConstInt c2) ->
let open Number in
if not (BigInt.eq c1.il_int c2.il_int)
then raise NoReification
| _ -> () (* FIXME add more failure cases if needed *)
in
check_nonvar f t;
let renv, mvs = Svs.fold (rt_of_var p.pat_vars f t) p.pat_vars
(renv, Mvs.empty) in
let lrt = List.map (function | {pat_node = Pvar v} -> Mvs.find v mvs
| _ -> assert false) pl in
renv, t_app cs lrt (Some p.pat_ty)
| Pvar v, Tapp (ls1, la1), Tapp(ls2, la2)
when ls_equal ls1 ls2 && t_v_occurs v f = 1
-> Debug.dprintf debug_reification "case app_var@.";
let renv, rt =
List.fold_left2
(fun (renv, acc) f t ->
if acc = None
then if t_v_occurs v f > 0
then let renv, rt = (invert_pat vl renv (p, f) t) in
renv, Some rt
else renv, acc
else (assert (t_v_occurs v f = 0);
renv, acc))
(renv,None) la1 la2 in
renv, Opt.get rt
| Pvar v, Tquant(Tforall, tq1), Tquant(Tforall, tq2)
| Pvar v, Tquant(Texists, tq1), Tquant(Texists, tq2)
when t_v_occurs v f = 1 ->
Debug.dprintf debug_reification "case quant_var@.";
let _,_,t1 = t_open_quant tq1 in
let vl,_,t2 = t_open_quant tq2 in
let bv = List.fold_left Svs.add_left renv.bound_vars vl in
let renv = { renv with bound_vars = bv } in
invert_nonvar_pat vl renv (p, t1) t2
| Por (p1, p2), _, _ ->
Debug.dprintf debug_reification "case or@.";
begin try invert_pat vl renv (p1, f) t
with NoReification -> invert_pat vl renv (p2, f) t
end
| Pvar _, Tvar _, Tvar _ | Pvar _, Tvar _, Tapp (_, [])
| Pvar _, Tvar _, Tconst _
-> Debug.dprintf debug_reification "case vars@.";
(renv, t)
| Pvar _, Tapp (ls, _hd::_tl), _
-> Debug.dprintf debug_reification "case interp@.";
invert_interp renv ls t
| Papp (cs, [{pat_node = Pvar v}]), Tvar v', Tconst _
when vs_equal v v'
-> Debug.dprintf debug_reification "case var_const@.";
renv, t_app cs [t] (Some p.pat_ty)
| Papp (cs, [{pat_node = Pvar _}]), Tapp(ls, _hd::_tl), _
when use_interp t (*FIXME*)
-> Debug.dprintf debug_reification "case interp_var@.";
let renv, rt = invert_interp renv ls t in
renv, (t_app cs [rt] (Some p.pat_ty))
| Papp _, Tapp (ls1, _), Tapp(ls2, _) ->
Debug.dprintf debug_reification "head symbol mismatch %a %a@."
Pretty.print_ls ls1 Pretty.print_ls ls2;
raise NoReification
| _ -> raise NoReification
and invert_var_pat vl (renv:reify_env) (p,f) t =
Debug.dprintf debug_reification
"invert_var_pat p %a f %a t %a@."
Pretty.print_pat p Pretty.print_term f Pretty.print_term t;
match p.pat_node, f.t_node with
| Papp (_, [{pat_node = Pvar v1}]),
Tapp (ffa,[{t_node = Tvar vy}; {t_node = Tvar v2}])
| Pvar v1, Tapp (ffa,[{t_node = Tvar vy}; {t_node = Tvar v2}])
when ty_equal v1.vs_ty ty_int
&& Svs.mem v1 p.pat_vars
&& vs_equal v1 v2
&& ls_equal ffa fs_func_app
&& List.exists (fun vs -> vs_equal vs vy) vl (*FIXME*)
->
Debug.dprintf debug_reification "case var@.";
let rty = (Some p.pat_ty) in
let app_pat trv = match p.pat_node with
| Papp (cs, _) -> t_app cs [trv] rty
| Pvar _ -> trv
| _ -> assert false in
let rec rm t =
let t = match t.t_node with
| Tapp (f,tl) -> t_app f (List.map rm tl) t.t_ty
| Tvar _ | Tconst _ -> t
| Tif (f,t1,t2) -> t_if (rm f) (rm t1) (rm t2)
| Tbinop (op,f1,f2) -> t_binary op (rm f1) (rm f2)
| Tnot f1 -> t_not (rm f1)
| Ttrue | Tfalse -> t
| _ -> t (* FIXME some cases missing *)
in
t_attr_set ?loc:t.t_loc Sattr.empty t
in
let t = rm t in
(* remove attributes to identify terms modulo attributes *)
if Mterm.mem t renv.store
then
begin
Debug.dprintf debug_reification "%a exists@." Pretty.print_term t;
(renv, app_pat (t_nat_const (snd (Mterm.find t renv.store))))
end
else
begin
Debug.dprintf debug_reification "%a is new@." Pretty.print_term t;
let bound = match t.t_node with
| Tvar v -> Svs.mem v renv.bound_vars
| _ -> false in
let renv, i=
if bound
then let i = renv.bound_fr in
{ renv with bound_fr = i-1 }, i
else
let vy = Mty.find vy.vs_ty renv.ty_to_map in
let fr = renv.fr in
let store = Mterm.add t (vy, fr) renv.store in
{ renv with store = store; fr = fr + 1 }, fr in
let const = Constant.int_const_of_int i in
(renv, app_pat (t_const const Ty.ty_int))
end
| _ -> raise NoReification
and invert_pat vl renv (p,f) t =
if (oty_equal f.t_ty t.t_ty)
then
try invert_nonvar_pat vl renv (p,f) t
with NoReification -> invert_var_pat vl renv (p,f) t
else begin
try
let crc = Coercion.find renv.crc_map
(Opt.get t.t_ty) (Opt.get f.t_ty) in
let apply_crc t ls = t_app_infer ls [t] in
let crc_t = List.fold_left apply_crc t crc in
assert (oty_equal f.t_ty crc_t.t_ty);
invert_pat vl renv (p,f) crc_t
with Not_found ->
Debug.dprintf debug_reification "type mismatch between %a and %a@."
Pretty.print_ty (Opt.get f.t_ty)
Pretty.print_ty (Opt.get t.t_ty);
raise NoReification
end
and invert_interp renv ls (t:term) =
let ld = try Opt.get (find_logic_definition renv.kn ls)
with Invalid_argument _ | Not_found ->
Debug.dprintf debug_reification
"did not find def of %a@."
Pretty.print_ls ls;
raise NoReification
in
let vl, f = open_ls_defn ld in
Debug.dprintf debug_reification "invert_interp ls %a t %a@."
Pretty.print_ls ls Pretty.print_term t;
invert_body { renv with interps = Sls.add ls renv.interps } ls vl f t
and invert_body renv ls vl f t =
match f.t_node with
| Tvar v when vs_equal v (List.hd vl) -> renv, t
| Tif (f, th, el) when t_equal th t_bool_true && t_equal el t_bool_false ->
invert_body renv ls vl f t
| Tcase (x, bl)
->
(match x.t_node with
| Tvar v when vs_equal v (List.hd vl) -> ()
| _ -> Debug.dprintf debug_reification "not matching on first param@.";
raise NoReification);
Debug.dprintf debug_reification "case match@.";
let rec aux invert = function
| [] -> raise NoReification
| tb::l ->
try invert vl renv (t_open_branch tb) t
with NoReification ->
Debug.dprintf debug_reification "match failed@."; aux invert l in
(try aux invert_nonvar_pat bl with NoReification -> aux invert_var_pat bl)
| Tapp (ls', _) ->
Debug.dprintf debug_reification "case app@.";
invert_interp renv ls' t
| _ -> Debug.dprintf debug_reification "function body not handled@.";
Debug.dprintf debug_reification "f: %a@." Pretty.print_term f;
raise NoReification
and invert_ctx_interp renv ls t l g =
let ld = try Opt.get (find_logic_definition renv.kn ls)
with | Not_found ->
Debug.dprintf debug_reification "did not find def of %a@."
Pretty.print_ls ls;
raise NoReification
| Invalid_argument _ -> assert false
in
let vl, f = open_ls_defn ld in
Debug.dprintf debug_reification "invert_ctx_interp ls %a @."
Pretty.print_ls ls;
let renv = { renv with interps = Sls.add ls renv.interps } in
invert_ctx_body renv ls vl f t l g
and invert_ctx_body renv ls vl f t l g =
match f.t_node with
| Tcase ({t_node = Tvar v}, [tbn; tbc] ) when vs_equal v (List.hd vl) ->
let ty_g = g.vs_ty in
let ty_list_g = ty_app ty_list [ty_g] in
if (not (ty_equal ty_list_g l.vs_ty))
then (Debug.dprintf debug_reification
"bad type for context interp function@.";
raise NoReification);
let nil = ns_find_ls th_list.th_export ["Nil"] in
let cons = ns_find_ls th_list.th_export ["Cons"] in
let (pn, fn) = t_open_branch tbn in
let (pc, fc) = t_open_branch tbc in
begin match pn.pat_node, fn.t_node, pc.pat_node, fc.t_node with
| Papp(n, []),
Tapp(eq'', [{t_node=Tapp(leq,{t_node = Tvar g'}::_)};btr'']),
Papp (c, [{pat_node = Pvar hdl};{pat_node = Pvar tll}]),
Tbinop(Timplies,
{t_node=(Tapp(eq, [({t_node = Tapp(leq', _)} as thd); btr]))},
{t_node = (Tapp(eq',
[({t_node =
Tapp(ls', {t_node = Tvar tll'}::{t_node=Tvar g''}::_)}
as ttl); btr']))})
when ls_equal n nil && ls_equal c cons && ls_equal ls ls'
&& vs_equal tll tll'
&& vs_equal g' g'' && ls_equal leq leq'
&& List.mem g' vl
&& not (Mvs.mem tll (t_vars thd))
&& not (Mvs.mem hdl (t_vars ttl))
&& ls_equal eq ps_equ && ls_equal eq' ps_equ
&& ls_equal eq'' ps_equ && t_equal btr t_bool_true
&& t_equal btr' t_bool_true && t_equal btr'' t_bool_true
->
Debug.dprintf debug_reification "reifying goal@.";
let (renv, rg) = invert_interp renv leq t in
let renv = { renv with subst = Mvs.add g rg renv.subst } in
Debug.dprintf debug_reification "filling context@.";
let rec add_to_ctx (renv, ctx) e =
try
match e.t_node with
| Teps _ -> (renv, ctx)
| Tbinop (Tand,e1,e2) ->
add_to_ctx (add_to_ctx (renv, ctx) e1) e2
| _ ->
let (renv,req) = invert_interp renv leq e in
(renv,(t_app cons [req; ctx] (Some ty_list_g)))
with
| NoReification -> renv,ctx
in
let renv, ctx =
task_fold
(fun (renv,ctx) td ->
match td.td_node with
| Decl {d_node = Dprop (Paxiom, _, e)}
-> add_to_ctx (renv, ctx) e
| Decl {d_node = Dlogic [ls, ld]} when ls.ls_args = []
->
add_to_ctx (renv, ctx) (ls_defn_axiom ld)
| _-> renv,ctx)
(renv, (t_app nil [] (Some ty_list_g))) renv.task in
{ renv with subst = Mvs.add l ctx renv.subst }
| _ -> Debug.dprintf debug_reification "unhandled interp structure@.";
raise NoReification
end
| Tif (c, th, el) when t_equal th t_bool_true && t_equal el t_bool_false ->
invert_ctx_body renv ls vl c t l g
| _ -> Debug.dprintf debug_reification "not a match on list@.";
raise NoReification
in
Debug.dprintf debug_reification "reify_term t %a rt %a@."
Pretty.print_term t Pretty.print_term rt;
if not (oty_equal t.t_ty rt.t_ty)
then (Debug.dprintf debug_reification "reification type mismatch %a %a@."
Pretty.print_ty (Opt.get t.t_ty)
Pretty.print_ty (Opt.get rt.t_ty);
raise NoReification);
match t.t_node, rt.t_node with
| _, Tapp(interp, {t_node = Tvar vx}::vyl)
when List.mem vx renv.lv
&& List.for_all
(fun t -> match t.t_node with
| Tvar vy -> List.mem vy renv.lv
| _ -> false)
vyl ->
Debug.dprintf debug_reification "case interp@.";
let renv = add_to_maps renv vyl in
let renv, x = invert_interp renv interp t in
{ renv with subst = Mvs.add vx x renv.subst }
| Tapp(eq, [t1; t2]), Tapp (eq', [rt1; rt2])
when ls_equal eq ps_equ && ls_equal eq' ps_equ
&& oty_equal t1.t_ty rt1.t_ty && oty_equal t2.t_ty rt2.t_ty
->
Debug.dprintf debug_reification "case eq@.";
reify_term (reify_term renv t1 rt1) t2 rt2
| _, Tapp(eq,[{t_node=Tapp(interp, {t_node = Tvar l}::{t_node = Tvar g}::vyl)}; tr])
when ls_equal eq ps_equ && t_equal tr t_bool_true
&& ty_equal (ty_app ty_list [g.vs_ty]) l.vs_ty
&& List.mem l renv.lv
&& List.mem g renv.lv
&& List.for_all
(fun t -> match t.t_node with
| Tvar vy -> List.mem vy renv.lv
| _ -> false)
vyl
->
Debug.dprintf debug_reification "case context@.";
let renv = add_to_maps renv vyl in
invert_ctx_interp renv interp t l g
| Tbinop(Tiff,t,{t_node=Ttrue}), Tapp(eq,[{t_node=Tapp(interp, {t_node = Tvar f}::vyl)}; tr])
when ls_equal eq ps_equ && t_equal tr t_bool_true
&& t.t_ty=None ->
Debug.dprintf debug_reification "case interp_fmla@.";
Debug.dprintf debug_reification "t %a rt %a@." Pretty.print_term t Pretty.print_term rt;
let renv = add_to_maps renv vyl in
let renv, rf = invert_interp renv interp t in
{ renv with subst = Mvs.add f rf renv.subst }
| _ -> Debug.dprintf debug_reification "no reify_term match@.";
Debug.dprintf debug_reification "lv = [%a]@."
(Pp.print_list Pp.space Pretty.print_vs)
renv.lv;
raise NoReification
let build_vars_map renv prev =
Debug.dprintf debug_reification "building vars map@.";
let subst, prev = Mvs.fold
(fun vy ty_vars (subst, prev) ->
Debug.dprintf debug_reification "creating var map %a@."
Pretty.print_vs vy;
let ly = create_fsymbol (Ident.id_fresh vy.vs_name.id_string)
[] ty_vars in
let y = t_app ly [] (Some ty_vars) in
let d = create_param_decl ly in
let prev = Task.add_decl prev d in
Mvs.add vy y subst, prev)
renv.var_maps (renv.subst, prev) in
let prev, mapdecls =
Mvs.fold
(fun vy _ (prev,prs) ->
Debug.dprintf debug_reification "checking %a@." Pretty.print_vs vy;
let vs = Mty.find vy.vs_ty renv.ty_to_map in
if vs_equal vy vs then prev,prs
else begin
Debug.dprintf debug_reification "aliasing %a and %a@."
Pretty.print_vs vy Pretty.print_vs vs;
let y = Mvs.find vy subst in
let z = Mvs.find vs subst in
let et = t_equ y z in
let pr = create_prsymbol (Ident.id_fresh "map_alias") in
let d = create_prop_decl Paxiom pr et in
Task.add_decl prev d, pr::prs end)
renv.var_maps (prev, []) in
if not (List.for_all (fun v -> Mvs.mem v subst) renv.lv)
then (Debug.dprintf debug_reification "vars not matched: %a@."
(Pp.print_list Pp.space Pretty.print_vs)
(List.filter (fun v -> not (Mvs.mem v subst)) renv.lv);
raise (Arg_error "vars not matched"));
Debug.dprintf debug_reification "all vars matched@.";
let prev, defdecls =
Mterm.fold
(fun t (vy,i) (prev,prs) ->
let y = Mvs.find vy subst in
let et = t_equ
(t_app fs_func_app [y; t_nat_const i]
t.t_ty)
t in
Debug.dprintf debug_reification "%a %d = %a@."
Pretty.print_vs vy i Pretty.print_term t;
let s = Format.sprintf "y_val%d" i in
let pr = create_prsymbol (Ident.id_fresh s) in
let d = create_prop_decl Paxiom pr et in
Task.add_decl prev d, pr::prs)
renv.store (prev,[]) in
subst, prev, mapdecls, defdecls
let build_goals do_trans renv prev mapdecls defdecls subst env lp g rt =
Debug.dprintf debug_refl "building goals@.";
let inst_rt = t_subst subst rt in
Debug.dprintf debug_refl "reified goal instantiated@.";
let inst_lp = List.map (t_subst subst) lp in
Debug.dprintf debug_refl "premises instantiated@.";
let hr = create_prsymbol (id_fresh "HR") in
let d_r = create_prop_decl Paxiom hr inst_rt in
let pr = create_prsymbol
(id_fresh "GR"
~attrs:(Sattr.singleton expl_reification_check)) in
let d = create_prop_decl Pgoal pr g in
let task_r = Task.add_decl (Task.add_decl prev d_r) d in
Debug.dprintf debug_refl "building cut indication rt %a g %a@."
Pretty.print_term rt Pretty.print_term g;
let compute_hyp_few pr = Compute.normalize_hyp_few None (Some pr) env in
let compute_in_goal = Compute.normalize_goal_transf_all env in
let ltask_r =
try let ci =
match (rt.t_node, g.t_node) with
| (Tapp(eq, rh::rl),
Tapp(eq', h::l))
when ls_equal eq eq' ->
List.fold_left2
(fun ci st rst ->
t_and ci (t_equ (t_subst subst rst) st))
(t_equ (t_subst subst rh) h)
l rl
| _,_ when g.t_ty <> None -> t_equ (t_subst subst rt) g
| _ -> raise Not_found in
Debug.dprintf debug_refl "cut ok@.";
Trans.apply (Cut.cut ci (Some "interp")) task_r
with Arg_trans _ | TypeMismatch _ | Not_found ->
Debug.dprintf debug_refl "no cut found@.";
if do_trans
then
let g, prev = task_separate_goal task_r in
let prev = Sls.fold
(fun ls t ->
Task.add_meta t Compute.meta_rewrite_def [Theory.MAls ls])
renv.interps prev in
let t = Task.add_tdecl prev g in
let t = Trans.apply (compute_hyp_few hr) t in
match t with
| [t] ->
let rewrite = Apply.rewrite_list false true
(mapdecls@defdecls) (Some hr) in
Trans.apply rewrite t
| [] -> []
| _ -> assert false
else [task_r] in
let lt = List.map (fun ng -> Task.add_decl prev
(create_prop_decl Pgoal (create_prsymbol (id_fresh "G")) ng))
inst_lp in
let lt = if do_trans
then Lists.apply (Trans.apply compute_in_goal) lt
else lt in
Debug.dprintf debug_refl "done@.";
ltask_r@lt
let reflection_by_lemma pr env : Task.task Trans.tlist = Trans.store (fun task ->
let kn = task_known task in
let g, prev = Task.task_separate_goal task in
let g = Apply.term_decl g in
Debug.dprintf debug_refl "start@.";
let l =
let kn' = task_known prev in (* TODO Do we want kn here ? *)
match find_prop_decl kn' pr with
| (_, t) -> t
| exception Not_found -> raise (Arg_error "lemma not found")
in
let (lp, lv, llet, rt) = Apply.intros l in
if llet <> []
then begin
(* TODO handle lets *)
Debug.dprintf debug_refl "let in procedure postcondition@.";
raise NoReification
end;
let nt = Args_wrapper.build_naming_tables task in
let crc = nt.Trans.coercion in
let renv = reify_term (init_renv kn crc lv env prev) g rt in
let subst, prev, mds, dds = build_vars_map renv prev in
build_goals true renv prev mds dds subst env lp g rt)
open Expr
open Ity
open Wstdlib
open Mlinterp
open Theory
open Pmodule
exception ReductionFail of reify_env
let reflection_by_function do_trans s env = Trans.store (fun task ->
Debug.dprintf debug_refl "reflection_f start@.";
let kn = task_known task in
let nt = Args_wrapper.build_naming_tables task in
let crc = nt.Trans.coercion in
let g, prev = Task.task_separate_goal task in
let g = Apply.term_decl g in
let ths = Task.used_theories task in
let re_dot = Re.Str.regexp_string "." in
let qs = Re.Str.split re_dot s in
let fname = List.hd (List.rev qs) in
let es = "Symbol "^fname^" not found in reflection metas" in
let fid = Mstr.find_exn (Arg_error es) s nt.Trans.meta_id_args in
Debug.dprintf debug_refl "looking for symbol %s@." fname;
let (pmod, rs) =
let fn acc = function
| [ MAid id ] ->
Debug.dprintf debug_refl "found symbol %s@." id.id_string;
if id_equal id fid
then id :: acc
else acc
| _ -> assert false in
begin match on_meta meta_decision_procedure fn [] task with
| [] ->
Debug.dprintf debug_refl "symbol not found in current goal@.";
let es = Format.sprintf "Symbol %s not found@." s in
raise (Arg_error es)
| [id] ->
let pm = restore_module_id id in
Debug.dprintf debug_refl "symbol in module %s@." pm.mod_theory.th_name.id_string;
(pm, ns_find_rs pm.mod_export qs)
| _ -> raise (Arg_error "symbol found twice")
end
in
let lpost = List.map open_post rs.rs_cty.cty_post in
if List.exists (fun pv -> pv.pv_ghost) rs.rs_cty.cty_args
then (Debug.dprintf debug_refl "ghost parameter@.";
raise (Arg_error "function has ghost parameters"));
Debug.dprintf debug_refl "building module map@.";
let mm = Mid.fold
(fun id th acc ->
try
let pm = Pmodule.restore_module th in
Mstr.add id.id_string pm acc
with Not_found -> acc)
ths (Mstr.singleton pmod.mod_theory.th_name.id_string pmod) in
Debug.dprintf debug_refl "module map built@.";
let args = List.map (fun pv -> pv.pv_vs) rs.rs_cty.cty_args in
let rec reify_post = function
| [] -> Debug.dprintf debug_refl "no postcondition reifies@.";
raise NoReification
| (vres, p)::t -> begin
try
Debug.dprintf debug_refl "new post@.";
Debug.dprintf debug_refl "post: %a, %a@."
Pretty.print_vs vres Pretty.print_term p;
let (lp, lv, llet, rt) = Apply.intros p in
if llet <> []
then begin
(* TODO handle lets *)
Debug.dprintf debug_refl "let in procedure postcondition@.";
raise NoReification
end;
let lv = lv @ args in
let renv = reify_term (init_renv kn crc lv env prev) g rt in
Debug.dprintf debug_refl "computing args@.";
let vars =
List.fold_left
(fun vars (vs, t) ->
if List.mem vs args
then begin
Debug.dprintf debug_refl "value of term %a for arg %a@."
Pretty.print_term t
Pretty.print_vs vs;
Mid.add vs.vs_name (value_of_term kn t) vars end
else vars)
Mid.empty
(Mvs.bindings renv.subst) in
Debug.dprintf debug_refl "evaluating@.";
let res =
try term_of_value (Mlinterp.interp env mm rs vars)
with Raised (xs,_,cs) ->
Format.eprintf "Raised %s %a@." (xs.xs_name.id_string)
(Pp.print_list Pp.semi Expr.print_rs) cs;
raise (ReductionFail renv) in
Debug.dprintf debug_refl "res %a@." Pretty.print_term res;
let rinfo = {renv with subst = Mvs.add vres res renv.subst} in
rinfo, lp, lv, rt
with NoReification -> reify_post t
end
in
try
let rinfo, lp, _lv, rt = reify_post lpost in
let lp = (rs.rs_cty.cty_pre)@lp in
let subst, prev, mds, dds = build_vars_map rinfo prev in
build_goals do_trans rinfo prev mds dds subst env lp g rt
with
ReductionFail renv ->
(* proof failed, show reification context for debugging *)
let _, prev, _, _ = build_vars_map renv prev in
let fg = create_prsymbol (id_fresh "Failure") in
let df = create_prop_decl Pgoal fg t_false in
[Task.add_decl prev df] )
let () = wrap_and_register
~desc:"reflection_l <prop>@ \
attempts@ to@ prove@ the@ goal@ by@ reflection@ \
using@ the@ lemma@ <prop>."
"reflection_l"
(Tprsymbol Tenvtrans_l) reflection_by_lemma
let () = wrap_and_register
~desc:"reflection_f <f>@ \
attempts@ to@ prove@ the@ goal@ by@ reflection@ \
using@ the@ contract@ of@ the@ program@ function@ <f>."
"reflection_f"
(Tstring Tenvtrans_l) (reflection_by_function true)
let () = wrap_and_register
~desc:"reflection_f <f>@ \
attempts@ to@ prove@ the@ goal@ by@ reflection@ \
using@ the@ contract@ of@ the@ program@ function@ <f>.@ \
Does@ not@ automatically@ perform@ transformations@ \
afterwards.@ Use@ for@ debugging."
"reflection_f_nt"
(Tstring Tenvtrans_l) (reflection_by_function false)
| (********************************************************************)
(* *)
(* The Why3 Verification Platform / The Why3 Development Team *)
(* Copyright 2010-2023 -- Inria - CNRS - Paris-Saclay University *)
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
(* General Public License version 2.1, with the special exception *)
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
|
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(library
(name tezos_proxy_server_config)
(public_name tezos-proxy-server-config)
(instrumentation (backend bisect_ppx))
(libraries
tezos-base
tezos-stdlib-unix)
(flags (:standard
-open Tezos_base.TzPervasives)))
| |
Signal.ml |
type 'a t =
| Data of 'a
| EndOfSignal
let pure (value : 'a) : 'a t = Data value
let empty () : 'a t = EndOfSignal
let default default_value = function
| Data value -> value
| EndOfSignal -> default_value
let satisfies f = function
| Data value -> f value
| EndOfSignal -> false
let map (f : 'a -> 'b) (ma : 'a t) : 'b t =
match ma with
| Data value -> Data (f value)
| EndOfSignal -> EndOfSignal
let filter (f : 'a -> bool) (ma : 'a t) : 'a t =
match ma with
| Data value when f value -> Data value
| Data _ | EndOfSignal -> EndOfSignal
let fold (f : 'a -> 'b -> 'a) (init : 'a) (ma : 'b t) : 'a =
match ma with
| Data value -> f init value
| EndOfSignal -> init
let from_option = function
| Some value -> Data value
| None -> EndOfSignal
let to_option = function
| Data value -> Some value
| EndOfSignal -> None
| |
t-divrem_newton_n_preinv.c |
#include "fq_nmod_poly.h"
#ifdef T
#undef T
#endif
#define T fq_nmod
#define CAP_T FQ_NMOD
#include "fq_poly_templates/test/t-divrem_newton_n_preinv.c"
#undef CAP_T
#undef T
| /*
Copyright (C) 2013 Mike Hansen
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
roll_storage.mli | (**
Basic roll manipulation.
If storage related to roll (a.k.a. `Storage.Roll`) are not used
outside of this module, this interface enforces the invariant that a
roll is always either in the limbo list or in a contract list.
*)
type error +=
| Consume_roll_change
| No_roll_for_delegate
| No_roll_snapshot_for_cycle of Cycle_repr.t
| Unregistered_delegate of Signature.Public_key_hash.t
(* `Permanent *)
val init : Raw_context.t -> Raw_context.t tzresult Lwt.t
val init_first_cycles : Raw_context.t -> Raw_context.t tzresult Lwt.t
val cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t
val snapshot_rolls : Raw_context.t -> Raw_context.t tzresult Lwt.t
val fold :
Raw_context.t ->
f:(Roll_repr.roll -> Signature.Public_key.t -> 'a -> 'a tzresult Lwt.t) ->
'a ->
'a tzresult Lwt.t
val baking_rights_owner :
Raw_context.t ->
Level_repr.t ->
priority:int ->
Signature.Public_key.t tzresult Lwt.t
val endorsement_rights_owner :
Raw_context.t ->
Level_repr.t ->
slot:int ->
Signature.Public_key.t tzresult Lwt.t
module Delegate : sig
val is_inactive :
Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t
val add_amount :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val remove_amount :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val set_inactive :
Raw_context.t ->
Signature.Public_key_hash.t ->
Raw_context.t tzresult Lwt.t
val set_active :
Raw_context.t ->
Signature.Public_key_hash.t ->
Raw_context.t tzresult Lwt.t
end
module Contract : sig
val add_amount :
Raw_context.t ->
Contract_repr.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val remove_amount :
Raw_context.t ->
Contract_repr.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
end
val delegate_pubkey :
Raw_context.t ->
Signature.Public_key_hash.t ->
Signature.Public_key.t tzresult Lwt.t
val get_rolls :
Raw_context.t ->
Signature.Public_key_hash.t ->
Roll_repr.t list tzresult Lwt.t
val get_change :
Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t
val update_tokens_per_roll :
Raw_context.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t
(**/**)
val get_contract_delegate :
Raw_context.t ->
Contract_repr.t ->
Signature.Public_key_hash.t option tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
manager_repr.ml | (* Tezos Protocol Implementation - Low level Repr. of Managers' keys *)
type manager_key =
| Hash of Signature.Public_key_hash.t
| Public_key of Signature.Public_key.t
type t = manager_key
open Data_encoding
let hash_case tag =
case tag
~title:"Public_key_hash"
Signature.Public_key_hash.encoding
(function
| Hash hash -> Some hash
| _ -> None)
(fun hash -> Hash hash)
let pubkey_case tag =
case tag
~title:"Public_key"
Signature.Public_key.encoding
(function
| Public_key hash -> Some hash
| _ -> None)
(fun hash -> Public_key hash)
let encoding =
union [
hash_case (Tag 0) ;
pubkey_case (Tag 1) ;
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
parseTest.ml |
module Top (TopConf:RunTest.Config) = struct
module SP =
Splitter.Make
(struct
let debug = TopConf.debug.Debug_herd.lexer
let check_rename = TopConf.check_rename
end)
let do_from_file start_time env name chan =
if TopConf.debug.Debug_herd.files then MyLib.pp_debug name ;
(* First split the input file in sections *)
let (splitted:Splitter.result) = SP.split name chan in
let tname = splitted.Splitter.name.Name.name in
let module Conf = struct (* override the precision and variant fields *)
(* Modify variant with the 'Variant' field of test *)
module TestConf =
TestVariant.Make
(struct
module Opt = Variant
let set_precision = Variant.set_precision
let info = splitted.Splitter.info
let precision = TopConf.precision
let variant = TopConf.variant
end)
(* Override *)
include TopConf
let precision = TestConf.precision
let variant = TestConf.variant
end in
if Conf.check_name tname then begin
(* Get arch *)
let arch = splitted.Splitter.arch in
(* Now, we have the architecture, call specific parsers
generically. *)
let model =
GetModel.parse
Conf.archcheck arch Conf.libfind Conf.variant Conf.model in
let cache_type = CacheType.get splitted.Splitter.info in
let dirty = DirtyBit.get splitted.Splitter.info in
let module ModelConfig = struct
let bell_model_info = Conf.bell_model_info
let model = model
let showsome =
begin match Conf.outputdir with
| PrettyConf.StdoutOutput | PrettyConf.Outputdir _ -> true
| _ -> false
end || Misc.is_some Conf.PC.view || Conf.variant Variant.MemTag
|| Conf.variant Variant.Morello
let through = Conf.through
let debug = Conf.debug.Debug_herd.barrier
let debug_files = Conf.debug.Debug_herd.files
let verbose = Conf.verbose
let skipchecks = Conf.skipchecks
let strictskip = Conf.strictskip
let cycles = Conf.cycles
let optace = Conf.optace
let libfind = Conf.libfind
let variant = Conf.variant
let dirty = dirty
let cache_type = cache_type
let statelessrc11 = Conf.statelessrc11
end in
let module ArchConfig = SemExtra.ConfigToArchConfig(Conf) in
match arch with
| `PPC ->
let module X = PPCParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `ARM ->
let module X = ARMParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `AArch64 ->
let module X = AArch64ParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `X86 ->
let module X = X86ParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `X86_64 ->
let module X = X86_64ParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `MIPS ->
let module X = MIPSParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `RISCV ->
let module X = MIPSParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `C ->
let module X = CParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `JAVA ->
let module X = CParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
| `LISA ->
let module X = LISAParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
(* START NOTWWW *)
| `ASL ->
let module X = ASLParseTest.Make(Conf)(ModelConfig) in
X.run cache_type dirty start_time name chan env splitted
(* END NOTWWW *)
| arch -> Warn.fatal "no support for arch '%s'" (Archs.pp arch)
end else env
(* Enter here... *)
let from_file name env =
(* START NOTWWW *)
(* Interval timer will be stopped just before output, see top_herd *)
Itimer.start name TopConf.timeout ;
(* END NOTWWW *)
let start_time = Sys.time () in
Misc.input_protect (do_from_file start_time env name) name
end
| (****************************************************************************)
(* the diy toolsuite *)
(* *)
(* Jade Alglave, University College London, UK. *)
(* Luc Maranget, INRIA Paris-Rocquencourt, France. *)
(* *)
(* Copyright 2012-present Institut National de Recherche en Informatique et *)
(* en Automatique and the authors. All rights reserved. *)
(* *)
(* This software is governed by the CeCILL-B license under French law and *)
(* abiding by the rules of distribution of free software. You can use, *)
(* modify and/ or redistribute the software under the terms of the CeCILL-B *)
(* license as circulated by CEA, CNRS and INRIA at the following URL *)
(* "http://www.cecill.info". We also give a copy in LICENSE.txt. *)
(****************************************************************************)
(* Authors: *)
(* Jade Alglave, University College London, UK. *)
(* Luc Maranget, INRIA Paris-Rocquencourt, France. *)
(* Hadrien Renaud, University College London, UK. *)
(****************************************************************************)
|
wasm.h |
// This header file is used only for test purposes! It is used by unit
// test inside the `src/` directory for the moment.
#ifndef TEST_WASM
#define TEST_WASM
#include "../wasm.h"
#include "../wasmer.h"
#include <stdio.h>
#include <string.h>
wasm_engine_t *wasm_engine_new() {
wasm_config_t *config = wasm_config_new();
char *wasmer_test_compiler = getenv("WASMER_CAPI_CONFIG");
char *wasmer_test_engine;
strtok_r(wasmer_test_compiler, "-", &wasmer_test_engine);
printf("Using compiler: %s, engine: %s\n", wasmer_test_compiler,
wasmer_test_engine);
if (strcmp(wasmer_test_compiler, "cranelift") == 0) {
assert(wasmer_is_compiler_available(CRANELIFT));
wasm_config_set_compiler(config, CRANELIFT);
} else if (strcmp(wasmer_test_compiler, "llvm") == 0) {
assert(wasmer_is_compiler_available(LLVM));
wasm_config_set_compiler(config, LLVM);
} else if (strcmp(wasmer_test_compiler, "singlepass") == 0) {
assert(wasmer_is_compiler_available(SINGLEPASS));
wasm_config_set_compiler(config, SINGLEPASS);
} else if (wasmer_test_compiler) {
printf("Compiler %s not recognized\n", wasmer_test_compiler);
abort();
}
if (strcmp(wasmer_test_engine, "universal") == 0) {
assert(wasmer_is_engine_available(UNIVERSAL));
wasm_config_set_engine(config, UNIVERSAL);
} else if (wasmer_test_engine) {
printf("Engine %s not recognized\n", wasmer_test_engine);
abort();
}
wasm_engine_t *engine = wasm_engine_new_with_config(config);
return engine;
}
#endif
| |
test_pattern_bind.mli | ||
Print.mli | (*
Print function definitions how we like them.
*)
(* Print OCaml code to stdout. *)
val generate_boilerplate : Conf.t -> Ast_ml.type_declaration list list -> unit
| (*
Print function definitions how we like them.
*) |
bsd-ifaddrs.c |
#include "uv.h"
#include "internal.h"
#include <errno.h>
#include <stddef.h>
#include <ifaddrs.h>
#include <net/if.h>
#if !defined(__CYGWIN__) && !defined(__MSYS__) && !defined(__GNU__)
#include <net/if_dl.h>
#endif
#if defined(__HAIKU__)
#define IFF_RUNNING IFF_LINK
#endif
static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) {
if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
return 1;
if (ent->ifa_addr == NULL)
return 1;
#if !defined(__CYGWIN__) && !defined(__MSYS__) && !defined(__GNU__)
/*
* If `exclude_type` is `UV__EXCLUDE_IFPHYS`, return whether `sa_family`
* equals `AF_LINK`. Otherwise, the result depends on the operating
* system with `AF_LINK` or `PF_INET`.
*/
if (exclude_type == UV__EXCLUDE_IFPHYS)
return (ent->ifa_addr->sa_family != AF_LINK);
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || \
defined(__HAIKU__)
/*
* On BSD getifaddrs returns information related to the raw underlying
* devices. We're not interested in this information.
*/
if (ent->ifa_addr->sa_family == AF_LINK)
return 1;
#elif defined(__NetBSD__) || defined(__OpenBSD__)
if (ent->ifa_addr->sa_family != PF_INET &&
ent->ifa_addr->sa_family != PF_INET6)
return 1;
#endif
return 0;
}
int uv_interface_addresses(uv_interface_address_t** addresses, int* count) {
struct ifaddrs* addrs;
struct ifaddrs* ent;
uv_interface_address_t* address;
#if !(defined(__CYGWIN__) || defined(__MSYS__)) && !defined(__GNU__)
int i;
#endif
*count = 0;
*addresses = NULL;
if (getifaddrs(&addrs) != 0)
return UV__ERR(errno);
/* Count the number of interfaces */
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFADDR))
continue;
(*count)++;
}
if (*count == 0) {
freeifaddrs(addrs);
return 0;
}
/* Make sure the memory is initiallized to zero using calloc() */
*addresses = uv__calloc(*count, sizeof(**addresses));
if (*addresses == NULL) {
freeifaddrs(addrs);
return UV_ENOMEM;
}
address = *addresses;
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFADDR))
continue;
address->name = uv__strdup(ent->ifa_name);
if (ent->ifa_addr->sa_family == AF_INET6) {
address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
} else {
address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
}
if (ent->ifa_netmask == NULL) {
memset(&address->netmask, 0, sizeof(address->netmask));
} else if (ent->ifa_netmask->sa_family == AF_INET6) {
address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
} else {
address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
}
address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
address++;
}
#if !(defined(__CYGWIN__) || defined(__MSYS__)) && !defined(__GNU__)
/* Fill in physical addresses for each interface */
for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFPHYS))
continue;
address = *addresses;
for (i = 0; i < *count; i++) {
if (strcmp(address->name, ent->ifa_name) == 0) {
struct sockaddr_dl* sa_addr;
sa_addr = (struct sockaddr_dl*)(ent->ifa_addr);
memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
}
address++;
}
}
#endif
freeifaddrs(addrs);
return 0;
}
void uv_free_interface_addresses(uv_interface_address_t* addresses,
int count) {
int i;
for (i = 0; i < count; i++) {
uv__free(addresses[i].name);
}
uv__free(addresses);
}
| /* Copyright libuv project contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/ |
Parse.mli | (*
Parse an ml file and extract the type definitions
*)
val extract_typedefs_from_ml_file :
Common.filename -> Ast_ml.type_declaration list list
(* helpers used also in Test_otarzan.ml *)
val parse : Common.filename -> Ast_ml.program
| (*
Parse an ml file and extract the type definitions
*) |
dune |
(library
(name impl)
(implements vlib)) | |
fun_trees.c |
/*
* TREES USED TO BUILD MODELS IN THE FUNCTION/ARRAY SOLVER.
*/
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include "model/fun_trees.h"
/*
* Initialization
*/
void init_fun_tree(fun_tree_t *tree, pstore_t *pstore) {
tree->root = NULL;
tree->ftype = NULL;
tree->pstore = pstore;
init_objstore(&tree->store, sizeof(fun_node_t), FUN_TREE_BANK_SIZE);
init_ivector(&tree->buffer, FUN_TREE_BUFFER_SIZE);
}
/*
* Deletion
*/
void delete_fun_tree(fun_tree_t *tree) {
tree->root = NULL;
delete_objstore(&tree->store);
delete_ivector(&tree->buffer);
}
/*
* Empty the tree
*/
void reset_fun_tree(fun_tree_t *tree) {
tree->root = NULL;
tree->ftype = NULL;
reset_objstore(&tree->store);
ivector_reset(&tree->buffer);
}
/*
* Allocate a new node
* - nothing is initialized
*/
static inline fun_node_t *fun_tree_alloc_node(fun_tree_t *tree) {
return (fun_node_t *) objstore_alloc(&tree->store);
}
/*
* Create a new leaf node
* - map = its map
* - v = its value
* - the next field is initialized to NULL
*/
static fun_node_t *fun_tree_make_leaf(fun_tree_t *tree, map_t *map, particle_t v) {
fun_node_t *leaf;
leaf = fun_tree_alloc_node(tree);
leaf->index = null_particle;
leaf->value = v;
leaf->size = 1;
leaf->next = NULL;
leaf->u.map = map;
return leaf;
}
#ifndef NDEBUG
/*
* FOR DEBUGGING: CHECK THE SIZES
*/
/*
* Add the size of all children of node p
*/
static uint32_t children_sizes(fun_node_t *p) {
fun_node_t *c;
uint32_t s;
assert(p->index != null_particle);
s = 0;
c = p->u.child;
while (c != NULL) {
s += c->size;
c = c->next;
}
return s;
}
/*
* Check that the size of node n is locally consistent
*/
static bool size_locally_good(fun_node_t *n) {
if (n->index == null_particle) {
return n->size == 1;
} else {
return n->size == children_sizes(n);
}
}
/*
* Check that the sizes are all nodes reachable from n are correct
*/
static bool good_sizes(fun_node_t *n) {
fun_node_t *c;
if (n->index != null_particle) {
// recursively check all children first
c = n->u.child;
while (c != NULL) {
if (! good_sizes(c)) {
return false;
}
c = c->next;
}
}
// check n
return size_locally_good(n);
}
/*
* Check the whole tree
*/
static bool good_sizes_in_tree(fun_tree_t *tree) {
return tree->root == NULL || good_sizes(tree->root);
}
#endif
/*
* Search a list of nodes:
* - list must be sorted in increasing order of values
* - return the last node in the list whose value is <= v
* - return NULL if all nodes in the list have a value > v
*/
static fun_node_t *search_list(fun_node_t *list, particle_t v) {
fun_node_t *pre;
pre = NULL;
while (list != NULL && list->value <= v) {
pre = list;
list = list->next;
}
return pre;
}
/*
* SIMPLE ADDITION
*/
/*
* Check whether m2 and the current map m1 of node n are distinct,
* if so add two children leaves to n, one for m1, the other for m2.
* - v must contain the indices used on the path from the root to n
* - return true if the split works (i.e., m1 and m2 are distinct)
* - return false otherwise
*/
static bool split_leaf(fun_tree_t *tree, fun_node_t *n, map_t *m2, ivector_t *v) {
map_t *m1;
function_type_t *f;
fun_node_t *left, *right;
particle_t idx, a, b;
assert(n->index == null_particle); // n must be a leaf
m1 = n->u.map;
idx = disagreement_point(m1, m2);
if (idx != null_particle) {
/*
* m1 and m2 disagree at idx
*/
a = eval_map(m1, idx);
b = eval_map(m2, idx);
} else {
/*
* Check whether the default values are distinct
*/
a = map_default_value(m1);
b = map_default_value(m2);
if (a != b) {
// get an idx not used on the path to n or in the domain of m1 or m2
collect_map_indices(m1, v);
collect_map_indices(m2, v);
f = tree->ftype;
if (f->ndom == 1) {
idx = get_distinct_particle(tree->pstore, f->domain[0], v->size, v->data);
} else {
idx = get_distinct_tuple(tree->pstore, f->ndom, f->domain, v->size, v->data);
}
if (idx == null_particle) {
/*
* this means that the domain is finite and all elements
* in the domain occur on the path from the root to n
* so the default values are irrelevant and the two maps are equal.
*/
return false;
}
} else {
// same default values: the maps are equal
return false;
}
}
/*
* Split node n here
*/
assert(a != b && idx != null_particle && a == eval_map(m1, idx) && b == eval_map(m2, idx));
if (a < b) {
left = fun_tree_make_leaf(tree, m1, a);
right = fun_tree_make_leaf(tree, m2, b);
} else {
left = fun_tree_make_leaf(tree, m2, b);
right = fun_tree_make_leaf(tree, m1, a);
}
// convert n to a non-leaf node of index idx
// add left and right as its children
n->index = idx;
n->u.child = left;
left->next = right;
return true;
}
/*
* Restore correct sizes if map m cannot be added.
* Follow the path defined by m. For all nodes on that path,
* reduce the size by one.
*/
static void restore_sizes(fun_tree_t *tree, map_t *m) {
fun_node_t *n;
particle_t idx, x;
n = tree->root;
for (;;) {
assert(n != NULL && n->size > 0);
n->size --;
idx = n->index;
if (idx == null_particle) {
break;
}
x = eval_map(m, idx);
n = search_list(n->u.child, x);
}
}
/*
* Attempt to add map m to tree. The addition succeeds if
* m is distinct from all the other maps already in tree.
* - tree->ftype must be set and m must be of that type.
* - return true if the addition works, false otherwise
*/
bool fun_tree_add_map(fun_tree_t *tree, map_t *m) {
fun_node_t *n, *new, *c;
ivector_t *v;
particle_t idx, x;
assert(tree->ftype != NULL && map_default_value(m) != null_particle);
n = tree->root;
if (n == NULL) {
tree->root = fun_tree_make_leaf(tree, m, null_particle);
assert(good_sizes_in_tree(tree));
return true;
}
// v: stores the indices on the path
v = &tree->buffer;
assert(v->size == 0);
/*
* Size update: if m is added successfully as a leaf N, the size counter
* of all nodes from root to N (excluding N) must be incremented.
* We do increment the counter on all nodes visited and fix it if the
* addition fails.
*/
n->size ++;
/*
* Loop invariant:
* - n = current node, idx = its index
* - m agrees with the path to n
* - v = set of all indices on the path from the root to n
*/
idx = n->index;
while (idx != null_particle) {
ivector_push(v, idx);
x = eval_map(m, idx); // x == m[idx]
assert(x != null_particle);
c = search_list(n->u.child, x);
if (c == NULL) {
// add m in a new leaf, first child of n
new = fun_tree_make_leaf(tree, m, x);
new->next = n->u.child;
n->u.child = new;
goto done;
} else if (c->value < x) {
// add m in a new leaf, after child c
new = fun_tree_make_leaf(tree, m, x);
new->next = c->next;
c->next = new;
goto done;
} else {
assert(c->value == x);
// continue with node c
n = c;
n->size ++;
idx = n->index;
}
}
/*
* - n is a leaf node
* - m agrees with the path from the root to n
*/
if (! split_leaf(tree, n, m, v)) {
// failed addition: n->u,map is equal to m
restore_sizes(tree, m);
assert(good_sizes_in_tree(tree));
ivector_reset(v);
return false;
}
done:
assert(good_sizes_in_tree(tree));
ivector_reset(v);
return true;
}
| /*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/ |
version.h |
#ifndef __XEN_PUBLIC_VERSION_H__
#define __XEN_PUBLIC_VERSION_H__
#include "xen.h"
/* NB. All ops return zero on success, except XENVER_{version,pagesize}
* XENVER_{version,pagesize,build_id} */
/* arg == NULL; returns major:minor (16:16). */
#define XENVER_version 0
/* arg == xen_extraversion_t. */
#define XENVER_extraversion 1
typedef char xen_extraversion_t[16];
#define XEN_EXTRAVERSION_LEN (sizeof(xen_extraversion_t))
/* arg == xen_compile_info_t. */
#define XENVER_compile_info 2
struct xen_compile_info {
char compiler[64];
char compile_by[16];
char compile_domain[32];
char compile_date[32];
};
typedef struct xen_compile_info xen_compile_info_t;
#define XENVER_capabilities 3
typedef char xen_capabilities_info_t[1024];
#define XEN_CAPABILITIES_INFO_LEN (sizeof(xen_capabilities_info_t))
#define XENVER_changeset 4
typedef char xen_changeset_info_t[64];
#define XEN_CHANGESET_INFO_LEN (sizeof(xen_changeset_info_t))
#define XENVER_platform_parameters 5
struct xen_platform_parameters {
xen_ulong_t virt_start;
};
typedef struct xen_platform_parameters xen_platform_parameters_t;
#define XENVER_get_features 6
struct xen_feature_info {
unsigned int submap_idx; /* IN: which 32-bit submap to return */
uint32_t submap; /* OUT: 32-bit submap */
};
typedef struct xen_feature_info xen_feature_info_t;
/* Declares the features reported by XENVER_get_features. */
#include "features.h"
/* arg == NULL; returns host memory page size. */
#define XENVER_pagesize 7
/* arg == xen_domain_handle_t.
*
* The toolstack fills it out for guest consumption. It is intended to hold
* the UUID of the guest.
*/
#define XENVER_guest_handle 8
#define XENVER_commandline 9
typedef char xen_commandline_t[1024];
/*
* Return value is the number of bytes written, or XEN_Exx on error.
* Calling with empty parameter returns the size of build_id.
*/
#define XENVER_build_id 10
struct xen_build_id {
uint32_t len; /* IN: size of buf[]. */
unsigned char buf[XEN_FLEX_ARRAY_DIM];
/* OUT: Variable length buffer with build_id. */
};
typedef struct xen_build_id xen_build_id_t;
#endif /* __XEN_PUBLIC_VERSION_H__ */
/*
* Local variables:
* mode: C
* c-file-style: "BSD"
* c-basic-offset: 4
* tab-width: 4
* indent-tabs-mode: nil
* End:
*/
| /******************************************************************************
* version.h
*
* Xen version, type, and compile information.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Copyright (c) 2005, Nguyen Anh Quynh <[email protected]>
* Copyright (c) 2005, Keir Fraser <[email protected]>
*/ |
parse_c.ml | module PI = Parse_info
let logger = Logging.get_logger [ __MODULE__ ]
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*
* Just a small wrapper around the C++ parser
*)
(*****************************************************************************)
(* Main entry point *)
(*****************************************************************************)
let parse file =
let { Parsing_result.ast; tokens; stat } =
Parse_cpp.parse_with_lang ~lang:Flag_parsing_cpp.C file
in
(* less: merge stat? *)
let ast, stat =
try (Ast_c_build.program ast, stat) with
| exn ->
let e = Exception.catch exn in
logger#error "PB: Ast_c_build, on %s (exn = %s)" file
(Common.exn_to_s exn);
(*None, { stat with Stat.bad = stat.Stat.bad + stat.Stat.correct } *)
Exception.reraise e
in
{ Parsing_result.ast; tokens; stat }
let parse_program file =
let res = parse file in
res.Parsing_result.ast
let any_of_string str =
let any = Parse_cpp.any_of_string Flag_parsing_cpp.C str in
Ast_c_build.any any
| (* Yoann Padioleau
*
* Copyright (C) 2012 Yoann Padioleau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*
*) |
meta_lexer.mli |
type token =
| Name of string
| String of string
| Minus
| Lparen
| Rparen
| Comma
| Equal
| Plus_equal
| Eof
type user_error = { user_error : 'a. Lexing.lexbuf -> string -> 'a }
val token : user_error -> Lexing.lexbuf -> token
| |
resize.c |
#include "nmod_mpoly.h"
void nmod_mpoly_resize(
nmod_mpoly_t A,
slong new_length,
const nmod_mpoly_ctx_t ctx)
{
slong old_length = A->length;
slong N;
new_length = FLINT_MAX(WORD(0), new_length);
N = mpoly_words_per_exp(A->bits, ctx->minfo);
if (new_length > old_length)
{
nmod_mpoly_fit_length(A, new_length, ctx);
/* must zero out the new coeffs/exps past the old end */
N = mpoly_words_per_exp(A->bits, ctx->minfo);
flint_mpn_zero(A->exps + N*old_length, N*(new_length - old_length));
_nmod_vec_zero(A->coeffs + old_length, new_length - old_length);
}
A->length = new_length;
}
| /*
Copyright (C) 2018 Daniel Schultz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
occ_map.mli |
(*
Copyright ENS, CNRS, INRIA
contributors: Bruno Blanchet, [email protected]
David Cadé
This software is a computer program whose purpose is to verify
cryptographic protocols in the computational model.
This software is governed by the CeCILL-B license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL-B
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL-B license and that you accept its terms.
*)
(* Maps from occurrences to 'a *)
type 'a occ_map
val empty : 'a occ_map
(* [map_add map min_occ max_occ image] returns a map that
maps all occurrences from [min_occ] to [max_occ] to [image],
and all other occurrences like [map] *)
val add : 'a occ_map -> int -> int -> 'a -> 'a occ_map
(* [map_find occ map] returns the image of [occ] by [map] *)
val find : int -> 'a occ_map -> 'a
| (*************************************************************
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet and David Cadé *
* *
* Copyright (C) ENS, CNRS, INRIA, 2005-2022 *
* *
*************************************************************) |
t-factor_smooth.c |
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <gmp.h>
#include "flint.h"
#include "fmpz.h"
#include "ulong_extras.h"
void checkb(fmpz_t n, slong bits)
{
fmpz_factor_t factor;
fmpz_t m;
slong i;
fmpz_factor_init(factor);
fmpz_init(m);
fmpz_factor_smooth(factor, n, bits, 0);
fmpz_factor_expand(m, factor);
if (!fmpz_equal(n, m))
{
flint_printf("ERROR: factors do not unfactor to original number!\n");
flint_printf("input: ");
fmpz_print(n);
flint_printf("\n");
flint_printf("computed factors: ");
fmpz_factor_print(factor);
flint_printf("\n");
flint_printf("value: ");
fmpz_print(m);
flint_printf("\n");
fflush(stdout);
flint_abort();
}
for (i = 0; i < factor->num; i++)
{
if (!fmpz_is_probabprime(factor->p + i))
{
flint_printf("ERROR: factor is not prime!\n");
flint_printf("input: ");
fmpz_print(n);
flint_printf("\n");
flint_printf("computed factors: ");
fmpz_factor_print(factor);
flint_printf("\n");
fflush(stdout);
flint_abort();
}
}
fmpz_clear(m);
fmpz_factor_clear(factor);
}
void randprime(fmpz_t p, flint_rand_t state, slong bits)
{
fmpz_randbits(p, state, bits);
if (fmpz_sgn(p) < 0)
fmpz_neg(p, p);
if (fmpz_is_even(p))
fmpz_add_ui(p, p, 1);
while (!fmpz_is_probabprime(p))
fmpz_add_ui(p, p, 2);
}
int main(void)
{
int i, j;
fmpz_t x, y, z, n;
fmpz_factor_t factors;
mpz_t y1;
FLINT_TEST_INIT(state);
flint_printf("factor_smooth....");
fflush(stdout);
fmpz_init(x);
mpz_init(y1);
/* Some corner cases */
fmpz_set_ui(x, UWORD_MAX);
checkb(x, 32);
fmpz_set_si(x, WORD_MAX);
checkb(x, 32);
fmpz_set_si(x, WORD_MIN);
checkb(x, 32);
fmpz_set_si(x, COEFF_MAX);
checkb(x, 32);
fmpz_set_si(x, COEFF_MIN);
checkb(x, 32);
/* Small integers */
for (i = -10000; i < 10000; i++)
{
fmpz_set_si(x, i);
checkb(x, 16);
}
/* Powers */
for (i = 1; i < 250; i++)
{
for (j = 0; j < 250; j++)
{
fmpz_set_ui(x, i);
fmpz_pow_ui(x, x, j);
checkb(x, 10);
}
}
/* Factorials */
for (i = 0; i < 1000; i++)
{
flint_mpz_fac_ui(y1, i);
fmpz_set_mpz(x, y1);
checkb(x, 12);
}
/* Powers of factorials */
for (i = 0; i < 100; i++)
{
for (j = 1; j < 5; j++)
{
flint_mpz_fac_ui(y1, i);
fmpz_set_mpz(x, y1);
fmpz_pow_ui(x, x, j);
checkb(x, 12);
}
}
/* Whole limbs */
for (i = 0; i < 1000; i++)
{
fmpz_set_ui(x, n_randtest(state));
if (n_randint(state, 2))
fmpz_neg(x, x);
checkb(x, 32);
}
/* Large negative integers */
fmpz_set_ui(x, 10);
fmpz_pow_ui(x, x, 100);
fmpz_neg(x, x);
checkb(x, 8);
flint_mpz_fac_ui(y1, 50);
mpz_neg(y1, y1);
fmpz_set_mpz(x, y1);
checkb(x, 8);
mpz_clear(y1);
fmpz_init(y);
fmpz_init(z);
fmpz_init(n);
for (i = 0; i < 20; i++) /* Test random n, three factors */
{
randprime(x, state, 40);
randprime(y, state, 40);
randprime(z, state, 40);
fmpz_mul(n, x, y);
fmpz_mul(n, n, z);
fmpz_factor_init(factors);
fmpz_factor_smooth(factors, n, 60, 1);
if (factors->num < 3)
{
flint_printf("FAIL:\n");
flint_printf("%ld factors found\n", factors->num);
fflush(stdout);
flint_abort();
}
fmpz_factor_clear(factors);
}
for (i = 0; i < 20; i++) /* Test random n, small factors */
{
randprime(x, state, 10);
randprime(y, state, 10);
randprime(z, state, 40);
fmpz_mul(n, x, y);
fmpz_mul(n, n, z);
fmpz_factor_init(factors);
fmpz_factor_smooth(factors, n, 20, 1);
if (factors->num < 3 && !fmpz_equal(x, y))
{
flint_printf("FAIL:\n");
flint_printf("%ld factors found\n", factors->num);
fflush(stdout);
flint_abort();
}
fmpz_factor_clear(factors);
}
for (i = 0; i < 5; i++) /* Test random squares */
{
randprime(x, state, 40);
fmpz_mul(n, x, x);
fmpz_factor_init(factors);
fmpz_factor_smooth(factors, n, 60, 1);
if (factors->num < 1)
{
flint_printf("FAIL:\n");
flint_printf("%ld factors found\n", factors->num);
fflush(stdout);
flint_abort();
}
fmpz_factor_clear(factors);
}
for (i = 0; i < 5; i++) /* Test random cubes */
{
randprime(x, state, 40);
fmpz_mul(n, x, x);
fmpz_mul(n, n, x);
fmpz_factor_init(factors);
fmpz_factor_smooth(factors, n, 60, 1);
if (factors->num < 1)
{
flint_printf("FAIL:\n");
flint_printf("%ld factors found\n", factors->num);
fflush(stdout);
flint_abort();
}
fmpz_factor_clear(factors);
}
fmpz_clear(n);
fmpz_clear(x);
fmpz_clear(y);
fmpz_clear(z);
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| /*
Copyright (C) 2010 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
pa_main.ml |
open Earley_core
open Pa_ocaml_prelude
open Pa_ocaml
open Input
open Earley
open Format
open Pa_lexing
let define_directive =
Str.regexp "[ \t]*define[ \t]*\\([^ \t]*\\)[ \t]*\\([^ \n\t\r]*\\)[ \t]*"
let if_directive =
Str.regexp "[ \t]*if"
let ifdef_directive =
Str.regexp "[ \t]*if[ \t]*def[ \t]*\\([^ \t]*\\)[ \t]*"
let ifundef_directive =
Str.regexp "[ \t]*if[ \t]*ndef[ \t]*\\([^ \t]*\\)[ \t]*"
let ifversion_directive =
Str.regexp "[ \t]*if[ \t]*version[ \t]*\\([<>=]*\\)[ \t]*\\([0-9]+\\)[.]\\([0-9]+\\)[ \t]*"
let else_directive =
Str.regexp "[ \t]*else[ \t]*"
let elif_directive =
Str.regexp "[ \t]*elif[ \t]*"
let endif_directive =
Str.regexp "[ \t]*endif[ \t]*"
let line_num_directive =
Str.regexp "[ \t]*\\([0-9]+\\)[ \t]*\\([\"]\\([^\"]*\\)[\"]\\)?[ \t]*$"
let test_directive fname num line =
if Str.string_match ifdef_directive line 1 then
let macro_name = Str.matched_group 1 line in
try ignore (Sys.getenv macro_name); true with Not_found -> false
else if Str.string_match ifundef_directive line 1 then
let macro_name = Str.matched_group 1 line in
try ignore (Sys.getenv macro_name); false with Not_found -> true
else if Str.string_match ifversion_directive line 1 then
let predicat = Str.matched_group 1 line in
let major' = Str.matched_group 2 line in
let minor' = Str.matched_group 3 line in
try
let predicat =
match predicat with
| "<>" -> (<>) | "=" -> (=) | "<" -> (<)
| ">" -> (>) | "<=" -> (<=) | ">=" -> (>=)
| _ -> raise Exit
in
let version =
try
Sys.getenv "OCAMLVERSION"
with
Not_found -> Sys.ocaml_version
in
let major, minor =
match Str.split (Str.regexp_string ".") version with
| major :: minor :: _ ->
let major = int_of_string major in
let minor = int_of_string minor in
major, minor
| _ -> assert false
in
predicat (major, minor) (int_of_string major', int_of_string minor')
with _ ->
Printf.eprintf "file: %s, line %d: bad predicate version\n%!" fname num;
exit 1
else (
Printf.eprintf "file: %s, line %d: unknown #if directive\n%!" fname num;
exit 1)
module OCamlPP : Preprocessor =
struct
type state = bool list
let initial_state = []
let active : state -> bool = fun st -> not (List.mem false st)
let update st name lnum line =
if line <> "" && line.[0] = '#' then
if Str.string_match define_directive line 1 && active st then
let macro_name = Str.matched_group 1 line in
let value = Str.matched_group 2 line in
Unix.putenv macro_name value;
(st, name, lnum, false)
else if Str.string_match if_directive line 1 then
(test_directive name lnum line :: st, name, lnum, false)
else if Str.string_match elif_directive line 1 then
match st with
| [] -> pp_error name "unexpected elif directive"
| _ :: st -> (test_directive name lnum line :: st, name, lnum, false)
else if Str.string_match else_directive line 1 then
match st with
| [] -> pp_error name "unexpected else directive"
| b :: st -> (not b :: st, name, lnum, false)
else if Str.string_match endif_directive line 1 then
match st with
| [] -> pp_error name "unexpected endif directive"
| _ :: st -> (st, name, lnum, false)
else if Str.string_match line_num_directive line 1 then
let lnum = int_of_string (Str.matched_group 1 line) in
let name = try Str.matched_group 3 line with Not_found -> name in
(st, name, lnum, false)
else
(st, name, lnum, active st)
else (st, name, lnum, active st)
let check_final st name =
match st with
| [] -> ()
| _ -> pp_error name "unclosed conditionals"
end
module PP = Earley.WithPP(OCamlPP)
module Start(Main : Extension) = struct
let _ =
let anon_fun s = file := Some s in
let usage = Printf.sprintf "usage: %s [options] file" Sys.argv.(0) in
Arg.parse Main.spec anon_fun usage
let _ = Main.before_parse_hook ()
let entry =
match !entry, !file with
| FromExt, Some s ->
let rec fn = function
| (ext, res)::l -> if Filename.check_suffix s ext then res else fn l
| [] -> eprintf "Don't know what to do with file %s\n%!" s; exit 1
in
fn Main.entry_points
| FromExt, None -> Implementation (Main.structure, ocaml_blank)
| Intf, _ -> Interface (Main.signature, ocaml_blank)
| Impl, _ -> Implementation (Main.structure, ocaml_blank)
let ast =
(* read the whole file with a buffer ...
to be able to read stdin *)
let filename, ch = match !file with
None -> "stdin", stdin
| Some name ->
name, open_in name
in
let run () =
match entry with
| Implementation (g, blank) -> `Struct (PP.parse_channel ~filename g blank ch)
| Interface (g, blank) -> `Sig (PP.parse_channel ~filename g blank ch)
in
Earley.handle_exception run ()
let _ =
match ast with
| `Struct ast -> Format.printf "%a\n%!" Pprintast.structure ast
| `Sig ast -> Format.printf "%a\n%!" Pprintast.signature ast
end
| (*
======================================================================
Copyright Christophe Raffalli & Rodolphe Lepigre
LAMA, UMR 5127 - Université Savoie Mont Blanc
[email protected]
[email protected]
This software contains implements a parser combinator library together
with a syntax extension mechanism for the OCaml language. It can be
used to write parsers using a BNF-like format through a syntax extens-
ion called pa_parser.
This software is governed by the CeCILL-B license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/or redistribute it under the terms of the CeCILL-B license
as circulated by CEA, CNRS and INRIA at the following URL:
http://www.cecill.info
The exercising of this freedom is conditional upon a strong obligation
of giving credits for everybody that distributes a software incorpora-
ting a software ruled by the current license so as all contributions
to be properly identified and acknowledged.
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided
only with a limited warranty and the software's author, the holder of
the economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards
their requirements in conditions enabling the security of their sys-
tems and/or data to be ensured and, more generally, to use and operate
it in the same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL-B license and that you accept its terms.
======================================================================
*) |
scriptable.ml |
open Error_monad
type output_format = Rows of {separator : string; escape : [`No | `OCaml]}
let rows separator escape = Rows {separator; escape}
let tsv = rows "\t" `No
let csv = rows "," `OCaml
let clic_arg () =
let open Clic in
arg
~doc:"Make the output script-friendly. Possible values are 'TSV' and 'CSV'."
~long:"for-script"
~placeholder:"FORMAT"
(parameter (fun _ spec ->
match String.lowercase_ascii spec with
| "tsv" -> return tsv
| "csv" -> return csv
| other ->
failwith
"Cannot recognize format %S, please try 'TSV' or 'CSV'"
other))
let fprintf_lwt chan fmt =
Format.kasprintf
(fun s -> protect (fun () -> Lwt_io.write chan s >>= fun () -> return_unit))
fmt
let output ?(channel = Lwt_io.stdout) how_option ~for_human ~for_script =
match how_option with
| None -> for_human ()
| Some (Rows {separator; escape}) ->
let open Format in
List.iter_es
(fun row ->
fprintf_lwt
channel
"%a@."
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt separator)
(fun fmt cell ->
match escape with
| `OCaml -> fprintf fmt "%S" cell
| `No -> pp_print_string fmt cell))
row)
(for_script ())
>>=? fun () ->
protect (fun () -> Lwt_io.flush channel >>= fun () -> return_unit)
let output_for_human how_option for_human =
output how_option ~for_human ~for_script:(fun () -> [])
let output_row ?channel how_option ~for_human ~for_script =
output ?channel how_option ~for_human ~for_script:(fun () -> [for_script ()])
| |
gDraw.mli | (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
(* and/or modify it under the terms of the GNU Library General *)
(* Public License as published by the Free Software Foundation *)
(* version 2, with the exception described in file COPYING which *)
(* comes with the library. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Library General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU Library General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 59 Temple Place, Suite 330, *)
(* Boston, MA 02111-1307 USA *)
(* *)
(* *)
(**************************************************************************)
(* $Id$ *)
open Gdk
(** Offscreen drawables *)
(** {3 Colors} *)
(** @gtkdoc gdk gdk-Colormaps-and-Colors *)
type color =
[ `COLOR of Gdk.color
| `WHITE
| `BLACK
| `NAME of string
| `RGB of int * int * int]
val color : color -> Gdk.color
(*
type optcolor =
[ `COLOR of Gdk.color
| `WHITE
| `BLACK
| `NAME of string
| `RGB of int * int * int
| `DEFAULT ]
val optcolor : ?colormap:colormap -> optcolor -> Gdk.color option
(** {3 GdkDrawable} *)
(** Functions for drawing points, lines, arcs, and text
@gtkdoc gdk gdk-Drawing-Primitives *)
class drawable : ?colormap:colormap -> ([>`drawable] Gobject.obj as 'a) ->
object
val mutable gc : gc
val w : 'a
method arc :
x:int ->
y:int ->
width:int ->
height:int ->
?filled:bool -> ?start:float -> ?angle:float -> unit -> unit
method color : color -> Gdk.color
method colormap : colormap
method depth : int
method gc : gc
method set_gc : gc -> unit
method gc_values : GC.values
method get_image : x:int -> y:int -> width:int -> height:int -> image
method get_pixbuf :
?dest_x:int -> ?dest_y:int -> ?width:int -> ?height:int ->
?src_x:int -> ?src_y:int -> GdkPixbuf.pixbuf -> unit
method line : x:int -> y:int -> x:int -> y:int -> unit
method point : x:int -> y:int -> unit
method polygon : ?filled:bool -> (int * int) list -> unit
method put_layout :
x: int -> y: int -> ?fore:color -> ?back:color -> Pango.layout -> unit
method put_image :
x:int -> y:int ->
?xsrc:int -> ?ysrc:int -> ?width:int -> ?height:int -> image -> unit
method put_pixmap :
x:int -> y:int ->
?xsrc:int -> ?ysrc:int -> ?width:int -> ?height:int -> pixmap -> unit
method put_rgb_data :
width:int -> height:int ->
?x:int -> ?y:int -> ?dither:Gdk.Tags.rgb_dither ->
?row_stride:int -> Gpointer.region -> unit
method put_pixbuf :
x:int -> y:int ->
?width:int -> ?height:int ->
?dither:Gdk.Tags.rgb_dither ->
?x_dither:int ->
?y_dither:int -> ?src_x:int -> ?src_y:int -> GdkPixbuf.pixbuf -> unit
method rectangle :
x:int ->
y:int -> width:int -> height:int -> ?filled:bool -> unit -> unit
method set_background : color -> unit
method set_foreground : color -> unit
method set_clip_region : region -> unit
method set_clip_origin : x:int -> y:int -> unit
method set_clip_mask : bitmap -> unit
method set_clip_rectangle : Rectangle.t -> unit
method set_line_attributes :
?width:int ->
?style:GC.gdkLineStyle ->
?cap:GC.gdkCapStyle -> ?join:GC.gdkJoinStyle -> unit -> unit
method size : int * int
method string : string -> font:font -> x:int -> y:int -> unit
method points : (int * int) list -> unit
method lines : (int * int) list -> unit
method segments : ((int * int) * (int * int)) list -> unit
end
(** {3 GdkPixmap} *)
(** Offscreen drawables
@gtkdoc gdk gdk-Bitmaps-and-Pixmaps *)
class pixmap :
?colormap:colormap -> ?mask:bitmap -> Gdk.pixmap ->
object
inherit drawable
val w : Gdk.pixmap
val bitmap : drawable option
val mask : bitmap option
method mask : bitmap option
method pixmap : Gdk.pixmap
end
class type misc_ops =
object
method colormap : colormap
method realize : unit -> unit
method visual_depth : int
method window : window
end
(** @gtkdoc gdk gdk-Bitmaps-and-Pixmaps *)
val pixmap :
width:int -> height:int -> ?mask:bool ->
?window:< misc : #misc_ops; .. > -> ?colormap:colormap ->
unit -> pixmap
val pixmap_from_xpm :
file:string ->
?window:< misc : #misc_ops; .. > ->
?colormap:colormap -> ?transparent:color -> unit -> pixmap
val pixmap_from_xpm_d :
data:string array ->
?window:< misc : #misc_ops; .. > ->
?colormap:colormap -> ?transparent:color -> unit -> pixmap
*)
module Cairo : sig
val create : window -> cairo
end
(** {3 GdkDragContext} *)
(** @gtkdoc gdk gdk-Drag-and-Drop *)
class drag_context : Gdk.drag_context ->
object
val context : Gdk.drag_context
method status : ?time:int32 -> Tags.drag_action option -> unit
method suggested_action : Tags.drag_action
method targets : string list
end
| (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
(* and/or modify it under the terms of the GNU Library General *)
(* Public License as published by the Free Software Foundation *)
(* version 2, with the exception described in file COPYING which *)
(* comes with the library. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Library General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU Library General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 59 Temple Place, Suite 330, *)
(* Boston, MA 02111-1307 USA *)
(* *)
(* *)
(**************************************************************************)
|
import.ml |
module Digest = Dune_digest
module Restore_result = Dune_cache_storage.Restore_result
module Store_result = Dune_cache_storage.Store_result
| |
IL.ml | module G = AST_generic
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(* Intermediate Language (IL) for static analysis.
*
* Just like for the CST -> AST, the goal of an AST -> IL transformation
* is to simplify things even more for program analysis purposes.
*
* Here are the simplifications done compared to the generic AST:
* - intermediate 'instr' type (instr for instruction), for expressions with
* side effects and statements without any control flow,
* moving Assign/Seq/Call/Conditional out of 'expr' and
* moving Assert out of 'stmt'
* - new expression type 'exp' for side-effect free expressions
* - intermediate 'lvalue' type; expressions are split into
* lvalue vs regular expressions, moved Dot/Index out of expr
*
* - Assign/Calls are now instructions, not expressions, and no more Seq
* - no AssignOp, or Decr/Incr, just Assign
* - Lambdas are now instructions (not nested again)
*
* - no For/Foreach/DoWhile/While, converted all to Loop,
* - no Foreach, converted to a Loop and 2 new special
* - no Switch, converted to Ifs
* - no Continue/Break, converted to goto
* - less use of expr option (in Return/Assert/...), use Unit in those cases
*
* - no Sgrep constructs
* - Naming has been performed, no more ident vs name
*
* TODO:
* - TODO? have all arguments of Calls be variables?
*
*
* Note that we still want to be close to the original code so that
* error reported on the IL can be mapped back to error on the original code
* (source "maps"), or more importantly semantic information computed
* on the IL (e.g., types, svalue, match range, taint) can be mapped back
* to the generic AST.
* This is why you will see some 'eorig', 'iorig' fields below and the use of
* refs such as svalue shared with the generic AST.
* TODO? alt: store just the range and id_info_id, so easy to propagate back
* info to generic AST or to return match ranges to semgrep.
*
* history:
* - cst_php.ml (was actually called ast_php.ml)
* - ast_php.ml (was called ast_php_simple.ml)
* - pil.ml, still for PHP
* - IL.ml for AST generic
*
* related work:
* - CIL, C Intermediate Language, Necula et al, CC'00
* - RIL, The Ruby Intermediate Language, Furr et al, DLS'09
* - SIL? in Infer? or more a generic AST than a generic IL?
* - Rust IL?
* - C-- in OCaml? too low-level?
* - LLVM IR (but too far away from original code? complicated
* source maps)
* - BRIL https://capra.cs.cornell.edu/bril/ used for teaching
* - gcc RTL (too low-level? similar to 3-address code?)
* - SiMPL language in BAP/BitBlaze dynamic analysis libraries
* but probably too close to assembly/bytecode
* - Jimpl in Soot/Wala
*)
(*****************************************************************************)
(* Token (leaf) *)
(*****************************************************************************)
(* the classic *)
type tok = G.tok [@@deriving show]
type 'a wrap = 'a G.wrap [@@deriving show]
(* useful mainly for empty containers *)
type 'a bracket = tok * 'a * tok [@@deriving show]
(*****************************************************************************)
(* Names *)
(*****************************************************************************)
type ident = G.ident [@@deriving show]
(* 'sid' below is the result of name resolution and variable disambiguation
* using a gensym (see Naming_AST.ml). A name is guaranteed to be
* global and unique (no need to handle variable shadowing, block scoping,
* etc; this has been done already).
* TODO: use it to also do SSA! so some control-flow insensitive analysis
* can become control-flow sensitive? (e.g., DOOP)
*
*)
type name = { ident : ident; sid : G.sid; id_info : G.id_info }
[@@deriving show]
(*****************************************************************************)
(* Fixme constructs *)
(*****************************************************************************)
(* AST-to-IL translation is still a work in progress. When we encounter some
* that we cannot handle, we insert a [FixmeExp], [FixmeInstr], or [FixmeStmt].
*)
type fixme_kind =
| ToDo (* some construct that we still don't support *)
| Sgrep_construct (* some Sgrep construct shows up in the code, e.g. `...' *)
| Impossible (* something we thought impossible happened *)
[@@deriving show]
(*****************************************************************************)
(* Mapping back to Generic *)
(*****************************************************************************)
(* Only use `SameAs` when the IL expression or instruction is indeed "the same as"
* (i.e., semantically equivalent to) that Generic expression.
*
* When an IL expression is derived from some other Generic expression or
* construct, but not semantically equivalent, you can use `Related`. Note that
* this info will be used by taint-tracking to match sources/sanitizers/sinks;
* so make sure that the annotation makes sense, or it could lead to weird taint
* findings.
*
* When no orig info is needed, or it cannot be provided, then use NoOrig. For
* example, auxiliary assignments where the RHS has the right orig-info can be
* annotated with NoOrig. This also helps making -dump_il more readable.
*)
type orig = SameAs of G.expr | Related of G.any | NoOrig
[@@deriving show { with_path = false }]
let related_tok tok = Related (G.Tk tok)
let related_exp exp_gen = Related (G.E exp_gen)
let any_of_orig = function
| SameAs e -> G.E e
| Related any -> any
| NoOrig -> G.Anys []
(*****************************************************************************)
(* Lvalue *)
(*****************************************************************************)
type lval = { base : base; rev_offset : offset list }
(** An lvalue, represented similarly as in CIL as a pair: base and offsets.
The offset list is *reversed*, so the first element in this list is the _last_
offset!
old: Previously we only kept one offset in lval and instead we used auxiliary
variables. But then we added field sensitivity to taint-mode and all those
extra variables became a problem, they would force us to add alias analysis
to handle even trivial cases of field sensitivity. *)
and base =
| Var of name
| VarSpecial of var_special wrap
(* aka DeRef, e.g. *E in C *)
(* THINK: Mem of exp -> Deref of name *)
| Mem of exp
and offset = {
o : offset_kind;
oorig : orig;
(** `oorig' should be a DotAccess expression and gives us the corresponding
* Generic expression for a sub-lvalue. Now that we represent `x.a.b.c` as
* { base = "x"; rev_offsets = ["c"; "b"; "a"]}, it makes it very easy to
* check whether a sub-lvalue is a source/santizer/sink by just checking
* the range of the `oorig'.
*
* alt: We could compute the range of the sub-lvalue from the ranges of all
* the offsets in the sub-lvalue, but this is probably less efficent
* unless we cache the range here. So it seems better to have `oorig'.
*)
}
and offset_kind =
(* What about computed field names?
* - handle them in Special?
* - convert in Index with a string exp?
* Note that Dot is used to access many different kinds of entities:
* objects/records (fields), classes (static fields), but also
* packages, modules, namespaces depending on the type of 'var' above.
*
* old: Previously the field was an `ident` but in some cases we want a
* proper (resolved) name here. For example, we want to resolve this.foo()
* to the class method "foo"; this is useful for our poor's man
* interprocedural analysis.
*)
| Dot of name
| Index of exp
(* transpile at some point? *)
and var_special = This | Super | Self | Parent
(*****************************************************************************)
(* Expression *)
(*****************************************************************************)
(* We use 'exp' instead of 'expr' to accentuate the difference
* with AST_generic.expr.
* Here 'exp' does not contain any side effect!
* todo: etype: typ;
*)
and exp = { e : exp_kind; eorig : orig }
and exp_kind =
| Fetch of lval (* lvalue used in a rvalue context *)
| Literal of G.literal
| Composite of composite_kind * exp list bracket
(* Record could be a Composite where the arguments are CTuple with
* the Literal (String) as a key, but they are pretty important I think
* for some analysis so better to support them more directly.
* TODO should we transform that in a New followed by a series of Assign
* with Dot? simpler?
* This could also be used for Dict.
*)
| Record of field list
| Cast of G.type_ * exp
(* This could be put in call_special, but dumped IL are then less readable
* (they are too many intermediate _tmp variables then) *)
| Operator of G.operator wrap * exp argument list
| FixmeExp of
fixme_kind
* G.any (* fixme source *)
* exp (* partial translation *) option
and field = Field of ident * exp | Spread of exp
and composite_kind =
| CTuple
| CArray
| CList
| CSet
| CDict (* could be merged with Record *)
| Constructor of name (* OCaml *)
| Regexp
and 'a argument = Unnamed of 'a | Named of ident * 'a
[@@deriving show { with_path = false }]
(*****************************************************************************)
(* Instruction *)
(*****************************************************************************)
(* Easier type to compute lvalue/rvalue set of a too general 'expr', which
* is now split into instr vs exp vs lval.
*)
type instr = { i : instr_kind; iorig : orig }
and instr_kind =
(* was called Set in CIL, but a bit ambiguous with Set module *)
| Assign of lval * exp
| AssignAnon of lval * anonymous_entity
| Call of lval option * exp (* less: enforce lval? *) * exp argument list
| CallSpecial of lval option * call_special wrap * exp argument list
(* todo: PhiSSA! *)
| FixmeInstr of fixme_kind * G.any
and call_special =
| Eval
(* TODO: lift up like in AST_generic *)
| New
| Typeof
| Instanceof
| Sizeof
(* old: better in exp: | Operator of G.arithmetic_operator *)
| Concat (* THINK: Normalize as a Operator G.Concat ? *)
| Spread
| Yield
| Await
(* was in stmt before, but with a new clean 'instr' type, better here *)
| Assert
(* was in expr before (only in C/PHP) *)
| Ref (* TODO: lift up, have AssignRef? *)
(* when transpiling certain features (e.g., patterns, foreach) *)
| ForeachNext
| ForeachHasNext
(* JS: require('foo') *)
| Require
(* primitives called under the hood *)
(* | IntAccess of composite_kind * int (* for tuples/array/list *)
| StringAccess of string (* for records/hashes *)
*)
and anonymous_entity =
| Lambda of function_definition
| AnonClass of G.class_definition
(*****************************************************************************)
(* Statement *)
(*****************************************************************************)
and stmt = { s : stmt_kind (* sorig: G.stmt; ?*) }
and stmt_kind =
| Instr of instr
(* Switch are converted to a series of If *)
| If of tok * exp * stmt list * stmt list
(* While/DoWhile/For are converted in a unified Loop construct.
* Break/Continue are handled via Label.
* alt: we could go further and transform in If+Goto, but nice to
* not be too far from the original code.
*)
| Loop of tok * exp * stmt list
| Return of tok * exp (* use Unit instead of 'exp option' *)
(* alt: do as in CIL and resolve that directly in 'Goto of stmt' *)
| Goto of tok * label
| Label of label
| Try of
stmt list
* (name * stmt list) list (* catches *)
* stmt list (* finally *)
| Throw of tok * exp (* less: enforce lval here? *)
| MiscStmt of other_stmt
| FixmeStmt of fixme_kind * G.any
and other_stmt =
(* everything except VarDef (which is transformed in an Assign instr) *)
| DefStmt of G.definition
| DirectiveStmt of G.directive
| Noop of (* for debugging purposes *) string
and label = ident * G.sid
(*****************************************************************************)
(* Defs *)
(*****************************************************************************)
(* See AST_generic.ml *)
and function_definition = {
fparams : name list;
frettype : G.type_ option;
fbody : stmt list;
}
[@@deriving show { with_path = false }]
(*****************************************************************************)
(* Control-flow graph (CFG) *)
(*****************************************************************************)
(* Similar to controlflow.ml, but with a simpler node_kind.
* See controlflow.ml for more information. *)
type node = {
n : node_kind;
(* old: there are tok in the nodes anyway
* t: Parse_info.t option;
*)
}
and node_kind =
| Enter
| Exit
| TrueNode
| FalseNode (* for Cond *)
| Join (* after Cond *)
| NInstr of instr
| NCond of tok * exp
| NGoto of tok * label
| NReturn of tok * exp
| NThrow of tok * exp
| NLambda of name list (* just the params, the body nodes follow this one *)
| NOther of other_stmt
| NTodo of stmt
[@@deriving show { with_path = false }]
(* For now there is just one kind of edge.
* (we may use more? the "ShadowNode" idea of Julia Lawall?)
*)
type edge = Direct
type cfg = (node, edge) CFG.t
(* an int representing the index of a node in the graph *)
type nodei = Ograph_extended.nodei
(*****************************************************************************)
(* Any *)
(*****************************************************************************)
type any = L of lval | E of exp | I of instr | S of stmt | Ss of stmt list
(* | N of node *)
[@@deriving show { with_path = false }]
(*****************************************************************************)
(* L/Rvalue helpers *)
(*****************************************************************************)
(* see IL_helpers.ml *)
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let str_of_name name = fst name.ident
let str_of_label ((n, _), _) = n
| (* Yoann Padioleau
* Iago Abal
*
* Copyright (C) 2019-2022 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* LICENSE for more details.
*) |
string_utils.ml |
let has_prefix ~prefix s =
let prefix_len = String.length prefix in
let len = String.length s in
prefix_len <= len && String.sub s 0 prefix_len = prefix
let has_suffix ~suffix s =
let suffix_len = String.length suffix in
let len = String.length s in
suffix_len <= len && String.sub s (len - suffix_len) suffix_len = suffix
let remove_prefix ~prefix s =
let ls = String.length s and prefix_len = String.length prefix in
if prefix_len <= ls && String.sub s 0 prefix_len = prefix then
Some (String.sub s prefix_len (ls - prefix_len))
else
None
let remove_suffix ~suffix s =
let ls = String.length s and suffix_len = String.length suffix in
if suffix_len <= ls &&
String.sub s (ls - suffix_len) (suffix_len) = suffix then
Some (String.sub s 0 (ls - suffix_len))
else
None
| |
dune |
(tests
(names test_lambda_streams_lwt)
(package lambda_streams_lwt)
(libraries alcotest alcotest-lwt lwt lwt.unix lambda_streams lambda_streams_lwt)
(action (run %{test})))
| |
test_pattern_matching_output.ml |
let _ =
let x = Some 1 in
Tezos_time_measurement_runtime.Default.Time_measurement.duration
("pattern_matching", [])
(fun () -> match x with Some a -> a | None -> 2)
| |
lTerm_windows.ml |
let (>|=) = Lwt.(>|=)
external get_acp : unit -> int = "lt_windows_get_acp"
external get_console_cp : unit -> int = "lt_windows_get_console_cp"
external set_console_cp : int -> unit = "lt_windows_set_console_cp"
external get_console_output_cp : unit -> int = "lt_windows_get_console_output_cp"
external set_console_output_cp : int -> unit = "lt_windows_set_console_output_cp"
type input =
| Resize
| Key of LTerm_key.t
| Mouse of LTerm_mouse.t
external read_console_input_job : Unix.file_descr -> input Lwt_unix.job = "lt_windows_read_console_input_job"
let controls = [|
Uchar.of_char ' ';
Uchar.of_char 'a';
Uchar.of_char 'b';
Uchar.of_char 'c';
Uchar.of_char 'd';
Uchar.of_char 'e';
Uchar.of_char 'f';
Uchar.of_char 'g';
Uchar.of_char 'h';
Uchar.of_char 'i';
Uchar.of_char 'j';
Uchar.of_char 'k';
Uchar.of_char 'l';
Uchar.of_char 'm';
Uchar.of_char 'n';
Uchar.of_char 'o';
Uchar.of_char 'p';
Uchar.of_char 'q';
Uchar.of_char 'r';
Uchar.of_char 's';
Uchar.of_char 't';
Uchar.of_char 'u';
Uchar.of_char 'v';
Uchar.of_char 'w';
Uchar.of_char 'x';
Uchar.of_char 'y';
Uchar.of_char 'z';
Uchar.of_char '[';
Uchar.of_char '\\';
Uchar.of_char ']';
Uchar.of_char '^';
Uchar.of_char '_';
|]
let read_console_input fd =
Lwt_unix.check_descriptor fd;
Lwt_unix.run_job ?async_method:None
(read_console_input_job (Lwt_unix.unix_file_descr fd))
>|= function
| Key({ LTerm_key.code = LTerm_key.Char ch ; _ } as key) when Uchar.to_int ch < 32 ->
Key { key with LTerm_key.code = LTerm_key.Char controls.(Uchar.to_int ch) }
| input ->
input
type text_attributes = {
foreground : int;
background : int;
}
type console_screen_buffer_info = {
size : LTerm_geom.size;
cursor_position : LTerm_geom.coord;
attributes : text_attributes;
window : LTerm_geom.rect;
maximum_window_size : LTerm_geom.size;
}
external get_console_screen_buffer_info : Unix.file_descr -> console_screen_buffer_info = "lt_windows_get_console_screen_buffer_info"
let get_console_screen_buffer_info fd =
Lwt_unix.check_descriptor fd;
get_console_screen_buffer_info (Lwt_unix.unix_file_descr fd)
type console_mode = {
cm_echo_input : bool;
cm_insert_mode : bool;
cm_line_input : bool;
cm_mouse_input : bool;
cm_processed_input : bool;
cm_quick_edit_mode : bool;
cm_window_input : bool;
}
external get_console_mode : Unix.file_descr -> console_mode = "lt_windows_get_console_mode"
external set_console_mode : Unix.file_descr -> console_mode -> unit = "lt_windows_set_console_mode"
let get_console_mode fd =
Lwt_unix.check_descriptor fd;
get_console_mode (Lwt_unix.unix_file_descr fd)
let set_console_mode fd mode =
Lwt_unix.check_descriptor fd;
set_console_mode (Lwt_unix.unix_file_descr fd) mode
external get_console_cursor_info : Unix.file_descr -> int * bool = "lt_windows_get_console_cursor_info"
external set_console_cursor_info : Unix.file_descr -> int -> bool -> unit = "lt_windows_set_console_cursor_info"
let get_console_cursor_info fd =
Lwt_unix.check_descriptor fd;
get_console_cursor_info (Lwt_unix.unix_file_descr fd)
let set_console_cursor_info fd size visible =
Lwt_unix.check_descriptor fd;
set_console_cursor_info (Lwt_unix.unix_file_descr fd) size visible
external set_console_cursor_position : Unix.file_descr -> LTerm_geom.coord -> unit = "lt_windows_set_console_cursor_position"
let set_console_cursor_position fd coord =
Lwt_unix.check_descriptor fd;
set_console_cursor_position (Lwt_unix.unix_file_descr fd) coord
external set_console_text_attribute : Unix.file_descr -> text_attributes -> unit = "lt_windows_set_console_text_attribute"
let set_console_text_attribute fd attrs =
Lwt_unix.check_descriptor fd;
set_console_text_attribute (Lwt_unix.unix_file_descr fd) attrs
type char_info = {
ci_char : Zed_char.t;
ci_foreground : int;
ci_background : int;
}
type char_info_raw = {
cir_char : Uchar.t;
cir_foreground : int;
cir_background : int;
}
let char_info_to_raw ci=
Zed_char.to_array ci.ci_char
|> Array.map (fun char->
{ cir_char= char;
cir_foreground= ci.ci_foreground;
cir_background= ci.ci_background
})
external write_console_output : Unix.file_descr -> char_info_raw array array -> LTerm_geom.size -> LTerm_geom.coord -> LTerm_geom.rect -> LTerm_geom.rect = "lt_windows_write_console_output"
let chars_to_raw chars=
Array.map
(fun line-> List.map (fun ci-> char_info_to_raw ci) (Array.to_list line) |> Array.concat)
chars
let write_console_output fd chars size coord rect =
Lwt_unix.check_descriptor fd;
if Array.length chars <> size.LTerm_geom.rows then invalid_arg "LTerm_windows.write_console_output";
Array.iter
(fun line ->
if Array.length line <> size.LTerm_geom.cols then invalid_arg "LTerm_windows.write_console_output")
chars;
let chars= chars_to_raw chars in
write_console_output (Lwt_unix.unix_file_descr fd) chars size coord rect
external fill_console_output_character : Unix.file_descr -> Uchar.t -> int -> LTerm_geom.coord -> int = "lt_windows_fill_console_output_character"
let fill_console_output_character fd char count coord =
Lwt_unix.check_descriptor fd;
fill_console_output_character (Lwt_unix.unix_file_descr fd) char count coord
| (*
* lTerm_windows.ml
* ----------------
* Copyright : (c) 2011, Jeremie Dimino <[email protected]>
* Licence : BSD3
*
* This file is a part of Lambda-Term.
*) |
state_hash.ml | let random_state_hash = "\076\064\204" (* rng(53): never used... *)
module H =
Blake2B.Make
(Base58)
(struct
let name = "random"
let title = "A random generation state"
let b58check_prefix = random_state_hash
let size = None
end)
include H
include Path_encoding.Make_hex (H)
let () = Base58.check_encoded_prefix b58check_encoding "rng" 53
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
file-register.c | /* SPDX-License-Identifier: MIT */
/*
* Description: run various file registration tests
*
*/
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/resource.h>
#include "helpers.h"
#include "liburing.h"
static int no_update = 0;
static void close_files(int *files, int nr_files, int add)
{
char fname[32];
int i;
for (i = 0; i < nr_files; i++) {
if (files)
close(files[i]);
if (!add)
sprintf(fname, ".reg.%d", i);
else
sprintf(fname, ".add.%d", i + add);
unlink(fname);
}
if (files)
free(files);
}
static int *open_files(int nr_files, int extra, int add)
{
char fname[32];
int *files;
int i;
files = t_calloc(nr_files + extra, sizeof(int));
for (i = 0; i < nr_files; i++) {
if (!add)
sprintf(fname, ".reg.%d", i);
else
sprintf(fname, ".add.%d", i + add);
files[i] = open(fname, O_RDWR | O_CREAT, 0644);
if (files[i] < 0) {
perror("open");
free(files);
files = NULL;
break;
}
}
if (extra) {
for (i = nr_files; i < nr_files + extra; i++)
files[i] = -1;
}
return files;
}
static int test_shrink(struct io_uring *ring)
{
int ret, off, fd;
int *files;
files = open_files(50, 0, 0);
ret = io_uring_register_files(ring, files, 50);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
off = 0;
do {
fd = -1;
ret = io_uring_register_files_update(ring, off, &fd, 1);
if (ret != 1) {
if (off == 50 && ret == -EINVAL)
break;
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
break;
}
off++;
} while (1);
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 50, 0);
return 0;
err:
close_files(files, 50, 0);
return 1;
}
static int test_grow(struct io_uring *ring)
{
int ret, off;
int *files, *fds = NULL;
files = open_files(50, 250, 0);
ret = io_uring_register_files(ring, files, 300);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
off = 50;
do {
fds = open_files(1, 0, off);
ret = io_uring_register_files_update(ring, off, fds, 1);
if (ret != 1) {
if (off == 300 && ret == -EINVAL)
break;
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
break;
}
if (off >= 300) {
fprintf(stderr, "%s: Succeeded beyond end-of-list?\n", __FUNCTION__);
goto err;
}
off++;
} while (1);
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 100, 0);
close_files(NULL, 251, 50);
return 0;
err:
close_files(files, 100, 0);
close_files(NULL, 251, 50);
return 1;
}
static int test_replace_all(struct io_uring *ring)
{
int *files, *fds = NULL;
int ret, i;
files = open_files(100, 0, 0);
ret = io_uring_register_files(ring, files, 100);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
fds = t_malloc(100 * sizeof(int));
for (i = 0; i < 100; i++)
fds[i] = -1;
ret = io_uring_register_files_update(ring, 0, fds, 100);
if (ret != 100) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 100, 0);
if (fds)
free(fds);
return 0;
err:
close_files(files, 100, 0);
if (fds)
free(fds);
return 1;
}
static int test_replace(struct io_uring *ring)
{
int *files, *fds = NULL;
int ret;
files = open_files(100, 0, 0);
ret = io_uring_register_files(ring, files, 100);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
fds = open_files(10, 0, 1);
ret = io_uring_register_files_update(ring, 90, fds, 10);
if (ret != 10) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 100, 0);
if (fds)
close_files(fds, 10, 1);
return 0;
err:
close_files(files, 100, 0);
if (fds)
close_files(fds, 10, 1);
return 1;
}
static int test_removals(struct io_uring *ring)
{
int *files, *fds = NULL;
int ret, i;
files = open_files(100, 0, 0);
ret = io_uring_register_files(ring, files, 100);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
fds = t_calloc(10, sizeof(int));
for (i = 0; i < 10; i++)
fds[i] = -1;
ret = io_uring_register_files_update(ring, 50, fds, 10);
if (ret != 10) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 100, 0);
if (fds)
free(fds);
return 0;
err:
close_files(files, 100, 0);
if (fds)
free(fds);
return 1;
}
static int test_additions(struct io_uring *ring)
{
int *files, *fds = NULL;
int ret;
files = open_files(100, 100, 0);
ret = io_uring_register_files(ring, files, 200);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
fds = open_files(2, 0, 1);
ret = io_uring_register_files_update(ring, 100, fds, 2);
if (ret != 2) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 100, 0);
if (fds)
close_files(fds, 2, 1);
return 0;
err:
close_files(files, 100, 0);
if (fds)
close_files(fds, 2, 1);
return 1;
}
static int test_sparse(struct io_uring *ring)
{
int *files;
int ret;
files = open_files(100, 100, 0);
ret = io_uring_register_files(ring, files, 200);
if (ret) {
if (ret == -EBADF) {
fprintf(stdout, "Sparse files not supported, skipping\n");
no_update = 1;
goto done;
}
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
done:
close_files(files, 100, 0);
return 0;
err:
close_files(files, 100, 0);
return 1;
}
static int test_basic_many(struct io_uring *ring)
{
int *files;
int ret;
files = open_files(768, 0, 0);
ret = io_uring_register_files(ring, files, 768);
if (ret) {
fprintf(stderr, "%s: register %d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister %d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, 768, 0);
return 0;
err:
close_files(files, 768, 0);
return 1;
}
static int test_basic(struct io_uring *ring, int fail)
{
int *files;
int ret;
int nr_files = fail ? 10 : 100;
files = open_files(nr_files, 0, 0);
ret = io_uring_register_files(ring, files, 100);
if (ret) {
if (fail) {
if (ret == -EBADF || ret == -EFAULT)
return 0;
}
fprintf(stderr, "%s: register %d\n", __FUNCTION__, ret);
goto err;
}
if (fail) {
fprintf(stderr, "Registration succeeded, but expected fail\n");
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister %d\n", __FUNCTION__, ret);
goto err;
}
close_files(files, nr_files, 0);
return 0;
err:
close_files(files, nr_files, 0);
return 1;
}
/*
* Register 0 files, but reserve space for 10. Then add one file.
*/
static int test_zero(struct io_uring *ring)
{
int *files, *fds = NULL;
int ret;
files = open_files(0, 10, 0);
ret = io_uring_register_files(ring, files, 10);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
fds = open_files(1, 0, 1);
ret = io_uring_register_files_update(ring, 0, fds, 1);
if (ret != 1) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
if (fds)
close_files(fds, 1, 1);
free(files);
return 0;
err:
if (fds)
close_files(fds, 1, 1);
free(files);
return 1;
}
static int test_fixed_read_write(struct io_uring *ring, int index)
{
struct io_uring_sqe *sqe;
struct io_uring_cqe *cqe;
struct iovec iov[2];
int ret;
iov[0].iov_base = t_malloc(4096);
iov[0].iov_len = 4096;
memset(iov[0].iov_base, 0x5a, 4096);
iov[1].iov_base = t_malloc(4096);
iov[1].iov_len = 4096;
sqe = io_uring_get_sqe(ring);
if (!sqe) {
fprintf(stderr, "%s: failed to get sqe\n", __FUNCTION__);
return 1;
}
io_uring_prep_writev(sqe, index, &iov[0], 1, 0);
sqe->flags |= IOSQE_FIXED_FILE;
sqe->user_data = 1;
ret = io_uring_submit(ring);
if (ret != 1) {
fprintf(stderr, "%s: got %d, wanted 1\n", __FUNCTION__, ret);
return 1;
}
ret = io_uring_wait_cqe(ring, &cqe);
if (ret < 0) {
fprintf(stderr, "%s: io_uring_wait_cqe=%d\n", __FUNCTION__, ret);
return 1;
}
if (cqe->res != 4096) {
fprintf(stderr, "%s: write cqe->res=%d\n", __FUNCTION__, cqe->res);
return 1;
}
io_uring_cqe_seen(ring, cqe);
sqe = io_uring_get_sqe(ring);
if (!sqe) {
fprintf(stderr, "%s: failed to get sqe\n", __FUNCTION__);
return 1;
}
io_uring_prep_readv(sqe, index, &iov[1], 1, 0);
sqe->flags |= IOSQE_FIXED_FILE;
sqe->user_data = 2;
ret = io_uring_submit(ring);
if (ret != 1) {
fprintf(stderr, "%s: got %d, wanted 1\n", __FUNCTION__, ret);
return 1;
}
ret = io_uring_wait_cqe(ring, &cqe);
if (ret < 0) {
fprintf(stderr, "%s: io_uring_wait_cqe=%d\n", __FUNCTION__, ret);
return 1;
}
if (cqe->res != 4096) {
fprintf(stderr, "%s: read cqe->res=%d\n", __FUNCTION__, cqe->res);
return 1;
}
io_uring_cqe_seen(ring, cqe);
if (memcmp(iov[1].iov_base, iov[0].iov_base, 4096)) {
fprintf(stderr, "%s: data mismatch\n", __FUNCTION__);
return 1;
}
free(iov[0].iov_base);
free(iov[1].iov_base);
return 0;
}
static void adjust_nfiles(int want_files)
{
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) < 0)
return;
if (rlim.rlim_cur >= want_files)
return;
rlim.rlim_cur = want_files;
setrlimit(RLIMIT_NOFILE, &rlim);
}
/*
* Register 8K of sparse files, update one at a random spot, then do some
* file IO to verify it works.
*/
static int test_huge(struct io_uring *ring)
{
int *files;
int ret;
adjust_nfiles(16384);
files = open_files(0, 8192, 0);
ret = io_uring_register_files(ring, files, 8192);
if (ret) {
/* huge sets not supported */
if (ret == -EMFILE) {
fprintf(stdout, "%s: No huge file set support, skipping\n", __FUNCTION__);
goto out;
}
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
files[7193] = open(".reg.7193", O_RDWR | O_CREAT, 0644);
if (files[7193] < 0) {
fprintf(stderr, "%s: open=%d\n", __FUNCTION__, errno);
goto err;
}
ret = io_uring_register_files_update(ring, 7193, &files[7193], 1);
if (ret != 1) {
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
if (test_fixed_read_write(ring, 7193))
goto err;
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
if (files[7193] != -1) {
close(files[7193]);
unlink(".reg.7193");
}
out:
free(files);
return 0;
err:
if (files[7193] != -1) {
close(files[7193]);
unlink(".reg.7193");
}
free(files);
return 1;
}
static int test_skip(struct io_uring *ring)
{
int *files;
int ret;
files = open_files(100, 0, 0);
ret = io_uring_register_files(ring, files, 100);
if (ret) {
fprintf(stderr, "%s: register ret=%d\n", __FUNCTION__, ret);
goto err;
}
files[90] = IORING_REGISTER_FILES_SKIP;
ret = io_uring_register_files_update(ring, 90, &files[90], 1);
if (ret != 1) {
if (ret == -EBADF) {
fprintf(stdout, "Skipping files not supported\n");
goto done;
}
fprintf(stderr, "%s: update ret=%d\n", __FUNCTION__, ret);
goto err;
}
/* verify can still use file index 90 */
if (test_fixed_read_write(ring, 90))
goto err;
ret = io_uring_unregister_files(ring);
if (ret) {
fprintf(stderr, "%s: unregister ret=%d\n", __FUNCTION__, ret);
goto err;
}
done:
close_files(files, 100, 0);
return 0;
err:
close_files(files, 100, 0);
return 1;
}
static int test_sparse_updates(void)
{
struct io_uring ring;
int ret, i, *fds, newfd;
ret = io_uring_queue_init(8, &ring, 0);
if (ret) {
fprintf(stderr, "queue_init: %d\n", ret);
return ret;
}
fds = t_malloc(256 * sizeof(int));
for (i = 0; i < 256; i++)
fds[i] = -1;
ret = io_uring_register_files(&ring, fds, 256);
if (ret) {
fprintf(stderr, "file_register: %d\n", ret);
return ret;
}
newfd = 1;
for (i = 0; i < 256; i++) {
ret = io_uring_register_files_update(&ring, i, &newfd, 1);
if (ret != 1) {
fprintf(stderr, "file_update: %d\n", ret);
return ret;
}
}
io_uring_unregister_files(&ring);
for (i = 0; i < 256; i++)
fds[i] = 1;
ret = io_uring_register_files(&ring, fds, 256);
if (ret) {
fprintf(stderr, "file_register: %d\n", ret);
return ret;
}
newfd = -1;
for (i = 0; i < 256; i++) {
ret = io_uring_register_files_update(&ring, i, &newfd, 1);
if (ret != 1) {
fprintf(stderr, "file_update: %d\n", ret);
return ret;
}
}
io_uring_unregister_files(&ring);
io_uring_queue_exit(&ring);
return 0;
}
static int test_fixed_removal_ordering(void)
{
char buffer[128];
struct io_uring ring;
struct io_uring_sqe *sqe;
struct io_uring_cqe *cqe;
struct __kernel_timespec ts;
int ret, fd, i, fds[2];
ret = io_uring_queue_init(8, &ring, 0);
if (ret < 0) {
fprintf(stderr, "failed to init io_uring: %s\n", strerror(-ret));
return ret;
}
if (pipe(fds)) {
perror("pipe");
return -1;
}
ret = io_uring_register_files(&ring, fds, 2);
if (ret) {
fprintf(stderr, "file_register: %d\n", ret);
return ret;
}
/* ring should have fds referenced, can close them */
close(fds[0]);
close(fds[1]);
sqe = io_uring_get_sqe(&ring);
if (!sqe) {
fprintf(stderr, "%s: get sqe failed\n", __FUNCTION__);
return 1;
}
/* outwait file recycling delay */
ts.tv_sec = 3;
ts.tv_nsec = 0;
io_uring_prep_timeout(sqe, &ts, 0, 0);
sqe->flags |= IOSQE_IO_LINK | IOSQE_IO_HARDLINK;
sqe->user_data = 1;
sqe = io_uring_get_sqe(&ring);
if (!sqe) {
printf("get sqe failed\n");
return -1;
}
io_uring_prep_write(sqe, 1, buffer, sizeof(buffer), 0);
sqe->flags |= IOSQE_FIXED_FILE;
sqe->user_data = 2;
ret = io_uring_submit(&ring);
if (ret != 2) {
fprintf(stderr, "%s: got %d, wanted 2\n", __FUNCTION__, ret);
return -1;
}
/* remove unused pipe end */
fd = -1;
ret = io_uring_register_files_update(&ring, 0, &fd, 1);
if (ret != 1) {
fprintf(stderr, "update off=0 failed\n");
return -1;
}
/* remove used pipe end */
fd = -1;
ret = io_uring_register_files_update(&ring, 1, &fd, 1);
if (ret != 1) {
fprintf(stderr, "update off=1 failed\n");
return -1;
}
for (i = 0; i < 2; ++i) {
ret = io_uring_wait_cqe(&ring, &cqe);
if (ret < 0) {
fprintf(stderr, "%s: io_uring_wait_cqe=%d\n", __FUNCTION__, ret);
return 1;
}
io_uring_cqe_seen(&ring, cqe);
}
io_uring_queue_exit(&ring);
return 0;
}
/* mix files requiring SCM-accounting and not in a single register */
static int test_mixed_af_unix(void)
{
struct io_uring ring;
int i, ret, fds[2];
int reg_fds[32];
int sp[2];
ret = io_uring_queue_init(8, &ring, 0);
if (ret < 0) {
fprintf(stderr, "failed to init io_uring: %s\n", strerror(-ret));
return ret;
}
if (pipe(fds)) {
perror("pipe");
return -1;
}
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sp) != 0) {
perror("Failed to create Unix-domain socket pair\n");
return 1;
}
for (i = 0; i < 16; i++) {
reg_fds[i * 2] = fds[0];
reg_fds[i * 2 + 1] = sp[0];
}
ret = io_uring_register_files(&ring, reg_fds, 32);
if (ret) {
fprintf(stderr, "file_register: %d\n", ret);
return ret;
}
close(fds[0]);
close(fds[1]);
close(sp[0]);
close(sp[1]);
io_uring_queue_exit(&ring);
return 0;
}
static int test_partial_register_fail(void)
{
char buffer[128];
struct io_uring ring;
int ret, fds[2];
int reg_fds[5];
ret = io_uring_queue_init(8, &ring, 0);
if (ret < 0) {
fprintf(stderr, "failed to init io_uring: %s\n", strerror(-ret));
return ret;
}
if (pipe(fds)) {
perror("pipe");
return -1;
}
/*
* Expect register to fail as it doesn't support io_uring fds, shouldn't
* leave any fds referenced afterwards.
*/
reg_fds[0] = fds[0];
reg_fds[1] = fds[1];
reg_fds[2] = -1;
reg_fds[3] = ring.ring_fd;
reg_fds[4] = -1;
ret = io_uring_register_files(&ring, reg_fds, 5);
if (!ret) {
fprintf(stderr, "file_register unexpectedly succeeded\n");
return 1;
}
/* ring should have fds referenced, can close them */
close(fds[1]);
/* confirm that fds[1] is actually close and to ref'ed by io_uring */
ret = read(fds[0], buffer, 10);
if (ret < 0)
perror("read");
close(fds[0]);
io_uring_queue_exit(&ring);
return 0;
}
static int file_update_alloc(struct io_uring *ring, int *fd)
{
struct io_uring_sqe *sqe;
struct io_uring_cqe *cqe;
int ret;
sqe = io_uring_get_sqe(ring);
io_uring_prep_files_update(sqe, fd, 1, IORING_FILE_INDEX_ALLOC);
ret = io_uring_submit(ring);
if (ret != 1) {
fprintf(stderr, "%s: got %d, wanted 1\n", __FUNCTION__, ret);
return -1;
}
ret = io_uring_wait_cqe(ring, &cqe);
if (ret < 0) {
fprintf(stderr, "%s: io_uring_wait_cqe=%d\n", __FUNCTION__, ret);
return -1;
}
ret = cqe->res;
io_uring_cqe_seen(ring, cqe);
return ret;
}
static int test_out_of_range_file_ranges(struct io_uring *ring)
{
int ret;
ret = io_uring_register_file_alloc_range(ring, 8, 3);
if (ret != -EINVAL) {
fprintf(stderr, "overlapping range %i\n", ret);
return 1;
}
ret = io_uring_register_file_alloc_range(ring, 10, 1);
if (ret != -EINVAL) {
fprintf(stderr, "out of range index %i\n", ret);
return 1;
}
ret = io_uring_register_file_alloc_range(ring, 7, ~1U);
if (ret != -EOVERFLOW) {
fprintf(stderr, "overflow %i\n", ret);
return 1;
}
return 0;
}
static int test_overallocating_file_range(struct io_uring *ring, int fds[2])
{
int roff = 7, rlen = 2;
int ret, i, fd;
ret = io_uring_register_file_alloc_range(ring, roff, rlen);
if (ret) {
fprintf(stderr, "io_uring_register_file_alloc_range %i\n", ret);
return 1;
}
for (i = 0; i < rlen; i++) {
fd = fds[0];
ret = file_update_alloc(ring, &fd);
if (ret != 1) {
fprintf(stderr, "file_update_alloc\n");
return 1;
}
if (fd < roff || fd >= roff + rlen) {
fprintf(stderr, "invalid off result %i\n", fd);
return 1;
}
}
fd = fds[0];
ret = file_update_alloc(ring, &fd);
if (ret != -ENFILE) {
fprintf(stderr, "overallocated %i, off %i\n", ret, fd);
return 1;
}
return 0;
}
static int test_zero_range_alloc(struct io_uring *ring, int fds[2])
{
int ret, fd;
ret = io_uring_register_file_alloc_range(ring, 7, 0);
if (ret) {
fprintf(stderr, "io_uring_register_file_alloc_range failed %i\n", ret);
return 1;
}
fd = fds[0];
ret = file_update_alloc(ring, &fd);
if (ret != -ENFILE) {
fprintf(stderr, "zero alloc %i\n", ret);
return 1;
}
return 0;
}
static int test_file_alloc_ranges(void)
{
struct io_uring ring;
int ret, pipe_fds[2];
if (pipe(pipe_fds)) {
fprintf(stderr, "pipes\n");
return 1;
}
ret = io_uring_queue_init(8, &ring, 0);
if (ret) {
fprintf(stderr, "queue_init: %d\n", ret);
return 1;
}
ret = io_uring_register_files_sparse(&ring, 10);
if (ret == -EINVAL) {
not_supported:
close(pipe_fds[0]);
close(pipe_fds[1]);
io_uring_queue_exit(&ring);
printf("file alloc ranges are not supported, skip\n");
return 0;
} else if (ret) {
fprintf(stderr, "io_uring_register_files_sparse %i\n", ret);
return ret;
}
ret = io_uring_register_file_alloc_range(&ring, 0, 1);
if (ret) {
if (ret == -EINVAL)
goto not_supported;
fprintf(stderr, "io_uring_register_file_alloc_range %i\n", ret);
return 1;
}
ret = test_overallocating_file_range(&ring, pipe_fds);
if (ret) {
fprintf(stderr, "test_overallocating_file_range() failed\n");
return 1;
}
ret = test_out_of_range_file_ranges(&ring);
if (ret) {
fprintf(stderr, "test_out_of_range_file_ranges() failed\n");
return 1;
}
ret = test_zero_range_alloc(&ring, pipe_fds);
if (ret) {
fprintf(stderr, "test_zero_range_alloc() failed\n");
return 1;
}
close(pipe_fds[0]);
close(pipe_fds[1]);
io_uring_queue_exit(&ring);
return 0;
}
int main(int argc, char *argv[])
{
struct io_uring ring;
int ret;
if (argc > 1)
return T_EXIT_SKIP;
ret = io_uring_queue_init(8, &ring, 0);
if (ret) {
fprintf(stderr, "ring setup failed\n");
return T_EXIT_FAIL;
}
ret = test_basic(&ring, 0);
if (ret) {
fprintf(stderr, "test_basic failed\n");
return T_EXIT_FAIL;
}
ret = test_basic(&ring, 1);
if (ret) {
fprintf(stderr, "test_basic failed\n");
return T_EXIT_FAIL;
}
ret = test_basic_many(&ring);
if (ret) {
fprintf(stderr, "test_basic_many failed\n");
return T_EXIT_FAIL;
}
ret = test_sparse(&ring);
if (ret) {
fprintf(stderr, "test_sparse failed\n");
return T_EXIT_FAIL;
}
if (no_update)
return T_EXIT_SKIP;
ret = test_additions(&ring);
if (ret) {
fprintf(stderr, "test_additions failed\n");
return T_EXIT_FAIL;
}
ret = test_removals(&ring);
if (ret) {
fprintf(stderr, "test_removals failed\n");
return T_EXIT_FAIL;
}
ret = test_replace(&ring);
if (ret) {
fprintf(stderr, "test_replace failed\n");
return T_EXIT_FAIL;
}
ret = test_replace_all(&ring);
if (ret) {
fprintf(stderr, "test_replace_all failed\n");
return T_EXIT_FAIL;
}
ret = test_grow(&ring);
if (ret) {
fprintf(stderr, "test_grow failed\n");
return T_EXIT_FAIL;
}
ret = test_shrink(&ring);
if (ret) {
fprintf(stderr, "test_shrink failed\n");
return T_EXIT_FAIL;
}
ret = test_zero(&ring);
if (ret) {
fprintf(stderr, "test_zero failed\n");
return T_EXIT_FAIL;
}
ret = test_huge(&ring);
if (ret) {
fprintf(stderr, "test_huge failed\n");
return T_EXIT_FAIL;
}
ret = test_skip(&ring);
if (ret) {
fprintf(stderr, "test_skip failed\n");
return T_EXIT_FAIL;
}
ret = test_sparse_updates();
if (ret) {
fprintf(stderr, "test_sparse_updates failed\n");
return T_EXIT_FAIL;
}
ret = test_fixed_removal_ordering();
if (ret) {
fprintf(stderr, "test_fixed_removal_ordering failed\n");
return T_EXIT_FAIL;
}
ret = test_mixed_af_unix();
if (ret) {
fprintf(stderr, "test_mixed_af_unix failed\n");
return T_EXIT_FAIL;
}
ret = test_partial_register_fail();
if (ret) {
fprintf(stderr, "test_partial_register_fail failed\n");
return T_EXIT_FAIL;
}
ret = test_file_alloc_ranges();
if (ret) {
fprintf(stderr, "test_partial_register_fail failed\n");
return T_EXIT_FAIL;
}
return T_EXIT_PASS;
}
| /* SPDX-License-Identifier: MIT */
/* |
baking.mli |
open Alpha_context
open Misc
type error += Invalid_fitness_gap of int64 * int64 (* `Permanent *)
type error += Timestamp_too_early of Timestamp.t * Timestamp.t (* `Permanent *)
type error += Invalid_block_signature of Block_hash.t * Signature.Public_key_hash.t (* `Permanent *)
type error += Unexpected_endorsement
type error += Invalid_signature (* `Permanent *)
type error += Invalid_stamp (* `Permanent *)
(** [minimal_time ctxt priority pred_block_time] returns the minimal
time, given the predecessor block timestamp [pred_block_time],
after which a baker with priority [priority] is allowed to
bake. Fail with [Invalid_time_between_blocks_constant] if the minimal
time cannot be computed. *)
val minimal_time: context -> int -> Time.t -> Time.t tzresult Lwt.t
(** [check_baking_rights ctxt block pred_timestamp] verifies that:
* the contract that owned the roll at cycle start has the block signer as delegate.
* the timestamp is coherent with the announced slot.
*)
val check_baking_rights:
context -> Block_header.contents -> Time.t ->
public_key tzresult Lwt.t
(** For a given level computes who has the right to
include an endorsement in the next block.
The result can be stored in Alpha_context.allowed_endorsements *)
val endorsement_rights:
context ->
Level.t ->
(public_key * int list * bool) Signature.Public_key_hash.Map.t tzresult Lwt.t
(** Check that the operation was signed by a delegate allowed
to endorse at the level specified by the endorsement. *)
val check_endorsement_rights:
context -> Chain_id.t -> Kind.endorsement Operation.t ->
(public_key_hash * int list * bool) tzresult Lwt.t
(** Returns the endorsement reward calculated w.r.t a given priority. *)
val endorsement_reward: context -> block_priority:int -> int -> Tez.t tzresult Lwt.t
(** [baking_priorities ctxt level] is the lazy list of contract's
public key hashes that are allowed to bake for [level]. *)
val baking_priorities:
context -> Level.t -> public_key lazy_list
(** [first_baking_priorities ctxt ?max_priority contract_hash level]
is a list of priorities of max [?max_priority] elements, where the
delegate of [contract_hash] is allowed to bake for [level]. If
[?max_priority] is [None], a sensible number of priorities is
returned. *)
val first_baking_priorities:
context ->
?max_priority:int ->
public_key_hash ->
Level.t ->
int list tzresult Lwt.t
(** [check_signature ctxt chain_id block id] check if the block is
signed with the given key, and belongs to the given [chain_id] *)
val check_signature: Block_header.t -> Chain_id.t -> public_key -> unit tzresult Lwt.t
(** Checks if the header that would be built from the given components
is valid for the given diffculty. The signature is not passed as it
is does not impact the proof-of-work stamp. The stamp is checked on
the hash of a block header whose signature has been zeroed-out. *)
val check_header_proof_of_work_stamp:
Block_header.shell_header -> Block_header.contents -> int64 -> bool
(** verify if the proof of work stamp is valid *)
val check_proof_of_work_stamp:
context -> Block_header.t -> unit tzresult Lwt.t
(** check if the gap between the fitness of the current context
and the given block is within the protocol parameters *)
val check_fitness_gap:
context -> Block_header.t -> unit tzresult Lwt.t
val dawn_of_a_new_cycle: context -> Cycle.t option tzresult Lwt.t
val earlier_predecessor_timestamp: context -> Level.t -> Timestamp.t tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
deleteVPCAssociationAuthorization.mli |
open Types
type input = DeleteVPCAssociationAuthorizationRequest.t
type output = unit
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type
error := error | |
utils.ml |
module Array = struct
include Array
let findi_opt p a =
let n = length a in
let rec loop i =
if i = n then None
else
let x = unsafe_get a i in
if p x then Some i else loop (succ i)
in
loop 0
end
| |
dune |
(library
(name duration)
(public_name duration)
(modules duration))
(test
(name tests)
(modules tests)
(libraries alcotest duration))
| |
gpg.ml |
open Common
type t = system
module U = Utils
let spf = Printf.sprintf
let gpg_lock = Lwt_mutex.create ()
(* gnupg does not work reliably when multiple processes are using the keyring at once (at least on OS X).
Example error without the lock:
warning: Feed http://0install.net/2006/interfaces/0publish: Failed to check feed signature:
Error checking signature for 'http://0install.net/2006/interfaces/0publish': GPG failed:
gpg: starting migration from earlier GnuPG versions
gpg: porting secret keys from '/Users/travis/.gnupg/secring.gpg' to gpg-agent
gpg: migration succeeded
gpg: can't open '/Users/travis/.gnupg/pubring.gpg'
gpg: keydb_get_keyblock failed: Value not found
*)
type fingerprint = string
type timestamp = float
type sig_error =
| UnsupportedAlgorithm of string
| UnknownKey of string
| UnknownSigError of int
type valid_details = {
fingerprint : fingerprint;
timestamp : timestamp;
}
type signature =
| ValidSig of valid_details
| BadSig of string (* Message has been tampered with *)
| ErrSig of sig_error
let string_of_sig = function
| ValidSig details -> spf "Valid signature from %s" details.fingerprint
| BadSig key -> spf "BAD signature by %s (the message has been tampered with)" key
| ErrSig (UnsupportedAlgorithm alg) -> spf "Unknown or unsupported algorithm '%s'" alg
| ErrSig (UnknownKey key) -> spf "Unknown key. Try 'gpg --recv-key %s'" key
| ErrSig (UnknownSigError code) -> spf "Unknown reason code from GPG: %d" code
let re_xml_comment_start = Str.regexp "^<!-- Base64 Signature$"
let re_newline = Str.regexp "[\n\r]+"
let gnupg_options = ref None
let make system = system
let get_gnupg_options system =
let gpg_path =
match system#getenv "ZEROINSTALL_GPG" with
| Some path -> path
| None ->
match U.find_in_path system "gpg" with
| Some path -> path
| None ->
match U.find_in_path system "gpg2" with
| Some path -> path
| None -> Safe_exn.failf "Can't find gpg or gpg2 in $PATH!" in
let gnupg_options = [gpg_path; "--no-secmem-warning"] in
if system#running_as_root && system#getenv "GNUPGHOME" = None then (
let gnupg_home = Basedir.get_unix_home system +/ ".gnupg" in
log_info "Running as root, so setting GnuPG home to %s" gnupg_home;
gnupg_options @ ["--homedir"; gnupg_home]
) else gnupg_options
let make_gpg_command system args =
let opts =
match !gnupg_options with
| None ->
let opts = get_gnupg_options system in
gnupg_options := Some opts;
opts
| Some opts -> opts in
let argv = opts @ args in
log_info "Running GnuPG: %s" (Logging.format_argv_for_logging argv);
(List.hd opts, argv |> Array.of_list)
(** Run gpg, passing [stdin] as input and collecting the output. *)
let run_gpg_full system ?stdin args =
let command = make_gpg_command system args in
let child = new Lwt_process.process_full command in
Lwt.catch
(fun () ->
(* Start collecting output... *)
let stdout = Lwt_io.read child#stdout in
let stderr = Lwt_io.read child#stderr in
(* At the same time, write the input, if any *)
begin match stdin with
| None -> Lwt.return ()
| Some stdin -> stdin child#stdin
end >>= fun () ->
Lwt_io.close child#stdin >>= fun () ->
(* Join the collection threads *)
stdout >>= fun stdout ->
stderr >>= fun stderr ->
child#close >>= fun status ->
Lwt.return (stdout, stderr, status)
)
(fun ex ->
(* child#terminate; - not in Debian *)
ignore child#close;
Lwt.fail ex
)
(** Run gpg, passing [stdin] as input and collecting the output.
* If the command returns an error, report stderr as the error (on success, stderr is discarded).
*)
let run_gpg system ?stdin args =
Lwt_mutex.with_lock gpg_lock @@ fun () ->
run_gpg_full system ?stdin args >>= fun (stdout, stderr, status) ->
if stdout <> "" then log_info "GPG: output:\n%s" (String.trim stdout);
if stderr <> "" then log_info "GPG: warnings:\n%s" (String.trim stderr);
match status with
| Unix.WEXITED 0 -> Lwt.return stdout
| status ->
if stderr = "" then System.check_exit_status status;
Safe_exn.failf "GPG failed: %s" stderr
(** Run "gpg --import" with this data as stdin. *)
let import_key system key_data =
let write_stdin stdin = Lwt_io.write stdin key_data in
run_gpg system ~stdin:write_stdin ["--quiet"; "--import"; "--batch"] >|= function
| "" -> ()
| output -> log_warning "Output from gpg:\n%s" output
(** Call 'gpg --list-keys' and return the results split into lines and columns. *)
let get_key_details system key_id : string array list Lwt.t =
(* Note: GnuPG 2 always uses --fixed-list-mode *)
run_gpg system ["--fixed-list-mode"; "--with-colons"; "--list-keys"; "--"; key_id] >>= fun output ->
let parse_line line = Str.split XString.re_colon line |> Array.of_list in
output |> Str.split re_newline |> List.map parse_line |> Lwt.return
(** Get the first human-readable name from the details. *)
let get_key_name system key_id =
get_key_details system key_id >|= fun details ->
details |> U.first_match (fun details ->
if Array.length details > 9 && details.(0) = "uid" then Some details.(9)
else None
)
let find_sig_end xml =
let rec skip_ws last =
match xml.[last - 1] with
| ' ' | '\n' | '\r' | '\t' -> skip_ws (last - 1)
| _ -> last in
let last_non_ws = skip_ws (String.length xml) in
let end_marker_index = last_non_ws - 4 in
if String.sub xml end_marker_index 4 <> "\n-->" then
Safe_exn.failf "Bad signature block: last line is not end-of-comment";
let rec skip_padding last =
match xml.[last - 1] with
| ' ' | '\n' | '\t' | '\r' | '=' -> skip_padding (last - 1)
| _ -> last in
skip_padding end_marker_index
(* The docs say GnuPG timestamps can be seconds since the epoch or an ISO 8601
string ("we are migrating to an ISO 8601 format"). We use --fixed-list-mode,
which says it will "print all timestamps as seconds since 1970-01-01 [...]
Since GnuPG 2.0.10, this mode is always used and thus this option is
obsolete; it does not harm to use it though." *)
let parse_timestamp ts =
float_of_string ts
let make_valid args = ValidSig {
fingerprint = args.(0);
timestamp = parse_timestamp args.(2);
}
let make_bad args = BadSig args.(0)
let make_err args = ErrSig (
(* GnuPG 2.1.16 sets the higher bits (possibly by mistake).
See: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=846834 *)
match XString.to_int_safe args.(5) land 0xffff with
| 4 -> UnsupportedAlgorithm args.(1)
| 9 -> UnknownKey args.(0)
| x -> UnknownSigError x
)
(** Parse the status output from gpg as a list of signatures. *)
let sigs_from_gpg_status_output status =
status |> Str.split re_newline |> List.filter_map (fun line ->
if XString.starts_with line "[GNUPG:] " then (
match XString.tail line 9 |> Str.split_delim XString.re_space with
| [] -> None
| code :: args ->
let args = Array.of_list args in
match code with
| "VALIDSIG" -> Some (make_valid args)
| "BADSIG" -> Some (make_bad args)
| "ERRSIG" -> Some (make_err args)
| _ -> None
) else (
(* The docs says every line starts with this, but if auto-key-retrieve
* is on then they might not. See bug #3420548 *)
log_warning "Invalid output from GnuPG: %s" (String.escaped line);
None
)
)
(** Verify the GPG signature at the end of data. *)
let verify (system:system) xml =
if not (XString.starts_with xml "<?xml ") then (
let len = min 120 (String.length xml) in
let start = String.sub xml 0 len |> String.escaped in
Safe_exn.failf "This is not a Zero Install feed! It should be an XML document, but it starts:\n%s" start
) else (
let index =
try Str.search_backward re_xml_comment_start xml (String.length xml)
with Not_found ->
Safe_exn.failf "No signature block in XML. Maybe this file isn't signed?" in
let sig_start = String.index_from xml index '\n' in
let sig_end = find_sig_end xml in
let base64_data = String.sub xml sig_start (sig_end - sig_start) |> Str.global_replace re_newline "" in
let sig_data =
try Base64.str_decode base64_data
with Base64.Invalid_char -> Safe_exn.failf "Invalid characters found in base 64 encoded signature" in
let tmp = Filename.temp_file "0install-" "-gpg" in
Lwt.finalize
(fun () ->
(* Don't use Lwt here, otherwise we may fork with the file open and leak it to a child
* process, which will break things on Windows. Unix.O_CLOEXEC requires OCaml >= 4.01 *)
U.finally_do close_out
(open_out_bin tmp)
(fun ch -> output_string ch sig_data);
let write_stdin stdin = Lwt_io.write_from_string_exactly stdin xml 0 index in
run_gpg_full system ~stdin:write_stdin [
(* Not all versions support this: *)
(* '--max-output', str(1024 * 1024), *)
"--batch";
(* Windows GPG can only cope with "1" here *)
"--status-fd"; "1";
(* Don't try to download missing keys; we'll do that *)
"--keyserver-options"; "no-auto-key-retrieve";
"--verify"; tmp; "-";
]
)
(fun () ->
begin try Unix.unlink tmp
with ex -> log_warning ~ex "Failed to clean up GnuPG temporary file '%s'" tmp end;
Lwt.return ()
)
>>= fun (stdout, stderr, exit_status) ->
ignore exit_status;
Lwt.return (sigs_from_gpg_status_output stdout, String.trim stderr)
)
type key_info = {
name : string option
}
(** Load a set of keys at once.
This is much more efficient than making individual calls to [load_key]. *)
let load_keys system fingerprints =
if fingerprints = [] then (
(* Otherwise GnuPG returns everything... *)
Lwt.return XString.Map.empty
) else (
run_gpg system @@ [
"--fixed-list-mode"; "--with-colons"; "--list-keys";
"--with-fingerprint"; "--with-fingerprint"] @ fingerprints
>>= fun output ->
let keys = ref XString.Map.empty in
fingerprints |> List.iter (fun fpr ->
keys := XString.Map.add fpr ({name = None}) !keys
);
let current_fpr = ref None in
let current_uid = ref None in
let maybe_set_name fpr name =
if XString.Map.mem fpr !keys then
keys := XString.Map.add fpr {name = Some name} !keys in
output |> Str.split re_newline |> List.iter (fun line ->
if XString.starts_with line "pub:" then (
current_fpr := None; current_uid := None
) else if XString.starts_with line "fpr:" then (
let fpr = List.nth (line |> Str.split_delim XString.re_colon) 9 in
current_fpr := Some fpr;
match !current_uid with
| None -> ()
| Some uid ->
(* This is probably a subordinate key, where the fingerprint
* comes after the uid, not before. Note: we assume the subkey is
* cross-certified, as recent always ones are. *)
maybe_set_name fpr uid
) else if XString.starts_with line "uid:" then (
match !current_fpr with
| None -> assert false
| Some fpr ->
(* Only take primary UID *)
if !current_uid = None then (
let uid = List.nth (line |> Str.split_delim XString.re_colon) 9 in
maybe_set_name fpr uid;
current_uid := Some uid
)
)
);
Lwt.return !keys
)
| (* Copyright (C) 2013, Thomas Leonard
* See the README file for details, or visit http://0install.net.
*) |
interval.h | #pragma once
#include "util/mpq.h"
#include "util/ext_numeral.h"
#include "util/rlimit.h"
/**
\brief Default configuration for interval manager.
It is used for documenting the required interface.
*/
class im_default_config {
unsynch_mpq_manager & m_manager;
public:
typedef unsynch_mpq_manager numeral_manager;
typedef mpq numeral;
// Every configuration object must provide an interval type.
// The actual fields are irrelevant, the interval manager
// accesses interval data using the following API.
struct interval {
numeral m_lower;
numeral m_upper;
unsigned m_lower_open:1;
unsigned m_upper_open:1;
unsigned m_lower_inf:1;
unsigned m_upper_inf:1;
interval():
m_lower_open(false),
m_upper_open(false),
m_lower_inf(true),
m_upper_inf(true) {}
};
// Should be NOOPs for precise numeral types.
// For imprecise types (e.g., floats) it should set the rounding mode.
void round_to_minus_inf() {}
void round_to_plus_inf() {}
void set_rounding(bool to_plus_inf) {}
// Getters
numeral const & lower(interval const & a) const { return a.m_lower; }
numeral const & upper(interval const & a) const { return a.m_upper; }
numeral & lower(interval & a) { return a.m_lower; }
numeral & upper(interval & a) { return a.m_upper; }
bool lower_is_open(interval const & a) const { return a.m_lower_open; }
bool upper_is_open(interval const & a) const { return a.m_upper_open; }
bool lower_is_inf(interval const & a) const { return a.m_lower_inf; }
bool upper_is_inf(interval const & a) const { return a.m_upper_inf; }
// Setters
void set_lower(interval & a, numeral const & n) { m_manager.set(a.m_lower, n); }
void set_upper(interval & a, numeral const & n) { m_manager.set(a.m_upper, n); }
void set_lower_is_open(interval & a, bool v) { a.m_lower_open = v; }
void set_upper_is_open(interval & a, bool v) { a.m_upper_open = v; }
void set_lower_is_inf(interval & a, bool v) { a.m_lower_inf = v; }
void set_upper_is_inf(interval & a, bool v) { a.m_upper_inf = v; }
// Reference to numeral manager
numeral_manager & m() const { return m_manager; }
im_default_config(numeral_manager & m):m_manager(m) {}
};
#define DEP_IN_LOWER1 1
#define DEP_IN_UPPER1 2
#define DEP_IN_LOWER2 4
#define DEP_IN_UPPER2 8
typedef short deps_combine_rule;
inline bool dep_in_lower1(deps_combine_rule d) { return (d & DEP_IN_LOWER1) != 0; }
inline bool dep_in_lower2(deps_combine_rule d) { return (d & DEP_IN_LOWER2) != 0; }
inline bool dep_in_upper1(deps_combine_rule d) { return (d & DEP_IN_UPPER1) != 0; }
inline bool dep_in_upper2(deps_combine_rule d) { return (d & DEP_IN_UPPER2) != 0; }
inline deps_combine_rule dep1_to_dep2(deps_combine_rule d) {
SASSERT(!dep_in_lower2(d) && !dep_in_upper2(d));
deps_combine_rule r = d << 2;
SASSERT(dep_in_lower1(d) == dep_in_lower2(r));
SASSERT(dep_in_upper1(d) == dep_in_upper2(r));
SASSERT(!dep_in_lower1(r) && !dep_in_upper1(r));
return r;
}
/**
\brief Interval dependencies for unary and binary operations on intervals.
It contains the dependencies for the output lower and upper bounds
for the resultant interval.
*/
struct interval_deps_combine_rule {
deps_combine_rule m_lower_combine;
deps_combine_rule m_upper_combine;
void reset() {
m_lower_combine = m_upper_combine = 0;
}
};
template<typename C>
class interval_manager {
public:
typedef typename C::numeral_manager numeral_manager;
typedef typename numeral_manager::numeral numeral;
typedef typename C::interval interval;
private:
reslimit& m_limit;
C m_c;
numeral m_result_lower;
numeral m_result_upper;
numeral m_mul_ad;
numeral m_mul_bc;
numeral m_mul_ac;
numeral m_mul_bd;
numeral m_one;
numeral m_minus_one;
numeral m_inv_k;
unsigned m_pi_n;
interval m_pi_div_2;
interval m_pi;
interval m_3_pi_div_2;
interval m_2_pi;
void round_to_minus_inf() { m_c.round_to_minus_inf(); }
void round_to_plus_inf() { m_c.round_to_plus_inf(); }
void set_rounding(bool to_plus_inf) { m_c.set_rounding(to_plus_inf); }
ext_numeral_kind lower_kind(interval const & a) const { return m_c.lower_is_inf(a) ? EN_MINUS_INFINITY : EN_NUMERAL; }
ext_numeral_kind upper_kind(interval const & a) const { return m_c.upper_is_inf(a) ? EN_PLUS_INFINITY : EN_NUMERAL; }
void set_lower(interval & a, numeral const & n) { m_c.set_lower(a, n); }
void set_upper(interval & a, numeral const & n) { m_c.set_upper(a, n); }
void set_lower_is_open(interval & a, bool v) { m_c.set_lower_is_open(a, v); }
void set_upper_is_open(interval & a, bool v) { m_c.set_upper_is_open(a, v); }
void set_lower_is_inf(interval & a, bool v) { m_c.set_lower_is_inf(a, v); }
void set_upper_is_inf(interval & a, bool v) { m_c.set_upper_is_inf(a, v); }
void nth_root_slow(numeral const & a, unsigned n, numeral const & p, numeral & lo, numeral & hi);
void A_div_x_n(numeral const & A, numeral const & x, unsigned n, bool to_plus_inf, numeral & r);
void rough_approx_nth_root(numeral const & a, unsigned n, numeral & o);
void approx_nth_root(numeral const & a, unsigned n, numeral const & p, numeral & o);
void nth_root_pos(numeral const & A, unsigned n, numeral const & p, numeral & lo, numeral & hi);
void nth_root(numeral const & a, unsigned n, numeral const & p, numeral & lo, numeral & hi);
void pi_series(int x, numeral & r, bool to_plus_inf);
void fact(unsigned n, numeral & o);
void sine_series(numeral const & a, unsigned k, bool upper, numeral & o);
void cosine_series(numeral const & a, unsigned k, bool upper, numeral & o);
void e_series(unsigned k, bool upper, numeral & o);
void div_mul(numeral const & k, interval const & a, interval & b, bool inv_k);
void checkpoint();
public:
interval_manager(reslimit& lim, C && c);
~interval_manager();
numeral_manager & m() const { return m_c.m(); }
void del(interval & a);
numeral const & lower(interval const & a) const { return m_c.lower(a); }
numeral const & upper(interval const & a) const { return m_c.upper(a); }
numeral & lower(interval & a) { return m_c.lower(a); }
numeral & upper(interval & a) { return m_c.upper(a); }
bool lower_is_open(interval const & a) const { return m_c.lower_is_open(a); }
bool upper_is_open(interval const & a) const { return m_c.upper_is_open(a); }
bool lower_is_inf(interval const & a) const { return m_c.lower_is_inf(a); }
bool upper_is_inf(interval const & a) const { return m_c.upper_is_inf(a); }
bool lower_is_neg(interval const & a) const { return ::is_neg(m(), lower(a), lower_kind(a)); }
bool lower_is_pos(interval const & a) const { return ::is_pos(m(), lower(a), lower_kind(a)); }
bool lower_is_zero(interval const & a) const { return ::is_zero(m(), lower(a), lower_kind(a)); }
bool upper_is_neg(interval const & a) const { return ::is_neg(m(), upper(a), upper_kind(a)); }
bool upper_is_pos(interval const & a) const { return ::is_pos(m(), upper(a), upper_kind(a)); }
bool upper_is_zero(interval const & a) const { return ::is_zero(m(), upper(a), upper_kind(a)); }
bool is_P(interval const & n) const { return lower_is_pos(n) || lower_is_zero(n); }
bool is_P0(interval const & n) const { return lower_is_zero(n) && !lower_is_open(n); }
bool is_P1(interval const & n) const { return lower_is_pos(n) || (lower_is_zero(n) && lower_is_open(n)); }
bool is_N(interval const & n) const { return upper_is_neg(n) || upper_is_zero(n); }
bool is_N0(interval const & n) const { return upper_is_zero(n) && !upper_is_open(n); }
bool is_N1(interval const & n) const { return upper_is_neg(n) || (upper_is_zero(n) && upper_is_open(n)); }
bool is_M(interval const & n) const { return lower_is_neg(n) && upper_is_pos(n); }
bool is_zero(interval const & n) const { return lower_is_zero(n) && upper_is_zero(n); }
void set(interval & t, interval const & s);
void set(interval & t, numeral const& n);
bool eq(interval const & a, interval const & b) const;
/**
\brief Return true if all values in 'a' are less than all values in 'b'.
*/
bool before(interval const & a, interval const & b) const;
/**
\brief Set lower bound to -oo.
*/
void reset_lower(interval & a);
/**
\brief Set upper bound to +oo.
*/
void reset_upper(interval & a);
/**
\brief Set interval to (-oo, oo)
*/
void reset(interval & a);
/**
\brief Return true if the given interval contains 0.
*/
bool contains_zero(interval const & n) const;
/**
\brief Return true if n contains v.
*/
bool contains(interval const & n, numeral const & v) const;
void display(std::ostream & out, interval const & n) const;
void display_pp(std::ostream & out, interval const & n) const;
bool check_invariant(interval const & n) const;
/**
\brief b <- -a
*/
void neg(interval const & a, interval & b, interval_deps_combine_rule & b_deps);
void neg(interval const & a, interval & b);
void neg_jst(interval const & a, interval_deps_combine_rule & b_deps);
/**
\brief c <- a + b
*/
void add(interval const & a, interval const & b, interval & c, interval_deps_combine_rule & c_deps);
void add(interval const & a, interval const & b, interval & c);
void add_jst(interval const & a, interval const & b, interval_deps_combine_rule & c_deps);
/**
\brief c <- a - b
*/
void sub(interval const & a, interval const & b, interval & c, interval_deps_combine_rule & c_deps);
void sub(interval const & a, interval const & b, interval & c);
void sub_jst(interval const & a, interval const & b, interval_deps_combine_rule & c_deps);
/**
\brief b <- k * a
*/
void mul(numeral const & k, interval const & a, interval & b, interval_deps_combine_rule & b_deps);
void mul(numeral const & k, interval const & a, interval & b) { div_mul(k, a, b, false); }
void mul_jst(numeral const & k, interval const & a, interval_deps_combine_rule & b_deps);
/**
\brief b <- (n/d) * a
*/
void mul(int n, int d, interval const & a, interval & b);
/**
\brief b <- a/k
\remark For imprecise numerals, this is not equivalent to
m().inv(k)
mul(k, a, b)
That is, we must invert k rounding towards +oo or -oo depending whether we
are computing a lower or upper bound.
*/
void div(interval const & a, numeral const & k, interval & b, interval_deps_combine_rule & b_deps);
void div(interval const & a, numeral const & k, interval & b) { div_mul(k, a, b, true); }
void div_jst(interval const & a, numeral const & k, interval_deps_combine_rule & b_deps) { mul_jst(k, a, b_deps); }
/**
\brief c <- a * b
*/
void mul(interval const & a, interval const & b, interval & c, interval_deps_combine_rule & c_deps);
void mul(interval const & a, interval const & b, interval & c);
void mul_jst(interval const & a, interval const & b, interval_deps_combine_rule & c_deps);
/**
\brief b <- a^n
*/
void power(interval const & a, unsigned n, interval & b, interval_deps_combine_rule & b_deps);
void power(interval const & a, unsigned n, interval & b);
void power_jst(interval const & a, unsigned n, interval_deps_combine_rule & b_deps);
/**
\brief b <- a^(1/n) with precision p.
\pre if n is even, then a must not contain negative numbers.
*/
void nth_root(interval const & a, unsigned n, numeral const & p, interval & b, interval_deps_combine_rule & b_deps);
void nth_root(interval const & a, unsigned n, numeral const & p, interval & b);
void nth_root_jst(interval const & a, unsigned n, numeral const & p, interval_deps_combine_rule & b_deps);
/**
\brief Given an equation x^n = y and an interval for y, compute the solution set for x with precision p.
\pre if n is even, then !lower_is_neg(y)
*/
void xn_eq_y(interval const & y, unsigned n, numeral const & p, interval & x, interval_deps_combine_rule & x_deps);
void xn_eq_y(interval const & y, unsigned n, numeral const & p, interval & x);
void xn_eq_y_jst(interval const & y, unsigned n, numeral const & p, interval_deps_combine_rule & x_deps);
/**
\brief b <- 1/a
\pre !contains_zero(a)
*/
void inv(interval const & a, interval & b, interval_deps_combine_rule & b_deps);
void inv(interval const & a, interval & b);
void inv_jst(interval const & a, interval_deps_combine_rule & b_deps);
/**
\brief c <- a/b
\pre !contains_zero(b)
\pre &a == &c (that is, c should not be an alias for a)
*/
void div(interval const & a, interval const & b, interval & c, interval_deps_combine_rule & c_deps);
void div(interval const & a, interval const & b, interval & c);
void div_jst(interval const & a, interval const & b, interval_deps_combine_rule & c_deps);
/**
\brief Store in r an interval that contains the number pi.
The size of the interval is (1/15)*(1/16^n)
*/
void pi(unsigned n, interval & r);
/**
\brief Set the precision of the internal interval representing pi.
*/
void set_pi_prec(unsigned n);
/**
\brief Set the precision of the internal interval representing pi to a precision of at least n.
*/
void set_pi_at_least_prec(unsigned n);
void sine(numeral const & a, unsigned k, numeral & lo, numeral & hi);
void cosine(numeral const & a, unsigned k, numeral & lo, numeral & hi);
/**
\brief Store in r the Euler's constant e.
The size of the interval is 4/(k+1)!
*/
void e(unsigned k, interval & r);
};
template<typename Manager>
class _scoped_interval {
public:
typedef typename Manager::interval interval;
private:
Manager & m_manager;
interval m_interval;
public:
_scoped_interval(Manager & m):m_manager(m) {}
~_scoped_interval() { m_manager.del(m_interval); }
Manager & m() const { return m_manager; }
operator interval const &() const { return m_interval; }
operator interval&() { return m_interval; }
interval const & get() const { return m_interval; }
interval & get() { return m_interval; }
interval * operator->() {
return &m_interval;
}
interval const * operator->() const {
return &m_interval;
}
};
| /*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
interval.h
Abstract:
Goodies/Templates for interval arithmetic
Author:
Leonardo de Moura (leonardo) 2012-07-19.
Revision History:
--*/ |
date_times.ml |
let texts =
[
"2020 jun 6 10am";
"2020 jun 6th 10am";
"6 jun 2020 10am";
"6th jun 2020 10am";
"2020 jun 6 10:15";
"2020 jun 6th 10:15";
"6 jun 2020 10:15";
"6th jun 2020 10:15";
"Australia/Sydney 2020 jun 6 10am";
"Australia/Sydney 2020 jun 6 10:15";
"2020 jun 6 10am Australia/Sydney";
"2020 jun 6 10:15 Australia/Sydney";
"2020-06-01 10:10";
"2020/06/01 10am";
"10:10 2020-06-01";
"10am 2020/06/01";
"01-06-2020 10:10";
"01/06/2020 10am";
"10:10 01-06-2020";
"10am 01/06/2020";
"6th of jul 2021 9:15am";
"6th of jul 2021 9:51";
"2021 6 of jul 9:15am";
"2021 6th of jul 9:51";
"jul 6 2021 9:15am";
"jul 6th 2021 9:15am";
"2020 jul 6";
"2020 jul 6th";
"6 jul 2020";
"6th jul 2020";
"2020/06/01";
"01/06/2020";
"1st of jun 2020";
"2020.06.01";
"01.06.2020";
"2020.6.1";
"1.6.2020";
"1.6.2020 24:00:00";
"2020.06.01 24:00";
"1.6.2020 24:00";
"2020.06.01 24:00";
]
let () =
List.iteri
(fun i text ->
Printf.printf "%d. %S\n" i text;
match Timere_parse.date_time ~tz:Timedesc.Time_zone.utc text with
| Ok dt -> Format.printf " Ok %a\n\n%!" (Timedesc.pp_rfc3339 ()) dt
| Error msg ->
Printf.printf " Error %s\n" msg;
print_endline " ^^^^^";
print_newline ())
texts
| |
protocol_store.mli | (** Protocol store *)
(** The type for the protocol store. *)
type t
(** [mem pstore proto_hash] tests the existence of the protocol
indexed by [proto_hash] in the store. *)
val mem : t -> Protocol_hash.t -> bool
(** [all pstore] returns the set of all stored protocols in [pstore]. *)
val all : t -> Protocol_hash.Set.t
(** [raw_store pstore proto_hash proto_bytes] stores on disk the
protocol [proto_bytes] (encoded bytes) indexed as
[proto_hash]. Returns [None] if the protocol already exists. *)
val raw_store : t -> Protocol_hash.t -> bytes -> Protocol_hash.t option Lwt.t
(** [store pstore proto_hash protocol] stores on disk the protocol
[protocol] indexed as [proto_hash]. Returns [None] if the protocol
already exists. *)
val store : t -> Protocol_hash.t -> Protocol.t -> Protocol_hash.t option Lwt.t
(** [read pstore proto_hash] reads from [pstore] and returns the
protocol indexed by [proto_hash]. Returns [None] if the protocol
cannot be read. *)
val read : t -> Protocol_hash.t -> Protocol.t option Lwt.t
(** [init store_dir] creates a store relatively to [store_dir] path
or loads it if it already exists. *)
val init : [`Store_dir] Naming.directory -> t Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020-2021 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
parsing_hacks_define.ml | open Common
open Parser_cpp
module Flag = Flag_parsing
module PI = Parse_info
module TH = Token_helpers_cpp
module Hack = Parsing_hacks_lib
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*
* To parse macro definitions I need to do some tricks
* as some information can be computed only at the lexing level. For instance
* the space after the name of the macro in '#define foo (x)' is meaningful
* but the grammar does not have this information. So define_ident() below
* look at such space and generate a special TOpar_Define token.
*
* In a similar way macro definitions can contain some antislash and newlines
* and the grammar need to know where the macro ends which is
* a line-level and so low token-level information. Hence the
* function define_line'()below and the TCommentNewline_DefineEndOfMacro.
*
* update: TCommentNewline_DefineEndOfMacro is handled in a special way
* at different places, a little bit like EOF, especially for error recovery,
* so this is an important token that should not be retagged!
*
* We also change the kind of TIdent to TIdent_Define to avoid bad interactions
* with other parsing_hack tricks. For instant if keep TIdent then
* the stringication heuristics can believe the TIdent is a string-macro.
* So simpler to change the kind of the TIdent in a macro too.
*
* ugly: maybe a better solution perhaps would be to erase
* TCommentNewline_DefineEndOfMacro from the Ast and list of tokens in parse_c.
*
* note: I do a +1 somewhere, it's for the unparsing to correctly sync.
*
* note: can't replace mark_end_define by simply a fakeInfo(). The reason
* is where is the \n TCommentSpace. Normally there is always a last token
* to synchronize on, either EOF or the token of the next toplevel.
* In the case of the #define we got in list of token
* [TCommentSpace "\n"; TDefEOL] but if TDefEOL is a fakeinfo then we will
* not synchronize on it and so we will not print the "\n".
* A solution would be to put the TDefEOL before the "\n".
*
* todo?: could put a ExpandedTok for that ?
*)
(*****************************************************************************)
(* Wrappers *)
(*****************************************************************************)
let pr2, _pr2_once = Common2.mk_pr2_wrappers Flag.verbose_lexing
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let mark_end_define ii =
let ii' =
{
Parse_info.token =
Parse_info.OriginTok
{
(Parse_info.unsafe_token_location_of_info ii) with
Parse_info.str = "";
Parse_info.charpos = PI.pos_of_info ii + 1;
};
transfo = Parse_info.NoTransfo;
}
in
(* fresh_tok *) TCommentNewline_DefineEndOfMacro ii'
let pos ii = Parse_info.string_of_info ii
(*****************************************************************************)
(* Parsing hacks for #define *)
(*****************************************************************************)
(* simple automata:
* state1 --'#define'--> state2 --change_of_line--> state1
*)
(* put the TCommentNewline_DefineEndOfMacro at the good place
* and replace \ with TCommentSpace
*)
let rec define_line_1 acc xs =
(* Tail-recursive to prevent stack overflows. *)
match xs with
| [] -> List.rev acc
| (TDefine ii as x) :: xs ->
let line = PI.line_of_info ii in
define_line_2 (x :: acc) line ii xs
| TCppEscapedNewline ii :: xs ->
pr2 (spf "WEIRD: a \\ outside a #define at %s" (pos ii));
define_line_1 ((* fresh_tok*) TCommentSpace ii :: acc) xs
| x :: xs -> define_line_1 (x :: acc) xs
and define_line_2 acc line lastinfo xs =
(* Tail-recursive to prevent stack overflows. *)
match xs with
| [] ->
(* should not happened, should meet EOF before *)
pr2 "PB: WEIRD in Parsing_hack_define.define_line_2";
List.rev (mark_end_define lastinfo :: acc)
| x :: xs -> (
let line' = TH.line_of_tok x in
let info = TH.info_of_tok x in
match x with
| EOF ii -> define_line_1 (EOF ii :: mark_end_define lastinfo :: acc) xs
| TCppEscapedNewline ii ->
if line' <> line then pr2 "PB: WEIRD: not same line number";
define_line_2
((* fresh_tok*) TCommentSpace ii :: acc)
(line + 1) info xs
| x ->
if line' =|= line then define_line_2 (x :: acc) line info xs
else define_line_1 (mark_end_define lastinfo :: acc) (x :: xs))
let define_line xs = define_line_1 [] xs
(* put the TIdent_Define and TOPar_Define *)
let define_ident xs =
(* Tail-recursive to prevent stack overflows. *)
let rec aux acc xs =
match xs with
| [] -> List.rev acc
| (TDefine ii as x) :: xs -> (
match xs with
| (TCommentSpace _ as x1)
:: TIdent (s, i2)
:: (* no space *) TOPar i3
:: xs ->
(* if TOPar_Define is just next to the ident (no space), then
* it's a macro-function. We change the token to avoid
* ambiguity between '#define foo(x)' and '#define foo (x)'
*)
let acc' =
Hack.fresh_tok (TOPar_Define i3)
:: Hack.fresh_tok (TIdent_Define (s, i2))
:: x1 :: x :: acc
in
aux acc' xs
| (TCommentSpace _ as x1) :: TIdent (s, i2) :: xs ->
let acc' =
Hack.fresh_tok (TIdent_Define (s, i2)) :: x1 :: x :: acc
in
aux acc' xs
| _ ->
pr2 (spf "WEIRD #define body, at %s" (pos ii));
aux (x :: acc) xs)
| x :: xs -> aux (x :: acc) xs
in
aux [] xs
(*****************************************************************************)
(* Entry point *)
(*****************************************************************************)
let fix_tokens_define xs = define_ident (define_line xs) [@@profiling]
| (* Yoann Padioleau
*
* Copyright (C) 2002-2008 Yoann Padioleau
* Copyright (C) 2011 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*
*) |
divide.h |
/*
** divide.h
**
** Martin Brain
** [email protected]
** 04/02/16
**
** Division of arbitrary precision floats
**
*/
#include "symfpu/core/unpackedFloat.h"
#include "symfpu/core/ite.h"
#include "symfpu/core/rounder.h"
#include "symfpu/core/operations.h"
#ifndef SYMFPU_DIVIDE
#define SYMFPU_DIVIDE
namespace symfpu {
template <class t>
unpackedFloat<t> addDivideSpecialCases (const typename t::fpt &format,
const unpackedFloat<t> &left,
const unpackedFloat<t> &right,
const typename t::prop &sign,
const unpackedFloat<t> ÷Result) {
typedef typename t::prop prop;
prop eitherArgumentNaN(left.getNaN() || right.getNaN());
prop generateNaN((left.getInf() && right.getInf()) ||
(left.getZero() && right.getZero()));
prop isNaN(eitherArgumentNaN || generateNaN);
prop isInf((!left.getZero() && right.getZero()) ||
(left.getInf() && !right.getInf()));
prop isZero((!left.getInf() && right.getInf()) ||
(left.getZero() && !right.getZero()));
return ITE(isNaN,
unpackedFloat<t>::makeNaN(format),
ITE(isInf,
unpackedFloat<t>::makeInf(format, sign),
ITE(isZero,
unpackedFloat<t>::makeZero(format, sign),
divideResult)));
}
template <class t>
unpackedFloat<t> arithmeticDivide (const typename t::fpt &format,
const unpackedFloat<t> &left,
const unpackedFloat<t> &right) {
typedef typename t::bwt bwt;
typedef typename t::prop prop;
typedef typename t::ubv ubv;
typedef typename t::sbv sbv;
typedef typename t::fpt fpt;
PRECONDITION(left.valid(format));
PRECONDITION(right.valid(format));
// Compute sign
prop divideSign(left.getSign() ^ right.getSign());
// Subtract up exponents
sbv exponentDiff(expandingSubtract<t>(left.getExponent(),right.getExponent()));
// Optimisation : do this late and use the increment as a carry in
sbv min(unpackedFloat<t>::minSubnormalExponent(format));
sbv max(unpackedFloat<t>::maxNormalExponent(format));
INVARIANT(expandingSubtract<t>(min,max) <= exponentDiff);
INVARIANT(exponentDiff <= expandingSubtract<t>(max, min));
// Optimisation : use the if-then-lazy-else to avoid dividing for underflow and overflow
// subnormal / greater-than-2^sigwidth does not need to be evaluated
// Divide the significands
// We need significandWidth() + 1 bits in the result but the top one may cancel, so add two bits
ubv extendedNumerator(left.getSignificand().append(ubv::zero(2)));
ubv extendedDenominator(right.getSignificand().append(ubv::zero(2)));
resultWithRemainderBit<t> divided(fixedPointDivide<t>(extendedNumerator, extendedDenominator));
bwt resWidth(divided.result.getWidth());
ubv topBit(divided.result.extract(resWidth - 1, resWidth - 1));
ubv nextBit(divided.result.extract(resWidth - 2, resWidth - 2));
// Alignment of inputs means at least one of the two MSB is 1
// i.e. [1,2) / [1,2) = [0.5,2)
// Top bit is set by the first round of the divide and thus is 50/50 1 or 0
prop topBitSet(topBit.isAllOnes());
INVARIANT(topBitSet || nextBit.isAllOnes());
INVARIANT(topBitSet == (left.getSignificand() >= right.getSignificand()));
// Re-align
sbv alignedExponent(conditionalDecrement<t>(!topBitSet, exponentDiff)); // Will not overflow as previously expanded
ubv alignedSignificand(conditionalLeftShiftOne<t>(!topBitSet, divided.result)); // Will not loose information
// Create the sticky bit, it is important that this is after alignment
ubv finishedSignificand(alignedSignificand | ubv(divided.remainderBit).extend(resWidth - 1));
// Put back together
unpackedFloat<t> divideResult(divideSign, alignedExponent.extend(1), finishedSignificand);
// A brief word about formats.
// You might think that the extend above is unnecessary : it is from a overflow point of view.
// It's needed so that it is a valid number with exponentWidth() + 2.
// +1 is sufficient in almost all cases. However:
// very large normal / very small subnormal
// can have an exponent greater than very large normal * 2 ( + 1)
// because the exponent range is asymmetric with more subnormal than normal.
fpt extendedFormat(format.exponentWidth() + 2, format.significandWidth() + 2);
POSTCONDITION(divideResult.valid(extendedFormat));
return divideResult;
}
// Put it all together...
template <class t>
unpackedFloat<t> divide (const typename t::fpt &format,
const typename t::rm &roundingMode,
const unpackedFloat<t> &left,
const unpackedFloat<t> &right) {
//typedef typename t::bwt bwt;
//typedef typename t::prop prop;
//typedef typename t::ubv ubv;
//typedef typename t::sbv sbv;
PRECONDITION(left.valid(format));
PRECONDITION(right.valid(format));
unpackedFloat<t> divideResult(arithmeticDivide(format, left, right));
unpackedFloat<t> roundedDivideResult(rounder(format, roundingMode, divideResult));
unpackedFloat<t> result(addDivideSpecialCases(format, left, right, roundedDivideResult.getSign(), roundedDivideResult));
POSTCONDITION(result.valid(format));
return result;
}
}
#endif
| /*
** Copyright (C) 2018 Martin Brain
**
** See the file LICENSE for licensing information.
*/ |
paths.ml |
open Internal_pervasives
type t = {root: string}
let make root =
{ root=
( if Caml.Filename.is_relative root then Caml.Sys.getcwd () // root
else root ) }
let root_path o = o.root
let pp fmt o = Fmt.pf fmt "@[<2>{Root:@ %s}@]" (root_path o)
let ob o : t = o#paths
let root o = ob o |> root_path
let cli_term ?(option_name = "root-path") ~default_root () =
Cmdliner.(
Term.(
pure make
$ Arg.(
value & opt string default_root
& info [option_name]
~doc:(sprintf "Root path for all configs/data to use."))))
| |
protocol_files.mli |
open Error_monad
val read_dir :
string ->
(Tezos_crypto.Hashed.Protocol_hash.t option * Protocol.t) tzresult Lwt.t
val write_dir :
string ->
?hash:Tezos_crypto.Hashed.Protocol_hash.t ->
Protocol.t ->
unit tzresult Lwt.t
| |
test_string.mli | (*_ This signature is deliberately empty. *)
| (*_ This signature is deliberately empty. *)
|
openapi.mli | (** OpenAPI specifications. *)
(** This is not a general library, in particular it does not support
content-types other than [application/json]. It only supports
what we actually use. *)
module Schema : sig
(** OpenAPI Schema Objects.
Not exactly the same as JSON schemas. *)
(** Nullable (i.e. non-ref) schemas. *)
type kind =
| Boolean
| Integer of {
minimum : int option;
maximum : int option;
enum : int list option;
}
| Number of {minimum : float option; maximum : float option}
| String of {enum : string list option; pattern : string option}
| Array of t
| Object of {properties : property list; additional_properties : t option}
| One_of of t list
| Any
and t =
| Ref of string
| Other of {
title : string option;
description : string option;
nullable : bool;
kind : kind;
}
(** Object fields. *)
and property = {name : string; required : bool; schema : t}
type maker =
?title:string -> ?description:string -> ?nullable:bool -> unit -> t
val boolean : maker
val integer : ?minimum:int -> ?maximum:int -> ?enum:int list -> maker
val number : ?minimum:float -> ?maximum:float -> maker
val string : ?enum:string list -> ?pattern:string -> maker
val array : items:t -> maker
val obj : ?additional_properties:t -> properties:property list -> maker
val one_of : cases:t list -> maker
val any : maker
val reference : string -> t
end
module Response : sig
type t = {code : int option; description : string; schema : Schema.t}
val make : ?code:int -> description:string -> Schema.t -> t
end
module Parameter : sig
type t = {name : string; description : string option; schema : Schema.t}
end
module Service : sig
type query_parameter = {required : bool; parameter : Parameter.t}
type t = {
description : string;
request_body : Schema.t option;
responses : Response.t list;
query : query_parameter list;
}
val make :
description:string ->
?request_body:Schema.t ->
?query:query_parameter list ->
Response.t list ->
t
end
module Path : sig
type item = Static of string | Dynamic of Parameter.t
val static : string -> item
val dynamic : ?description:string -> schema:Schema.t -> string -> item
type t = item list
val to_string : t -> string
end
module Endpoint : sig
(** API endpoints, i.e. paths associated with one or more HTTP methods. *)
(** Associative lists for methods and their implementation. *)
type methods = (Method.t * Service.t) list
(** API endpoints specifications. *)
type t = {path : Path.t; methods : methods}
(** Get the service associated to a method for a given endpoint, if any. *)
val get_method : t -> Method.t -> Service.t option
val make :
?get:Service.t ->
?post:Service.t ->
?put:Service.t ->
?delete:Service.t ->
?patch:Service.t ->
Path.t ->
t
end
module Server : sig
type t = {url : string; description : string option}
val make : ?description:string -> string -> t
end
type t = {
title : string;
description : string option;
version : string;
servers : Server.t list;
definitions : (string * Schema.t) list;
endpoints : Endpoint.t list;
}
val make :
title:string ->
?description:string ->
version:string ->
?servers:Server.t list ->
?definitions:(string * Schema.t) list ->
Endpoint.t list ->
t
val to_json : t -> Json.u
val of_json : Json.t -> t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
ezHex.ml | module Hex = struct
type t = string
let compare = String.compare
(* let equal = String.equal *)
let equal = (=)
let char_hex n =
Char.unsafe_chr (n + if n < 10 then Char.code '0' else (Char.code 'a' - 10))
let encode d =
let len = String.length d in
let result = Bytes.create (len*2) in
for i = 0 to len-1 do
let x = Char.code d.[i] in
Bytes.unsafe_set result (i*2) (char_hex (x lsr 4));
Bytes.unsafe_set result (i*2+1) (char_hex (x land 0x0f));
done;
Bytes.unsafe_to_string result
let char_hexU n =
Char.unsafe_chr (n + if n < 10 then Char.code '0' else (Char.code 'A' - 10))
let encodeU d =
let len = String.length d in
let result = Bytes.create (len*2) in
for i = 0 to len-1 do
let x = Char.code d.[i] in
Bytes.unsafe_set result (i*2) (char_hexU (x lsr 4));
Bytes.unsafe_set result (i*2+1) (char_hexU (x land 0x0f));
done;
Bytes.unsafe_to_string result
let decode s =
let len = String.length s in
if len mod 2 <> 0 then invalid_arg "Hex.decode";
let digit c =
match c with
| '0'..'9' -> Char.code c - Char.code '0'
| 'A'..'F' -> Char.code c - Char.code 'A' + 10
| 'a'..'f' -> Char.code c - Char.code 'a' + 10
| _ -> raise (Invalid_argument "Hex.decode")
in
let byte i = digit s.[i] lsl 4 + digit s.[i+1] in
let result = Bytes.create (len/2) in
for i = 0 to len/2 - 1 do
Bytes.set result i (Char.chr (byte (2 * i)));
done;
Bytes.unsafe_to_string result
let encode_bytes b = encode (Bytes.unsafe_to_string b)
let encodeU_bytes b = encodeU (Bytes.unsafe_to_string b)
let decode_bytes s = Bytes.unsafe_of_string (decode s)
end
| (**************************************************************************)
(* *)
(* Copyright 2017-2018 OCamlPro *)
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
(* GNU Lesser General Public License version 2.1, with the special *)
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
|
database.ml |
open Lwt.Syntax
module Core = Sihl_core
exception Exception of string
let log_src = Logs.Src.create ~doc:"database" "sihl.service.database"
module Logs = (val Logs.src_log log_src : Logs.LOG)
let pool_ref : (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t option ref =
ref None
;;
type config =
{ url : string
; pool_size : int option
}
let config url pool_size = { url; pool_size }
let schema =
let open Conformist in
make
[ string ~meta:"The database connection url" "DATABASE_URL"
; optional (int ~default:5 "DATABASE_POOL_SIZE")
]
config
;;
let raise_error err =
match err with
| Error err -> raise (Exception (Caqti_error.show err))
| Ok result -> result
;;
let print_pool_usage pool =
let n_connections = Caqti_lwt.Pool.size pool in
let max_connections =
Option.value (Core.Configuration.read schema).pool_size ~default:10
in
Logs.debug (fun m -> m "Pool usage: %i/%i" n_connections max_connections)
;;
let fetch_pool () =
match !pool_ref with
| Some pool ->
Logs.debug (fun m -> m "Skipping pool creation, re-using existing pool");
pool
| None ->
let pool_size = Option.value (Core.Configuration.read schema).pool_size ~default:10 in
Logs.debug (fun m -> m "Create pool with size %i" pool_size);
(Core.Configuration.read schema).url
|> Uri.of_string
|> Caqti_lwt.connect_pool ~max_size:pool_size
|> (function
| Ok pool ->
pool_ref := Some pool;
pool
| Error err ->
let msg = "Failed to connect to DB pool" in
Logs.err (fun m -> m "%s %s" msg (Caqti_error.show err));
raise (Exception ("Failed to create pool " ^ msg)))
;;
let transaction f =
let pool = fetch_pool () in
print_pool_usage pool;
let* result =
Caqti_lwt.Pool.use
(fun connection ->
Logs.debug (fun m -> m "Fetched connection from pool");
let (module Connection : Caqti_lwt.CONNECTION) = connection in
let* start_result = Connection.start () in
match start_result with
| Error msg ->
Logs.debug (fun m -> m "Failed to start transaction %s" (Caqti_error.show msg));
Lwt.return @@ Error msg
| Ok () ->
Logs.debug (fun m -> m "Started transaction");
Lwt.catch
(fun () ->
let* result = f connection in
let* commit_result = Connection.commit () in
match commit_result with
| Ok () ->
Logs.debug (fun m -> m "Successfully committed transaction");
Lwt.return @@ Ok result
| Error error ->
Logs.err (fun m ->
m "Failed to commit transaction %s" (Caqti_error.show error));
Lwt.fail @@ Exception "Failed to commit transaction")
(fun e ->
let* rollback_result = Connection.rollback () in
match rollback_result with
| Ok () ->
Logs.debug (fun m -> m "Successfully rolled back transaction");
Lwt.fail e
| Error error ->
Logs.err (fun m ->
m "Failed to rollback transaction %s" (Caqti_error.show error));
Lwt.fail @@ Exception "Failed to rollback transaction"))
pool
in
match result with
| Ok result -> Lwt.return result
| Error error ->
let msg = Caqti_error.show error in
Logs.err (fun m -> m "%s" msg);
Lwt.fail (Exception msg)
;;
let query f =
let pool = fetch_pool () in
print_pool_usage pool;
let* result =
Caqti_lwt.Pool.use (fun connection -> f connection |> Lwt.map Result.ok) pool
in
match result with
| Ok result -> Lwt.return result
| Error error ->
let msg = Caqti_error.show error in
Logs.err (fun m -> m "%s" msg);
Lwt.fail (Exception msg)
;;
(* Service lifecycle *)
let start () =
(* Make sure that database is online when starting service. *)
Core.Configuration.require schema;
let _ = fetch_pool () in
Lwt.return ()
;;
let stop _ = Lwt.return ()
let lifecycle = Core.Container.Lifecycle.create "database" ~start ~stop
let register () =
let configuration = Core.Configuration.make ~schema () in
Core.Container.Service.create ~configuration lifecycle
;;
| |
js-functor.ml |
module M =
Foo (G)
(H)
module M =
Foo
(G)
(struct
let x
end)
(H)
(* To me, this looks fine as it is. The rule seems fine as "indent arguments by
2". To illustrate, with a case where the functor name is longer: *)
module M =
Functor (G)
(H)
(I)
include Foo (struct
let x
end) (struct
let y
end)
include
Foo (struct
let x
end) (struct
let y
end)
include
Foo
(struct
let x
end) (struct
let y
end)
include Persistent.Make
(struct let version = 1 end)
(Stable.Cr_soons_or_pending.V1)
include Persistent.Make
(struct
let version = 1
end)
(Stable.Cr_soons_or_pending.V1)
include
Persistent.Make
(struct let version = 1 end)
(Stable.Cr_soons_or_pending.V1)
include
Persistent.Make
(struct
let version = 1
end)
(Stable.Cr_soons_or_pending.V1)
module M =
Foo (struct
let x
end) (struct
let y
end)
module M : S =
Make (M)
module M : S with type t := int =
Make (M)
module Simple_command(Arg:sig
end) = struct end
module Simple_command(Arg : sig
end) = struct end
module Simple_command (Arg:sig
end) = struct end
module Simple_command (Arg : sig
end) = struct end
module Simple_command
(Arg : sig
end) = struct end
| |
symbol_tables.c |
/*
* SYMBOL TABLES: MAP STRINGS TO 32BIT INTEGERS
*/
#include <assert.h>
#include <stdbool.h>
#include <string.h>
#define TRACE_RESIZE 0
#if TRACE_RESIZE
// PROVISIONAL
#include <stdio.h>
#include <inttypes.h>
#endif
#include "utils/hash_functions.h"
#include "utils/memalloc.h"
#include "utils/symbol_tables.h"
/*
* For debugging: check whether n is a power of two
*/
#ifndef NDEBUG
static bool is_power_of_two(uint32_t n) {
return (n & (n - 1)) == 0;
}
#endif
/*
* Default finalizer: do nothing
*/
static void default_stbl_finalizer(stbl_rec_t *r) {
}
/*
* Allocate and initialize a bank
*/
static stbl_bank_t *stbl_alloc_bank(void) {
stbl_bank_t *b;
uint32_t i;
b = (stbl_bank_t *) safe_malloc(sizeof(stbl_bank_t));
for (i=0; i<STBL_BANK_SIZE; i++) {
b->block[i].string = NULL;
}
return b;
}
/*
* Allocate a record
*/
static stbl_rec_t *stbl_alloc_record(stbl_t *sym_table) {
stbl_rec_t *tmp;
stbl_bank_t *new_bnk;
uint32_t i;
tmp = sym_table->free_rec;
if (tmp != NULL) {
assert(sym_table->ndeleted > 0);
sym_table->free_rec = tmp->next;
sym_table->ndeleted --;
return tmp;
}
i = sym_table->free_idx;
if (i == 0) {
new_bnk = stbl_alloc_bank();
new_bnk->next = sym_table->bnk;
sym_table->bnk = new_bnk;
i = STBL_BANK_SIZE;
}
assert(i > 0);
i --;
tmp = sym_table->bnk->block + i;
sym_table->free_idx = i;
return tmp;
}
/*
* Free a record: put it on the free list
*/
static void stbl_free_record(stbl_t *sym_table, stbl_rec_t *r) {
assert(r != NULL);
r->string = NULL;
r->next = sym_table->free_rec;
sym_table->free_rec = r;
sym_table->ndeleted ++;
}
/*
* Initialize a record: store h, val, and s.
*/
static void stbl_init_record(stbl_rec_t *r, uint32_t h, int32_t val, char *s) {
r->hash = h;
r->value = val;
r->string = s;
}
/*
* Insert all the records from list into array tmp
* - mask = size of tmp - 1 (tmp's size is a power of 2)
* - the records are inserted in reverse order
*/
static void stbl_restore_list(stbl_rec_t **tmp, uint32_t mask, stbl_rec_t *list) {
stbl_rec_t *r, *p;
uint32_t i;
// reverse the list
p = NULL;;
while (list != NULL) {
r = list->next;
list->next = p;
p = list;
list = r;
}
// now p = list in reverse order
while (p != NULL) {
r = p->next;
assert(p->string != NULL);
i = p->hash & mask;
p->next = tmp[i];
tmp[i] = p;
p = r;
}
}
/*
* Extend the table: make it twice as large.
* - do nothing if malloc fails or if the table has maximal size already
*/
static void stbl_extend(stbl_t *sym_table) {
stbl_rec_t **tmp;
stbl_rec_t *list;
uint32_t i, n, old_size, mask;
old_size = sym_table->size;
n = old_size << 1;
if (n == 0 || n >= MAX_STBL_SIZE) {
// overflow: cannot expand
return;
}
assert(is_power_of_two(n));
// new data array
tmp = (stbl_rec_t **) malloc(n * sizeof(stbl_rec_t *));
if (tmp == NULL) return;
for (i=0; i<n; i++) {
tmp[i] = NULL;
}
// move the data lists to tmp
mask = n-1;
for (i=0; i<old_size; i++) {
list = sym_table->data[i];
if (list != NULL) {
stbl_restore_list(tmp, mask, list);
}
}
// clean up
safe_free(sym_table->data);
sym_table->data = tmp;
sym_table->size = n;
#if TRACE_RESIZE
printf("resize table %p: cost = %"PRIu32", nelems = %"PRIu32", ndeleted = %"PRIu32
", old size = %"PRIu32", new size = %"PRIu32"\n",
sym_table, sym_table->cost, sym_table->nelems, sym_table->ndeleted, old_size, n);
fflush(stdout);
#endif
}
/*
* Initialize: empty table of size n. n must be a power of 2.
* If n = 0, the default size is used.
*/
void init_stbl(stbl_t *sym_table, uint32_t n) {
uint32_t i;
stbl_rec_t **tmp;
if (n == 0) {
n = STBL_DEFAULT_SIZE;
}
if (n >= MAX_STBL_SIZE) {
out_of_memory(); // abort if too large
}
assert(is_power_of_two(n));
tmp = (stbl_rec_t**) safe_malloc(n * sizeof(stbl_rec_t *));
for (i=0; i<n; i++) {
tmp[i] = NULL;
}
sym_table->data = tmp;
sym_table->bnk = NULL;
sym_table->free_rec = NULL;
sym_table->size = n;
sym_table->nelems = 0;
sym_table->ndeleted = 0;
sym_table->free_idx = 0;
sym_table->lctr = STBL_NLOOKUPS;
sym_table->cost = 0;
sym_table->finalize = default_stbl_finalizer;
}
/*
* Delete all the table
*/
void delete_stbl(stbl_t *sym_table) {
stbl_bank_t *b, *next;
stbl_rec_t *r;
uint32_t k;
#if TRACE_RESIZE
printf("delete table %p: cost = %"PRIu32", nelems = %"PRIu32", ndeleted = %"PRIu32", size = %"PRIu32"\n",
sym_table, sym_table->cost, sym_table->nelems, sym_table->ndeleted, sym_table->size);
fflush(stdout);
#endif
b = sym_table->bnk;
sym_table->bnk = NULL;
k = sym_table->free_idx; // first live record in first bank
while (b != NULL) {
// apply finalizer to all live records
for (r = b->block + k; r < b->block + STBL_BANK_SIZE; r ++) {
if (r->string != NULL) {
sym_table->finalize(r);
}
}
// delete b
next = b->next;
safe_free(b);
b = next;
k = 0;
}
safe_free(sym_table->data);
sym_table->data = NULL;
}
/*
* Empty the table
*/
void reset_stbl(stbl_t *sym_table) {
uint32_t i, n;
stbl_rec_t *r, *p;
n = sym_table->size;
for (i=0; i<n; i++) {
r = sym_table->data[i];
while (r != NULL) {
p = r->next;
sym_table->finalize(r);
stbl_free_record(sym_table, r);
r = p;
}
sym_table->data[i] = NULL;
}
sym_table->nelems = 0;
sym_table->lctr = STBL_NLOOKUPS;
sym_table->cost = 0;
}
/*
* Remove first occurrence of symbol.
* No effect if symbol is not present.
*/
void stbl_remove(stbl_t *sym_table, const char *symbol) {
uint32_t h, mask, i;
stbl_rec_t *r, *p;
mask = sym_table->size - 1;
h = jenkins_hash_string(symbol);
i = h & mask;
p = NULL;
for (r = sym_table->data[i]; r != NULL; r = r->next) {
if (r->hash == h && strcmp(symbol, r->string) == 0) {
if (p == NULL) {
sym_table->data[i] = r->next;
} else {
p->next = r->next;
}
sym_table->finalize(r);
stbl_free_record(sym_table, r);
return;
}
p = r;
}
}
/*
* Remove the first occurrence of (symbol, value).
* No effect if it's not present.
*/
void stbl_delete_mapping(stbl_t *sym_table, const char *symbol, int32_t val) {
uint32_t h, mask, i;
stbl_rec_t *r, *p;
mask = sym_table->size - 1;
h = jenkins_hash_string(symbol);
i = h & mask;
p = NULL;
for (r = sym_table->data[i]; r != NULL; r = r->next) {
if (r->hash == h && r->value == val && strcmp(symbol, r->string) == 0) {
if (p == NULL) {
sym_table->data[i] = r->next;
} else {
p->next = r->next;
}
sym_table->finalize(r);
stbl_free_record(sym_table, r);
return;
}
p = r;
}
}
/*
* Check whether the list sym_table->data[i] has many duplicates
* - r must either be NULL or be a pointer to one list record (not the first one)
* - return true if all elements before r have the same hash code
* - in such a case, and if r is not NULL, we move r to the front
* of the list
*/
static bool list_has_duplicates(stbl_t *sym_table, uint32_t i, stbl_rec_t *r) {
stbl_rec_t *p, *l;
uint32_t h;
assert(i < sym_table->size);
l = sym_table->data[i];
h = l->hash;
assert(l != r);
for (;;) {
p = l;
l = l->next;
if (l == r) break;
if (l->hash != h) return false;
}
/*
* all elements before r have the same hash code
* p = predecessor of r
*/
assert(p->next == r && p->hash == h);
if (r != NULL) {
p->next = r->next;
r->next = sym_table->data[i];
sym_table->data[i] = r;
}
return true;
}
/*
* Return value of first occurrence of symbol, or -1 if symbol is not
* present.
* - update the cost
*/
int32_t stbl_find(stbl_t *sym_table, const char *symbol) {
uint32_t mask, i, h, steps;
int32_t result;
stbl_rec_t *r;
result = -1;
steps = 0;
mask = sym_table->size - 1;
h = jenkins_hash_string(symbol);
i = h & mask;
for (r = sym_table->data[i]; r != NULL; r = r->next) {
steps ++;
if (r->hash == h && strcmp(symbol, r->string) == 0) {
result = r->value;
break;
}
}
/*
* Check whether the list contains many duplicates and move r to the
* front if possible. If the list has duplicates, we reduce steps to 1,
* since resizing won't help much.
*/
if (steps > STBL_MAXVISITS && list_has_duplicates(sym_table, i, r)) {
steps = 1;
}
/*
* Update cost and counter. Resize if the last NLOOKUPS have a
* high total cost.
*/
assert(sym_table->lctr > 0);
sym_table->cost += steps;
sym_table->lctr --;
if (sym_table->lctr == 0) {
if (sym_table->cost > STBL_RESIZE_THRESHOLD && sym_table->size <= (MAX_STBL_SIZE/2)) {
stbl_extend(sym_table);
}
sym_table->cost = 0;
sym_table->lctr = STBL_NLOOKUPS;
}
return result;
}
/*
* Add new mapping for symbol.
*/
void stbl_add(stbl_t *sym_table, char *symbol, int32_t value) {
uint32_t mask, i, h;
stbl_rec_t *r;
assert(value >= 0);
mask = sym_table->size - 1;
h = jenkins_hash_string(symbol);
i = h & mask;
r = stbl_alloc_record(sym_table);
stbl_init_record(r, h, value, symbol);
r->next = sym_table->data[i];
sym_table->data[i] = r;
sym_table->nelems ++;
}
/*
* Iterator: call f(aux, r) for every live record r in the table
* - aux is an arbitrary pointer, provided by the caller
* - f must not have side effects (it must not add or remove anything
* from the symbol table, or modify the record r).
*/
void stbl_iterate(stbl_t *sym_table, void *aux, stbl_iterator_t f) {
stbl_bank_t *b;
stbl_rec_t *r;
uint32_t k;
k = sym_table->free_idx;
for (b = sym_table->bnk; b != NULL; b = b->next) {
for (r = b->block + k; r < b->block + STBL_BANK_SIZE; r++) {
if (r->string != NULL) {
// r is a live record
f(aux, r);
}
}
k = 0;
}
}
/*
* Remove records using a filter
* - calls f(aux, r) on every record r present in the table
* - if f(aux, r) returns true, then the finalizer is called
* then r is removed from the table.
* - f must not have side effects
*/
void stbl_remove_records(stbl_t *sym_table, void *aux, stbl_filter_t f) {
uint32_t i, n;
stbl_rec_t *r, *p, **q;
n = sym_table->size;
for (i=0; i<n; i++) {
q = sym_table->data + i;
r = sym_table->data[i];
while (r != NULL) {
p = r->next;
if (f(aux, r)) {
sym_table->finalize(r);
stbl_free_record(sym_table, r);
r = p;
} else {
// keep r
*q = r;
q = &r->next;
}
}
*q = NULL;
}
}
| /*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/ |
partial_memory.mli |
include Memory_sig.S
val content : memory -> Chunked_byte_vector.t
| |
cryptokitBignum.mli | (** Operations on big integers, used for the implementation of module
{!Cryptokit}. *)
type t
val zero : t
val one : t
val of_int : int -> t
val compare : t -> t -> int
val add : t -> t -> t
val sub : t -> t -> t
val mult : t -> t -> t
val mod_ : t -> t -> t
val relative_prime : t -> t -> bool
val mod_power : t -> t -> t -> t
val mod_power_CRT : t -> t -> t -> t -> t -> t -> t
val mod_inv : t -> t -> t
val of_bytes : string -> t
val to_bytes : ?numbits:int -> t -> string
val random : rng:(bytes -> int -> int -> unit) -> ?odd:bool -> int -> t
val random_prime : rng:(bytes -> int -> int -> unit) -> int -> t
val wipe : t -> unit
| (***********************************************************************)
(* *)
(* The Cryptokit library *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 2002 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the GNU Library General Public License, with *)
(* the special exception on linking described in file LICENSE. *)
(* *)
(***********************************************************************)
|
typing_errors.ml | (* file: typing_errors.ml *)
(* Warning: *)
(* This file has been done from CamlLight, Lucid Synchrone and the book *)
(* "Le langage Caml" Pierre Weis Xavier Leroy *)
(* created: 2004-05-13 *)
(* author: Louis Mandel *)
(* $Id$ *)
(* Printing of error messages during typing *)
open Misc
open Def_types
open Types
open Reac_ast
(* type clash *)
let expr_wrong_type_err exp actual_ty expected_ty =
Format.fprintf !err_fmt
"%aThis expression has type %a,\n\
but is used with type %a.\n"
Location.print exp.expr_loc
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let patt_wrong_type_err patt actual_ty expected_ty =
Format.fprintf !err_fmt
"%aThis pattern has type %a,\n\
but is used with type %a.\n"
Location.print patt.patt_loc
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let event_wrong_type_err evt actual_ty expected_ty =
Format.fprintf !err_fmt
"The event %s has type %a,\n\
but is used with type %a.\n"
(Ident.name evt)
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let emit_wrong_type_err loc actual_ty expected_ty =
Format.fprintf !err_fmt
"%aThe emitted value has type %a,\n\
but is used with type %a.\n"
Location.print loc
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let run_wrong_type_err loc actual_ty expected_ty =
Format.fprintf !err_fmt
"%aThis expression has type %a,\n\
but is used with type %a.\n"
Location.print loc
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let var_wrong_type_err loc actual_ty expected_ty =
Format.fprintf !err_fmt
"%aThis pattern has type %a,\n\
but is used with type %a.\n"
Location.print loc
Types_printer.output actual_ty
Types_printer.output expected_ty;
raise Error
let application_of_non_function_err exp ty =
begin try
let _ = filter_arrow ty in
Format.fprintf !err_fmt
"%aThis function is applied to too many arguments.\n"
Location.print exp.expr_loc
with Unify ->
Format.fprintf !err_fmt
"%aThis expression is not a function, it cannot be applied.\n"
Location.print exp.expr_loc
end;
raise Error
let non_event_err exp =
Format.fprintf !err_fmt
"%aThis expression is not an event.\n"
Location.print exp.expr_loc;
raise Error
let non_event_err2 conf =
Format.fprintf !err_fmt
"%aThis expression is not an event.\n"
Location.print conf.conf_loc;
raise Error
let non_event_patt_err conf =
Format.fprintf !err_fmt
"%aThis expression is not an event with a pattern.\n"
Location.print conf.conf_loc;
raise Error
let partial_match_err conf =
Format.fprintf !err_fmt
"%aPartial match is not allowed.\n"
Location.print conf.conf_loc;
raise Error
(* typing errors *)
(* unbound *)
let unbound_typ_err name loc =
Format.fprintf !err_fmt "%aThe type variable \'%s is unbound.\n"
Location.print loc name;
raise Error
let unbound_typ_constr_err gr loc =
Format.fprintf !err_fmt "%aThe type constructor %a is unbound.\n"
Location.print loc
Global_ident.print gr;
raise Error
let unbound_global_ident_err gr loc =
Format.fprintf !err_fmt "%aThe name %a is unbound.\n"
Location.print loc
Global_ident.print gr;
raise Error
let unbound_ident_err n loc =
Format.fprintf !err_fmt "%aThe name %s is unbound.\n"
Location.print loc
(Ident.name n);
raise Error
let unbound_constructor_err c loc =
Format.fprintf !err_fmt "%aThe constructor %a is unbound.\n"
Location.print loc
Global_ident.print c;
raise Error
let unbound_label_err label loc =
Format.fprintf !err_fmt "%aThe label %a is unbound.\n"
Location.print loc
Global_ident.print label;
raise Error
(* arity *)
let constr_arity_err gr loc =
Format.fprintf !err_fmt "%aThe value constructor %a expects 1 argument, \
but is here applied to 0 argument.\n"
Location.print loc
Global_ident.print gr;
raise Error
let constr_arity_err_2 gr loc =
Format.fprintf !err_fmt "%aThe value constructor %a expects 0 argument, \
but is here applied to 1 argument.\n"
Location.print loc
Global_ident.print gr;
raise Error
let type_constr_arity_err gr arit' arit loc =
Format.fprintf !err_fmt "%aThe type constructor %a expects %d argument(s), \
but is here given %d argument(s).\n"
Location.print loc
Global_ident.print gr
arit'
arit;
raise Error
(* bound several times *)
let non_linear_pattern_err pat n =
Format.fprintf !err_fmt
"%aThe variable %s is bound several times in this pattern.\n"
Location.print pat.patt_loc n;
raise Error
let non_linear_config_err conf n =
Format.fprintf !err_fmt
"%aThe variable %s is bound several times in this event configuration.\n"
Location.print conf.conf_loc n;
raise Error
let non_linear_record_err label loc =
Format.fprintf !err_fmt
"%aThe label %a is defined several times\n"
Location.print loc
Global_ident.print label;
raise Error
let repeated_constructor_definition_err s loc =
Format.fprintf !err_fmt "%aTwo constructors are named %s\n"
Location.print loc s;
raise Error
let repeated_label_definition_err s loc =
Format.fprintf !err_fmt "%aTwo labels are named %s\n"
Location.print loc s;
raise Error
let orpat_vars loc s =
Format.fprintf !err_fmt
"%aVariable %s must occur on both sides of this | pattern.\n"
Location.print loc s;
raise Error
let orconfig_vars loc s =
Format.fprintf !err_fmt
"%aVariable %s must occur on both branchs of this \\/ configuration.\n"
Location.print loc s;
raise Error
(* label *)
let label_not_mutable_err exp lbl =
Format.fprintf !err_fmt "%aThe label %a is not mutable.\n"
Location.print exp.expr_loc
Global_ident.print lbl;
raise Error
(* Top level *)
let cannot_generalize_err expr =
Format.fprintf !err_fmt
"%aThe type of this expression, %a,\n\
contains type variables that cannot be generalized"
Location.print expr.expr_loc
Types_printer.output expr.expr_type;
raise Error
;;
let cannot_generalize_err2 loc typ =
Format.fprintf !err_fmt
"%aThe type of this declaration, %a,\n\
contains type variables that cannot be generalized"
Location.print loc
Types_printer.output typ;
raise Error
;;
(* Warnings *)
let partial_apply_warning loc =
Format.fprintf !err_fmt "%aWarning: this function application is partial,\n\
maybe some arguments are missing.\n"
Location.print loc
let not_unit_type_warning expr =
Format.fprintf !err_fmt "%aWarning: this expression should have type unit.\n"
Location.print expr.expr_loc
| (**********************************************************************)
(* *)
(* ReactiveML *)
(* http://reactiveML.org *)
(* http://rml.inria.fr *)
(* *)
(* Louis Mandel *)
(* *)
(* Copyright 2002, 2007 Louis Mandel. All rights reserved. *)
(* This file is distributed under the terms of the Q Public License *)
(* version 1.0. *)
(* *)
(* ReactiveML has been done in the following labs: *)
(* - theme SPI, Laboratoire d'Informatique de Paris 6 (2002-2005) *)
(* - Verimag, CNRS Grenoble (2005-2006) *)
(* - projet Moscova, INRIA Rocquencourt (2006-2007) *)
(* *)
(**********************************************************************)
|
pa_lispr.ml | open Pcaml;
open Versdep;
(* Buffer *)
module Buff =
struct
value buff = ref (string_create 80);
value store len x = do {
if len >= string_length buff.val then
buff.val :=
string_cat buff.val (string_create (string_length buff.val))
else ();
string_set buff.val len x;
succ len
};
value get len = bytes_to_string (string_sub buff.val 0 len);
end
;
(* Lexer *)
value rec skip_to_eol len =
parser
[ [: `('\n' | '\r' as c) :] -> Buff.store len c
| [: `c :] ->
let s = strm__ in
skip_to_eol (Buff.store len c) s ]
;
value no_ident = ['('; ')'; ' '; '\t'; '\n'; '\r'; ';'];
value rec ident len =
parser
[: :] ->
match Stream.peek strm__ with
[ Some x when not (List.mem x no_ident) → do {
Stream.junk strm__;
let s = strm__ in
ident (Buff.store len x) s
}
| _ → Buff.get len ]
;
value rec string len =
parser
[ [: `'"' :] -> Buff.get len
| [: `'\\'; `c :] ->
let s = strm__ in
string (Buff.store (Buff.store len '\\') c) s
| [: `x :] ->
let s = strm__ in
string (Buff.store len x) s ]
;
value rec number len =
parser
[ [: `('0'..'9' as c) :] ->
let s = strm__ in
number (Buff.store len c) s
| [: :] -> ("INT", Buff.get len) ]
;
value char_or_quote_id x =
parser
[ [: `''' :] -> ("CHAR", String.make 1 x)
| [: :] ->
let s = strm__ in
let len = Buff.store (Buff.store 0 ''') x in
("LIDENT", ident len s) ]
;
value rec char len =
parser
[ [: `''' :] -> len
| [: `x :] ->
let s = strm__ in
char (Buff.store len x) s ]
;
value quote =
parser
[ [: `'\\'; len = char (Buff.store 0 '\\') :] -> ("CHAR", Buff.get len)
| [: `x :] ->
let s = strm__ in
char_or_quote_id x s ]
;
value rec next_token_after_spaces kwt =
parser bp
[ [: `'(' :] -> (("", "("), (bp, bp + 1))
| [: `')' :] -> (("", ")"), (bp, bp + 1))
| [: `'"'; s = string 0 :] ->
let ep = Stream.count strm__ in
(("STRING", s), (bp, ep))
| [: `'''; tok = quote :] ->
let ep = Stream.count strm__ in
(tok, (bp, ep))
| [: `'<'; tok = less :] ->
let ep = Stream.count strm__ in
(tok, (bp, ep))
| [: `('0'..'9' as c); n = number (Buff.store 0 c) :] ->
let ep = Stream.count strm__ in
(n, (bp, ep))
| [: `x; s = ident (Buff.store 0 x) :] ->
let ep = Stream.count strm__ in
let con =
try do {
(Hashtbl.find kwt s : unit);
""
}
with
[ Not_found →
match x with
[ 'A'..'Z' → "UIDENT"
| _ → "LIDENT" ] ]
in
((con, s), (bp, ep))
| [: :] -> (("EOI", ""), (bp, bp + 1)) ]
and less =
parser
[ [: `':'; lab = label 0; `'<' ? "'<' expected"; q = quotation 0 :] ->
("QUOT", lab ^ ":" ^ q)
| [: :] -> ("LIDENT", "<") ]
and label len =
parser
[ [: `('a'..'z' | 'A'..'Z' | '_' as c) :] ->
let s = strm__ in
label (Buff.store len c) s
| [: :] -> Buff.get len ]
and quotation len =
parser
[ [: `'>' :] ->
let s = strm__ in
quotation_greater len s
| [: `x :] ->
let s = strm__ in
quotation (Buff.store len x) s
| [: :] -> failwith "quotation not terminated" ]
and quotation_greater len =
parser
[ [: `'>' :] -> Buff.get len
| [: a = quotation (Buff.store len '>') :] -> a ]
;
value get_buff len _ = Buff.get len;
value rec lexer len kwt =
parser bp
[ [: `(' ' | '\t' | '\n' | '\r' as c) :] ->
let s = strm__ in
lexer (Buff.store len c) kwt s
| [: `';'; a = semi (Buff.store len ';') kwt bp :] -> a
| [: comm = get_buff len; a = next_token_after_spaces kwt :] -> (comm, a) ]
and semi len kwt bp =
parser
[ [: `';'; len = skip_to_eol (Buff.store len ';') :] ->
let s = strm__ in
lexer len kwt s
| [: :] ->
let ep = Stream.count strm__ in
(Buff.get len, (("", ";"), (bp, ep))) ]
;
value lexer_using kwt (con, prm) =
match con with
[ "CHAR" | "EOI" | "INT" | "LIDENT" | "QUOT" | "STRING" | "UIDENT" → ()
| "ANTIQUOT" | "ANTIQUOT_LOC" → ()
| "" → try Hashtbl.find kwt prm with [ Not_found → Hashtbl.add kwt prm () ]
| _ →
raise
(Plexing.Error
("the constructor \"" ^ con ^ "\" is not recognized by Plexer")) ]
;
value lexer_text (con, prm) =
if con = "" then "'" ^ prm ^ "'"
else if prm = "" then con
else con ^ " \"" ^ prm ^ "\""
;
value lexer_gmake () =
let kwt = Hashtbl.create 89
and lexer2 kwt (s, _, _) =
let (comm, (t, loc)) = lexer 0 kwt s in
(t, Ploc.make_loc Plexing.input_file.val 0 0 loc comm)
in
{Plexing.tok_func = Plexing.lexer_func_of_parser (lexer2 kwt);
Plexing.tok_using = lexer_using kwt; Plexing.tok_removing = fun [];
Plexing.tok_match = Plexing.default_match; Plexing.tok_text = lexer_text;
Plexing.tok_comm = None}
;
(* Building AST *)
type sexpr =
[ Sexpr of MLast.loc and list sexpr
| Satom of MLast.loc and atom and string
| Squot of MLast.loc and string and string ]
and atom = [ Alid | Auid | Aint | Achar | Astring ];
value error_loc loc err = Ploc.raise loc (Stream.Error (err ^ " expected"));
value error se err =
let loc =
match se with [ Satom loc _ _ | Sexpr loc _ | Squot loc _ _ → loc ]
in
error_loc loc err
;
value expr_id loc s =
match s.[0] with
[ 'A'..'Z' → <:expr< $uid:s$ >>
| _ → <:expr< $lid:s$ >> ]
;
value is_lident s =
match s.[0] with
[ 'A'..'Z' → False
| _ → True ]
;
value patt_id loc s =
match s.[0] with
[ 'A'..'Z' → <:patt< $uid:s$ >>
| _ → <:patt< $lid:s$ >> ]
;
value ctyp_id loc s =
match s.[0] with
[ ''' →
let s = String.sub s 1 (String.length s - 1) in
<:ctyp< '$s$ >>
| 'A'..'Z' → failwith "must not call ctyp_id with UIDs"
| _ → <:ctyp< $lid:s$ >> ]
;
value split_at_dots loc s =
loop 0 0 where rec loop ibeg i =
if i = String.length s then
if i > ibeg then [ (String.sub s ibeg (i - ibeg)) ]
else Ploc.raise (Ploc.sub loc (i - 1) 1) (Stream.Error "ctyp expected")
else if s.[i] = '.' then
if i > ibeg then
let t1 = [ (String.sub s ibeg (i - ibeg)) ] in
let t2 = loop (i + 1) (i + 1) in
t1 @ t2
else Ploc.raise (Ploc.sub loc (i - 1) 1) (Stream.Error "ctyp expected")
else loop ibeg (i + 1)
;
value split_last l =
match List.rev l with [
[] -> failwith "split_last: empty list"
| [ h :: t ] -> (List.rev t, h)
]
;
value capitalized s =
match s.[0] with [ 'A'..'Z' -> True | _ -> False ]
;
value strm_n = "strm__";
value peek_fun loc = <:expr< Stream.peek >>;
value junk_fun loc = <:expr< Stream.junk >>;
value rec module_expr_se =
fun
[ Sexpr loc [Satom _ Alid "struct" :: sl] →
let mel = List.map str_item_se sl in
<:module_expr< struct $list:mel$ end >>
| Satom loc Auid s → <:module_expr< $uid:s$ >>
| se → error se "module expr" ]
and str_item_se se =
match se with
[ Satom loc _ _ | Squot loc _ _ →
let e = expr_se se in
<:str_item< $exp:e$ >>
| Sexpr loc [Satom _ Alid "module"; Satom _ Auid i; se] →
let mb = module_binding_se se in
<:str_item< module $uid:i$ = $mb$ >>
| Sexpr loc [Satom _ Alid "open"; Satom _ Auid s] →
<:str_item< open $uid:s$ >>
| Sexpr loc [Satom _ Alid "type" :: sel] →
let tdl = type_declaration_list_se sel in
<:str_item< type $list:tdl$ >>
| Sexpr loc [Satom _ Alid "value" :: sel] →
let (r, sel) =
match sel with
[ [Satom _ Alid "rec" :: sel] → (True, sel)
| _ → (False, sel) ]
in
let lbs = value_binding_se sel in
<:str_item< value $flag:r$ $list:lbs$ >>
| Sexpr loc _ →
let e = expr_se se in
<:str_item< $exp:e$ >> ]
and value_binding_se =
fun
[ [se1; se2 :: sel] → [(ipatt_se se1, expr_se se2, <:vala< [] >>) :: value_binding_se sel]
| [] → []
| [se :: _] → error se "value_binding" ]
and module_binding_se se = module_expr_se se
and expr_se =
fun
[ Satom loc (Alid | Auid) s → expr_ident_se loc s
| Satom loc Aint s → <:expr< $int:s$ >>
| Satom loc Achar s → <:expr< $chr:s$ >>
| Satom loc Astring s → <:expr< $str:s$ >>
| Sexpr loc [] → <:expr< () >>
| Sexpr loc [Satom _ Alid "if"; se; se1] →
let e = expr_se se in
let e1 = expr_se se1 in
<:expr< if $e$ then $e1$ else () >>
| Sexpr loc [Satom _ Alid "if"; se; se1; se2] →
let e = expr_se se in
let e1 = expr_se se1 in
let e2 = expr_se se2 in
<:expr< if $e$ then $e1$ else $e2$ >>
| Sexpr loc [Satom loc1 Alid "lambda"] → <:expr< fun [] >>
| Sexpr loc [Satom loc1 Alid "lambda"; sep :: sel] →
let e = progn_se loc1 sel in
match ipatt_opt_se sep with
[ Left p → <:expr< fun $p$ -> $e$ >>
| Right (se, sel) →
List.fold_right
(fun se e →
let p = ipatt_se se in
<:expr< fun $p$ -> $e$ >>)
[se :: sel] e ]
| Sexpr loc [Satom _ Alid "lambda_match" :: sel] →
let pel = List.map (match_case loc) sel in
<:expr< fun [ $list:pel$ ] >>
| Sexpr loc [Satom _ Alid "let" :: sel] →
let (r, sel) =
match sel with
[ [Satom _ Alid "rec" :: sel] → (True, sel)
| _ → (False, sel) ]
in
match sel with
[ [Sexpr _ sel1 :: sel2] →
let lbs = List.map let_binding_se sel1 in
let e = progn_se loc sel2 in
<:expr< let $flag:r$ $list:lbs$ in $e$ >>
| [se :: _] → error se "let_binding"
| _ → error_loc loc "let_binding" ]
| Sexpr loc [Satom _ Alid "let*" :: sel] →
match sel with
[ [Sexpr _ sel1 :: sel2] →
List.fold_right
(fun se ek →
let (p, e, _) = let_binding_se se in
<:expr< let $p$ = $e$ in $ek$ >>)
sel1 (progn_se loc sel2)
| [se :: _] → error se "let_binding"
| _ → error_loc loc "let_binding" ]
| Sexpr loc [Satom _ Alid "match"; se :: sel] →
let e = expr_se se in
let pel = List.map (match_case loc) sel in
<:expr< match $e$ with [ $list:pel$ ] >>
| Sexpr loc [Satom _ Alid "parser" :: sel] →
let e =
match sel with
[ [(Satom _ _ _ as se) :: sel] →
let p = patt_se se in
let pc = parser_cases_se loc sel in
<:expr< let $p$ = Stream.count $lid:strm_n$ in $pc$ >>
| _ → parser_cases_se loc sel ]
in
<:expr< fun ($lid:strm_n$ : Stream.t _) -> $e$ >>
| Sexpr loc [Satom _ Alid "try"; se :: sel] →
let e = expr_se se in
let pel = List.map (match_case loc) sel in
<:expr< try $e$ with [ $list:pel$ ] >>
| Sexpr loc [Satom _ Alid "progn" :: sel] →
let el = List.map expr_se sel in
<:expr< do { $list:el$ } >>
| Sexpr loc [Satom _ Alid "while"; se :: sel] →
let e = expr_se se in
let el = List.map expr_se sel in
<:expr< while $e$ do { $list:el$ } >>
| Sexpr loc [Satom _ Alid ":="; se1; se2] →
let e2 = expr_se se2 in
match expr_se se1 with
[ <:expr< $uid:"()"$ $e1$ $i$ >> → <:expr< $e1$.($i$) := $e2$ >>
| e1 → <:expr< $e1$ := $e2$ >> ]
| Sexpr loc [Satom _ Alid "[]"; se1; se2] →
let e1 = expr_se se1 in
let e2 = expr_se se2 in
<:expr< $e1$.[$e2$] >>
| Sexpr loc [Satom _ Alid "," :: sel] →
let el = List.map expr_se sel in
<:expr< ( $list:el$ ) >>
| Sexpr loc [Satom _ Alid "{}" :: sel] →
let lel = List.map (label_expr_se loc) sel in
<:expr< { $list:lel$ } >>
| Sexpr loc [Satom _ Alid ":"; se1; se2] →
let e = expr_se se1 in
let t = ctyp_se se2 in
<:expr< ( $e$ : $t$ ) >>
| Sexpr loc [Satom _ Alid "list" :: sel] →
loop sel where rec loop =
fun
[ [] → <:expr< [] >>
| [se1; Satom _ Alid "::"; se2] →
let e = expr_se se1 in
let el = expr_se se2 in
<:expr< [$e$ :: $el$] >>
| [se :: sel] →
let e = expr_se se in
let el = loop sel in
<:expr< [$e$ :: $el$] >> ]
| Sexpr loc [se :: sel] →
List.fold_left
(fun e se →
let e1 = expr_se se in
<:expr< $e$ $e1$ >>)
(expr_se se) sel
| Squot loc typ txt → Pcaml.handle_expr_quotation loc (typ, txt) ]
and progn_se loc =
fun
[ [] → <:expr< () >>
| [se] → expr_se se
| sel →
let el = List.map expr_se sel in
<:expr< do { $list:el$ } >> ]
and let_binding_se =
fun
[ Sexpr loc [se1; se2] → (ipatt_se se1, expr_se se2, <:vala< [] >>)
| se → error se "let_binding" ]
and match_case loc =
fun
[ Sexpr _ [se1; se2] → (patt_se se1, <:vala< None >>, expr_se se2)
| Sexpr _ [se1; sew; se2] →
(patt_se se1, <:vala< (Some (expr_se sew)) >>, expr_se se2)
| se → error se "match_case" ]
and label_expr_se loc =
fun
[ Sexpr _ [se1; se2] → (patt_se se1, expr_se se2)
| se → error se "label_expr" ]
and expr_ident_se loc s =
if s.[0] = '<' then <:expr< $lid:s$ >>
else
let l = Versdep.split_on_char '.' s in
Asttools.expr_of_string_list loc l
and parser_cases_se loc =
fun
[ [] → <:expr< raise Stream.Failure >>
| [Sexpr loc [Sexpr _ spsel :: act] :: sel] →
let ekont _ = parser_cases_se loc sel in
let act =
match act with
[ [se] → expr_se se
| [sep; se] →
let p = patt_se sep in
let e = expr_se se in
<:expr< let $p$ = Stream.count $lid:strm_n$ in $e$ >>
| _ → error_loc loc "parser_case" ]
in
stream_pattern_se loc act ekont spsel
| [se :: _] → error se "parser_case" ]
and stream_pattern_se loc act ekont =
fun
[ [] → act
| [se :: sel] →
let ckont err = <:expr< raise (Stream.Error $err$) >> in
let skont = stream_pattern_se loc act ckont sel in
stream_pattern_component skont ekont <:expr< "" >> se ]
and stream_pattern_component skont ekont err =
fun
[ Sexpr loc [Satom _ Alid "`"; se :: wol] →
let wo =
match wol with
[ [se] → Some (expr_se se)
| [] → None
| _ → error_loc loc "stream_pattern_component" ]
in
let e = peek_fun loc in
let p = patt_se se in
let j = junk_fun loc in
let k = ekont err in
<:expr< match $e$ $lid:strm_n$ with
[ Some $p$ $opt:wo$ -> do { $j$ $lid:strm_n$ ; $skont$ }
| _ -> $k$ ] >>
| Sexpr loc [se1; se2] →
let p = patt_se se1 in
let e =
let e = expr_se se2 in
<:expr< try Some ($e$ $lid:strm_n$) with [ Stream.Failure -> None ] >>
in
let k = ekont err in
<:expr< match $e$ with [ Some $p$ -> $skont$ | _ -> $k$ ] >>
| Sexpr loc [Satom _ Alid "?"; se1; se2] →
stream_pattern_component skont ekont (expr_se se2) se1
| Satom loc Alid s → <:expr< let $lid:s$ = $lid:strm_n$ in $skont$ >>
| se → error se "stream_pattern_component" ]
and patt_se =
fun
[ Satom loc Alid "_" → <:patt< _ >>
| Satom loc (Alid | Auid) s → patt_ident_se loc s
| Satom loc Aint s → <:patt< $int:s$ >>
| Satom loc Achar s → <:patt< $chr:s$ >>
| Satom loc Astring s → <:patt< $str:s$ >>
| Sexpr loc [Satom _ Alid "or"; se :: sel] →
List.fold_left
(fun p se →
let p1 = patt_se se in
<:patt< $p$ | $p1$ >>)
(patt_se se) sel
| Sexpr loc [Satom _ Alid "range"; se1; se2] →
let p1 = patt_se se1 in
let p2 = patt_se se2 in
<:patt< $p1$ .. $p2$ >>
| Sexpr loc [Satom _ Alid "," :: sel] →
let pl = List.map patt_se sel in
<:patt< ( $list:pl$ ) >>
| Sexpr loc [Satom _ Alid "as"; se1; se2] →
let p1 = patt_se se1 in
let p2 = patt_se se2 in
<:patt< ($p1$ as $p2$) >>
| Sexpr loc [Satom _ Alid "list" :: sel] →
loop sel where rec loop =
fun
[ [] → <:patt< [] >>
| [se1; Satom _ Alid "::"; se2] →
let p = patt_se se1 in
let pl = patt_se se2 in
<:patt< [$p$ :: $pl$] >>
| [se :: sel] →
let p = patt_se se in
let pl = loop sel in
<:patt< [$p$ :: $pl$] >> ]
| Sexpr loc [se :: sel] →
List.fold_left
(fun p se →
let p1 = patt_se se in
<:patt< $p$ $p1$ >>)
(patt_se se) sel
| Sexpr loc [] → <:patt< () >>
| Squot loc typ txt → Pcaml.handle_patt_quotation loc (typ, txt) ]
and patt_ident_se loc s =
let sl = split_at_dots loc s in
let (hdl, lid) = split_last sl in do {
if not (List.for_all capitalized hdl) then
Ploc.raise loc (Stream.Error "patt expected, but components aren't capitalized")
else () ;
match hdl with [
[] -> patt_id loc lid
| [ h :: t ] ->
let me = List.fold_left (fun me uid -> <:extended_longident< $longid:me$ . $uid:uid$ >>)
<:extended_longident< $uid:h$ >> t in
<:patt< $longid:me$ . $lid:lid$ >>
]}
and ipatt_se se =
match ipatt_opt_se se with
[ Left p → p
| Right (se, _) → error se "ipatt" ]
and ipatt_opt_se =
fun
[ Satom loc Alid "_" → Left <:patt< _ >>
| Satom loc Alid s → Left <:patt< $lid:s$ >>
| Sexpr loc [Satom _ Alid "," :: sel] →
let pl = List.map ipatt_se sel in
Left <:patt< ( $list:pl$ ) >>
| Sexpr loc [] → Left <:patt< () >>
| Sexpr loc [se :: sel] → Right (se, sel)
| se → error se "ipatt" ]
and type_declaration_list_se =
fun
[ [se1; se2 :: sel] →
let (n1, loc1, tpl) =
match se1 with
[ Sexpr _ [Satom loc Alid n :: sel] →
(n, loc, List.map type_parameter_se sel)
| Satom loc Alid n → (n, loc, [])
| se → error se "type declaration" ]
in
let empty = [] in
let n = (loc1, <:vala< n1 >>) in
let td =
{MLast.tdIsDecl = <:vala< True >> ;
MLast.tdNam = <:vala< n >>; MLast.tdPrm = <:vala< tpl >>;
MLast.tdPrv = <:vala< False >>; MLast.tdDef = ctyp_se se2;
MLast.tdCon = <:vala< empty >>;
MLast.tdAttributes = <:vala< [] >>}
in
[td :: type_declaration_list_se sel]
| [] → []
| [se :: _] → error se "type_decl" ]
and type_parameter_se =
fun
[ Satom _ Alid s when String.length s >= 2 && s.[0] = ''' →
let s = String.sub s 1 (String.length s - 1) in
(<:vala< (Some s) >>, (None, False))
| se → error se "type_parameter" ]
and ctyp_se =
fun
[ Sexpr loc [Satom _ Alid "sum" :: sel] →
let cdl = List.map constructor_declaration_se sel in
<:ctyp< [ $list:cdl$ ] >>
| Sexpr loc [se :: sel] →
List.fold_left
(fun t se →
let t2 = ctyp_se se in
<:ctyp< $t$ $t2$ >>)
(ctyp_se se) sel
| Satom loc (Alid | Auid) s → ctyp_ident_se loc s
| se → error se "ctyp" ]
and ctyp_ident_se loc s =
let sl = split_at_dots loc s in
let (hdl, lid) = split_last sl in do {
if not (List.for_all capitalized hdl) then
Ploc.raise loc (Stream.Error "ctyp expected, but components aren't capitalized")
else () ;
match hdl with [
[] -> ctyp_id loc lid
| [ h :: t ] ->
let me = List.fold_left (fun me uid -> <:extended_longident< $longid:me$ . $uid:uid$ >>)
<:extended_longident< $uid:h$ >> t in
<:ctyp< $longid:me$ . $lid:lid$ >>
]}
and constructor_declaration_se =
fun
[ Sexpr loc [Satom _ Auid ci :: sel] →
(loc, <:vala< ci >>, <:vala< [] >>, <:vala< (List.map ctyp_se sel) >>, <:vala< None >>, <:vala< [] >>)
| se → error se "constructor_declaration" ]
;
value top_phrase_se se =
match se with
[ Satom loc _ _ | Squot loc _ _ → str_item_se se
| Sexpr loc [Satom _ Alid s :: sl] →
if s.[0] = '#' then
let n = String.sub s 1 (String.length s - 1) in
match sl with
[ [Satom _ Astring s] → <:str_item< # $lid:n$ $str:s$ >>
| _ → match () with [] ]
else str_item_se se
| Sexpr loc _ → str_item_se se ]
;
(* Parser *)
value phony_quot = ref False;
Pcaml.add_option "-phony_quot" (Arg.Set phony_quot) "phony quotations";
Pcaml.no_constructors_arity.val := False;
do {
Grammar.Unsafe.gram_reinit gram (lexer_gmake ());
Grammar.Unsafe.clear_entry interf;
Grammar.Unsafe.clear_entry implem;
Grammar.Unsafe.clear_entry top_phrase;
Grammar.Unsafe.clear_entry use_file;
Grammar.Unsafe.clear_entry module_type;
Grammar.Unsafe.clear_entry module_expr;
Grammar.Unsafe.clear_entry sig_item;
Grammar.Unsafe.clear_entry str_item;
Grammar.Unsafe.clear_entry expr;
Grammar.Unsafe.clear_entry patt;
Grammar.Unsafe.clear_entry ctyp;
Grammar.Unsafe.clear_entry let_binding;
Grammar.Unsafe.clear_entry class_type;
Grammar.Unsafe.clear_entry class_expr;
Grammar.Unsafe.clear_entry class_sig_item;
Grammar.Unsafe.clear_entry class_str_item
};
Pcaml.(set_ast_parse transduce_interf (Grammar.Entry.parse interf));
Pcaml.(set_ast_parse transduce_implem (Grammar.Entry.parse implem));
Pcaml.(set_ast_parse transduce_top_phrase (Grammar.Entry.parse top_phrase));
Pcaml.(set_ast_parse transduce_use_file (Grammar.Entry.parse use_file));
value sexpr = Grammar.Entry.create gram "sexpr";
value atom = Grammar.Entry.create gram "atom";
EXTEND
implem:
[ [ st = LIST0 [ s = str_item → (s, loc) ]; eoi_loc = [ EOI → loc ] →
(st, Some eoi_loc) ] ]
;
top_phrase:
[ [ se = sexpr → Some (top_phrase_se se)
| EOI → None ] ]
;
use_file:
[ [ l = LIST0 sexpr; EOI → (List.map top_phrase_se l, False) ] ]
;
str_item:
[ [ se = sexpr → str_item_se se
| e = expr → <:str_item< $exp:e$ >> ] ]
;
expr:
[ "top"
[ se = sexpr → expr_se se ] ]
;
patt:
[ [ se = sexpr → patt_se se ] ]
;
sexpr:
[ [ "("; sl = LIST0 sexpr; ")" → Sexpr loc sl
| a = atom → Satom loc Alid a
| s = LIDENT → Satom loc Alid s
| s = UIDENT → Satom loc Auid s
| s = INT → Satom loc Aint s
| s = CHAR → Satom loc Achar s
| s = STRING → Satom loc Astring s
| s = QUOT →
let i = String.index s ':' in
let typ = String.sub s 0 i in
let txt = String.sub s (i + 1) (String.length s - i - 1) in
if phony_quot.val then
Satom loc Alid ("<:" ^ typ ^ "<" ^ txt ^ ">>")
else Squot loc typ txt ] ]
;
atom:
[ [ "_" → "_"
| "," → ","
| "=" → "="
| ":" → ":"
| "." → "." ] ]
;
END;
| (* camlp5 pa_r.cmo pa_rp.cmo pa_extend.cmo q_MLast.cmo pr_dump.cmo *)
(* pa_lisp.ml,v *)
(* Copyright (c) INRIA 2007-2017 *)
|
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(library
(name tezos_protocol_environment_013_PtJakart)
(public_name tezos-protocol-013-PtJakart.environment)
(instrumentation (backend bisect_ppx))
(libraries
tezos-protocol-environment)
(library_flags (:standard -linkall))
(modules Tezos_protocol_environment_013_PtJakart))
(rule
(targets tezos_protocol_environment_013_PtJakart.ml)
(action
(write-file
%{targets}
"module Name = struct let name = \"013-PtJakart\" end\ninclude Tezos_protocol_environment.V5.Make(Name)()\n")))
(library
(name tezos_raw_protocol_013_PtJakart)
(public_name tezos-protocol-013-PtJakart.raw)
(instrumentation (backend bisect_ppx))
(libraries
tezos-protocol-013-PtJakart.environment)
(library_flags (:standard -linkall))
(flags
(:standard)
-w -51
-nostdlib
-nopervasives
-open Tezos_protocol_environment_013_PtJakart
-open Tezos_protocol_environment_013_PtJakart.Pervasives
-open Tezos_protocol_environment_013_PtJakart.Error_monad)
(modules
Misc
Non_empty_string
Path_encoding
Storage_description
State_hash
Nonce_hash
Script_expr_hash
Contract_hash
Blinded_public_key_hash
Block_payload_hash
Origination_nonce
Tx_rollup_prefixes
Merkle_list
Bitset
Slot_repr
Tez_repr
Period_repr
Time_repr
Round_repr
Block_payload_repr
Fixed_point_repr
Saturation_repr
Gas_limit_repr
Constants_repr
Raw_level_repr
Fitness_repr
Cycle_repr
Level_repr
Sc_rollup_repr
Skip_list_repr
Sc_rollup_inbox_repr
Seed_repr
Sampler
Voting_period_repr
Script_string_repr
Script_int_repr
Script_timestamp_repr
Ticket_hash_repr
Michelson_v1_primitives
Script_repr
Cache_memory_helpers
Contract_repr
Indexable
Entrypoint_repr
Tx_rollup_level_repr
Tx_rollup_l2_proof
Tx_rollup_l2_address
Tx_rollup_l2_qty
Tx_rollup_l2_context_hash
Tx_rollup_repr
Tx_rollup_withdraw_repr
Tx_rollup_withdraw_list_hash_repr
Tx_rollup_reveal_repr
Tx_rollup_message_repr
Tx_rollup_message_hash_repr
Tx_rollup_inbox_repr
Tx_rollup_message_result_repr
Tx_rollup_message_result_hash_repr
Tx_rollup_commitment_repr
Tx_rollup_errors_repr
Tx_rollup_state_repr
Bond_id_repr
Vote_repr
Liquidity_baking_repr
Block_header_repr
Destination_repr
Operation_repr
Manager_repr
Commitment_repr
Parameters_repr
Sapling_repr
Lazy_storage_kind
Receipt_repr
Migration_repr
Sc_rollup_tick_repr
Raw_context_intf
Raw_context
Storage_costs
Storage_sigs
Storage_functors
Storage
Ticket_hash_builder
Constants_storage
Tx_rollup_gas
Tx_rollup_hash_builder
Level_storage
Nonce_storage
Seed_storage
Contract_manager_storage
Delegate_activation_storage
Frozen_deposits_storage
Sapling_storage
Lazy_storage_diff
Commitment_storage
Voting_period_storage
Cache_repr
Contract_delegate_storage
Stake_storage
Contract_storage
Token
Delegate_storage
Bootstrap_storage
Vote_storage
Fees_storage
Ticket_storage
Liquidity_baking_storage
Liquidity_baking_cpmm
Liquidity_baking_lqt
Liquidity_baking_migration
Legacy_script_patches_for_J
Init_storage
Sapling_validator
Global_constants_costs
Global_constants_storage
Tx_rollup_state_storage
Tx_rollup_reveal_storage
Tx_rollup_inbox_storage
Tx_rollup_commitment_storage
Tx_rollup_storage
Sc_rollup_storage
Alpha_context
Carbonated_map_costs
Carbonated_map
Tx_rollup_l2_storage_sig
Tx_rollup_l2_context_sig
Tx_rollup_l2_context
Tx_rollup_l2_batch
Tx_rollup_l2_apply
Tx_rollup_l2_verifier
Local_gas_counter
Script_tc_errors
Gas_monad
Script_ir_annot
Dependent_bool
Script_typed_ir
Script_comparable
Gas_comparable_input_size
Script_set
Script_map
Gas_input_size
Script_typed_ir_size
Script_typed_ir_size_costs
Michelson_v1_gas
Script_list
Script_tc_context
Apply_results
Script_ir_translator
Script_cache
Script_tc_errors_registration
Ticket_costs
Ticket_scanner
Ticket_token
Ticket_balance_key
Ticket_lazy_storage_diff
Ticket_balance_migration_for_j
Tx_rollup_parameters
Ticket_token_map
Ticket_operations_diff
Ticket_accounting
Tx_rollup_ticket
Script_interpreter_defs
Script_interpreter
Sc_rollup_operations
Sc_rollup_PVM_sem
Sc_rollup_game
Sc_rollup_arith
Sc_rollups
Baking
Amendment
Apply
Services_registration
Constants_services
Sapling_services
Contract_services
Delegate_services
Voting_services
Tx_rollup_services
Alpha_services
Main))
(library
(name tezos_protocol_013_PtJakart)
(public_name tezos-protocol-013-PtJakart)
(instrumentation (backend bisect_ppx))
(libraries
tezos-protocol-environment
tezos-protocol-environment.sigs
tezos-protocol-013-PtJakart.raw)
(flags
(:standard)
-w -51
-nopervasives)
(modules Protocol Tezos_protocol_013_PtJakart))
(install
(package tezos-protocol-013-PtJakart)
(section lib)
(files (TEZOS_PROTOCOL as raw/TEZOS_PROTOCOL)))
(rule
(targets protocol.ml)
(action
(write-file
%{targets}
"\nlet hash = Tezos_crypto.Hashed.Protocol_hash.of_b58check_exn \"PtJakart2xVj7pYXJBXrqHgd82rdkLey5ZeeGwDgPp9rhQUbSqY\"\nlet name = Tezos_protocol_environment_013_PtJakart.Name.name\ninclude Tezos_raw_protocol_013_PtJakart\ninclude Tezos_raw_protocol_013_PtJakart.Main\n")))
(rule
(targets tezos_protocol_013_PtJakart.ml)
(action
(write-file
%{targets}
"\nmodule Environment = Tezos_protocol_environment_013_PtJakart\nmodule Protocol = Protocol\n")))
(rule
(alias runtest_compile_protocol)
(deps
misc.ml misc.mli
non_empty_string.ml non_empty_string.mli
path_encoding.ml path_encoding.mli
storage_description.ml storage_description.mli
state_hash.ml state_hash.mli
nonce_hash.ml nonce_hash.mli
script_expr_hash.ml script_expr_hash.mli
contract_hash.ml contract_hash.mli
blinded_public_key_hash.ml blinded_public_key_hash.mli
block_payload_hash.ml block_payload_hash.mli
origination_nonce.ml origination_nonce.mli
tx_rollup_prefixes.ml tx_rollup_prefixes.mli
merkle_list.ml merkle_list.mli
bitset.ml bitset.mli
slot_repr.ml slot_repr.mli
tez_repr.ml tez_repr.mli
period_repr.ml period_repr.mli
time_repr.ml time_repr.mli
round_repr.ml round_repr.mli
block_payload_repr.ml block_payload_repr.mli
fixed_point_repr.ml fixed_point_repr.mli
saturation_repr.ml saturation_repr.mli
gas_limit_repr.ml gas_limit_repr.mli
constants_repr.ml constants_repr.mli
raw_level_repr.ml raw_level_repr.mli
fitness_repr.ml fitness_repr.mli
cycle_repr.ml cycle_repr.mli
level_repr.ml level_repr.mli
sc_rollup_repr.ml sc_rollup_repr.mli
skip_list_repr.ml skip_list_repr.mli
sc_rollup_inbox_repr.ml sc_rollup_inbox_repr.mli
seed_repr.ml seed_repr.mli
sampler.ml sampler.mli
voting_period_repr.ml voting_period_repr.mli
script_string_repr.ml script_string_repr.mli
script_int_repr.ml script_int_repr.mli
script_timestamp_repr.ml script_timestamp_repr.mli
ticket_hash_repr.ml ticket_hash_repr.mli
michelson_v1_primitives.ml michelson_v1_primitives.mli
script_repr.ml script_repr.mli
cache_memory_helpers.ml
contract_repr.ml contract_repr.mli
indexable.ml indexable.mli
entrypoint_repr.ml entrypoint_repr.mli
tx_rollup_level_repr.ml tx_rollup_level_repr.mli
tx_rollup_l2_proof.ml tx_rollup_l2_proof.mli
tx_rollup_l2_address.ml tx_rollup_l2_address.mli
tx_rollup_l2_qty.ml tx_rollup_l2_qty.mli
tx_rollup_l2_context_hash.ml tx_rollup_l2_context_hash.mli
tx_rollup_repr.ml tx_rollup_repr.mli
tx_rollup_withdraw_repr.ml tx_rollup_withdraw_repr.mli
tx_rollup_withdraw_list_hash_repr.ml tx_rollup_withdraw_list_hash_repr.mli
tx_rollup_reveal_repr.ml tx_rollup_reveal_repr.mli
tx_rollup_message_repr.ml tx_rollup_message_repr.mli
tx_rollup_message_hash_repr.ml tx_rollup_message_hash_repr.mli
tx_rollup_inbox_repr.ml tx_rollup_inbox_repr.mli
tx_rollup_message_result_repr.ml tx_rollup_message_result_repr.mli
tx_rollup_message_result_hash_repr.ml
tx_rollup_message_result_hash_repr.mli
tx_rollup_commitment_repr.ml tx_rollup_commitment_repr.mli
tx_rollup_errors_repr.ml
tx_rollup_state_repr.ml tx_rollup_state_repr.mli
bond_id_repr.ml bond_id_repr.mli
vote_repr.ml vote_repr.mli
liquidity_baking_repr.ml liquidity_baking_repr.mli
block_header_repr.ml block_header_repr.mli
destination_repr.ml destination_repr.mli
operation_repr.ml operation_repr.mli
manager_repr.ml manager_repr.mli
commitment_repr.ml commitment_repr.mli
parameters_repr.ml parameters_repr.mli
sapling_repr.ml
lazy_storage_kind.ml lazy_storage_kind.mli
receipt_repr.ml receipt_repr.mli
migration_repr.ml migration_repr.mli
sc_rollup_tick_repr.ml sc_rollup_tick_repr.mli
raw_context_intf.ml
raw_context.ml raw_context.mli
storage_costs.ml storage_costs.mli
storage_sigs.ml
storage_functors.ml storage_functors.mli
storage.ml storage.mli
ticket_hash_builder.ml ticket_hash_builder.mli
constants_storage.ml constants_storage.mli
tx_rollup_gas.ml tx_rollup_gas.mli
tx_rollup_hash_builder.ml
level_storage.ml level_storage.mli
nonce_storage.ml nonce_storage.mli
seed_storage.ml seed_storage.mli
contract_manager_storage.ml contract_manager_storage.mli
delegate_activation_storage.ml delegate_activation_storage.mli
frozen_deposits_storage.ml frozen_deposits_storage.mli
sapling_storage.ml
lazy_storage_diff.ml lazy_storage_diff.mli
commitment_storage.ml commitment_storage.mli
voting_period_storage.ml voting_period_storage.mli
cache_repr.ml cache_repr.mli
contract_delegate_storage.ml contract_delegate_storage.mli
stake_storage.ml stake_storage.mli
contract_storage.ml contract_storage.mli
token.ml token.mli
delegate_storage.ml delegate_storage.mli
bootstrap_storage.ml bootstrap_storage.mli
vote_storage.ml vote_storage.mli
fees_storage.ml fees_storage.mli
ticket_storage.ml ticket_storage.mli
liquidity_baking_storage.ml liquidity_baking_storage.mli
liquidity_baking_cpmm.ml
liquidity_baking_lqt.ml
liquidity_baking_migration.ml liquidity_baking_migration.mli
legacy_script_patches_for_J.ml
init_storage.ml init_storage.mli
sapling_validator.ml
global_constants_costs.ml global_constants_costs.mli
global_constants_storage.ml global_constants_storage.mli
tx_rollup_state_storage.ml tx_rollup_state_storage.mli
tx_rollup_reveal_storage.ml tx_rollup_reveal_storage.mli
tx_rollup_inbox_storage.ml tx_rollup_inbox_storage.mli
tx_rollup_commitment_storage.ml tx_rollup_commitment_storage.mli
tx_rollup_storage.ml tx_rollup_storage.mli
sc_rollup_storage.ml sc_rollup_storage.mli
alpha_context.ml alpha_context.mli
carbonated_map_costs.ml carbonated_map_costs.mli
carbonated_map.ml carbonated_map.mli
tx_rollup_l2_storage_sig.ml
tx_rollup_l2_context_sig.ml
tx_rollup_l2_context.ml
tx_rollup_l2_batch.ml tx_rollup_l2_batch.mli
tx_rollup_l2_apply.ml tx_rollup_l2_apply.mli
tx_rollup_l2_verifier.ml tx_rollup_l2_verifier.mli
local_gas_counter.ml local_gas_counter.mli
script_tc_errors.ml
gas_monad.ml gas_monad.mli
script_ir_annot.ml script_ir_annot.mli
dependent_bool.ml dependent_bool.mli
script_typed_ir.ml script_typed_ir.mli
script_comparable.ml script_comparable.mli
gas_comparable_input_size.ml gas_comparable_input_size.mli
script_set.ml script_set.mli
script_map.ml script_map.mli
gas_input_size.ml gas_input_size.mli
script_typed_ir_size.ml script_typed_ir_size.mli
script_typed_ir_size_costs.ml script_typed_ir_size_costs.mli
michelson_v1_gas.ml michelson_v1_gas.mli
script_list.ml script_list.mli
script_tc_context.ml script_tc_context.mli
apply_results.ml apply_results.mli
script_ir_translator.ml script_ir_translator.mli
script_cache.ml script_cache.mli
script_tc_errors_registration.ml script_tc_errors_registration.mli
ticket_costs.ml ticket_costs.mli
ticket_scanner.ml ticket_scanner.mli
ticket_token.ml ticket_token.mli
ticket_balance_key.ml ticket_balance_key.mli
ticket_lazy_storage_diff.ml ticket_lazy_storage_diff.mli
ticket_balance_migration_for_j.ml ticket_balance_migration_for_j.mli
tx_rollup_parameters.ml tx_rollup_parameters.mli
ticket_token_map.ml ticket_token_map.mli
ticket_operations_diff.ml ticket_operations_diff.mli
ticket_accounting.ml ticket_accounting.mli
tx_rollup_ticket.ml tx_rollup_ticket.mli
script_interpreter_defs.ml
script_interpreter.ml script_interpreter.mli
sc_rollup_operations.ml sc_rollup_operations.mli
sc_rollup_PVM_sem.ml
sc_rollup_game.ml sc_rollup_game.mli
sc_rollup_arith.ml sc_rollup_arith.mli
sc_rollups.ml sc_rollups.mli
baking.ml baking.mli
amendment.ml amendment.mli
apply.ml apply.mli
services_registration.ml services_registration.mli
constants_services.ml constants_services.mli
sapling_services.ml
contract_services.ml contract_services.mli
delegate_services.ml delegate_services.mli
voting_services.ml voting_services.mli
tx_rollup_services.ml tx_rollup_services.mli
alpha_services.ml alpha_services.mli
main.ml main.mli
(:src_dir TEZOS_PROTOCOL))
(action (run %{bin:octez-protocol-compiler} -warning -51 -warn-error +a .)))
(library
(name tezos_protocol_013_PtJakart_functor)
(libraries
tezos-protocol-environment
tezos-protocol-environment.sigs)
(flags
(:standard)
-w -51
-nopervasives)
(modules Functor))
(rule
(targets functor.ml)
(deps
misc.ml misc.mli
non_empty_string.ml non_empty_string.mli
path_encoding.ml path_encoding.mli
storage_description.ml storage_description.mli
state_hash.ml state_hash.mli
nonce_hash.ml nonce_hash.mli
script_expr_hash.ml script_expr_hash.mli
contract_hash.ml contract_hash.mli
blinded_public_key_hash.ml blinded_public_key_hash.mli
block_payload_hash.ml block_payload_hash.mli
origination_nonce.ml origination_nonce.mli
tx_rollup_prefixes.ml tx_rollup_prefixes.mli
merkle_list.ml merkle_list.mli
bitset.ml bitset.mli
slot_repr.ml slot_repr.mli
tez_repr.ml tez_repr.mli
period_repr.ml period_repr.mli
time_repr.ml time_repr.mli
round_repr.ml round_repr.mli
block_payload_repr.ml block_payload_repr.mli
fixed_point_repr.ml fixed_point_repr.mli
saturation_repr.ml saturation_repr.mli
gas_limit_repr.ml gas_limit_repr.mli
constants_repr.ml constants_repr.mli
raw_level_repr.ml raw_level_repr.mli
fitness_repr.ml fitness_repr.mli
cycle_repr.ml cycle_repr.mli
level_repr.ml level_repr.mli
sc_rollup_repr.ml sc_rollup_repr.mli
skip_list_repr.ml skip_list_repr.mli
sc_rollup_inbox_repr.ml sc_rollup_inbox_repr.mli
seed_repr.ml seed_repr.mli
sampler.ml sampler.mli
voting_period_repr.ml voting_period_repr.mli
script_string_repr.ml script_string_repr.mli
script_int_repr.ml script_int_repr.mli
script_timestamp_repr.ml script_timestamp_repr.mli
ticket_hash_repr.ml ticket_hash_repr.mli
michelson_v1_primitives.ml michelson_v1_primitives.mli
script_repr.ml script_repr.mli
cache_memory_helpers.ml
contract_repr.ml contract_repr.mli
indexable.ml indexable.mli
entrypoint_repr.ml entrypoint_repr.mli
tx_rollup_level_repr.ml tx_rollup_level_repr.mli
tx_rollup_l2_proof.ml tx_rollup_l2_proof.mli
tx_rollup_l2_address.ml tx_rollup_l2_address.mli
tx_rollup_l2_qty.ml tx_rollup_l2_qty.mli
tx_rollup_l2_context_hash.ml tx_rollup_l2_context_hash.mli
tx_rollup_repr.ml tx_rollup_repr.mli
tx_rollup_withdraw_repr.ml tx_rollup_withdraw_repr.mli
tx_rollup_withdraw_list_hash_repr.ml tx_rollup_withdraw_list_hash_repr.mli
tx_rollup_reveal_repr.ml tx_rollup_reveal_repr.mli
tx_rollup_message_repr.ml tx_rollup_message_repr.mli
tx_rollup_message_hash_repr.ml tx_rollup_message_hash_repr.mli
tx_rollup_inbox_repr.ml tx_rollup_inbox_repr.mli
tx_rollup_message_result_repr.ml tx_rollup_message_result_repr.mli
tx_rollup_message_result_hash_repr.ml
tx_rollup_message_result_hash_repr.mli
tx_rollup_commitment_repr.ml tx_rollup_commitment_repr.mli
tx_rollup_errors_repr.ml
tx_rollup_state_repr.ml tx_rollup_state_repr.mli
bond_id_repr.ml bond_id_repr.mli
vote_repr.ml vote_repr.mli
liquidity_baking_repr.ml liquidity_baking_repr.mli
block_header_repr.ml block_header_repr.mli
destination_repr.ml destination_repr.mli
operation_repr.ml operation_repr.mli
manager_repr.ml manager_repr.mli
commitment_repr.ml commitment_repr.mli
parameters_repr.ml parameters_repr.mli
sapling_repr.ml
lazy_storage_kind.ml lazy_storage_kind.mli
receipt_repr.ml receipt_repr.mli
migration_repr.ml migration_repr.mli
sc_rollup_tick_repr.ml sc_rollup_tick_repr.mli
raw_context_intf.ml
raw_context.ml raw_context.mli
storage_costs.ml storage_costs.mli
storage_sigs.ml
storage_functors.ml storage_functors.mli
storage.ml storage.mli
ticket_hash_builder.ml ticket_hash_builder.mli
constants_storage.ml constants_storage.mli
tx_rollup_gas.ml tx_rollup_gas.mli
tx_rollup_hash_builder.ml
level_storage.ml level_storage.mli
nonce_storage.ml nonce_storage.mli
seed_storage.ml seed_storage.mli
contract_manager_storage.ml contract_manager_storage.mli
delegate_activation_storage.ml delegate_activation_storage.mli
frozen_deposits_storage.ml frozen_deposits_storage.mli
sapling_storage.ml
lazy_storage_diff.ml lazy_storage_diff.mli
commitment_storage.ml commitment_storage.mli
voting_period_storage.ml voting_period_storage.mli
cache_repr.ml cache_repr.mli
contract_delegate_storage.ml contract_delegate_storage.mli
stake_storage.ml stake_storage.mli
contract_storage.ml contract_storage.mli
token.ml token.mli
delegate_storage.ml delegate_storage.mli
bootstrap_storage.ml bootstrap_storage.mli
vote_storage.ml vote_storage.mli
fees_storage.ml fees_storage.mli
ticket_storage.ml ticket_storage.mli
liquidity_baking_storage.ml liquidity_baking_storage.mli
liquidity_baking_cpmm.ml
liquidity_baking_lqt.ml
liquidity_baking_migration.ml liquidity_baking_migration.mli
legacy_script_patches_for_J.ml
init_storage.ml init_storage.mli
sapling_validator.ml
global_constants_costs.ml global_constants_costs.mli
global_constants_storage.ml global_constants_storage.mli
tx_rollup_state_storage.ml tx_rollup_state_storage.mli
tx_rollup_reveal_storage.ml tx_rollup_reveal_storage.mli
tx_rollup_inbox_storage.ml tx_rollup_inbox_storage.mli
tx_rollup_commitment_storage.ml tx_rollup_commitment_storage.mli
tx_rollup_storage.ml tx_rollup_storage.mli
sc_rollup_storage.ml sc_rollup_storage.mli
alpha_context.ml alpha_context.mli
carbonated_map_costs.ml carbonated_map_costs.mli
carbonated_map.ml carbonated_map.mli
tx_rollup_l2_storage_sig.ml
tx_rollup_l2_context_sig.ml
tx_rollup_l2_context.ml
tx_rollup_l2_batch.ml tx_rollup_l2_batch.mli
tx_rollup_l2_apply.ml tx_rollup_l2_apply.mli
tx_rollup_l2_verifier.ml tx_rollup_l2_verifier.mli
local_gas_counter.ml local_gas_counter.mli
script_tc_errors.ml
gas_monad.ml gas_monad.mli
script_ir_annot.ml script_ir_annot.mli
dependent_bool.ml dependent_bool.mli
script_typed_ir.ml script_typed_ir.mli
script_comparable.ml script_comparable.mli
gas_comparable_input_size.ml gas_comparable_input_size.mli
script_set.ml script_set.mli
script_map.ml script_map.mli
gas_input_size.ml gas_input_size.mli
script_typed_ir_size.ml script_typed_ir_size.mli
script_typed_ir_size_costs.ml script_typed_ir_size_costs.mli
michelson_v1_gas.ml michelson_v1_gas.mli
script_list.ml script_list.mli
script_tc_context.ml script_tc_context.mli
apply_results.ml apply_results.mli
script_ir_translator.ml script_ir_translator.mli
script_cache.ml script_cache.mli
script_tc_errors_registration.ml script_tc_errors_registration.mli
ticket_costs.ml ticket_costs.mli
ticket_scanner.ml ticket_scanner.mli
ticket_token.ml ticket_token.mli
ticket_balance_key.ml ticket_balance_key.mli
ticket_lazy_storage_diff.ml ticket_lazy_storage_diff.mli
ticket_balance_migration_for_j.ml ticket_balance_migration_for_j.mli
tx_rollup_parameters.ml tx_rollup_parameters.mli
ticket_token_map.ml ticket_token_map.mli
ticket_operations_diff.ml ticket_operations_diff.mli
ticket_accounting.ml ticket_accounting.mli
tx_rollup_ticket.ml tx_rollup_ticket.mli
script_interpreter_defs.ml
script_interpreter.ml script_interpreter.mli
sc_rollup_operations.ml sc_rollup_operations.mli
sc_rollup_PVM_sem.ml
sc_rollup_game.ml sc_rollup_game.mli
sc_rollup_arith.ml sc_rollup_arith.mli
sc_rollups.ml sc_rollups.mli
baking.ml baking.mli
amendment.ml amendment.mli
apply.ml apply.mli
services_registration.ml services_registration.mli
constants_services.ml constants_services.mli
sapling_services.ml
contract_services.ml contract_services.mli
delegate_services.ml delegate_services.mli
voting_services.ml voting_services.mli
tx_rollup_services.ml tx_rollup_services.mli
alpha_services.ml alpha_services.mli
main.ml main.mli (:src_dir TEZOS_PROTOCOL))
(action
(with-stdout-to
%{targets}
(chdir
%{workspace_root}
(run %{bin:octez-protocol-compiler.octez-protocol-packer} %{src_dir})))))
(library
(name tezos_embedded_protocol_013_PtJakart)
(public_name tezos-embedded-protocol-013-PtJakart)
(instrumentation (backend bisect_ppx))
(libraries
tezos-protocol-013-PtJakart
tezos-protocol-updater
tezos-protocol-environment)
(library_flags (:standard -linkall))
(flags
(:standard)
-w -51)
(modules Registerer))
(rule
(targets registerer.ml)
(deps
misc.ml misc.mli
non_empty_string.ml non_empty_string.mli
path_encoding.ml path_encoding.mli
storage_description.ml storage_description.mli
state_hash.ml state_hash.mli
nonce_hash.ml nonce_hash.mli
script_expr_hash.ml script_expr_hash.mli
contract_hash.ml contract_hash.mli
blinded_public_key_hash.ml blinded_public_key_hash.mli
block_payload_hash.ml block_payload_hash.mli
origination_nonce.ml origination_nonce.mli
tx_rollup_prefixes.ml tx_rollup_prefixes.mli
merkle_list.ml merkle_list.mli
bitset.ml bitset.mli
slot_repr.ml slot_repr.mli
tez_repr.ml tez_repr.mli
period_repr.ml period_repr.mli
time_repr.ml time_repr.mli
round_repr.ml round_repr.mli
block_payload_repr.ml block_payload_repr.mli
fixed_point_repr.ml fixed_point_repr.mli
saturation_repr.ml saturation_repr.mli
gas_limit_repr.ml gas_limit_repr.mli
constants_repr.ml constants_repr.mli
raw_level_repr.ml raw_level_repr.mli
fitness_repr.ml fitness_repr.mli
cycle_repr.ml cycle_repr.mli
level_repr.ml level_repr.mli
sc_rollup_repr.ml sc_rollup_repr.mli
skip_list_repr.ml skip_list_repr.mli
sc_rollup_inbox_repr.ml sc_rollup_inbox_repr.mli
seed_repr.ml seed_repr.mli
sampler.ml sampler.mli
voting_period_repr.ml voting_period_repr.mli
script_string_repr.ml script_string_repr.mli
script_int_repr.ml script_int_repr.mli
script_timestamp_repr.ml script_timestamp_repr.mli
ticket_hash_repr.ml ticket_hash_repr.mli
michelson_v1_primitives.ml michelson_v1_primitives.mli
script_repr.ml script_repr.mli
cache_memory_helpers.ml
contract_repr.ml contract_repr.mli
indexable.ml indexable.mli
entrypoint_repr.ml entrypoint_repr.mli
tx_rollup_level_repr.ml tx_rollup_level_repr.mli
tx_rollup_l2_proof.ml tx_rollup_l2_proof.mli
tx_rollup_l2_address.ml tx_rollup_l2_address.mli
tx_rollup_l2_qty.ml tx_rollup_l2_qty.mli
tx_rollup_l2_context_hash.ml tx_rollup_l2_context_hash.mli
tx_rollup_repr.ml tx_rollup_repr.mli
tx_rollup_withdraw_repr.ml tx_rollup_withdraw_repr.mli
tx_rollup_withdraw_list_hash_repr.ml tx_rollup_withdraw_list_hash_repr.mli
tx_rollup_reveal_repr.ml tx_rollup_reveal_repr.mli
tx_rollup_message_repr.ml tx_rollup_message_repr.mli
tx_rollup_message_hash_repr.ml tx_rollup_message_hash_repr.mli
tx_rollup_inbox_repr.ml tx_rollup_inbox_repr.mli
tx_rollup_message_result_repr.ml tx_rollup_message_result_repr.mli
tx_rollup_message_result_hash_repr.ml
tx_rollup_message_result_hash_repr.mli
tx_rollup_commitment_repr.ml tx_rollup_commitment_repr.mli
tx_rollup_errors_repr.ml
tx_rollup_state_repr.ml tx_rollup_state_repr.mli
bond_id_repr.ml bond_id_repr.mli
vote_repr.ml vote_repr.mli
liquidity_baking_repr.ml liquidity_baking_repr.mli
block_header_repr.ml block_header_repr.mli
destination_repr.ml destination_repr.mli
operation_repr.ml operation_repr.mli
manager_repr.ml manager_repr.mli
commitment_repr.ml commitment_repr.mli
parameters_repr.ml parameters_repr.mli
sapling_repr.ml
lazy_storage_kind.ml lazy_storage_kind.mli
receipt_repr.ml receipt_repr.mli
migration_repr.ml migration_repr.mli
sc_rollup_tick_repr.ml sc_rollup_tick_repr.mli
raw_context_intf.ml
raw_context.ml raw_context.mli
storage_costs.ml storage_costs.mli
storage_sigs.ml
storage_functors.ml storage_functors.mli
storage.ml storage.mli
ticket_hash_builder.ml ticket_hash_builder.mli
constants_storage.ml constants_storage.mli
tx_rollup_gas.ml tx_rollup_gas.mli
tx_rollup_hash_builder.ml
level_storage.ml level_storage.mli
nonce_storage.ml nonce_storage.mli
seed_storage.ml seed_storage.mli
contract_manager_storage.ml contract_manager_storage.mli
delegate_activation_storage.ml delegate_activation_storage.mli
frozen_deposits_storage.ml frozen_deposits_storage.mli
sapling_storage.ml
lazy_storage_diff.ml lazy_storage_diff.mli
commitment_storage.ml commitment_storage.mli
voting_period_storage.ml voting_period_storage.mli
cache_repr.ml cache_repr.mli
contract_delegate_storage.ml contract_delegate_storage.mli
stake_storage.ml stake_storage.mli
contract_storage.ml contract_storage.mli
token.ml token.mli
delegate_storage.ml delegate_storage.mli
bootstrap_storage.ml bootstrap_storage.mli
vote_storage.ml vote_storage.mli
fees_storage.ml fees_storage.mli
ticket_storage.ml ticket_storage.mli
liquidity_baking_storage.ml liquidity_baking_storage.mli
liquidity_baking_cpmm.ml
liquidity_baking_lqt.ml
liquidity_baking_migration.ml liquidity_baking_migration.mli
legacy_script_patches_for_J.ml
init_storage.ml init_storage.mli
sapling_validator.ml
global_constants_costs.ml global_constants_costs.mli
global_constants_storage.ml global_constants_storage.mli
tx_rollup_state_storage.ml tx_rollup_state_storage.mli
tx_rollup_reveal_storage.ml tx_rollup_reveal_storage.mli
tx_rollup_inbox_storage.ml tx_rollup_inbox_storage.mli
tx_rollup_commitment_storage.ml tx_rollup_commitment_storage.mli
tx_rollup_storage.ml tx_rollup_storage.mli
sc_rollup_storage.ml sc_rollup_storage.mli
alpha_context.ml alpha_context.mli
carbonated_map_costs.ml carbonated_map_costs.mli
carbonated_map.ml carbonated_map.mli
tx_rollup_l2_storage_sig.ml
tx_rollup_l2_context_sig.ml
tx_rollup_l2_context.ml
tx_rollup_l2_batch.ml tx_rollup_l2_batch.mli
tx_rollup_l2_apply.ml tx_rollup_l2_apply.mli
tx_rollup_l2_verifier.ml tx_rollup_l2_verifier.mli
local_gas_counter.ml local_gas_counter.mli
script_tc_errors.ml
gas_monad.ml gas_monad.mli
script_ir_annot.ml script_ir_annot.mli
dependent_bool.ml dependent_bool.mli
script_typed_ir.ml script_typed_ir.mli
script_comparable.ml script_comparable.mli
gas_comparable_input_size.ml gas_comparable_input_size.mli
script_set.ml script_set.mli
script_map.ml script_map.mli
gas_input_size.ml gas_input_size.mli
script_typed_ir_size.ml script_typed_ir_size.mli
script_typed_ir_size_costs.ml script_typed_ir_size_costs.mli
michelson_v1_gas.ml michelson_v1_gas.mli
script_list.ml script_list.mli
script_tc_context.ml script_tc_context.mli
apply_results.ml apply_results.mli
script_ir_translator.ml script_ir_translator.mli
script_cache.ml script_cache.mli
script_tc_errors_registration.ml script_tc_errors_registration.mli
ticket_costs.ml ticket_costs.mli
ticket_scanner.ml ticket_scanner.mli
ticket_token.ml ticket_token.mli
ticket_balance_key.ml ticket_balance_key.mli
ticket_lazy_storage_diff.ml ticket_lazy_storage_diff.mli
ticket_balance_migration_for_j.ml ticket_balance_migration_for_j.mli
tx_rollup_parameters.ml tx_rollup_parameters.mli
ticket_token_map.ml ticket_token_map.mli
ticket_operations_diff.ml ticket_operations_diff.mli
ticket_accounting.ml ticket_accounting.mli
tx_rollup_ticket.ml tx_rollup_ticket.mli
script_interpreter_defs.ml
script_interpreter.ml script_interpreter.mli
sc_rollup_operations.ml sc_rollup_operations.mli
sc_rollup_PVM_sem.ml
sc_rollup_game.ml sc_rollup_game.mli
sc_rollup_arith.ml sc_rollup_arith.mli
sc_rollups.ml sc_rollups.mli
baking.ml baking.mli
amendment.ml amendment.mli
apply.ml apply.mli
services_registration.ml services_registration.mli
constants_services.ml constants_services.mli
sapling_services.ml
contract_services.ml contract_services.mli
delegate_services.ml delegate_services.mli
voting_services.ml voting_services.mli
tx_rollup_services.ml tx_rollup_services.mli
alpha_services.ml alpha_services.mli
main.ml main.mli (:src_dir TEZOS_PROTOCOL))
(action
(with-stdout-to
%{targets}
(chdir
%{workspace_root}
(run %{bin:octez-embedded-protocol-packer} %{src_dir} 013_PtJakart)))))
| |
event.ml | module Simple = struct
include Internal_event.Simple
let section = ["sc_rollup_node"]
let starting_node =
declare_0
~section
~name:"starting_sc_rollup_node"
~msg:"Starting the smart contract rollup node"
~level:Notice
()
let shutdown_node =
declare_1
~section
~name:"stopping_sc_rollup_node"
~msg:"Stopping the smart contract rollup node"
~level:Notice
("exit_status", Data_encoding.int8)
let node_is_ready =
declare_2
~section
~name:"sc_rollup_node_is_ready"
~msg:"The smart contract rollup node is listening to {addr}:{port}"
~level:Notice
("addr", Data_encoding.string)
("port", Data_encoding.uint16)
let rollup_exists =
declare_2
~section
~name:"sc_rollup_node_knows_its_rollup"
~msg:
"The smart contract rollup node is interacting with rollup {addr} of \
kind {kind}"
~level:Notice
("addr", Protocol.Alpha_context.Sc_rollup.Address.encoding)
("kind", Data_encoding.string)
end
let starting_node = Simple.(emit starting_node)
let shutdown_node exit_status = Simple.(emit shutdown_node exit_status)
let node_is_ready ~rpc_addr ~rpc_port =
Simple.(emit node_is_ready (rpc_addr, rpc_port))
let rollup_exists ~addr ~kind =
let kind = Protocol.Sc_rollups.string_of_kind kind in
Simple.(emit rollup_exists (addr, kind))
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
mirage_runtime.ml |
type log_threshold = [ `All | `Src of string ] * Logs.level
let set_level ~default l =
let srcs = Logs.Src.list () in
let default =
try snd @@ List.find (function `All, _ -> true | _ -> false) l
with Not_found -> default
in
Logs.set_level (Some default);
List.iter
(function
| `All, _ -> ()
| `Src src, level -> (
try
let s = List.find (fun s -> Logs.Src.name s = src) srcs in
Logs.Src.set_level s (Some level)
with Not_found ->
Fmt.(pf stdout)
"%a %s is not a valid log source.\n%!"
Fmt.(styled `Yellow string)
"Warning:" src))
l
module Arg = struct
include Functoria_runtime.Arg
let make of_string to_string : _ Cmdliner.Arg.conv =
let parser s =
match of_string s with
| Error (`Msg m) -> `Error ("Can't parse ip address: " ^ s ^ ": " ^ m)
| Ok ip -> `Ok ip
and pp ppf ip = Fmt.string ppf (to_string ip) in
(parser, pp)
module type S = sig
type t
val of_string : string -> (t, [ `Msg of string ]) result
val to_string : t -> string
end
let of_module (type t) (module M : S with type t = t) =
make M.of_string M.to_string
let ip_address = of_module (module Ipaddr)
let ipv4_address = of_module (module Ipaddr.V4)
let ipv4 = of_module (module Ipaddr.V4.Prefix)
let ipv6_address = of_module (module Ipaddr.V6)
let ipv6 = of_module (module Ipaddr.V6.Prefix)
let log_threshold =
let enum =
[
("error", Logs.Error);
("warning", Logs.Warning);
("info", Logs.Info);
("debug", Logs.Debug);
]
in
let level_of_string x =
try List.assoc x enum
with Not_found -> Fmt.kstr failwith "%s is not a valid log level" x
in
let string_of_level x =
try fst @@ List.find (fun (_, y) -> x = y) enum
with Not_found -> "warning"
in
let parser str =
match String.split_on_char ':' str with
| [ _ ] -> `Ok (`All, level_of_string str)
| [ "*"; lvl ] -> `Ok (`All, level_of_string lvl)
| [ src; lvl ] -> `Ok (`Src src, level_of_string lvl)
| _ -> `Error ("Can't parse log threshold: " ^ str)
in
let serialize ppf = function
| `All, l -> Fmt.string ppf (string_of_level l)
| `Src s, l -> Fmt.pf ppf "%s:%s" s (string_of_level l)
in
(parser, serialize)
let allocation_policy =
Cmdliner.Arg.enum
[
("next-fit", `Next_fit);
("first-fit", `First_fit);
("best-fit", `Best_fit);
]
end
include (
Functoria_runtime : module type of Functoria_runtime with module Arg := Arg)
let exit_hooks = ref []
let enter_iter_hooks = ref []
let leave_iter_hooks = ref []
let run t = List.iter (fun f -> f ()) !t
let add f t = t := f :: !t
let run_exit_hooks () =
Lwt_list.iter_s
(fun hook -> Lwt.catch (fun () -> hook ()) (fun _ -> Lwt.return_unit))
!exit_hooks
let run_enter_iter_hooks () = run enter_iter_hooks
let run_leave_iter_hooks () = run leave_iter_hooks
let at_exit f = add f exit_hooks
let at_leave_iter f = add f leave_iter_hooks
let at_enter_iter f = add f enter_iter_hooks
| (*
* Copyright (c) 2014 David Sheets <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*) |
is_perfect_power.c |
#include <gmp.h>
#define ulong ulongxx /* interferes with system includes */
#include <math.h>
#undef ulong
#include "flint.h"
#include "ulong_extras.h"
int n_is_perfect_power(ulong * root, ulong n)
{
static unsigned char mod63[63] = {7,7,4,0,5,4,0,5,6,5,4,4,0,4,4,0,5,4,5,4,
4,0,5,4,0,5,4,6,7,4,0,4,4,0,4,6,7,5,4,0,4,4,0,5,
4,4,5,4,0,5,4,0,4,4,4,6,4,0,5,4,0,4,6};
static unsigned char mod61[61] = {7,7,0,3,1,1,0,0,2,3,0,6,1,5,5,1,1,0,0,1,
3,4,1,2,2,1,0,3,2,4,0,0,4,2,3,0,1,2,2,1,4,3,1,0,
0,1,1,5,5,1,6,0,3,2,0,0,1,1,3,0,7};
static unsigned char mod44[44] = {7,7,0,2,3,3,0,2,2,3,0,6,7,2,0,2,3,2,0,2,
3,6,0,6,2,3,0,2,2,2,0,2,6,7,0,2,3,3,0,2,2,2,0,6};
static unsigned char mod31[31] = {7,7,3,0,3,5,4,1,3,1,1,0,0,0,1,2,3,0,1,1,
1,0,0,2,0,5,4,2,1,2,6};
static unsigned char mod72[72] = {7,7,0,0,0,7,0,7,7,7,0,7,0,7,0,0,7,7,0,7,
0,0,0,7,0,7,0,7,0,7,0,7,7,0,0,7,0,7,0,0,7,7,0,7,
0,7,0,7,0,7,0,0,0,7,0,7,7,0,0,7,0,7,0,7,7,7,0,7,
0,0,0,7};
static unsigned char mod49[49] = {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,
0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1};
static unsigned char mod67[67] = {2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2};
static unsigned char mod79[79] = {4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,4};
unsigned char t;
ulong count, exp, r;
/* check for powers 2, 3, 5 */
t = mod31[n%31];
t &= mod44[n%44];
t &= mod61[n%61];
t &= mod63[n%63];
if (t & 1)
{
ulong y = n_sqrtrem(&r, n);
if (r == 0)
{
*root = y;
return 2;
}
}
if (t & 2)
{
ulong y = n_cbrtrem(&r, n);
if (r == 0)
if (n == n_pow(y, 3))
{
*root = y;
return 3;
}
}
if (t & 4)
{
ulong y = n_rootrem(&r, n, 5);
if (r == 0)
{
*root = y;
return 5;
}
}
/* check for power 7, 11, 13 */
t = mod49[n%49];
t |= mod67[n%67];
t |= mod79[n%79];
t &= mod72[n%72];
if (t & 1)
{
ulong y = n_rootrem(&r, n, 7);
if (r == 0)
{
*root = y;
return 7;
}
}
if (t & 2)
{
ulong y = n_rootrem(&r, n, 11);
if (r == 0)
{
*root = y;
return 11;
}
}
if (t & 13)
{
ulong y = n_rootrem(&r, n, 13);
if (r == 0)
{
*root = y;
return 13;
}
}
/* highest power of 2 */
count_trailing_zeros(count, n);
n >>= count;
if (n == 1)
{
if (count == 1)
return 0;
*root = 2;
return count;
}
/* check other powers (exp >= 17, root <= 13 and odd) */
exp = 0;
while ((n % 3) == 0)
{
n /= 3;
exp += 1;
}
if (exp > 0)
{
if (n == 1 && exp > 1)
{
if (count == 0)
{
*root = 3;
return exp;
} else if (count == exp)
{
*root = 6;
return exp;
} else if (count == 2*exp)
{
*root = 12;
return exp;
}
}
return 0;
}
#if FLINT64
exp = 0;
while ((n % 5) == 0)
{
n /= 5;
exp += 1;
}
if (exp > 0)
{
if (n == 1 && exp > 1)
{
if (count == 0)
{
*root = 5;
return exp;
} else if (count == exp)
{
*root = 10;
return exp;
}
}
return 0;
}
if (count > 0)
return 0;
exp = 0;
while ((n % 7) == 0)
{
n /= 7;
exp += 1;
}
if (exp > 0)
{
if (n == 1 && exp > 1)
{
*root = 7;
return exp;
}
return 0;
}
exp = 0;
while ((n % 11) == 0)
{
n /= 11;
exp += 1;
}
if (exp > 0)
{
if (n == 1 && exp > 1)
{
*root = 11;
return exp;
}
return 0;
}
exp = 0;
while ((n % 13) == 0)
{
n /= 13;
exp += 1;
}
if (exp > 0)
{
if (n == 1 && exp > 1)
{
*root = 13;
return exp;
}
return 0;
}
#endif
return 0;
}
| /*
Copyright (C) 2009 Thomas Boothby
Copyright (C) 2009, 2017 William Hart
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
Main.mli | (******************************************************************************)
(* *)
(* Monolith *)
(* *)
(* François Pottier *)
(* *)
(* Copyright Inria. All rights reserved. This file is distributed under the *)
(* terms of the GNU Lesser General Public License as published by the Free *)
(* Software Foundation, either version 3 of the License, or (at your *)
(* option) any later version, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
|
|
gPack.mli | (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
(* and/or modify it under the terms of the GNU Library General *)
(* Public License as published by the Free Software Foundation *)
(* version 2, with the exception described in file COPYING which *)
(* comes with the library. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Library General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU Library General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 59 Temple Place, Suite 330, *)
(* Boston, MA 02111-1307 USA *)
(* *)
(* *)
(**************************************************************************)
(* $Id$ *)
open Gtk
open GObj
open GContainer
(** Several container widgets *)
(** {3 Boxes} *)
(** @gtkdoc gtk GtkBox *)
class box_skel : ([> box] as 'a) obj ->
object
inherit GContainer.container
val obj : 'a obj
method pack :
?from:Tags.pack_type ->
?expand:bool -> ?fill:bool -> ?padding:int -> widget -> unit
(** @param from default value is [`START]
@param expand default value is [false]
@param fill default value is [true], ignored if [expand] is [false] *)
method reorder_child : widget -> pos:int -> unit
method set_child_packing :
?from:Tags.pack_type ->
?expand:bool -> ?fill:bool -> ?padding:int -> widget -> unit
method set_homogeneous : bool -> unit
method homogeneous : bool
method set_spacing : int -> unit
method spacing : int
end
(** A base class for box containers
@gtkdoc gtk GtkBox *)
class box : ([> Gtk.box] as 'a) obj ->
object
inherit box_skel
val obj : 'a obj
method connect : GContainer.container_signals
end
(** @gtkdoc gtk GtkBox
@param homogeneous default value is [false] *)
val box :
Tags.orientation ->
?homogeneous:bool ->
?spacing:int ->
?border_width:int ->
?width:int ->
?height:int -> ?packing:(widget -> unit) -> ?show:bool -> unit -> box
(** @gtkdoc gtk GtkVBox
@param homogeneous default value is [false] *)
val vbox :
?homogeneous:bool ->
?spacing:int ->
?border_width:int ->
?width:int ->
?height:int -> ?packing:(widget -> unit) -> ?show:bool -> unit -> box
(** @gtkdoc gtk GtkHVBox
@param homogeneous default value is [false] *)
val hbox :
?homogeneous:bool ->
?spacing:int ->
?border_width:int ->
?width:int ->
?height:int -> ?packing:(widget -> unit) -> ?show:bool -> unit -> box
(** @gtkdoc gtk GtkButtonBox *)
class button_box : ([> Gtk.button_box] as 'a) obj ->
object
inherit box
val obj : 'a obj
method set_child_ipadding : ?x:int -> ?y:int -> unit -> unit (** @deprecated . *)
method set_child_size : ?width:int -> ?height:int -> unit -> unit (** @deprecated . *)
method set_layout : Gtk.Tags.button_box_style -> unit
method layout : Gtk.Tags.button_box_style
method get_child_secondary : widget -> bool (** @since GTK 2.4 *)
method set_child_secondary : widget -> bool -> unit (** @since GTK 2.4 *)
end
(** @gtkdoc gtk GtkButtonBox *)
val button_box :
Tags.orientation ->
?spacing:int ->
?child_width:int ->
?child_height:int ->
?child_ipadx:int ->
?child_ipady:int ->
?layout:GtkPack.BBox.bbox_style ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> button_box
(** {3 GtkTable} *)
(** Pack widgets in regular patterns
@gtkdoc gtk GtkTable *)
class table :
Gtk.table obj ->
object
inherit GContainer.container_full
val obj : Gtk.table obj
method attach :
left:int ->
top:int ->
?right:int ->
?bottom:int ->
?expand:Tags.expand_type ->
?fill:Tags.expand_type ->
?shrink:Tags.expand_type ->
?xpadding:int -> ?ypadding:int -> widget -> unit
(** @param left column number to attach the left side of the widget to
@param top row number to attach the top of the widget to
@param right default value is [left+1]
@param bottom default value is [top+1]
@param expand default value is [`NONE]
@param fill default value is [`BOTH]
@param shrink default value is [`NONE] *)
method col_spacings : int
method columns : int
method homogeneous : bool
method row_spacings : int
method rows : int
method set_col_spacing : int -> int -> unit
method set_col_spacings : int -> unit
method set_columns : int -> unit
method set_homogeneous : bool -> unit
method set_row_spacing : int -> int -> unit
method set_row_spacings : int -> unit
method set_rows : int -> unit
end
(** @gtkdoc gtk GtkTable *)
val table :
?columns:int ->
?rows:int ->
?homogeneous:bool ->
?row_spacings:int ->
?col_spacings:int ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> table
(** {3 GtkFixed} *)
(** A container which allows you to position widgets at fixed coordinates
@gtkdoc gtk GtkFixed *)
class fixed :
Gtk.fixed obj ->
object
inherit GContainer.container_full
val obj : Gtk.fixed obj
method event : event_ops
method move : widget -> x:int -> y:int -> unit
method put : widget -> x:int -> y:int -> unit
method set_has_window : bool -> unit
method has_window : bool
end
(** @gtkdoc gtk GtkFixed *)
val fixed :
?has_window: bool ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> fixed
(** {3 GtkLayout} *)
(** Infinite scrollable area containing child widgets and/or custom drawing
@gtkdoc gtk GtkLayout *)
class layout :
'a obj ->
object
inherit GContainer.container_full
constraint 'a = [> Gtk.layout]
val obj : 'a obj
method event : event_ops
method bin_window : Gdk.window
method freeze : unit -> unit
method hadjustment : GData.adjustment
method height : int
method move : widget -> x:int -> y:int -> unit
method put : widget -> x:int -> y:int -> unit
method set_hadjustment : GData.adjustment -> unit
method set_height : int -> unit
method set_vadjustment : GData.adjustment -> unit
method set_width : int -> unit
method thaw : unit -> unit
method vadjustment : GData.adjustment
method width : int
end
(** @gtkdoc gtk GtkLayout *)
val layout :
?hadjustment:GData.adjustment ->
?vadjustment:GData.adjustment ->
?layout_width:int ->
?layout_height:int ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> layout
(** {3 GtkNotebook} *)
(** @gtkdoc gtk GtkNotebook *)
class notebook_signals : [> Gtk.notebook] obj ->
object
inherit GContainer.container_signals
method change_current_page : callback:(int -> unit) -> GtkSignal.id
method create_window : callback:(page:GObj.widget -> x:int -> y:int -> unit) -> GtkSignal.id
method move_focus_out : callback:(GtkEnums.direction_type -> unit) -> GtkSignal.id
method notify_enable_popup : callback:(bool -> unit) -> GtkSignal.id
method notify_homogeneous_tabs : callback:(bool -> unit) -> GtkSignal.id
method notify_scrollable : callback:(bool -> unit) -> GtkSignal.id
method notify_show_border : callback:(bool -> unit) -> GtkSignal.id
method notify_show_tabs : callback:(bool -> unit) -> GtkSignal.id
method notify_tab_hborder : callback:(int -> unit) -> GtkSignal.id
method notify_tab_pos : callback:(GtkEnums.position_type -> unit) -> GtkSignal.id
method notify_tab_vborder : callback:(int -> unit) -> GtkSignal.id
method page_added : callback:(GObj.widget -> int -> unit) -> GtkSignal.id
method page_removed : callback:(GObj.widget -> int -> unit) -> GtkSignal.id
method page_reordered : callback:(GObj.widget -> int -> unit) -> GtkSignal.id
method reorder_tab : callback:(GtkEnums.direction_type -> bool -> unit) -> GtkSignal.id
method select_page : callback:(bool -> unit) -> GtkSignal.id
method switch_page : callback:(int -> unit) -> GtkSignal.id
end
(** A tabbed notebook container
@gtkdoc gtk GtkNotebook *)
class notebook : Gtk.notebook obj ->
object
inherit GContainer.container
val obj : Gtk.notebook obj
method as_notebook : Gtk.notebook Gtk.obj
method event : event_ops
method append_page :
?tab_label:widget -> ?menu_label:widget -> widget -> int
method connect : notebook_signals
method current_page : int
method get_menu_label : widget -> widget
method get_nth_page : int -> widget
method get_tab_label : widget -> widget
method get_tab_reorderable : widget -> bool
method goto_page : int -> unit
method insert_page :
?tab_label:widget -> ?menu_label:widget -> ?pos:int -> widget -> int
method next_page : unit -> unit
method page_num : widget -> int
method prepend_page :
?tab_label:widget -> ?menu_label:widget -> widget -> int
method previous_page : unit -> unit
method remove_page : int -> unit
method reorder_child : widget -> int -> unit
method set_enable_popup : bool -> unit
method set_homogeneous_tabs : bool -> unit
method set_page :
?tab_label:widget -> ?menu_label:widget -> widget -> unit
method set_scrollable : bool -> unit
method set_show_border : bool -> unit
method set_show_tabs : bool -> unit
method set_tab_border : int -> unit
method set_tab_hborder : int -> unit
method set_tab_reorderable : widget -> bool -> unit
method set_tab_vborder : int -> unit
method set_tab_pos : Tags.position -> unit
method enable_popup : bool
method homogeneous_tabs : bool
method scrollable : bool
method show_border : bool
method show_tabs : bool
method tab_hborder : int
method tab_pos : GtkEnums.position_type
method tab_vborder : int
end
(** @gtkdoc gtk GtkNotebook *)
val notebook :
?enable_popup:bool ->
?homogeneous_tabs:bool ->
?scrollable:bool ->
?show_border:bool ->
?show_tabs:bool ->
?tab_border:int ->
?tab_pos:Tags.position ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> notebook
(** {3 GtkPaned} *)
(** Base class for widgets with two adjustable panes
@gtkdoc gtk GtkPaned *)
class paned :
Gtk.paned obj ->
object
inherit GContainer.container_full
val obj : Gtk.paned obj
method event : event_ops
method add1 : widget -> unit
method add2 : widget -> unit
method pack1 : ?resize:bool -> ?shrink:bool -> widget -> unit
(** @param resize default value is [false]
@param shrink default value is [false] *)
method pack2 : ?resize:bool -> ?shrink:bool -> widget -> unit
(** @param resize default value is [false]
@param shrink default value is [false] *)
method child1 : widget
method child2 : widget
method set_position : int -> unit
method position : int
method max_position : int (** @since GTK 2.4 *)
method min_position : int (** @since GTK 2.4 *)
end
(** @gtkdoc gtk GtkPaned *)
val paned :
Tags.orientation ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> paned
| (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
(* and/or modify it under the terms of the GNU Library General *)
(* Public License as published by the Free Software Foundation *)
(* version 2, with the exception described in file COPYING which *)
(* comes with the library. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Library General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU Library General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 59 Temple Place, Suite 330, *)
(* Boston, MA 02111-1307 USA *)
(* *)
(* *)
(**************************************************************************)
|
types.h | /* -*- Mode:C; c-basic-offset:4; tab-width:4 -*-
****************************************************************************
* (C) 2003 - Rolf Neugebauer - Intel Research Cambridge
****************************************************************************
*
* File: types.h
* Author: Rolf Neugebauer ([email protected])
* Changes:
*
* Date: May 2003
*
* Environment: Xen Minimal OS
* Description: a random collection of type definitions
*
****************************************************************************
* $Id: h-insert.h,v 1.4 2002/11/08 16:03:55 rn Exp $
****************************************************************************
*/
#ifndef _TYPES_H_
#define _TYPES_H_
#include <stddef.h>
/* FreeBSD compat types */
#ifndef HAVE_LIBC
typedef unsigned char u_char;
typedef unsigned int u_int;
typedef unsigned long u_long;
#endif
#if defined(__i386__) || defined(__arm__)
typedef long long quad_t;
typedef unsigned long long u_quad_t;
#elif defined(__x86_64__)
typedef long quad_t;
typedef unsigned long u_quad_t;
#endif /* __i386__ || __x86_64__ */
#ifdef HAVE_LIBC
#include <limits.h>
#include <stdint.h>
#else
#if defined(__i386__) || defined(__arm__)
typedef unsigned int uintptr_t;
typedef int intptr_t;
#elif defined(__x86_64__) || defined(__aarch64__)
typedef unsigned long uintptr_t;
typedef long intptr_t;
#endif /* __i386__ || __x86_64__ */
typedef unsigned char uint8_t;
typedef signed char int8_t;
typedef unsigned short uint16_t;
typedef signed short int16_t;
typedef unsigned int uint32_t;
typedef signed int int32_t;
#if defined(__i386__) || defined(__arm__)
typedef signed long long int64_t;
typedef unsigned long long uint64_t;
#elif defined(__x86_64__) || defined(__aarch64__)
typedef signed long int64_t;
typedef unsigned long uint64_t;
#endif
typedef uint64_t uintmax_t;
typedef int64_t intmax_t;
typedef int64_t off_t;
#endif
typedef intptr_t ptrdiff_t;
#ifndef HAVE_LIBC
typedef long ssize_t;
#endif
#endif /* _TYPES_H_ */
| /* -*- Mode:C; c-basic-offset:4; tab-width:4 -*-
****************************************************************************
* (C) 2003 - Rolf Neugebauer - Intel Research Cambridge
****************************************************************************
*
* File: types.h
* Author: Rolf Neugebauer ([email protected])
* Changes:
*
* Date: May 2003
*
* Environment: Xen Minimal OS
* Description: a random collection of type definitions
*
****************************************************************************
* $Id: h-insert.h,v 1.4 2002/11/08 16:03:55 rn Exp $
****************************************************************************
*/ |
streaming.ml |
open! Core
open! Async
let connect_and_get_pipe hnp =
let%bind client =
Rpc.Connection.client (Tcp.Where_to_connect.of_host_and_port hnp)
>>| Result.map_error ~f:Error.of_exn
|> Deferred.Or_error.ok_exn
in
Rpc.Pipe_rpc.dispatch_exn Fzf_test_lib.pipe_rpc client () >>| fst
;;
let command =
Command.async
~summary:"streaming fzf testing binary"
(let%map_open.Command hnp = anon ("host and port" %: host_and_port) in
fun () ->
let%bind pipe = connect_and_get_pipe hnp in
let%map result =
Fzf.pick_one (Streaming (Fzf.Streaming.of_strings_raise_on_newlines pipe))
|> Deferred.Or_error.ok_exn
in
print_s [%message (result : string option)])
;;
let () = Command_unix.run command
| |
dune |
(copy_files ../../common/{jsoo_lib.ml,jsoo_lib.mli})
(library
(public_name bls12-381-js)
(name bls12_381_js)
(modules bls12_381 fq12 fr g1 g2 pairing stubs jsoo_lib)
(private_modules stubs jsoo_lib)
(modes byte)
(preprocess (pps js_of_ocaml-ppx))
(implements bls12-381)
(libraries bls12-381-gen bls12-381-js-gen zarith js_of_ocaml js_of_ocaml-ppx)
)
| |
selective.mli | (** A [Selective] (applicative functor) allows to declare effects statically and
select which execute dynamically. It is an algebraic structure between
{!module:Applicative} and {!module:Monad}. A [Selective] is also an
{!module:Applicative}. *)
(** {2 Laws}
To have a predictable behaviour, the instance of [Selective] must obey some
laws.
+ [x <*? pure id = Either.case id id <$> x]
+ [pure x <*? (y *> z) = (pure x <*? y) *> (pure x <*? z)]
+ [x <*? (y <*? z) = (f <$> x) <*? (g <$> y) <*? (h <$> z)]
+ [f <$> select x y) = (select (Bifunctor.map_snd f <$> x) (((%) f) <$> y)]
+ [(select (Bifunctor.map_fst f <$> x) y) = (select x ((%>) f) <$> y))]
+ [(select x (f <$> y)) = (select (Bifunctor.map_fst (flip f) <$> x) ((|>) \
<$> y))]
+ [(x <*? pure y) = (Either.case y id <$> x)]
+ [(pure (Right x) <*? y) = pure x]
+ [(pure (Left x) <*? y) = ((|>) x) <$> y]
{3 Laws for Rigid Selectives}
A [selective] is [Rigid] if [apply] can be defined in term of [select]
+ [f <*> g = apply f g]
+ [(x *> (y <*? z)) = ((x *> y) <*? z)] *)
open Preface_core.Shims
(** {1 Minimal definition} *)
(** Minimal definition using [select] without {!module:Applicative}
requirements. *)
module type WITH_SELECT = sig
type 'a t
(** The type held by the [Selective]. *)
val select : ('a, 'b) Either.t t -> ('a -> 'b) t -> 'b t
(** [select e f] apply [f] if [e] is [Left]. It allow to skip effect using
[Right]. *)
end
(** Minimal definition using [branch] without {!module:Applicative}
requirements. *)
module type WITH_BRANCH = sig
type 'a t
(** The type held by the [Selective]. *)
val branch : ('a, 'b) Either.t t -> ('a -> 'c) t -> ('b -> 'c) t -> 'c t
(** [branch] is like [select]. It chooses between two effects. *)
end
(** Standard requirement including [pure] and [select]. *)
module type WITH_PURE_AND_SELECT = sig
include WITH_SELECT
(** @inline *)
val pure : 'a -> 'a t
(** Create a new ['a t]. *)
end
(** Standard requirement including [pure] and [branch]. *)
module type WITH_PURE_AND_BRANCH = sig
include WITH_BRANCH
(** @inline *)
val pure : 'a -> 'a t
(** Create a new ['a t]. *)
end
(** {1 Structure anatomy} *)
(** Basis operation. *)
module type CORE = sig
include WITH_SELECT
(** @inline *)
include WITH_BRANCH with type 'a t := 'a t
(** @inline *)
include Applicative.CORE with type 'a t := 'a t
(** @inline *)
end
(** Additional operations. *)
module type OPERATION = sig
type 'a t
(** The type held by the [Selective]. *)
include Applicative.OPERATION with type 'a t := 'a t
(** @inline *)
val if_ : bool t -> 'a t -> 'a t -> 'a t
(** Same of [branch] but using a [Boolean] as disjunction. *)
val bind_bool : bool t -> (bool -> 'a t) -> 'a t
(** {!module:Monad} [bind] specialized for Boolean. *)
val when_ : bool t -> unit t -> unit t
(** Conditionally perform an effect. *)
val exists : ('a -> bool t) -> 'a list -> bool t
(** Selective version of [List.exists]. *)
val for_all : ('a -> bool t) -> 'a list -> bool t
(** Selective version of [List.for_all]. *)
val or_ : bool t -> bool t -> bool t
(** Or combinator. *)
val and_ : bool t -> bool t -> bool t
(** And combinator. *)
val while_ : bool t -> unit t
(** Keep checking an effectful condition while it holds. *)
end
(** Syntax extensions. *)
module type SYNTAX = sig
include Applicative.SYNTAX
(** @inline *)
end
(** Infix operators. *)
module type INFIX = sig
type 'a t
(** The type held by the [Selective]. *)
include Applicative.INFIX with type 'a t := 'a t
(** @inline *)
val ( <*? ) : ('a, 'b) Either.t t -> ('a -> 'b) t -> 'b t
(** Infix version of {!val:CORE.select}. *)
val ( <||> ) : bool t -> bool t -> bool t
(** Infix version of {!val:CORE.or_}. *)
val ( <&&> ) : bool t -> bool t -> bool t
(** Infix version of {!val:CORE.and_}. *)
end
(** {1 Complete API} *)
(** The complete interface of a [Selective]. *)
module type API = sig
(** {1 Type} *)
type 'a t
(** The type held by the [Selective]. *)
(** {1 Functions} *)
include CORE with type 'a t := 'a t
(** @inline *)
include OPERATION with type 'a t := 'a t
(** @inline *)
(** {1 Infix operators} *)
module Infix : INFIX with type 'a t = 'a t
include INFIX with type 'a t := 'a t
(** @inline *)
(** {1 Syntax} *)
module Syntax : SYNTAX with type 'a t = 'a t
include SYNTAX with type 'a t := 'a t
(** @inline *)
end
(** {1 Additional references}
- {{:http://hackage.haskell.org/package/selective} Haskell's documentation
of a Selective Application Functor}
- {{:https://www.staff.ncl.ac.uk/andrey.mokhov/selective-functors.pdf}
Selective Applicative Functors} *)
| (** A [Selective] (applicative functor) allows to declare effects statically and
select which execute dynamically. It is an algebraic structure between
{!module:Applicative} and {!module:Monad}. A [Selective] is also an
{!module:Applicative}. *) |
client_proto_utils_commands.ml | open Client_proto_utils
let group = {Clic.name = "utilities"; title = "Utility Commands"}
let unsigned_block_header_param =
let open Clic in
param
~name:"unsigned block header"
~desc:"A hex or JSON encoded unsigned block header"
@@ parameter (fun _ s ->
let bytes_opt = `Hex s |> Hex.to_bytes in
let enc = Protocol.Alpha_context.Block_header.unsigned_encoding in
Option.bind bytes_opt (Data_encoding.Binary.of_bytes_opt enc)
|> function
| Some s -> return s
| None -> (
let error =
Exn
(Failure
"Cannot decode unsigned block header: is it valid JSON or \
hexadecimal?")
in
let open Data_encoding.Json in
from_string s |> function
| Error _ -> fail error
| Ok json -> (
try destruct enc json |> return with _ -> fail error)))
let commands () =
let open Clic in
let string_param ~name ~desc =
param ~name ~desc Client_proto_args.string_parameter
in
let block_arg =
default_arg
~long:"branch"
~short:'b'
~placeholder:"hash|tag"
~doc:
"Block hash used to create the no-op operation to sign (possible tags \
are 'head' and 'genesis'). Defaults to 'genesis'. Note that the the \
genesis block hash is network-dependent."
~default:(Block_services.to_string `Genesis)
(Client_config.block_parameter ())
in
[
command
~group
~desc:
"Sign a message and display it using the failing_noop operation. This \
operation is not executable in the protocol. Please note that \
signing/checking an arbitrary message in itself is not sufficient to \
verify a key ownership"
(args1 block_arg)
(prefixes ["sign"; "message"]
@@ string_param ~name:"message" ~desc:"message to sign"
@@ prefixes ["for"]
@@ Client_keys.Secret_key.source_param
~name:"src"
~desc:"name of the signer contract"
@@ stop)
(fun block_head message src_sk cctxt ->
Shell_services.Blocks.hash cctxt ~chain:cctxt#chain ~block:block_head ()
>>=? fun block ->
sign_message cctxt ~src_sk ~block ~message >>=? fun signature ->
cctxt#message "Signature: %a" Signature.pp signature >>= fun () ->
return_unit);
command
~group
~desc:
"Check the signature of an arbitrary message using the failing_noop \
operation. Please note that signing/checking an arbitrary message in \
itself is not sufficient to verify a key ownership."
(args2
block_arg
(switch ~doc:"Use only exit codes" ~short:'q' ~long:"quiet" ()))
(prefixes ["check"; "that"; "message"]
@@ string_param ~name:"message" ~desc:"signed message"
@@ prefixes ["was"; "signed"; "by"]
@@ Client_keys.Public_key.alias_param
~name:"signer"
~desc:"name of the signer contract"
@@ prefixes ["to"; "produce"]
@@ param
~name:"signature"
~desc:"the signature to check"
Client_proto_args.signature_parameter
@@ stop)
(fun (block_head, quiet)
message
(_, (key_locator, _))
signature
(cctxt : #Protocol_client_context.full) ->
Shell_services.Blocks.hash cctxt ~chain:cctxt#chain ~block:block_head ()
>>=? fun block ->
check_message cctxt ~key_locator ~block ~quiet ~message ~signature
>>=? function
| false -> cctxt#error "invalid signature"
| true ->
if quiet then return_unit
else
cctxt#message "Signature check successful" >>= fun () ->
return_unit);
command
~group
~desc:
"Sign an arbitrary unsigned block header for a given delegate and \
return the signed block."
no_options
(prefixes ["sign"; "block"]
@@ unsigned_block_header_param
@@ prefixes ["for"]
@@ Client_keys.Public_key_hash.source_param
~name:"delegate"
~desc:"signing delegate"
@@ stop)
(fun ()
unsigned_block_header
delegate
(cctxt : #Protocol_client_context.full) ->
let unsigned_header =
Data_encoding.Binary.to_bytes_exn
Protocol.Alpha_context.Block_header.unsigned_encoding
unsigned_block_header
in
Shell_services.Chain.chain_id cctxt ~chain:cctxt#chain ()
>>=? fun chain_id ->
Client_keys.get_key cctxt delegate >>=? fun (_, _, sk) ->
Client_keys.sign
cctxt
~watermark:
(Protocol.Alpha_context.Block_header.to_watermark
(Block_header chain_id))
sk
unsigned_header
>>=? fun s -> cctxt#message "%a" Hex.pp (Signature.to_hex s) >>= return);
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020 Metastate AG <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
layout.mli | (** The layout of the Dune cache storage, used by local and cloud build caches. *)
(* CR-someday amokhov: Jenga used "value" entries to store the standard output
of anonymous actions, but Dune currently stores everything in "file" entries.
We decided to keep support for values for now but will re-evaluate this
decision in 6 months. *)
open Stdune
open Import
(** The path to the root directory of the cache. *)
val root_dir : Path.t
(** Create a few subdirectories in [root_dir]. We expose this function because
we don't want to modify the file system when the cache is disabled. *)
val create_cache_directories : unit -> unit
(** This directory stores metadata files, one per each historically executed
build rule or output-producing action. (While this is a convenient mental
model, in reality we need to occasionally remove some outdated metadata
files to free disk space.)
A metadata file corresponding to a build rule is named by the rule digest
and stores file names and content digests of all artifacts produced by the
rule.
A metadata file corresponding to an output-producing action is named by the
action digest and stores the content digest of the resulting output. *)
val metadata_storage_dir : Path.t
(** Path to the metadata file corresponding to a build action or rule with the
given [rule_or_action_digest]. *)
val metadata_path : rule_or_action_digest:Digest.t -> Path.t
(** This is a storage for artifacts, where files named by content digests store
the matching contents. We will create hard links to these files from build
directories and rely on the hard link count, as well as on the last access
time as useful metrics during cache trimming. *)
val file_storage_dir : Path.t
(** Path to the artifact corresponding to a given [file_digest]. *)
val file_path : file_digest:Digest.t -> Path.t
(** This is a storage for outputs and, more generally, other values that the
build system might choose to store in the cache in future. As in
[files_path], we store the values in the files named by their content
digests. However, these files will always have the hard link count equal to
one because they do not appear anywhere in build directories. By storing
them in a separate directory, we simplify the job of the cache trimmer. *)
val value_storage_dir : Path.t
(** Path to the value corresponding to a given [value_digest]. *)
val value_path : value_digest:Digest.t -> Path.t
(** This directory contains temporary files used for atomic file operations
needed when storing new artifacts in the cache. See [write_atomically]. *)
val temp_dir : Path.t
(** Support for all versions of the layout, used by the cache trimmer. The
functions provided by the top module are obtained by a partial application
of the corresponding function defined here to a suitable current version. *)
module Versioned : sig
val metadata_storage_dir : Version.Metadata.t -> Path.t
val metadata_path :
Version.Metadata.t -> rule_or_action_digest:Digest.t -> Path.t
val file_storage_dir : Version.File.t -> Path.t
val file_path : Version.File.t -> file_digest:Digest.t -> Path.t
val value_storage_dir : Version.Value.t -> Path.t
val value_path : Version.Value.t -> value_digest:Digest.t -> Path.t
(** List all metadata entries currently stored in the cache. Note that there
is no guarantee that the result is up-to-date, since files can be added or
removed concurrently by other processes. *)
val list_metadata_entries : Version.Metadata.t -> (Path.t * Digest.t) list
(** List [list_metadata_entries] but for file entries. *)
val list_file_entries : Version.File.t -> (Path.t * Digest.t) list
(** List [list_metadata_entries] but for value entries. *)
val list_value_entries : Version.Value.t -> (Path.t * Digest.t) list
end
| (** The layout of the Dune cache storage, used by local and cloud build caches. *)
|
client_proto_fa12_commands.ml | open Protocol
open Alpha_context
open Client_proto_args
let group =
{
Tezos_clic.name = "tokens";
title = "Commands for managing FA1.2-compatible smart contracts";
}
let alias_param = Client_proto_contracts.ContractAlias.destination_param
let token_contract_param () =
alias_param
~name:"contract"
~desc:"name or address of the FA1.2-compatible contract"
let from_param () =
alias_param ~name:"from" ~desc:"name or address of the sender"
let to_param () = alias_param ~name:"to" ~desc:"name or address of the receiver"
let amount_param () =
Tezos_clic.param
~name:"amount"
~desc:"number of tokens"
(Tezos_clic.parameter (fun _ s ->
try
let v = Z.of_string s in
assert (Compare.Z.(v >= Z.zero)) ;
return v
with _ -> failwith "invalid amount (must be a non-negative number)"))
let tez_amount_arg =
tez_arg ~default:"0" ~parameter:"tez-amount" ~doc:"amount in \xEA\x9C\xA9"
let as_arg =
Client_proto_contracts.ContractAlias.destination_arg
~name:"as"
~doc:"name or address of the caller of the contract"
()
let payer_arg =
Client_proto_contracts.ContractAlias.destination_arg
~name:"payer"
~doc:"name of the payer (i.e. SOURCE) contract for the transaction"
()
let callback_entrypoint_arg =
Tezos_clic.arg
~doc:"Entrypoint the view should use to callback to"
~long:"callback-entrypoint"
~placeholder:"name"
string_parameter
let contract_call_options =
Tezos_clic.args14
tez_amount_arg
fee_arg
Client_proto_context_commands.dry_run_switch
Client_proto_context_commands.verbose_signing_switch
gas_limit_arg
storage_limit_arg
counter_arg
no_print_source_flag
minimal_fees_arg
minimal_nanotez_per_byte_arg
minimal_nanotez_per_gas_unit_arg
force_low_fee_arg
fee_cap_arg
burn_cap_arg
let contract_view_options =
Tezos_clic.args15
callback_entrypoint_arg
tez_amount_arg
fee_arg
Client_proto_context_commands.dry_run_switch
Client_proto_context_commands.verbose_signing_switch
gas_limit_arg
storage_limit_arg
counter_arg
no_print_source_flag
minimal_fees_arg
minimal_nanotez_per_byte_arg
minimal_nanotez_per_gas_unit_arg
force_low_fee_arg
fee_cap_arg
burn_cap_arg
let view_options =
Tezos_clic.args3
run_gas_limit_arg
payer_arg
(unparsing_mode_arg ~default:"Readable")
let dummy_callback =
Contract.implicit_contract Tezos_crypto.Signature.V0.Public_key_hash.zero
let get_contract_caller_keys cctxt caller =
match Contract.is_implicit caller with
| None ->
failwith "only implicit accounts can be the source of a contract call"
| Some source ->
Client_keys_v0.get_key cctxt source >>=? fun (_, caller_pk, caller_sk) ->
return (source, caller_pk, caller_sk)
let commands_ro () : #Protocol_client_context.full Tezos_clic.command list =
Tezos_clic.
[
command
~group
~desc:"Check that a contract is FA1.2-compatible."
no_options
(prefixes ["check"; "contract"]
@@ token_contract_param ()
@@ prefixes ["implements"; "fa1.2"]
@@ stop)
(fun () (_, contract) (cctxt : #Protocol_client_context.full) ->
Client_proto_fa12.contract_has_fa12_interface
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
()
>>=? fun _ ->
Format.printf
"Contract %a has an FA1.2 interface.\n%!"
Contract.pp
contract ;
return_unit);
command
~group
~desc:"Ask for an address's balance offchain"
view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "balance"; "for"]
@@ alias_param
~name:"from"
~desc:
"name or address of the account to lookup (also the source \
contract)"
@@ stop)
(fun (gas, payer, unparsing_mode)
(_, contract)
(_, addr)
(cctxt : #Protocol_client_context.full) ->
let action =
Client_proto_fa12.Get_balance (addr, (dummy_callback, None))
in
let payer = Option.map snd payer in
Client_proto_fa12.run_view_action
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
~source:addr
?gas
?payer
~unparsing_mode
()
>>= fun res -> Client_proto_programs.print_view_result cctxt res);
command
~group
~desc:"Ask for an address's allowance offchain"
view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "allowance"; "on"]
@@ alias_param
~name:"owner"
~desc:"name or address of the account giving the allowance"
@@ prefix "as"
@@ alias_param
~name:"operator"
~desc:"name or address of the account receiving the allowance"
@@ stop)
(fun (gas, payer, unparsing_mode)
(_, contract)
(_, source)
(_, destination)
(cctxt : #Protocol_client_context.full) ->
let action =
Client_proto_fa12.Get_allowance
(source, destination, (dummy_callback, None))
in
let payer = Option.map snd payer in
Client_proto_fa12.run_view_action
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
~source
?gas
?payer
~unparsing_mode
()
>>= fun res -> Client_proto_programs.print_view_result cctxt res);
command
~group
~desc:"Ask for the contract's total token supply offchain"
view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "total"; "supply"]
@@ stop)
(fun (gas, payer, unparsing_mode)
(_, contract)
(cctxt : #Protocol_client_context.full) ->
let action =
Client_proto_fa12.Get_total_supply (dummy_callback, None)
in
let payer = Option.map snd payer in
Client_proto_fa12.run_view_action
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?gas
?payer
~unparsing_mode
()
>>= fun res -> Client_proto_programs.print_view_result cctxt res);
command
~group
~desc:"Ask for an address's balance using a callback contract"
contract_view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "balance"; "for"]
@@ alias_param
~name:"from"
~desc:
"name or address of the account to lookup (also the source \
contract)"
@@ prefixes ["callback"; "on"]
@@ alias_param
~name:"callback"
~desc:"name or address of the callback contract"
@@ stop)
(fun ( callback_entrypoint,
tez_amount,
fee,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
(_, contract)
(_, addr)
(_, callback)
(cctxt : #Protocol_client_context.full) ->
get_contract_caller_keys cctxt addr
>>=? fun (source, src_pk, src_sk) ->
let action =
Client_proto_fa12.Get_balance (addr, (callback, callback_entrypoint))
in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
Client_proto_fa12.call_contract
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
?fee
~source
~src_pk
~src_sk
~tez_amount
?gas_limit
?storage_limit
?counter
~fee_parameter
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"transfer simulation failed"
cctxt
>>= fun _ -> return_unit);
command
~group
~desc:"Ask for an address's allowance using a callback contract"
contract_view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "allowance"; "on"]
@@ alias_param
~name:"from"
~desc:"name or address of the account giving the allowance"
@@ prefix "as"
@@ alias_param
~name:"to"
~desc:"name or address of the account receiving the allowance"
@@ prefixes ["callback"; "on"]
@@ alias_param
~name:"callback"
~desc:"name or address of the callback contract"
@@ stop)
(fun ( callback_entrypoint,
tez_amount,
fee,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
(_, contract)
(_, src)
(_, dst)
(_, callback)
(cctxt : #Protocol_client_context.full) ->
get_contract_caller_keys cctxt src
>>=? fun (source, src_pk, src_sk) ->
let action =
Client_proto_fa12.Get_allowance
(src, dst, (callback, callback_entrypoint))
in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
Client_proto_fa12.call_contract
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
?fee
~source
~src_pk
~src_sk
~tez_amount
?gas_limit
?storage_limit
?counter
~fee_parameter
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"transfer simulation failed"
cctxt
>>= fun _ -> return_unit);
command
~group
~desc:
"Ask for a contract's total token supply using a callback contract"
contract_view_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param ()
@@ prefixes ["get"; "total"; "supply"; "as"]
@@ alias_param
~name:"from"
~desc:"name or address of the source account"
@@ prefixes ["callback"; "on"]
@@ alias_param
~name:"callback"
~desc:"name or address of the callback contract"
@@ stop)
(fun ( callback_entrypoint,
tez_amount,
fee,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
(_, contract)
(_, addr)
(_, callback)
(cctxt : #Protocol_client_context.full) ->
get_contract_caller_keys cctxt addr
>>=? fun (source, src_pk, src_sk) ->
let action =
Client_proto_fa12.Get_total_supply (callback, callback_entrypoint)
in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
Client_proto_fa12.call_contract
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
?fee
~source
~src_pk
~src_sk
~tez_amount
?gas_limit
?storage_limit
?counter
~fee_parameter
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"transfer simulation failed"
cctxt
>>= fun _ -> return_unit);
]
let commands_rw () : #Protocol_client_context.full Tezos_clic.command list =
let open Client_proto_args in
Tezos_clic.
[
command
~group
~desc:"Transfer tokens between two given accounts"
(Tezos_clic.args15
as_arg
tez_amount_arg
fee_arg
Client_proto_context_commands.dry_run_switch
Client_proto_context_commands.verbose_signing_switch
gas_limit_arg
storage_limit_arg
counter_arg
no_print_source_flag
minimal_fees_arg
minimal_nanotez_per_byte_arg
minimal_nanotez_per_gas_unit_arg
force_low_fee_arg
fee_cap_arg
burn_cap_arg)
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param () @@ prefix "transfer" @@ amount_param ()
@@ prefix "from" @@ from_param () @@ prefix "to" @@ to_param () @@ stop
)
(fun ( as_address,
tez_amount,
fee,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
(_, contract)
amount
src
(_, dst)
(cctxt : #Protocol_client_context.full) ->
let _, caller = Option.value ~default:src as_address in
get_contract_caller_keys cctxt caller
>>=? fun (source, caller_pk, caller_sk) ->
let action = Client_proto_fa12.Transfer (snd src, dst, amount) in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
Client_proto_fa12.call_contract
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
?fee
~source
~src_pk:caller_pk
~src_sk:caller_sk
~tez_amount
?gas_limit
?storage_limit
?counter
~fee_parameter
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"transfer simulation failed"
cctxt
>>= fun _ -> return_unit);
command
~group
~desc:"Allow account to transfer an amount of token"
contract_call_options
(prefixes ["from"; "fa1.2"; "contract"]
@@ token_contract_param () @@ prefix "as"
@@ alias_param ~name:"as" ~desc:"name or address of the sender"
@@ prefix "approve" @@ amount_param () @@ prefix "from"
@@ alias_param
~name:"from"
~desc:"name or address to approve withdrawal"
@@ stop)
(fun ( tez_amount,
fee,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
(_, contract)
(_, source)
amount
(_, dst)
(cctxt : #Protocol_client_context.full) ->
get_contract_caller_keys cctxt source
>>=? fun (source, src_pk, src_sk) ->
let action = Client_proto_fa12.Approve (dst, amount) in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
Client_proto_fa12.call_contract
cctxt
~chain:cctxt#chain
~block:cctxt#block
~contract
~action
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
?fee
~source
~src_pk
~src_sk
~tez_amount
?gas_limit
?storage_limit
?counter
~fee_parameter
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"transfer simulation failed"
cctxt
>>= fun _ -> return_unit);
command
~group
~desc:
"Execute multiple token transfers from a single source account. If \
one of the token transfers fails, none of them are executed."
(args14
default_fee_arg
as_arg
Client_proto_context_commands.dry_run_switch
Client_proto_context_commands.verbose_signing_switch
default_gas_limit_arg
default_storage_limit_arg
counter_arg
no_print_source_flag
minimal_fees_arg
minimal_nanotez_per_byte_arg
minimal_nanotez_per_gas_unit_arg
force_low_fee_arg
fee_cap_arg
burn_cap_arg)
(prefixes ["multiple"; "fa1.2"; "transfers"; "from"]
@@ alias_param
~name:"src"
~desc:"name or address of the source of the transfers"
@@ prefix "using"
@@ param
~name:"transfers.json"
~desc:
(Format.sprintf
"List of token transfers to inject from the source contract \
in JSON format (as a file or string). The JSON must be an \
array of objects of the form: '[ {\"token_contract\": \
address or alias, \"destination\": address or alias, \
\"amount\": non-negative integer (, <field>: <val> ...) } \
(, ...) ]', where an optional <field> can either be \
\"tez-amount\", \"fee\", \"gas-limit\" or \
\"storage-limit\". The complete schema can be inspected via \
`tezos-codec describe %s.fa1.2.token_transfer json schema`."
Protocol.name)
Client_proto_context_commands.json_file_or_text_parameter
@@ stop)
(fun ( fee,
as_address,
dry_run,
verbose_signing,
gas_limit,
storage_limit,
counter,
no_print_source,
minimal_fees,
minimal_nanotez_per_byte,
minimal_nanotez_per_gas_unit,
force_low_fee,
fee_cap,
burn_cap )
src
operations_json
cctxt ->
let _, caller = Option.value ~default:src as_address in
let fee_parameter =
{
Injection.minimal_fees;
minimal_nanotez_per_byte;
minimal_nanotez_per_gas_unit;
force_low_fee;
fee_cap;
burn_cap;
}
in
match
Data_encoding.Json.destruct
(Data_encoding.list Client_proto_fa12.token_transfer_encoding)
operations_json
with
| [] -> failwith "Empty operation list"
| operations ->
get_contract_caller_keys cctxt caller
>>=? fun (source, src_pk, src_sk) ->
Client_proto_fa12.inject_token_transfer_batch
cctxt
~chain:cctxt#chain
~block:cctxt#block
?confirmations:cctxt#confirmations
~dry_run
~verbose_signing
~sender:(snd src)
~source
~src_pk
~src_sk
~token_transfers:operations
~fee_parameter
?counter
?default_fee:fee
?default_gas_limit:gas_limit
?default_storage_limit:storage_limit
()
>>= Client_proto_context_commands.report_michelson_errors
~no_print_source
~msg:"multiple transfers simulation failed"
cctxt
>>= fun _ -> return_unit
| exception (Data_encoding.Json.Cannot_destruct (path, exn2) as exn)
-> (
match (path, operations_json) with
| [`Index n], `A lj -> (
match List.nth_opt lj n with
| Some j ->
failwith
"Invalid transfer at index %i: %a %a"
n
(fun ppf -> Data_encoding.Json.print_error ppf)
exn2
Data_encoding.Json.pp
j
| _ ->
failwith
"Invalid transfer at index %i: %a"
n
(fun ppf -> Data_encoding.Json.print_error ppf)
exn2)
| _ ->
failwith
"Invalid transfer file: %a %a"
(fun ppf -> Data_encoding.Json.print_error ppf)
exn
Data_encoding.Json.pp
operations_json));
]
let commands () = commands_ro () @ commands_rw ()
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020 Nomadic Labs <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
exec.h |
/* values of cmdtype */
#define CMDUNKNOWN -1 /* no entry in table for command */
#define CMDNORMAL 0 /* command is an executable program */
#define CMDFUNCTION 1 /* command is a shell function */
#define CMDBUILTIN 2 /* command is a shell builtin */
struct cmdentry {
int cmdtype;
union param {
int index;
const struct builtincmd *cmd;
struct funcnode *func;
} u;
};
/* action to find_command() */
#define DO_ERR 0x01 /* prints errors */
#define DO_ABS 0x02 /* checks absolute paths */
#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
#define DO_ALTPATH 0x08 /* using alternate path */
#define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
union node;
extern const char *pathopt; /* set by padvance */
void shellexec(char **, const char *, int)
__attribute__((__noreturn__));
int padvance_magic(const char **path, const char *name, int magic);
int hashcmd(int, char **);
void find_command(char *, struct cmdentry *, int, const char *);
struct builtincmd *find_builtin(const char *);
void hashcd(void);
void changepath(const char *);
#ifdef notdef
void getcmdentry(char *, struct cmdentry *);
#endif
void defun(union node *);
void unsetfunc(const char *);
int typecmd(int, char **);
int commandcmd(int, char **);
static inline int padvance(const char **path, const char *name)
{
return padvance_magic(path, name, 1);
}
| /*-
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
* Copyright (c) 1997-2005
* Herbert Xu <[email protected]>. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Kenneth Almquist.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)exec.h 8.3 (Berkeley) 6/8/95
*/ |
SFFont.ml |
type u
external createFromFile: filename:string -> u = "caml_sfFont_createFromFile"
external createFromMemory: data:string -> u = "caml_sfFont_createFromMemory"
external copy: u -> u = "caml_sfFont_copy"
external destroy: u -> unit = "caml_sfFont_destroy"
type glyph = {
advance: float;
bounds: float SFRect.t;
textureRect: int SFRect.t;
}
external getGlyph: u -> codePoint:int32 -> characterSize:int -> bold:bool -> glyph
= "caml_sfFont_getGlyph"
external getKerning: u -> first:int32 -> second:int32 -> characterSize:int -> float
= "caml_sfFont_getKerning"
external getLineSpacing: u -> characterSize:int -> float
= "caml_sfFont_getLineSpacing"
external getUnderlinePosition: u -> characterSize:int -> float
= "caml_sfFont_getUnderlinePosition"
external getUnderlineThickness: u -> characterSize:int -> float
= "caml_sfFont_getUnderlineThickness"
(* annotation "boxed" is explained here:
http://caml.inria.fr/pub/docs/manual-ocaml-4.08/intfc.html#sec433 *)
type info = { family: string } [@@boxed]
external getInfo: u -> info = "caml_sfFont_getInfo"
(* ================ *)
type t = { u:u }
let debug = true
let destroy font =
if debug
then Printf.eprintf "# finalising font...\n%!";
destroy font.u
let createFromFile ~filename =
let u = createFromFile ~filename in
let t = { u=u } in
Gc.finalise destroy t;
(t)
let createFromMemory ~data =
let u = createFromMemory ~data in
let t = { u=u } in
Gc.finalise destroy t;
(t)
let copy font =
let u = copy font.u in
let t = { u=u } in
Gc.finalise destroy t;
(t)
let getGlyph font = getGlyph font.u
let getKerning font = getKerning font.u
let getLineSpacing font = getLineSpacing font.u
let getUnderlinePosition font = getUnderlinePosition font.u
let getUnderlineThickness font = getUnderlineThickness font.u
let getInfo font = getInfo font.u
| |
tan_series.c |
#include "arb_poly.h"
#define TAN_NEWTON_CUTOFF 20
void
_arb_poly_tan_series(arb_ptr g,
arb_srcptr h, slong hlen, slong len, slong prec)
{
hlen = FLINT_MIN(hlen, len);
if (hlen == 1)
{
arb_tan(g, h, prec);
_arb_vec_zero(g + 1, len - 1);
}
else if (len == 2)
{
arb_t t;
arb_init(t);
arb_tan(g, h, prec);
arb_mul(t, g, g, prec);
arb_add_ui(t, t, 1, prec);
arb_mul(g + 1, t, h + 1, prec); /* safe since hlen >= 2 */
arb_clear(t);
}
else
{
arb_ptr t, u;
t = _arb_vec_init(2 * len);
u = t + len;
NEWTON_INIT(TAN_NEWTON_CUTOFF, len)
NEWTON_BASECASE(n)
_arb_poly_sin_cos_series_basecase(t, u, h, hlen, n, prec, 0);
_arb_poly_div_series(g, t, n, u, n, n, prec);
NEWTON_END_BASECASE
NEWTON_LOOP(m, n)
_arb_poly_mullow(u, g, m, g, m, n, prec);
arb_add_ui(u, u, 1, prec);
_arb_poly_atan_series(t, g, m, n, prec);
_arb_poly_sub(t + m, h + m, FLINT_MAX(0, hlen - m), t + m, n - m, prec);
_arb_poly_mullow(g + m, u, n, t + m, n - m, n - m, prec);
NEWTON_END_LOOP
NEWTON_END
_arb_vec_clear(t, 2 * len);
}
}
void
arb_poly_tan_series(arb_poly_t g, const arb_poly_t h, slong n, slong prec)
{
if (h->length == 0 || n == 0)
{
arb_poly_zero(g);
return;
}
if (g == h)
{
arb_poly_t t;
arb_poly_init(t);
arb_poly_tan_series(t, h, n, prec);
arb_poly_swap(g, t);
arb_poly_clear(t);
return;
}
arb_poly_fit_length(g, n);
_arb_poly_tan_series(g->coeffs, h->coeffs, h->length, n, prec);
_arb_poly_set_length(g, n);
_arb_poly_normalise(g);
}
| /*
Copyright (C) 2013 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/ |
script_typed_ir_size.mli | (** This module provides overapproximation of memory footprint for
Michelson-related values.
These overapproximations are used by the cache to evaluate its own
memory footprint and enforce declared limit over its size.
*)
(** [value_size ty v] returns an overapproximation of the size of the
in-memory representation of [v] of type [ty]. *)
val value_size :
'a Script_typed_ir.ty -> 'a -> Cache_memory_helpers.nodes_and_size
(** [ty_size ty] returns an overapproximation of the size of the
in-memory representation of type [ty]. *)
val ty_size : 'a Script_typed_ir.ty -> Cache_memory_helpers.nodes_and_size
(** [comparable_ty_size cty] returns an overapproximation of the size
of the in-memory representation of comparable type [cty]. *)
val comparable_ty_size :
'a Script_typed_ir.comparable_ty -> Cache_memory_helpers.nodes_and_size
(** [lambda_size l] returns an overapproximation of the size of the
internal IR for the Michelson lambda abstraction [l]. *)
val lambda_size :
('a, 'b) Script_typed_ir.lambda -> Cache_memory_helpers.nodes_and_size
(** [kinstr_size i] returns an overapproximation of the size of the
internal IR [i]. *)
val kinstr_size :
('a, 's, 'r, 'f) Script_typed_ir.kinstr -> Cache_memory_helpers.nodes_and_size
(** [node_size root] returns the size of the in-memory representation
of [root] in bytes. This is an over-approximation of the memory
actually consumed by [root] since no sharing is taken into
account. *)
val node_size : Script_repr.node -> Cache_memory_helpers.nodes_and_size
(** Pointwise addition (reexport from {!Cache_memory_helpers}) *)
val ( ++ ) :
Cache_memory_helpers.nodes_and_size ->
Cache_memory_helpers.nodes_and_size ->
Cache_memory_helpers.nodes_and_size
(** Zero vector (reexport from {!Cache_memory_helpers}) *)
val zero : Cache_memory_helpers.nodes_and_size
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
voting_services.mli | open Alpha_context
val ballots :
'a #RPC_context.simple -> 'a -> Vote.ballots shell_tzresult Lwt.t
val ballot_list :
'a #RPC_context.simple -> 'a -> (Signature.Public_key_hash.t * Vote.ballot) list shell_tzresult Lwt.t
val current_period_kind :
'a #RPC_context.simple -> 'a -> Voting_period.kind shell_tzresult Lwt.t
val current_quorum :
'a #RPC_context.simple -> 'a -> Int32.t shell_tzresult Lwt.t
val listings :
'a #RPC_context.simple -> 'a -> (Signature.Public_key_hash.t * int32) list shell_tzresult Lwt.t
val proposals :
'a #RPC_context.simple -> 'a -> Int32.t Protocol_hash.Map.t shell_tzresult Lwt.t
val current_proposal :
'a #RPC_context.simple -> 'a -> Protocol_hash.t option shell_tzresult Lwt.t
val register : unit -> unit
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
dune |
(library
(name grenier_trope)
(public_name grenier.trope)
(wrapped false)
(synopsis "Track positions accross rope(-like) operations")
(libraries grenier.orderme grenier.baltree))
| |
Option.ml |
let none = None
let some x = Some x
let value x fail return =
match x with
| Some x' -> return x'
| None -> fail ()
let value_unsafe x =
match x with
| Some x' -> x'
| None -> assert false
let map f x =
match x with
| Some x' -> Some (f x')
| _ -> None
let map2 f x y =
match x, y with
| Some x', Some y' -> Some (f x' y')
| _, _ -> None
| |
bdd.ml | (* $Id: bdd.ml 7017 2005-08-12 09:22:04Z xleroy $ *)
(* Translated to Caml by Xavier Leroy *)
(* Original code written in SML by ... *)
type bdd =
| One
| Zero
| Node of bdd * int * int * bdd
let rec eval bdd vars =
match bdd with
| Zero -> false
| One -> true
| Node (l, v, _, h) -> if vars.(v) then eval h vars else eval l vars
let getId bdd =
match bdd with
| Node (_, _, id, _) -> id
| Zero -> 0
| One -> 1
let initSize_1 = (8 * 1024) - 1
let nodeC = ref 1
let sz_1 = ref initSize_1
let htab = ref (Array.make (!sz_1 + 1) [])
let n_items = ref 0
let hashVal x y v = (x lsl 1) + y + (v lsl 2)
let resize newSize =
let arr = !htab in
let newSz_1 = newSize - 1 in
let newArr = Array.make newSize [] in
let rec copyBucket bucket =
match bucket with
| [] -> ()
| n :: ns -> (
match n with
| Node (l, v, _, h) ->
let ind = hashVal (getId l) (getId h) v land newSz_1 in
newArr.(ind) <- n :: newArr.(ind);
copyBucket ns
| _ -> assert false)
in
for n = 0 to !sz_1 do
copyBucket arr.(n)
done;
htab := newArr;
sz_1 := newSz_1
let insert idl idh v ind bucket newNode =
if !n_items <= !sz_1
then (
!htab.(ind) <- newNode :: bucket;
incr n_items)
else (
resize (!sz_1 + !sz_1 + 2);
let ind = hashVal idl idh v land !sz_1 in
!htab.(ind) <- newNode :: !htab.(ind))
let resetUnique () =
sz_1 := initSize_1;
htab := Array.make (!sz_1 + 1) [];
n_items := 0;
nodeC := 1
let mkNode low v high =
let idl = getId low in
let idh = getId high in
if idl = idh
then low
else
let ind = hashVal idl idh v land !sz_1 in
let bucket = !htab.(ind) in
let rec lookup b =
match b with
| [] ->
let n =
Node
( low
, v
, (incr nodeC;
!nodeC)
, high )
in
insert (getId low) (getId high) v ind bucket n;
n
| n :: ns -> (
match n with
| Node (l, v', _id, h) ->
if v = v' && idl = getId l && idh = getId h then n else lookup ns
| _ -> assert false)
in
lookup bucket
type ordering =
| LESS
| EQUAL
| GREATER
let cmpVar (x : int) (y : int) = if x < y then LESS else if x > y then GREATER else EQUAL
let zero = Zero
let one = One
let mkVar x = mkNode zero x one
let cacheSize = 1999
let andslot1 = Array.make cacheSize 0
let andslot2 = Array.make cacheSize 0
let andslot3 = Array.make cacheSize zero
let xorslot1 = Array.make cacheSize 0
let xorslot2 = Array.make cacheSize 0
let xorslot3 = Array.make cacheSize zero
let notslot1 = Array.make cacheSize 0
let notslot2 = Array.make cacheSize one
let hash x y = ((x lsl 1) + y) mod cacheSize
let rec not n =
match n with
| Zero -> One
| One -> Zero
| Node (l, v, id, r) ->
let h = id mod cacheSize in
if id = notslot1.(h)
then notslot2.(h)
else
let f = mkNode (not l) v (not r) in
notslot1.(h) <- id;
notslot2.(h) <- f;
f
let rec and2 n1 n2 =
match n1 with
| Node (l1, v1, i1, r1) -> (
match n2 with
| Node (l2, v2, i2, r2) ->
let h = hash i1 i2 in
if i1 = andslot1.(h) && i2 = andslot2.(h)
then andslot3.(h)
else
let f =
match cmpVar v1 v2 with
| EQUAL -> mkNode (and2 l1 l2) v1 (and2 r1 r2)
| LESS -> mkNode (and2 l1 n2) v1 (and2 r1 n2)
| GREATER -> mkNode (and2 n1 l2) v2 (and2 n1 r2)
in
andslot1.(h) <- i1;
andslot2.(h) <- i2;
andslot3.(h) <- f;
f
| Zero -> Zero
| One -> n1)
| Zero -> Zero
| One -> n2
let rec xor n1 n2 =
match n1 with
| Node (l1, v1, i1, r1) -> (
match n2 with
| Node (l2, v2, i2, r2) ->
let h = hash i1 i2 in
if i1 = andslot1.(h) && i2 = andslot2.(h)
then andslot3.(h)
else
let f =
match cmpVar v1 v2 with
| EQUAL -> mkNode (xor l1 l2) v1 (xor r1 r2)
| LESS -> mkNode (xor l1 n2) v1 (xor r1 n2)
| GREATER -> mkNode (xor n1 l2) v2 (xor n1 r2)
in
andslot1.(h) <- i1;
andslot2.(h) <- i2;
andslot3.(h) <- f;
f
| Zero -> n1
| One -> not n1)
| Zero -> n2
| One -> not n2
let hwb n =
let rec h i j =
if i = j
then mkVar i
else xor (and2 (not (mkVar j)) (h i (j - 1))) (and2 (mkVar j) (g i (j - 1)))
and g i j =
if i = j
then mkVar i
else xor (and2 (not (mkVar i)) (h (i + 1) j)) (and2 (mkVar i) (g (i + 1) j))
in
h 0 (n - 1)
(* Testing *)
let seed = ref 0
let random () =
seed := (!seed * 25173) + 17431;
!seed land 1 > 0
let random_vars n =
let vars = Array.make n false in
for i = 0 to n - 1 do
vars.(i) <- random ()
done;
vars
let test_hwb bdd vars =
(* We should have
eval bdd vars = vars.(n-1) if n > 0
eval bdd vars = false if n = 0
where n is the number of "true" elements in vars. *)
let ntrue = ref 0 in
for i = 0 to Array.length vars - 1 do
if vars.(i) then incr ntrue
done;
eval bdd vars = if !ntrue > 0 then vars.(!ntrue - 1) else false
let main () =
let n = if Array.length Sys.argv >= 2 then int_of_string Sys.argv.(1) else 22 in
let ntests = if Array.length Sys.argv >= 3 then int_of_string Sys.argv.(2) else 100 in
let bdd = hwb n in
let succeeded = ref true in
for _ = 1 to ntests do
succeeded := !succeeded && test_hwb bdd (random_vars n)
done;
assert !succeeded
(*
if !succeeded
then print_string "OK\n"
else print_string "FAILED\n";
Format.eprintf "%d@." !nodeC;
exit 0
*)
let _ = main ()
| (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the Q Public License version 1.0. *)
(* *)
(***********************************************************************)
|
compose_mod_brent_kung_vec_preinv_threaded.c |
#include <gmp.h>
#include "flint.h"
#include "fmpz_vec.h"
#include "fmpz_mod_poly.h"
#include "fmpz_mod_mat.h"
#include "ulong_extras.h"
#include "thread_support.h"
typedef struct
{
fmpz_mod_poly_struct * res;
fmpz_mod_mat_struct * C;
const fmpz * h;
const fmpz * poly;
const fmpz * polyinv;
const fmpz * p;
fmpz * t;
volatile slong * j;
slong k;
slong m;
slong len;
slong leninv;
slong len2;
#if FLINT_USES_PTHREAD
pthread_mutex_t * mutex;
#endif
}
compose_vec_arg_t;
void
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_worker(void * arg_ptr)
{
compose_vec_arg_t arg = *((compose_vec_arg_t *) arg_ptr);
slong i, j, k = arg.k, n = arg.len - 1;
slong len = arg.len, leninv = arg.leninv;
fmpz * t = arg.t;
const fmpz * h = arg.h;
const fmpz * poly = arg.poly;
const fmpz * polyinv = arg.polyinv;
fmpz_mod_poly_struct * res = arg.res;
fmpz_mat_struct * C = arg.C->mat;
const fmpz * p = arg.p;
while (1)
{
#if FLINT_USES_PTHREAD
pthread_mutex_lock(arg.mutex);
#endif
j = *arg.j;
*arg.j = j + 1;
#if FLINT_USES_PTHREAD
pthread_mutex_unlock(arg.mutex);
#endif
if (j >= arg.len2)
return;
_fmpz_vec_set(res[j].coeffs, C->rows[(j + 1)*k - 1], n);
if (n == 1) /* special case, constant polynomials */
{
for (i = 2; i <= k; i++)
{
fmpz_mul(t + 0, res[j].coeffs + 0, h + 0);
fmpz_add(res[j].coeffs + 0, t + 0,
C->rows[(j + 1)*k - i] + 0);
fmpz_mod(res[j].coeffs + 0, res[j].coeffs + 0, p);
}
}
else
{
for (i = 2; i <= k; i++)
{
_fmpz_mod_poly_mulmod_preinv(t, res[j].coeffs, n, h, n, poly,
len, polyinv, leninv, p);
_fmpz_mod_poly_add(res[j].coeffs, t, n,
C->rows[(j + 1)*k - i], n, p);
}
}
}
}
void
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded_pool(fmpz_mod_poly_struct * res,
const fmpz_mod_poly_struct * polys,
slong lenpolys, slong l,
const fmpz * g, slong glen,
const fmpz * poly, slong len,
const fmpz * polyinv, slong leninv,
const fmpz_t p,
thread_pool_handle * threads,
slong num_threads)
{
fmpz_mod_mat_t A, B, C;
slong i, j, n, m, k, len2 = l, len1, shared_j = 0;
fmpz * h;
compose_vec_arg_t * args;
#if FLINT_USES_PTHREAD
pthread_mutex_t mutex;
#endif
n = len - 1;
m = n_sqrt(n*len2) + 1;
h = _fmpz_vec_init(n);
k = len/m + 1;
fmpz_mod_mat_init(A, m, n, p);
fmpz_mod_mat_init(B, k*len2, m, p);
fmpz_mod_mat_init(C, k*len2, n, p);
/* Set rows of B to the segments of polys */
for (j = 0; j < len2; j++)
{
len1 = polys[j].length;
for (i = 0; i < len1 / m; i++)
_fmpz_vec_set(B->mat->rows[i + j*k], polys[j].coeffs + i*m, m);
_fmpz_vec_set(B->mat->rows[i + j*k], polys[j].coeffs + i*m,
len1 % m);
}
/* Set rows of A to powers of last element of polys */
_fmpz_mod_poly_powers_mod_preinv_threaded_pool(A->mat->rows, g, glen,
m, poly, len, polyinv, leninv, p, threads, num_threads);
_fmpz_mod_mat_mul_classical_threaded_pool_op(C, NULL, B, A, 0,
threads, num_threads);
/* Evaluate block composition using the Horner scheme */
if (n == 1)
{
fmpz_mul(h + 0, A->mat->rows[m - 1] + 0, A->mat->rows[1] + 0);
fmpz_mod(h + 0, h + 0, p);
} else
{
_fmpz_mod_poly_mulmod_preinv(h, A->mat->rows[m - 1], n, A->mat->rows[1],
n, poly, len, polyinv, leninv, p);
}
args = (compose_vec_arg_t *)
flint_malloc(sizeof(compose_vec_arg_t)*(num_threads + 1));
for (i = 0; i < num_threads + 1; i++)
{
args[i].res = res;
args[i].C = C;
args[i].h = h;
args[i].k = k;
args[i].m = m;
args[i].j = &shared_j;
args[i].poly = poly;
args[i].t = _fmpz_vec_init(len);
args[i].len = len;
args[i].polyinv = polyinv;
args[i].leninv = leninv;
args[i].p = p;
args[i].len2 = len2;
#if FLINT_USES_PTHREAD
args[i].mutex = &mutex;
#endif
}
#if FLINT_USES_PTHREAD
pthread_mutex_init(&mutex, NULL);
#endif
for (i = 0; i < num_threads; i++)
{
thread_pool_wake(global_thread_pool, threads[i], 0,
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_worker, &args[i]);
}
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_worker(&args[num_threads]);
for (i = 0; i < num_threads; i++)
{
thread_pool_wait(global_thread_pool, threads[i]);
}
#if FLINT_USES_PTHREAD
pthread_mutex_destroy(&mutex);
#endif
for (i = 0; i < num_threads + 1; i++)
_fmpz_vec_clear(args[i].t, len);
flint_free(args);
_fmpz_vec_clear(h, n);
fmpz_mod_mat_clear(A);
fmpz_mod_mat_clear(B);
fmpz_mod_mat_clear(C);
}
void
fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded_pool(fmpz_mod_poly_struct * res,
const fmpz_mod_poly_struct * polys,
slong len1, slong n,
const fmpz_mod_poly_t g,
const fmpz_mod_poly_t poly,
const fmpz_mod_poly_t polyinv,
const fmpz_mod_ctx_t ctx,
thread_pool_handle * threads,
slong num_threads)
{
slong len2 = poly->length;
slong i;
if (n == 0)
return;
if (len2 == 1)
{
for (i = 0; i < n; i++)
fmpz_mod_poly_zero(res + i, ctx);
}
if (len2 == 2)
{
for (i = 0; i < n; i++)
fmpz_mod_poly_set(res + i, polys + i, ctx);
return;
}
for (i = 0; i < n; i++)
{
fmpz_mod_poly_fit_length(res + i, len2 - 1, ctx);
_fmpz_mod_poly_set_length(res + i, len2 - 1);
}
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded_pool(res, polys,
len1, n,
g->coeffs, g->length,
poly->coeffs, len2,
polyinv->coeffs,
polyinv->length,
fmpz_mod_ctx_modulus(ctx),
threads,
num_threads);
for (i = 0; i < n; i++)
_fmpz_mod_poly_normalise(res + i);
}
void
fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded(fmpz_mod_poly_struct * res,
const fmpz_mod_poly_struct * polys,
slong len1, slong n,
const fmpz_mod_poly_t g,
const fmpz_mod_poly_t poly,
const fmpz_mod_poly_t polyinv,
const fmpz_mod_ctx_t ctx)
{
slong i, len2 = poly->length;
thread_pool_handle * threads;
slong num_threads;
for (i = 0; i < len1; i++)
{
if (polys[i].length >= len2)
{
flint_printf
("Exception (fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded)."
"The degree of the first polynomial must be smaller than that of the "
" modulus\n");
flint_abort();
}
}
if (n > len1)
{
flint_printf
("Exception (fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded)."
"n is larger than the length of polys\n");
flint_abort();
}
if (n == 0)
return;
if (len2 == 1)
{
for (i = 0; i < n; i++)
fmpz_mod_poly_zero(res + i, ctx);
return;
}
if (len2 == 2)
{
for (i = 0; i < n; i++)
fmpz_mod_poly_set(res + i, polys + i, ctx);
return;
}
for (i = 0; i < n; i++)
{
fmpz_mod_poly_fit_length(res + i, len2 - 1, ctx);
_fmpz_mod_poly_set_length(res + i, len2 - 1);
}
num_threads = flint_request_threads(&threads, flint_get_num_threads());
_fmpz_mod_poly_compose_mod_brent_kung_vec_preinv_threaded_pool(res, polys,
len1, n,
g->coeffs, g->length,
poly->coeffs, len2,
polyinv->coeffs,
polyinv->length,
fmpz_mod_ctx_modulus(ctx),
threads,
num_threads);
flint_give_back_threads(threads, num_threads);
for (i = 0; i < n; i++)
_fmpz_mod_poly_normalise(res + i);
}
| /*
Copyright (C) 2011 Fredrik Johansson
Copyright (C) 2012 Lina Kulakova
Copyright (C) 2014 Martin Lee
Copyright (C) 2020 William Hart
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
Subsets and Splits