filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
p-gcd.c
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <gmp.h> #include "flint.h" #include "nmod_poly.h" /* Profiling and benchmarking code for GCD in nmod_poly. For three different prime moduli p[i], for a sequence of degrees degs[k], we create 100 random polynomials A, B, C of degree degs[k]/2 and then compute GCD(AC, BC) repeatedly, runs[i][k] times. */ #define N 50 int main(void) { FLINT_TEST_INIT(state); mp_limb_t p[] = {17ul, 2147483659ul, 9223372036854775837ul}; const slong degs[] = { 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 520, 540, 560, 580, 600, 620, 640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940, 960, 980, 1000}; const slong runs[3][N] = {{ 2000, 1000, 500, 300, 200, 200, 200, 180, 140, 140, 100, 80, 80, 80, 50, 50, 40, 30, 30, 20, 18, 16, 14, 12, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 5}, { 1400, 800, 400, 260, 160, 140, 120, 100, 60, 60, 50, 50, 40, 40, 30, 30, 20, 20, 20, 15, 14, 13, 12, 11, 10, 10, 10, 10, 10, 10, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4}, { 1400, 800, 400, 260, 160, 120, 100, 80, 60, 50, 50, 40, 30, 20, 20, 20, 15, 15, 15, 12, 12, 11, 11, 10, 10, 10, 10, 10, 10, 10, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4}}; clock_t c0, c1; long double cpu[3][2][N]; slong i, k, c, n; nmod_poly_t A, B, C, G; for (i = 0; i < 3; i++) { flint_printf("---[Modulus %wu]---\n", p[i]), fflush(stdout); for (k = 0; k < N; k++) { const slong d = degs[k]; const slong r = runs[i][k]; cpu[i][0][k] = 0; cpu[i][1][k] = 0; nmod_poly_init(A, p[i]); nmod_poly_init(B, p[i]); nmod_poly_init(C, p[i]); nmod_poly_init(G, p[i]); for (c = 0; c < 100; c++) { nmod_poly_randtest(A, state, d/2); nmod_poly_randtest(B, state, d/2); nmod_poly_randtest(C, state, d/2); nmod_poly_mul(A, A, C); nmod_poly_mul(B, B, C); c0 = clock(); for (n = 0; n < r; n++) nmod_poly_gcd_euclidean(G, A, B); c1 = clock(); cpu[i][0][k] += (c1 - c0); c0 = clock(); for (n = 0; n < r; n++) nmod_poly_gcd_hgcd(G, A, B); c1 = clock(); cpu[i][1][k] += (c1 - c0); } cpu[i][0][k] = (long double) cpu[i][0][k] / (long double) CLOCKS_PER_SEC; cpu[i][1][k] = (long double) cpu[i][1][k] / (long double) CLOCKS_PER_SEC; cpu[i][0][k] = (long double) cpu[i][0][k] / (long double) (100*r); cpu[i][1][k] = (long double) cpu[i][1][k] / (long double) (100*r); flint_printf("%4ld %10.WORD(8)f %10.WORD(8)f\n", A->length, cpu[i][0][k], cpu[i][1][k]); fflush(stdout); nmod_poly_clear(A); nmod_poly_clear(B); nmod_poly_clear(G); } } flint_printf("cpu = ["); for (i = 0; i < 3; i++) { flint_printf("[["); for (k = 0; k < N; k++) flint_printf("%.WORD(8)f,", cpu[i][0][k]); flint_printf("],"); flint_printf("["); for (k = 0; k < N; k++) flint_printf("%.WORD(8)f,", cpu[i][1][k]); flint_printf("]],"); } flint_printf("]\n"); flint_randclear(state); return EXIT_SUCCESS; }
/* Copyright (C) 2010, 2011 Sebastian Pancratz 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/>. */
client.ml
(** A client session example. *) module Mp_client = Mysql_protocol.Mp_client module Mp_data = Mysql_protocol.Mp_data module Mp_execute = Mysql_protocol.Mp_execute module Mp_result_set_packet = Mysql_protocol.Mp_result_set_packet module Mp_capabilities = Mysql_protocol.Mp_capabilities let run() = (* helper function to display ok result (INSERT, UPDATE... result) *) let print_result sql r = print_endline ("Result of the SQL statement \"" ^ sql ^ "\": \n " ^ (Mp_client.dml_dcl_result_to_string r) ^ "\n") in (* helper functions to display set result (SELECT result) *) let print_row fields row = let print_data f = let (field_name, field_pos) = f in let data = List.nth row field_pos in print_endline (" " ^ field_name ^ ": " ^ (Option.value (Mp_data.to_string data) ~default:"")) in let () = List.iter print_data fields in print_endline " -- -- " in let print_set sql r = let (fields, rows) = r.Mp_result_set_packet.rows in let () = print_endline ("Result set for the SQL statement \"" ^ sql ^ "\": \n") in let print_rows = let () = List.iter (print_row fields) rows in print_newline () in print_rows in (* server address *) (* let addr = Unix.inet_addr_of_string "192.168.1.20" in *) (* server port *) (* let port = 3306 in *) (* let sockaddr = Unix.ADDR_INET(addr, port) in *) let sockaddr = Unix.ADDR_UNIX "/usr/jails/mariadb/var/run/mysql/mysql.sock" in (* MySQL user login *) let db_user = "user_ocaml_ocmp" in let db_user_2 = "u_ocmp_npauth" in (* MySQL user password *) let db_password = "ocmp" in let db_password_2 = "ocmpnpauth" in (* database name *) let db_name = "test_ocaml_ocmp_utf8" in (* configuration *) let config = Mp_client.configuration ~user:db_user ~password:db_password ~sockaddr:sockaddr ~databasename:db_name () in (* connection *) let connection = Mp_client.connect ~configuration:config () in (* use database *) let () = Mp_client.use_database ~connection:connection ~databasename:db_name in (* delete table with a non prepared statement to have a clean database *) let sql = "DROP TABLE IF EXISTS ocmp_table" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result r in let r = Mp_client.get_result_ok r in let () = print_result sql r in (* create table with a non prepared statement *) let sql = "CREATE TABLE IF NOT EXISTS ocmp_table (id BIGINT AUTO_INCREMENT, col1 VARCHAR(255), col2 DECIMAL(30,10), PRIMARY KEY(id))" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result r in let r = Mp_client.get_result_ok r in let () = print_result sql r in (* send non prepared SQL statement *) let sql = "INSERT INTO ocmp_table (col1, col2) VALUES ('col1', 123.45)" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result r in let r = Mp_client.get_result_ok r in let () = print_result sql r in (* send prepared SQL statement with params *) let params = [Mp_data.data_varstring "col2"; Mp_data.data_decimal (Num.num_of_string "98765/100")] in let sql = "INSERT INTO ocmp_table (col1, col2) VALUES (?, ?)" in let stmt = Mp_client.create_statement_from_string sql in let prep = Mp_client.prepare ~connection:connection ~statement:stmt in let r = Mp_client.execute ~connection:connection ~statement:prep ~params:params () in let () = Mp_client.close_statement ~connection:connection ~statement:prep in let r = Mp_client.get_result r in let r = Mp_client.get_result_ok r in let () = print_result sql r in (* send non prepared SELECT statement *) let sql = "SELECT * FROM ocmp_table ORDER BY col1" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result r in let r = Mp_client.get_result_set r in let () = print_set sql r in (* send prepared SELECT statement with params but no fetch *) let params = [Mp_data.data_decimal (Num.num_of_string "98765/100")] in let sql = "SELECT * FROM ocmp_table WHERE col2=?" in let stmt = Mp_client.create_statement_from_string sql in let prep = Mp_client.prepare ~connection:connection ~statement:stmt in let r = Mp_client.execute ~connection:connection ~statement:prep ~params:params () in let () = Mp_client.close_statement ~connection:connection ~statement:prep in let r = Mp_client.get_result r in let r = Mp_client.get_result_set r in let () = print_set sql r in (* send prepared SELECT statement with params and fetch the result *) let params = [Mp_data.data_varstring "col1"] in let sql = "SELECT * FROM ocmp_table WHERE col1=?" in let stmt = Mp_client.create_statement_from_string sql in let prep = Mp_client.prepare ~connection:connection ~statement:stmt in let stmt = Mp_client.execute ~connection:connection ~statement:prep ~params:params ~flag:Mp_execute.Cursor_type_read_only () in let () = try while true do let rows = Mp_client.fetch ~connection:connection ~statement:stmt () in let rows = Mp_client.get_fetch_result_set rows in print_set sql rows done with | Mp_client.Fetch_no_more_rows -> () (* no more rows in the result *) in let () = Mp_client.close_statement ~connection:connection ~statement:prep in (* send non prepared SELECT statement and embed the print function *) let sql = "SELECT * FROM ocmp_table ORDER BY col1" in let stmt = Mp_client.create_statement_from_string sql in let () = print_endline ("Result set for the SQL statement \"" ^ sql ^ "\" (print function embedded): \n") in let _ = Mp_client.execute ~connection:connection ~statement:stmt ~iter:(Some print_row) () in (* PING server *) let () = Mp_client.ping ~connection:connection in (* change user *) let _ = Mp_client.change_user ~connection:connection ~user:db_user_2 ~password:db_password_2 ~databasename:db_name () in (* reset session (equivalent to a disconnect and reconnect) *) let () = Mp_client.reset_session ~connection:connection in (* reset connection without re-authentication *) let () = Mp_client.reset_connection ~connection:connection in (* catch MySQL error *) let stmt = Mp_client.create_statement_from_string ("BAD SQL QUERY") in let () = try let _ = Mp_client.execute ~connection:connection ~statement:stmt () in () with | Mp_client.Error error -> print_newline (); print_endline ("This is a test to show how to catch a MySQL error, the exception is: " ^ (Mp_client.error_exception_to_string error)); print_newline (); in (* create and call a procedure *) let sql = "DROP PROCEDURE IF EXISTS ocmp_proc" in let stmt = Mp_client.create_statement_from_string sql in let _ = Mp_client.execute ~connection:connection ~statement:stmt () in let sql = "CREATE PROCEDURE ocmp_proc() BEGIN SELECT * FROM ocmp_table; END" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result r in let r = Mp_client.get_result_ok r in let () = print_result sql r in let sql = "CALL ocmp_proc()" in let stmt = Mp_client.create_statement_from_string sql in let r = Mp_client.execute ~connection:connection ~statement:stmt () in let r = Mp_client.get_result_multiple r in let f e = try let rs = Mp_client.get_result_set e in print_set sql rs with | Failure _ -> let rs = Mp_client.get_result_ok e in let affected_rows = rs.Mp_client.affected_rows in print_endline (Printf.sprintf "Result OK: affected rows=%Ld" affected_rows) in let () = List.iter f r in (* disconnect *) let () = Mp_client.disconnect ~connection:connection in ()
michelson_v1_printer.ml
open Protocol open Alpha_context open Tezos_micheline open Micheline open Micheline_printer let anon = {comment = None} let print_expr ppf expr = expr |> Michelson_v1_primitives.strings_of_prims |> Micheline.inject_locations (fun _ -> anon) |> print_expr ppf let print_expr_unwrapped ppf expr = expr |> Michelson_v1_primitives.strings_of_prims |> Micheline.inject_locations (fun _ -> anon) |> print_expr_unwrapped ppf let print_var_annots ppf = List.iter (Format.fprintf ppf "%s ") let print_annot_expr_unwrapped ppf (expr, annot) = Format.fprintf ppf "%a%a" print_var_annots annot print_expr_unwrapped expr let print_stack ppf = function | [] -> Format.fprintf ppf "[]" | more -> Format.fprintf ppf "@[<hov 0>[ %a ]@]" (Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf "@ : ") print_annot_expr_unwrapped) more let print_execution_trace ppf trace = Format.pp_print_list (fun ppf (loc, gas, stack) -> Format.fprintf ppf "- @[<v 0>location: %d (remaining gas: %a)@,[ @[<v 0>%a ]@]@]" loc Gas.pp gas (Format.pp_print_list (fun ppf (e, annot) -> Format.fprintf ppf "@[<v 0>%a \t%s@]" print_expr e (match annot with None -> "" | Some a -> a))) stack) ppf trace let print_big_map_diff ppf lazy_storage_diff = let diff = Contract.Legacy_big_map_diff.of_lazy_storage_diff lazy_storage_diff in let pp_map ppf id = if Compare.Z.(id < Z.zero) then Format.fprintf ppf "temp(%s)" (Z.to_string (Z.neg id)) else Format.fprintf ppf "map(%s)" (Z.to_string id) in Format.fprintf ppf "@[<v 0>%a@]" (Format.pp_print_list ~pp_sep:Format.pp_print_space (fun ppf -> function | Contract.Legacy_big_map_diff.Clear id -> Format.fprintf ppf "Clear %a" pp_map id | Contract.Legacy_big_map_diff.Alloc {big_map; key_type; value_type} -> Format.fprintf ppf "New %a of type (big_map %a %a)" pp_map big_map print_expr key_type print_expr value_type | Contract.Legacy_big_map_diff.Copy {src; dst} -> Format.fprintf ppf "Copy %a to %a" pp_map src pp_map dst | Contract.Legacy_big_map_diff.Update {big_map; diff_key; diff_value; _} -> Format.fprintf ppf "%s %a[%a]%a" (match diff_value with None -> "Unset" | Some _ -> "Set") pp_map big_map print_expr diff_key (fun ppf -> function | None -> () | Some x -> Format.fprintf ppf " to %a" print_expr x) diff_value)) (diff :> Contract.Legacy_big_map_diff.item list) let inject_types type_map parsed = let rec inject_expr = function | Seq (loc, items) -> Seq (inject_loc `before loc, List.map inject_expr items) | Prim (loc, name, items, annot) -> Prim (inject_loc `after loc, name, List.map inject_expr items, annot) | Int (loc, value) -> Int (inject_loc `after loc, value) | String (loc, value) -> String (inject_loc `after loc, value) | Bytes (loc, value) -> Bytes (inject_loc `after loc, value) and inject_loc which loc = let comment = let ( >?? ) = Option.bind in List.assoc ~equal:Int.equal loc parsed.Michelson_v1_parser.expansion_table >?? fun (_, locs) -> let locs = List.sort compare locs in List.hd locs >?? fun head_loc -> List.assoc ~equal:Int.equal head_loc type_map >?? fun (bef, aft) -> let stack = match which with `before -> bef | `after -> aft in Some (Format.asprintf "%a" print_stack stack) in {comment} in inject_expr (root parsed.unexpanded) let unparse ?type_map parse expanded = let source = match type_map with | Some type_map -> let unexpanded, unexpansion_table = expanded |> Michelson_v1_primitives.strings_of_prims |> root |> Michelson_v1_macros.unexpand_rec |> Micheline.extract_locations in let rec inject_expr = function | Seq (loc, items) -> Seq (inject_loc `before loc, List.map inject_expr items) | Prim (loc, name, items, annot) -> Prim (inject_loc `after loc, name, List.map inject_expr items, annot) | Int (loc, value) -> Int (inject_loc `after loc, value) | String (loc, value) -> String (inject_loc `after loc, value) | Bytes (loc, value) -> Bytes (inject_loc `after loc, value) and inject_loc which loc = let comment = let ( >?? ) = Option.bind in List.assoc ~equal:Int.equal loc unexpansion_table >?? fun loc -> List.assoc ~equal:Int.equal loc type_map >?? fun (bef, aft) -> let stack = match which with `before -> bef | `after -> aft in Some (Format.asprintf "%a" print_stack stack) in {comment} in unexpanded |> root |> inject_expr |> Format.asprintf "%a" Micheline_printer.print_expr | None -> expanded |> Michelson_v1_primitives.strings_of_prims |> root |> Michelson_v1_macros.unexpand_rec |> Micheline.strip_locations |> Micheline_printer.printable (fun n -> n) |> Format.asprintf "%a" Micheline_printer.print_expr in match parse source with | res, [] -> res | _, _ :: _ -> Stdlib.failwith "Michelson_v1_printer.unparse" let unparse_toplevel ?type_map = unparse ?type_map Michelson_v1_parser.parse_toplevel let unparse_expression = unparse Michelson_v1_parser.parse_expression let unparse_invalid expanded = let source = expanded |> root |> Michelson_v1_macros.unexpand_rec |> Micheline.strip_locations |> Micheline_printer.printable (fun n -> n) |> Format.asprintf "%a" Micheline_printer.print_expr_unwrapped in fst (Michelson_v1_parser.parse_toplevel source) let ocaml_constructor_of_prim prim = (* Assuming all the prim constructor prefixes match the [[Michelson_v1_primitives.namespace]]. *) let prefix = Michelson_v1_primitives.(namespace prim |> string_of_namespace) in Format.asprintf "%s_%s" prefix @@ Michelson_v1_primitives.string_of_prim prim let micheline_string_of_expression ~zero_loc expression = let string_of_list : string list -> string = fun xs -> String.concat "; " xs |> Format.asprintf "[%s]" in let show_loc loc = if zero_loc then 0 else loc in let rec string_of_node = function | Int (loc, i) -> let z = match Z.to_int i with | 0 -> "Z.zero" | 1 -> "Z.one" | i -> Format.asprintf "Z.of_int %d" i in Format.asprintf "Int (%d, %s)" (show_loc loc) z | String (loc, s) -> Format.asprintf "String (%d, \"%s\")" (show_loc loc) s | Bytes (loc, b) -> Format.asprintf "Bytes (%d, Bytes.of_string \"%s\")" (show_loc loc) Bytes.(escaped b |> to_string) | Prim (loc, prim, nodes, annot) -> Format.asprintf "Prim (%d, %s, %s, %s)" (show_loc loc) (ocaml_constructor_of_prim prim) (string_of_list @@ List.map string_of_node nodes) (string_of_list @@ List.map (Format.asprintf "\"%s\"") annot) | Seq (loc, nodes) -> Format.asprintf "Seq (%d, %s)" (show_loc loc) (string_of_list @@ List.map string_of_node nodes) in string_of_node (root expression)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
parser.ml
module State = struct type 'a t = | Partial of 'a partial | Lazy of 'a t Lazy.t | Done of int * 'a | Fail of int * string list * string and 'a partial = { committed : int ; continue : Bigstringaf.t -> off:int -> len:int -> More.t -> 'a t } end type 'a with_state = Input.t -> int -> More.t -> 'a type 'a failure = (string list -> string -> 'a State.t) with_state type ('a, 'r) success = ('a -> 'r State.t) with_state type 'a t = { run : 'r. ('r failure -> ('a, 'r) success -> 'r State.t) with_state } let fail_k input pos _ marks msg = State.Fail(pos - Input.client_committed_bytes input, marks, msg) let succeed_k input pos _ v = State.Done(pos - Input.client_committed_bytes input, v) let rec to_exported_state = function | State.Partial {committed;continue} -> Exported_state.Partial { committed ; continue = fun bs ~off ~len more -> to_exported_state (continue bs ~off ~len more)} | State.Done (i,x) -> Exported_state.Done (i,x) | State.Fail (i, sl, s) -> Exported_state.Fail (i, sl, s) | State.Lazy x -> to_exported_state (Lazy.force x) let parse p = let input = Input.create Bigstringaf.empty ~committed_bytes:0 ~off:0 ~len:0 in to_exported_state (p.run input 0 Incomplete fail_k succeed_k) let parse_bigstring p input = let input = Input.create input ~committed_bytes:0 ~off:0 ~len:(Bigstringaf.length input) in Exported_state.state_to_result (to_exported_state (p.run input 0 Complete fail_k succeed_k)) module Monad = struct let return v = { run = fun input pos more _fail succ -> succ input pos more v } let fail msg = { run = fun input pos more fail _succ -> fail input pos more [] msg } let (>>=) p f = { run = fun input pos more fail succ -> let succ' input' pos' more' v = (f v).run input' pos' more' fail succ in p.run input pos more fail succ' } let (>>|) p f = { run = fun input pos more fail succ -> let succ' input' pos' more' v = succ input' pos' more' (f v) in p.run input pos more fail succ' } let (<$>) f m = m >>| f let (<*>) f m = (* f >>= fun f -> m >>| f *) { run = fun input pos more fail succ -> let succ0 input0 pos0 more0 f = let succ1 input1 pos1 more1 m = succ input1 pos1 more1 (f m) in m.run input0 pos0 more0 fail succ1 in f.run input pos more fail succ0 } let lift f m = f <$> m let lift2 f m1 m2 = { run = fun input pos more fail succ -> let succ1 input1 pos1 more1 m1 = let succ2 input2 pos2 more2 m2 = succ input2 pos2 more2 (f m1 m2) in m2.run input1 pos1 more1 fail succ2 in m1.run input pos more fail succ1 } let lift3 f m1 m2 m3 = { run = fun input pos more fail succ -> let succ1 input1 pos1 more1 m1 = let succ2 input2 pos2 more2 m2 = let succ3 input3 pos3 more3 m3 = succ input3 pos3 more3 (f m1 m2 m3) in m3.run input2 pos2 more2 fail succ3 in m2.run input1 pos1 more1 fail succ2 in m1.run input pos more fail succ1 } let lift4 f m1 m2 m3 m4 = { run = fun input pos more fail succ -> let succ1 input1 pos1 more1 m1 = let succ2 input2 pos2 more2 m2 = let succ3 input3 pos3 more3 m3 = let succ4 input4 pos4 more4 m4 = succ input4 pos4 more4 (f m1 m2 m3 m4) in m4.run input3 pos3 more3 fail succ4 in m3.run input2 pos2 more2 fail succ3 in m2.run input1 pos1 more1 fail succ2 in m1.run input pos more fail succ1 } let ( *>) a b = (* a >>= fun _ -> b *) { run = fun input pos more fail succ -> let succ' input' pos' more' _ = b.run input' pos' more' fail succ in a.run input pos more fail succ' } let (<* ) a b = (* a >>= fun x -> b >>| fun _ -> x *) { run = fun input pos more fail succ -> let succ0 input0 pos0 more0 x = let succ1 input1 pos1 more1 _ = succ input1 pos1 more1 x in b.run input0 pos0 more0 fail succ1 in a.run input pos more fail succ0 } end module Choice = struct let (<?>) p mark = { run = fun input pos more fail succ -> let fail' input' pos' more' marks msg = fail input' pos' more' (mark::marks) msg in p.run input pos more fail' succ } let (<|>) p q = { run = fun input pos more fail succ -> let fail' input' pos' more' marks msg = (* The only two constructors that introduce new failure continuations are * [<?>] and [<|>]. If the initial input position is less than the length * of the committed input, then calling the failure continuation will * have the effect of unwinding all choices and collecting marks along * the way. *) if pos < Input.parser_committed_bytes input' then fail input' pos' more marks msg else q.run input' pos more' fail succ in p.run input pos more fail' succ } end module Monad_use_for_debugging = struct let return = Monad.return let fail = Monad.fail let (>>=) = Monad.(>>=) let (>>|) m f = m >>= fun x -> return (f x) let (<$>) f m = m >>| f let (<*>) f m = f >>= fun f -> m >>| f let lift = (>>|) let lift2 f m1 m2 = f <$> m1 <*> m2 let lift3 f m1 m2 m3 = f <$> m1 <*> m2 <*> m3 let lift4 f m1 m2 m3 m4 = f <$> m1 <*> m2 <*> m3 <*> m4 let ( *>) a b = a >>= fun _ -> b let (<* ) a b = a >>= fun x -> b >>| fun _ -> x end
tx_rollup_level_repr.mli
type level = t (** @raise Invalid_argument when the level to encode is not positive *) val encoding : level Data_encoding.t val rpc_arg : level RPC_arg.arg val pp : Format.formatter -> level -> unit include Compare.S with type t := level val to_int32 : level -> int32 (** @raise Invalid_argument when the level to encode is negative *) val of_int32_exn : int32 -> level (** Can trigger Unexpected_level error when the level to encode is negative *) val of_int32 : int32 -> level tzresult val diff : level -> level -> int32 val root : level val succ : level -> level val pred : level -> level option (** [add l i] i must be positive *) val add : level -> int -> level (** [sub l i] i must be positive *) val sub : level -> int -> level option module Index : Storage_description.INDEX with type t = level
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Marigold <contact@marigold.dev> *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* Copyright (c) 2022 Oxhead Alpha <info@oxhead-alpha.com> *) (* *) (* 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. *) (* *) (*****************************************************************************) type t
test_polynomial.ml
open Smol module K = Int module Poly = Polynomial.Make (Helpers.LString) module Polynomial = Poly.Make_Ring (K) module Monomial = Monomial.Make (Helpers.LString) include Test_helpers.Make (Polynomial) let ampli = 256 let x = "x" let y = "y" let z = "z" let i = Helpers.int_sampler let sampler l max_exp num_mono () = List.fold_left (fun acc _ -> Polynomial.add acc (Polynomial.singleton (Helpers.mono_sampler l max_exp ()) (i ()))) Polynomial.zero (List.init num_mono (fun _ -> ())) let s () = let a = sampler [x; y; z] 10 (Random.int 6) () in Format.printf "%a\n" pp a ; a let (name_tests, tests_algebra) = Test_helpers.make_tests_ring ~ampli ~name:"Polynomials" ~commutative:true (module Polynomial) (sampler [x; y; z] 3 3) let test_of_literal () = let p = Polynomial.of_literal x in Alcotest.(check int) "test_of_literal_1" 1 (Polynomial.deg x p) ; Alcotest.(check int) "test_of_literal_0" 0 (Polynomial.deg y p) ; Alcotest.(check int) "test_of_literal_k" 1 (Polynomial.get_coef (Monomial.of_literal x) p) ; Alcotest.(check int) "test_of_literal_card" 1 (Polynomial.cardinal p) let test_of_monomial () = let m = Test_monomial.s () in let p = Polynomial.of_monomial m in Alcotest.(check int) "test_of_monomial_coef" 1 (Polynomial.get_coef m p) ; Alcotest.(check int) "test_of_monomial_card" 1 (Polynomial.cardinal p) let test_of_scalar () = let k = i () in let p = Polynomial.of_scalar k in Alcotest.(check int) "test_of_scalar_coef" k (Polynomial.get_coef Monomial.one p) ; if k = 0 then Alcotest.(check bool) "test_of_monomial_zero" true (Polynomial.is_zero p) else Alcotest.(check int) "test_of_monomial_card" 1 (Polynomial.cardinal p) let test_singleton () = let k = i () in let m = Test_monomial.s () in let p = Polynomial.singleton m k in if k = 0 then Alcotest.(check bool) "test_of_monomial_zero" true (Polynomial.is_zero p) else ( Alcotest.(check int) "test_of_monomial_coef" k (Polynomial.get_coef m p) ; Alcotest.(check int) "test_of_monomial_card" 1 (Polynomial.cardinal p)) let test_card_zero () = Alcotest.(check int) "test_card_zero" 0 (Polynomial.cardinal Polynomial.zero) let test_support () = let p = s () in if Polynomial.is_zero p then ( Alcotest.(check bool) "test_support_zero_deg" false (Polynomial.deg x p >= 0) ; Alcotest.(check int) "test_support_zero" 0 (List.length (Polynomial.get_support p))) else if List.mem x (Polynomial.get_support p) then Alcotest.(check (neg int)) "test_support_deg" 0 (Polynomial.deg x p) else Alcotest.(check int) "test_support_not" 0 (Polynomial.deg x p) let test_mul_scalar () = let (k1, k2) = (i (), i ()) in let m = Test_monomial.s () in let p = Polynomial.singleton m k1 in check ~msg:"test_mul_scalar" ~expected:(Polynomial.singleton m (k1 * k2)) ~actual:(Polynomial.mul_scalar k2 p) let test_mul_scalar_distrib () = let k = i () in let (p1, p2) = (s (), s ()) in check ~msg:"test_mul_scalar_distrib" ~expected:Polynomial.Infix.((k *. p1) + (k *. p2)) ~actual:Polynomial.Infix.(k *. (p1 + p2)) let test_eval () = let k = i () in let p0 = sampler [y; z] 10 (Random.int 6) () in let p1 = sampler [y; z] 10 (Random.int 6) () in let p2 = sampler [y; z] 10 (Random.int 6) () in let x' = Polynomial.of_literal x in let px = Polynomial.Infix.(p0 + (x' * p1) + (x' * x' * p2)) in let e = Polynomial.eval (Helpers.LiteralMap.singleton x k) px in let result = Polynomial.Infix.(p0 + (k *. p1) + (Int.mul k k *. p2)) in Alcotest.check testable "test_eval" result e let test_substitution () = let px = s () in let py = s () in let p0 = sampler [z] 10 (Random.int 6) () in let p1 = sampler [z] 10 (Random.int 6) () in let p2 = sampler [z] 10 (Random.int 6) () in let p3 = sampler [z] 10 (Random.int 6) () in let x' = Polynomial.of_literal x in let y' = Polynomial.of_literal y in let p = Polynomial.Infix.(p0 + (x' * p1) + (y' * p2) + (x' * y' * p3)) in let sub = Polynomial.substitution (Helpers.LiteralMap.singleton x px |> Helpers.LiteralMap.add y py) p in let result = Polynomial.Infix.(p0 + (px * p1) + (py * p2) + (px * py * p3)) in check ~msg:"test_substitution" ~expected:result ~actual:sub let test_deriv () = let e = Int.abs (i ()) + 1 in let p0 = sampler [y; z] 10 (Random.int 6) () in let p1 = sampler [y; z] 10 (Random.int 6) () in let p2 = sampler [y; z] 10 (Random.int 6) () in let x' = Polynomial.of_literal x in let m = Polynomial.of_monomial (Monomial.singleton x e) in let m' = Polynomial.of_monomial (Monomial.singleton x (e - 1)) in let px = Polynomial.Infix.(p0 + (x' * p1) + (m * p2)) in let d = Polynomial.deriv x px |> Polynomial.map (fun (a, b) -> a * b) in let result = Polynomial.Infix.(p1 + (e *. (m' * p2))) in check ~msg:"test_deriv" ~expected:result ~actual:d let poly_tests = let open Test_helpers in [ (Unit, "Test polynomial from literal", test_of_literal); (Rand, "Test polynomial from monomial", test_of_monomial); (Rand, "Test polynomial from scalar", test_of_scalar); (Rand, "Test polynomial singleton", test_singleton); (Unit, "Test cardinality of zero polynomial", test_card_zero); (Rand, "Test support of polynomial", test_support); (Rand, "Test scalar multiplication", test_mul_scalar); (Rand, "Test scalar multiplication distributivity", test_mul_scalar_distrib); (Rand, "Test evaluation", test_eval); (Rand, "Test substitution", test_substitution); (Rand, "Test derivation", test_deriv); ] let tests = [(name_tests, tests_algebra @ Test_helpers.get_tests ampli poly_tests)]
getifaddrs_test.ml
open Tuntap open Ipaddr let () = let addrs = getifaddrs () in List.iter (function | n, `V4 cidr -> Printf.printf "%s -> %s\n" n (V4.Prefix.to_string cidr) | n, `V6 cidr -> Printf.printf "%s -> %s\n" n (V6.Prefix.to_string cidr) ) addrs
recdef.mli
open Constr val tclUSER_if_not_mes : unit Proofview.tactic -> bool -> Names.Id.t list option -> unit Proofview.tactic val recursive_definition : interactive_proof:bool -> is_mes:bool -> Names.Id.t -> Constrintern.internalization_env -> Constrexpr.constr_expr -> Constrexpr.constr_expr -> int -> Constrexpr.constr_expr -> ( pconstant -> Indfun_common.tcc_lemma_value ref -> pconstant -> pconstant -> int -> EConstr.types -> int -> EConstr.constr -> unit) -> Constrexpr.constr_expr list -> Declare.Proof.t option
preprocess.mli
open Import module Pps : sig type 'a t = { loc : Loc.t ; pps : 'a list ; flags : String_with_vars.t list ; staged : bool } val compare_no_locs : ('a -> 'a -> Ordering.t) -> 'a t -> 'a t -> Ordering.t end type 'a t = | No_preprocessing | Action of Loc.t * Dune_lang.Action.t | Pps of 'a Pps.t | Future_syntax of Loc.t val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val map : 'a t -> f:('a -> 'b) -> 'b t module Without_instrumentation : sig type t = Loc.t * Lib_name.t val compare_no_locs : t -> t -> Ordering.t end module With_instrumentation : sig type t = | Ordinary of Without_instrumentation.t | Instrumentation_backend of { libname : Loc.t * Lib_name.t ; deps : Dep_conf.t list ; flags : String_with_vars.t list } val equal : t -> t -> bool end val decode : Without_instrumentation.t t Dune_lang.Decoder.t module Without_future_syntax : sig type 'a t = | No_preprocessing | Action of Loc.t * Dune_lang.Action.t | Pps of 'a Pps.t end val loc : _ t -> Loc.t option module Pp_flag_consumer : sig type t = | Compiler | Merlin end val remove_future_syntax : 'a t -> for_:Pp_flag_consumer.t -> Ocaml.Version.t -> 'a Without_future_syntax.t module Per_module : sig type 'a preprocess = 'a t type 'a t = 'a preprocess Module_name.Per_item.t val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val decode : Without_instrumentation.t t Dune_lang.Decoder.t val no_preprocessing : unit -> 'a t val default : unit -> 'a t (** [find module_name] find the preprocessing specification for a given module *) val find : Module_name.t -> 'a t -> 'a preprocess val pps : Without_instrumentation.t t -> Without_instrumentation.t list (** Preprocessing specification used by all modules or [No_preprocessing] *) val single_preprocess : 'a t -> 'a preprocess val add_instrumentation : With_instrumentation.t t -> loc:Loc.t -> flags:String_with_vars.t list -> deps:Dep_conf.t list -> Loc.t * Lib_name.t -> With_instrumentation.t t val without_instrumentation : With_instrumentation.t t -> Without_instrumentation.t t val with_instrumentation : With_instrumentation.t t -> instrumentation_backend: (Loc.t * Lib_name.t -> Without_instrumentation.t option Resolve.Memo.t) -> Without_instrumentation.t t Resolve.Memo.t val instrumentation_deps : With_instrumentation.t t -> instrumentation_backend: (Loc.t * Lib_name.t -> Without_instrumentation.t option Resolve.Memo.t) -> Dep_conf.t list Resolve.Memo.t end with type 'a preprocess := 'a t
monads.ml
(* Widely used module types. *) module type S = sig type 'a t val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t val return : 'a -> 'a t val run : 'a t -> 'a end (* Signature of a state monad. *) module type State_sig = sig type state type key type value include S with type 'a t = state -> 'a * state val empty : unit -> state val set : key -> value -> unit t val get : key -> value option t val iter_list : ('a -> unit t) -> 'a list -> unit t end module Make_state_monad (X : Stores.S) : State_sig with type state = X.state and type key = X.key and type value = X.value and type 'a t = X.state -> 'a * X.state = struct include X type 'a t = state -> 'a * state let ( >>= ) m f s = let (x, s) = m s in f x s let return x s = (x, s) let run m = fst (m (empty ())) let set k v s = ((), set k v s) let get k s = (get k s, s) let rec iter_list (f : 'a -> unit t) (l : 'a list) = match l with | [] -> return () | elt :: tl -> f elt >>= fun () -> iter_list f tl end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
traps.h
#ifndef _TRAPS_H_ #define _TRAPS_H_ struct pt_regs { unsigned long r0; unsigned long r1; unsigned long r2; unsigned long r3; unsigned long r4; unsigned long r5; unsigned long r6; unsigned long r7; unsigned long r8; unsigned long r9; unsigned long r10; unsigned long r11; unsigned long r12; }; #endif
michelson_v1_entrypoints.ml
open Protocol open Protocol_client_context open Alpha_context type error += Contract_without_code of Contract.t let () = register_error_kind `Permanent ~id:"contractWithoutCode" ~title:"The given contract has no code" ~description: "Attempt to get the code of a contract failed because it has nocode. No \ scriptless contract should remain." ~pp:(fun ppf contract -> Format.fprintf ppf "Contract has no code %a." Contract.pp contract) Data_encoding.(obj1 (req "contract" Contract.encoding)) (function Contract_without_code c -> Some c | _ -> None) (fun c -> Contract_without_code c) let print_errors (cctxt : #Client_context.printer) errs = cctxt#error "%a" Error_monad.pp_print_trace errs >>= fun () -> return_unit let script_entrypoint_type cctxt ~(chain : Chain_services.chain) ~block (program : Script.expr) ~entrypoint = Plugin.RPC.Scripts.entrypoint_type cctxt (chain, block) ~script:program ~entrypoint >>= function | Ok ty -> return_some ty | Error (Environment.Ecoproto_error (Script_tc_errors.No_such_entrypoint _) :: _) -> return None | Error _ as err -> Lwt.return err let contract_entrypoint_type cctxt ~(chain : Chain_services.chain) ~block ~contract ~entrypoint ~normalize_types = Alpha_services.Contract.entrypoint_type cctxt (chain, block) contract entrypoint ~normalize_types >>= function | Ok ty -> return_some ty | Error (Tezos_rpc.Context.Not_found _ :: _) -> return None | Error _ as err -> Lwt.return err let print_entrypoint_type (cctxt : #Client_context.printer) ?(on_errors = print_errors cctxt) ~emacs ?contract ?script_name ~entrypoint = function | Ok (Some ty) -> (if emacs then cctxt#message "@[<v 2>((entrypoint . %a) (type . %a))@]@." Entrypoint.pp entrypoint Michelson_v1_emacs.print_expr ty else cctxt#message "@[<v 2>Entrypoint %a: %a@]@." Entrypoint.pp entrypoint Michelson_v1_printer.print_expr ty) >>= fun () -> return_unit | Ok None -> cctxt#message "@[<v 2>No entrypoint named %a%a%a@]@." Entrypoint.pp entrypoint (Format.pp_print_option (fun ppf -> Format.fprintf ppf " for contract %a" Contract_hash.pp)) contract (Format.pp_print_option (fun ppf -> Format.fprintf ppf " for script %s")) script_name >>= fun () -> return_unit | Error errs -> on_errors errs let list_contract_unreachables_and_entrypoints cctxt ~chain ~block ~contract ~normalize_types = Alpha_services.Contract.list_entrypoints cctxt (chain, block) contract ~normalize_types let list_contract_unreachables cctxt ~chain ~block ~contract = let normalize_types = (* no need to normalize types as typed entrypoints are ignored *) false in list_contract_unreachables_and_entrypoints cctxt ~chain ~block ~contract ~normalize_types >>=? fun (unreachables, _typed_entrypoints) -> return unreachables let list_contract_entrypoints cctxt ~chain ~block ~contract ~normalize_types = list_contract_unreachables_and_entrypoints cctxt ~chain ~block ~contract ~normalize_types >>=? fun (_, entrypoints) -> if not @@ List.mem_assoc ~equal:String.equal "default" entrypoints then contract_entrypoint_type cctxt ~chain ~block ~contract ~entrypoint:Entrypoint.default ~normalize_types >>= function | Ok (Some ty) -> return (("default", ty) :: entrypoints) | Ok None -> return entrypoints | Error _ as err -> Lwt.return err else return entrypoints let list_unreachables cctxt ~chain ~block (program : Script.expr) = Plugin.RPC.Scripts.list_entrypoints cctxt (chain, block) ~script:program >>=? fun (unreachables, _) -> return unreachables let list_entrypoints cctxt ~chain ~block (program : Script.expr) = Plugin.RPC.Scripts.list_entrypoints cctxt (chain, block) ~script:program >>=? fun (_, entrypoints) -> if not @@ List.mem_assoc ~equal:String.equal "default" entrypoints then script_entrypoint_type cctxt ~chain ~block program ~entrypoint:Entrypoint.default >>= function | Ok (Some ty) -> return (("default", ty) :: entrypoints) | Ok None -> return entrypoints | Error _ as err -> Lwt.return err else return entrypoints let print_entrypoints_list (cctxt : #Client_context.printer) ?(on_errors = print_errors cctxt) ~emacs ?contract ?script_name = function | Ok entrypoint_list -> (if emacs then cctxt#message "@[<v 2>(@[%a@])@." (Format.pp_print_list ~pp_sep:Format.pp_print_cut (fun ppf (entrypoint, ty) -> Format.fprintf ppf "@[<v 2>( ( entrypoint . %s ) ( type . @[%a@]))@]" entrypoint Michelson_v1_emacs.print_expr ty)) entrypoint_list else cctxt#message "@[<v 2>Entrypoints%a%a: @,%a@]@." (Format.pp_print_option (fun ppf -> Format.fprintf ppf " for contract %a" Contract_hash.pp)) contract (Format.pp_print_option (fun ppf -> Format.fprintf ppf " for script %s")) script_name (Format.pp_print_list ~pp_sep:Format.pp_print_cut (fun ppf (entrypoint, ty) -> Format.fprintf ppf "@[<v 2>%s: @[%a@]@]" entrypoint Michelson_v1_printer.print_expr ty)) entrypoint_list) >>= fun () -> return_unit | Error errs -> on_errors errs let print_unreachables (cctxt : #Client_context.printer) ?(on_errors = print_errors cctxt) ~emacs ?contract ?script_name = function | Ok unreachable -> (if emacs then cctxt#message "@[<v 2>(@[%a@])@." (Format.pp_print_list ~pp_sep:Format.pp_print_cut (fun ppf path -> Format.fprintf ppf "@[<h>( unreachable-path . %a )@]" (Format.pp_print_list ~pp_sep:Format.pp_print_space (fun ppf prim -> Format.pp_print_string ppf @@ Michelson_v1_primitives.string_of_prim prim)) path)) unreachable else match unreachable with | [] -> cctxt#message "@[<v 2>None.@]@." | _ -> cctxt#message "@[<v 2>Unreachable paths in the argument%a%a: @[%a@]@." (Format.pp_print_option (fun ppf -> Format.fprintf ppf " of contract %a" Contract_hash.pp)) contract (Format.pp_print_option (fun ppf -> Format.fprintf ppf " of script %s")) script_name (Format.pp_print_list ~pp_sep:Format.pp_print_cut (fun ppf -> Format.fprintf ppf "@[<h> %a @]" (Format.pp_print_list ~pp_sep:(fun ppf _ -> Format.pp_print_string ppf "/") (fun ppf prim -> Format.pp_print_string ppf @@ Michelson_v1_primitives.string_of_prim prim)))) unreachable) >>= fun () -> return_unit | Error errs -> on_errors errs
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2019 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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_period_storage.ml
(* The shell uses the convention that a context at level n is the resulting context of the application of block n. Therefore when using an RPC on the last level of a voting period, the context that is inspected is the resulting one. However [Amendment.may_start_new_voting_period] is run at the end of voting period and it has to prepare the context for validating operations of the next period. This causes the counter-intuitive result that the info returned by RPCs at last level of a voting period mention data of the next voting period. For example, when validating the last block of a proposal period at level n we have: - Input context: voting_period = { kind = Proposal; index = i; start_position = n - blocks_per_voting_period} - position = n - start_position = blocks_per_voting_period - remaining = blocks_per_voting_period - (position + 1) = 0 - Output context: voting_period = { kind = Testing_vote; index = i + 1; start_position = n + 1} Now if we calculate position and remaining in the voting period we get strange results: - position = n - (n + 1) = -1 - remaining = blocks_per_voting_period In order to have the correct value for the RPCs a fix has been applied in [voting_service] by calling a specific function [voting_period_storage.get_rpc_fixed_current_info]. This odd behaviour could be fixed if [Amendment.may_start_new_voting_period] was called when we start validating a block instead that at the end. This should be carefully done because the voting period listing depends on the rolls and it might break some invariant. When this is implemented one should: - remove the function [voting_period_storage.get_rpc_fixed_current_info] - edit the function [reset_current] and [inc_current] to use the current level and not the next one. - remove the storage for pred_kind - make Voting_period_repr.t abstract You can also look at the MR description here: https://gitlab.com/metastatedev/tezos/-/merge_requests/333 *) let set_current = Storage.Vote.Current_period.set let get_current = Storage.Vote.Current_period.get let init = Storage.Vote.Current_period.init let init_first_period ctxt ~start_position = init ctxt @@ Voting_period_repr.root ~start_position >>=? fun ctxt -> Storage.Vote.Pred_period_kind.init ctxt Voting_period_repr.Proposal let common ctxt = get_current ctxt >>=? fun current_period -> Storage.Vote.Pred_period_kind.set ctxt current_period.kind >|=? fun ctxt -> let start_position = (* because we are preparing the voting period for the next block we need to use the next level. *) Int32.succ (Level_storage.current ctxt).level_position in (ctxt, current_period, start_position) let reset ctxt = common ctxt >>=? fun (ctxt, current_period, start_position) -> Voting_period_repr.reset current_period ~start_position |> set_current ctxt let succ ctxt = common ctxt >>=? fun (ctxt, current_period, start_position) -> Voting_period_repr.succ current_period ~start_position |> set_current ctxt let get_current_kind ctxt = get_current ctxt >|=? fun {kind; _} -> kind let get_current_info ctxt = get_current ctxt >|=? fun voting_period -> let blocks_per_voting_period = Constants_storage.blocks_per_voting_period ctxt in let level = Level_storage.current ctxt in let position = Voting_period_repr.position_since level voting_period in let remaining = Voting_period_repr.remaining_blocks level voting_period blocks_per_voting_period in Voting_period_repr.{voting_period; position; remaining} let get_current_remaining ctxt = get_current ctxt >|=? fun voting_period -> let blocks_per_voting_period = Constants_storage.blocks_per_voting_period ctxt in Voting_period_repr.remaining_blocks (Level_storage.current ctxt) voting_period blocks_per_voting_period let is_last_block ctxt = get_current_remaining ctxt >|=? fun remaining -> Compare.Int32.(remaining = 0l) let get_rpc_fixed_current_info ctxt = get_current_info ctxt >>=? fun ({voting_period; position; _} as voting_period_info) -> if Compare.Int32.(position = Int32.minus_one) then let level = Level_storage.current ctxt in let blocks_per_voting_period = Constants_storage.blocks_per_voting_period ctxt in Storage.Vote.Pred_period_kind.get ctxt >|=? fun pred_kind -> let voting_period : Voting_period_repr.t = { index = Int32.pred voting_period.index; kind = pred_kind; start_position = Int32.(sub voting_period.start_position blocks_per_voting_period); } in let position = Voting_period_repr.position_since level voting_period in let remaining = Voting_period_repr.remaining_blocks level voting_period ~blocks_per_voting_period in ({voting_period; remaining; position} : Voting_period_repr.info) else return voting_period_info let get_rpc_fixed_succ_info ctxt = get_current ctxt >|=? fun voting_period -> let blocks_per_voting_period = Constants_storage.blocks_per_voting_period ctxt in let level = Level_storage.from_raw ctxt ~offset:1l (Level_storage.current ctxt).level in let position = Voting_period_repr.position_since level voting_period in let remaining = Voting_period_repr.remaining_blocks level voting_period blocks_per_voting_period in Voting_period_repr.{voting_period; position; remaining}
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *) (* *) (* 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. *) (* *) (*****************************************************************************)
camltk.h
/* $Id$ */ #if defined(_WIN32) && defined(CAML_DLL) && defined(IN_CAMLTKSUPPORT) #define CAMLTKextern CAMLexport #else #define CAMLTKextern CAMLextern #endif /* compatibility with earlier versions of Tcl/Tk */ #ifndef CONST84 #define CONST84 #endif /*Tcl_GetResult(), Tcl_GetStringResult(), Tcl_SetResult(), */ /*Tcl_SetStringResult(), Tcl_GetErrorLine() */ /* if Tcl_GetStringResult is not defined, we use interp->result */ /*#ifndef Tcl_GetStringResult*/ /*# define Tcl_GetStringResult(interp) (interp->result)*/ /*#endif*/ /* cltkMisc.c */ /* copy an OCaml string to the C heap. Must be deallocated with stat_free */ extern char *string_to_c(value s); /* cltkUtf.c */ extern value tcl_string_to_caml( const char * ); extern char * caml_string_to_tcl( value ); /* cltkEval.c */ CAMLTKextern Tcl_Interp *cltclinterp; /* The Tcl interpretor */ extern value copy_string_list(int argc, char **argv); /* cltkCaml.c */ /* pointers to OCaml values */ extern value *tkerror_exn; extern value *handler_code; extern int CamlCBCmd(ClientData clientdata, Tcl_Interp *interp, int argc, CONST84 char *argv[]); CAMLTKextern void tk_error(const char * errmsg) Noreturn; /* cltkMain.c */ extern int signal_events; extern void invoke_pending_caml_signals(ClientData clientdata); extern Tk_Window cltk_mainWindow; extern int cltk_slave_mode; /* check that initialisations took place */ #define CheckInit() if (!cltclinterp) tk_error("Tcl/Tk not initialised") #define RCNAME ".camltkrc" #define CAMLCB "camlcb"
/*************************************************************************/ /* */ /* OCaml LablTk library */ /* */ /* Francois Rouaix, Francois Pessaux and Jun Furuse */ /* projet Cristal, INRIA Rocquencourt */ /* Jacques Garrigue, Kyoto University RIMS */ /* */ /* Copyright 1999 Institut National de Recherche en Informatique et */ /* en Automatique and Kyoto University. 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. */ /* */ /*************************************************************************/
oprint.ml
open Format open Outcometree exception Ellipsis let cautious f ppf arg = try f ppf arg with Ellipsis -> fprintf ppf "..." let print_lident ppf = function | "::" -> pp_print_string ppf "(::)" | s -> pp_print_string ppf s let rec print_ident ppf = function Oide_ident s -> print_lident ppf s.printed_name | Oide_dot (id, s) -> print_ident ppf id; pp_print_char ppf '.'; print_lident ppf s | Oide_apply (id1, id2) -> fprintf ppf "%a(%a)" print_ident id1 print_ident id2 let out_ident = ref print_ident (* Check a character matches the [identchar_latin1] class from the lexer *) let is_ident_char c = match c with | 'A'..'Z' | 'a'..'z' | '_' | '\192'..'\214' | '\216'..'\246' | '\248'..'\255' | '\'' | '0'..'9' -> true | _ -> false let all_ident_chars s = let rec loop s len i = if i < len then begin if is_ident_char s.[i] then loop s len (i+1) else false end else begin true end in let len = String.length s in loop s len 0 let parenthesized_ident name = (List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"]) || not (all_ident_chars name) let value_ident ppf name = if parenthesized_ident name then fprintf ppf "( %s )" name else pp_print_string ppf name (* Values *) let valid_float_lexeme s = let l = String.length s in let rec loop i = if i >= l then s ^ "." else match s.[i] with | '0' .. '9' | '-' -> loop (i+1) | _ -> s in loop 0 let float_repres f = match classify_float f with FP_nan -> "nan" | FP_infinite -> if f < 0.0 then "neg_infinity" else "infinity" | _ -> let float_val = let s1 = Printf.sprintf "%.12g" f in if f = float_of_string s1 then s1 else let s2 = Printf.sprintf "%.15g" f in if f = float_of_string s2 then s2 else Printf.sprintf "%.18g" f in valid_float_lexeme float_val let parenthesize_if_neg ppf fmt v isneg = if isneg then pp_print_char ppf '('; fprintf ppf fmt v; if isneg then pp_print_char ppf ')' let escape_string s = (* Escape only C0 control characters (bytes <= 0x1F), DEL(0x7F), '\\' and '"' *) let n = ref 0 in for i = 0 to String.length s - 1 do n := !n + (match String.unsafe_get s i with | '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2 | '\x00' .. '\x1F' | '\x7F' -> 4 | _ -> 1) done; if !n = String.length s then s else begin let s' = Bytes.create !n in n := 0; for i = 0 to String.length s - 1 do begin match String.unsafe_get s i with | ('\"' | '\\') as c -> Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c | '\n' -> Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n' | '\t' -> Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't' | '\r' -> Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r' | '\b' -> Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b' | '\x00' .. '\x1F' | '\x7F' as c -> let a = Char.code c in Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n (Char.chr (48 + a / 100)); incr n; Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10)); incr n; Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10)); | c -> Bytes.unsafe_set s' !n c end; incr n done; Bytes.to_string s' end let print_out_string ppf s = let not_escaped = (* let the user dynamically choose if strings should be escaped: *) match Sys.getenv_opt "OCAMLTOP_UTF_8" with | None -> true | Some x -> match bool_of_string_opt x with | None -> true | Some f -> f in if not_escaped then fprintf ppf "\"%s\"" (escape_string s) else fprintf ppf "%S" s let print_out_value ppf tree = let rec print_tree_1 ppf = function | Oval_constr (name, [param]) -> fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param | Oval_constr (name, (_ :: _ as params)) -> fprintf ppf "@[<1>%a@ (%a)@]" print_ident name (print_tree_list print_tree_1 ",") params | Oval_variant (name, Some param) -> fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param | tree -> print_simple_tree ppf tree and print_constr_param ppf = function | Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0) | Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l) | Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L) | Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n) | Oval_float f -> parenthesize_if_neg ppf "%s" (float_repres f) (f < 0.0 || 1. /. f = neg_infinity) | Oval_string (_,_, Ostr_bytes) as tree -> pp_print_char ppf '('; print_simple_tree ppf tree; pp_print_char ppf ')'; | tree -> print_simple_tree ppf tree and print_simple_tree ppf = function Oval_int i -> fprintf ppf "%i" i | Oval_int32 i -> fprintf ppf "%lil" i | Oval_int64 i -> fprintf ppf "%LiL" i | Oval_nativeint i -> fprintf ppf "%nin" i | Oval_float f -> pp_print_string ppf (float_repres f) | Oval_char c -> fprintf ppf "%C" c | Oval_string (s, maxlen, kind) -> begin try let len = String.length s in let s = if len > maxlen then String.sub s 0 maxlen else s in begin match kind with | Ostr_bytes -> fprintf ppf "Bytes.of_string %S" s | Ostr_string -> print_out_string ppf s end; (if len > maxlen then fprintf ppf "... (* string length %d; truncated *)" len ) with Invalid_argument _ (* "String.create" *)-> fprintf ppf "<huge string>" end | Oval_list tl -> fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl | Oval_array tl -> fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl | Oval_constr (name, []) -> print_ident ppf name | Oval_variant (name, None) -> fprintf ppf "`%s" name | Oval_stuff s -> pp_print_string ppf s | Oval_record fel -> fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel | Oval_ellipsis -> raise Ellipsis | Oval_printer f -> f ppf | Oval_tuple tree_list -> fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list | tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree and print_fields first ppf = function [] -> () | (name, tree) :: fields -> if not first then fprintf ppf ";@ "; fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1) tree; print_fields false ppf fields and print_tree_list print_item sep ppf tree_list = let rec print_list first ppf = function [] -> () | tree :: tree_list -> if not first then fprintf ppf "%s@ " sep; print_item ppf tree; print_list false ppf tree_list in cautious (print_list true) ppf tree_list in cautious print_tree_1 ppf tree let out_value = ref print_out_value (* Types *) let rec print_list_init pr sep ppf = function [] -> () | a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l let rec print_list pr sep ppf = function [] -> () | [a] -> pr ppf a | a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l let pr_present = print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ") let pr_var = Pprintast.tyvar let pr_vars = print_list pr_var (fun ppf -> fprintf ppf "@ ") let rec print_out_type ppf = function | Otyp_alias (ty, s) -> fprintf ppf "@[%a@ as %a@]" print_out_type ty pr_var s | Otyp_poly (sl, ty) -> fprintf ppf "@[<hov 2>%a.@ %a@]" pr_vars sl print_out_type ty | ty -> print_out_type_1 ppf ty and print_out_type_1 ppf = function Otyp_arrow (lab, ty1, ty2) -> pp_open_box ppf 0; if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':'); print_out_type_2 ppf ty1; pp_print_string ppf " ->"; pp_print_space ppf (); print_out_type_1 ppf ty2; pp_close_box ppf () | ty -> print_out_type_2 ppf ty and print_out_type_2 ppf = function Otyp_tuple tyl -> fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl | ty -> print_simple_out_type ppf ty and print_simple_out_type ppf = function Otyp_class (ng, id, tyl) -> fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "") print_ident id | Otyp_constr (id, tyl) -> pp_open_box ppf 0; print_typargs ppf tyl; print_ident ppf id; pp_close_box ppf () | Otyp_object (fields, rest) -> fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields | Otyp_stuff s -> pp_print_string ppf s | Otyp_var (ng, s) -> pr_var ppf (if ng then "_" ^ s else s) | Otyp_variant (non_gen, row_fields, closed, tags) -> let print_present ppf = function None | Some [] -> () | Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l in let print_fields ppf = function Ovar_fields fields -> print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ") ppf fields | Ovar_typ typ -> print_simple_out_type ppf typ in fprintf ppf "%s@[<hov>[%s@[<hv>@[<hv>%a@]%a@]@ ]@]" (if non_gen then "_" else "") (if closed then if tags = None then " " else "< " else if tags = None then "> " else "? ") print_fields row_fields print_present tags | Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty -> pp_open_box ppf 1; pp_print_char ppf '('; print_out_type ppf ty; pp_print_char ppf ')'; pp_close_box ppf () | Otyp_abstract | Otyp_open | Otyp_sum _ | Otyp_manifest (_, _) -> () | Otyp_record lbls -> print_record_decl ppf lbls | Otyp_module (p, n, tyl) -> fprintf ppf "@[<1>(module %a" print_ident p; let first = ref true in List.iter2 (fun s t -> let sep = if !first then (first := false; "with") else "and" in fprintf ppf " %s type %s = %a" sep s print_out_type t ) n tyl; fprintf ppf ")@]" | Otyp_attribute (t, attr) -> fprintf ppf "@[<1>(%a [@@%s])@]" print_out_type t attr.oattr_name and print_record_decl ppf lbls = fprintf ppf "{%a@;<1 -2>}" (print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls and print_fields rest ppf = function [] -> begin match rest with Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "") | None -> () end | [s, t] -> fprintf ppf "%s : %a" s print_out_type t; begin match rest with Some _ -> fprintf ppf ";@ " | None -> () end; print_fields rest ppf [] | (s, t) :: l -> fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l and print_row_field ppf (l, opt_amp, tyl) = let pr_of ppf = if opt_amp then fprintf ppf " of@ &@ " else if tyl <> [] then fprintf ppf " of@ " else fprintf ppf "" in fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &") tyl and print_typlist print_elem sep ppf = function [] -> () | [ty] -> print_elem ppf ty | ty :: tyl -> print_elem ppf ty; pp_print_string ppf sep; pp_print_space ppf (); print_typlist print_elem sep ppf tyl and print_typargs ppf = function [] -> () | [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf () | tyl -> pp_open_box ppf 1; pp_print_char ppf '('; print_typlist print_out_type "," ppf tyl; pp_print_char ppf ')'; pp_close_box ppf (); pp_print_space ppf () and print_out_label ppf (name, mut, arg) = fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name print_out_type arg let out_type = ref print_out_type (* Class types *) let print_type_parameter ppf s = if s = "_" then fprintf ppf "_" else pr_var ppf s let type_parameter ppf (ty, (co, cn)) = fprintf ppf "%s%a" (if not cn then "+" else if not co then "-" else "") print_type_parameter ty let print_out_class_params ppf = function [] -> () | tyl -> fprintf ppf "@[<1>[%a]@]@ " (print_list type_parameter (fun ppf -> fprintf ppf ", ")) tyl let rec print_out_class_type ppf = function Octy_constr (id, tyl) -> let pr_tyl ppf = function [] -> () | tyl -> fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl in fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id | Octy_arrow (lab, ty, cty) -> fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "") print_out_type_2 ty print_out_class_type cty | Octy_signature (self_ty, csil) -> let pr_param ppf = function Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty | None -> () in fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty (print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ ")) csil and print_out_class_sig_item ppf = function Ocsg_constraint (ty1, ty2) -> fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1 !out_type ty2 | Ocsg_method (name, priv, virt, ty) -> fprintf ppf "@[<2>method %s%s%s :@ %a@]" (if priv then "private " else "") (if virt then "virtual " else "") name !out_type ty | Ocsg_value (name, mut, vr, ty) -> fprintf ppf "@[<2>val %s%s%s :@ %a@]" (if mut then "mutable " else "") (if vr then "virtual " else "") name !out_type ty let out_class_type = ref print_out_class_type (* Signature *) let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type") let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item") let out_signature = ref (fun _ -> failwith "Oprint.out_signature") let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension") let rec print_out_functor funct ppf = function Omty_functor (_, None, mty_res) -> if funct then fprintf ppf "() %a" (print_out_functor true) mty_res else fprintf ppf "functor@ () %a" (print_out_functor true) mty_res | Omty_functor (name, Some mty_arg, mty_res) -> begin match name, funct with | "_", true -> fprintf ppf "->@ %a ->@ %a" print_out_module_type mty_arg (print_out_functor false) mty_res | "_", false -> fprintf ppf "%a ->@ %a" print_out_module_type mty_arg (print_out_functor false) mty_res | name, true -> fprintf ppf "(%s : %a) %a" name print_out_module_type mty_arg (print_out_functor true) mty_res | name, false -> fprintf ppf "functor@ (%s : %a) %a" name print_out_module_type mty_arg (print_out_functor true) mty_res end | m -> if funct then fprintf ppf "->@ %a" print_out_module_type m else print_out_module_type ppf m and print_out_module_type ppf = function Omty_abstract -> () | Omty_functor _ as t -> fprintf ppf "@[<2>%a@]" (print_out_functor false) t | Omty_ident id -> fprintf ppf "%a" print_ident id | Omty_signature sg -> fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" !out_signature sg | Omty_alias id -> fprintf ppf "(module %a)" print_ident id and print_out_signature ppf = function [] -> () | [item] -> !out_sig_item ppf item | Osig_typext(ext, Oext_first) :: items -> (* Gather together the extension constructors *) let rec gather_extensions acc items = match items with Osig_typext(ext, Oext_next) :: items -> gather_extensions ((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc) items | _ -> (List.rev acc, items) in let exts, items = gather_extensions [(ext.oext_name, ext.oext_args, ext.oext_ret_type)] items in let te = { otyext_name = ext.oext_type_name; otyext_params = ext.oext_type_params; otyext_constructors = exts; otyext_private = ext.oext_private } in fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items | item :: items -> fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items and print_out_sig_item ppf = function Osig_class (vir_flag, name, params, clt, rs) -> fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]" (if rs = Orec_next then "and" else "class") (if vir_flag then " virtual" else "") print_out_class_params params name !out_class_type clt | Osig_class_type (vir_flag, name, params, clt, rs) -> fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]" (if rs = Orec_next then "and" else "class type") (if vir_flag then " virtual" else "") print_out_class_params params name !out_class_type clt | Osig_typext (ext, Oext_exception) -> fprintf ppf "@[<2>exception %a@]" print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type) | Osig_typext (ext, _es) -> print_out_extension_constructor ppf ext | Osig_modtype (name, Omty_abstract) -> fprintf ppf "@[<2>module type %s@]" name | Osig_modtype (name, mty) -> fprintf ppf "@[<2>module type %s =@ %a@]" name !out_module_type mty | Osig_module (name, Omty_alias id, _) -> fprintf ppf "@[<2>module %s =@ %a@]" name print_ident id | Osig_module (name, mty, rs) -> fprintf ppf "@[<2>%s %s :@ %a@]" (match rs with Orec_not -> "module" | Orec_first -> "module rec" | Orec_next -> "and") name !out_module_type mty | Osig_type(td, rs) -> print_out_type_decl (match rs with | Orec_not -> "type nonrec" | Orec_first -> "type" | Orec_next -> "and") ppf td | Osig_value vd -> let kwd = if vd.oval_prims = [] then "val" else "external" in let pr_prims ppf = function [] -> () | s :: sl -> fprintf ppf "@ = \"%s\"" s; List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl in fprintf ppf "@[<2>%s %a :@ %a%a%a@]" kwd value_ident vd.oval_name !out_type vd.oval_type pr_prims vd.oval_prims (fun ppf -> List.iter (fun a -> fprintf ppf "@ [@@@@%s]" a.oattr_name)) vd.oval_attributes | Osig_ellipsis -> fprintf ppf "..." and print_out_type_decl kwd ppf td = let print_constraints ppf = List.iter (fun (ty1, ty2) -> fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1 !out_type ty2) td.otype_cstrs in let type_defined ppf = match td.otype_params with [] -> pp_print_string ppf td.otype_name | [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name | _ -> fprintf ppf "@[(@[%a)@]@ %s@]" (print_list type_parameter (fun ppf -> fprintf ppf ",@ ")) td.otype_params td.otype_name in let print_manifest ppf = function Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty | _ -> () in let print_name_params ppf = fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type in let ty = match td.otype_type with Otyp_manifest (_, ty) -> ty | _ -> td.otype_type in let print_private ppf = function Asttypes.Private -> fprintf ppf " private" | Asttypes.Public -> () in let print_immediate ppf = if td.otype_immediate then fprintf ppf " [%@%@immediate]" else () in let print_unboxed ppf = if td.otype_unboxed then fprintf ppf " [%@%@unboxed]" else () in let print_out_tkind ppf = function | Otyp_abstract -> () | Otyp_record lbls -> fprintf ppf " =%a %a" print_private td.otype_private print_record_decl lbls | Otyp_sum constrs -> let variants fmt constrs = if constrs = [] then fprintf fmt "|" else fprintf fmt "%a" (print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs in fprintf ppf " =%a@;<1 2>%a" print_private td.otype_private variants constrs | Otyp_open -> fprintf ppf " =%a .." print_private td.otype_private | ty -> fprintf ppf " =%a@;<1 2>%a" print_private td.otype_private !out_type ty in fprintf ppf "@[<2>@[<hv 2>%t%a@]%t%t%t@]" print_name_params print_out_tkind ty print_constraints print_immediate print_unboxed and print_out_constr ppf (name, tyl,ret_type_opt) = let name = match name with | "::" -> "(::)" (* #7200 *) | s -> s in match ret_type_opt with | None -> begin match tyl with | [] -> pp_print_string ppf name | _ -> fprintf ppf "@[<2>%s of@ %a@]" name (print_typlist print_simple_out_type " *") tyl end | Some ret_type -> begin match tyl with | [] -> fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type | _ -> fprintf ppf "@[<2>%s :@ %a -> %a@]" name (print_typlist print_simple_out_type " *") tyl print_simple_out_type ret_type end and print_out_extension_constructor ppf ext = let print_extended_type ppf = match ext.oext_type_params with [] -> fprintf ppf "%s" ext.oext_type_name | [ty_param] -> fprintf ppf "@[%a@ %s@]" print_type_parameter ty_param ext.oext_type_name | _ -> fprintf ppf "@[(@[%a)@]@ %s@]" (print_list print_type_parameter (fun ppf -> fprintf ppf ",@ ")) ext.oext_type_params ext.oext_type_name in fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]" print_extended_type (if ext.oext_private = Asttypes.Private then " private" else "") print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type) and print_out_type_extension ppf te = let print_extended_type ppf = match te.otyext_params with [] -> fprintf ppf "%s" te.otyext_name | [param] -> fprintf ppf "@[%a@ %s@]" print_type_parameter param te.otyext_name | _ -> fprintf ppf "@[(@[%a)@]@ %s@]" (print_list print_type_parameter (fun ppf -> fprintf ppf ",@ ")) te.otyext_params te.otyext_name in fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]" print_extended_type (if te.otyext_private = Asttypes.Private then " private" else "") (print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) te.otyext_constructors let _ = out_module_type := print_out_module_type let _ = out_signature := print_out_signature let _ = out_sig_item := print_out_sig_item let _ = out_type_extension := print_out_type_extension (* Phrases *) let print_out_exception ppf exn outv = match exn with Sys.Break -> fprintf ppf "Interrupted.@." | Out_of_memory -> fprintf ppf "Out of memory during evaluation.@." | Stack_overflow -> fprintf ppf "Stack overflow during evaluation (looping recursion?).@." | _ -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv let rec print_items ppf = function [] -> () | (Osig_typext(ext, Oext_first), None) :: items -> (* Gather together extension constructors *) let rec gather_extensions acc items = match items with (Osig_typext(ext, Oext_next), None) :: items -> gather_extensions ((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc) items | _ -> (List.rev acc, items) in let exts, items = gather_extensions [(ext.oext_name, ext.oext_args, ext.oext_ret_type)] items in let te = { otyext_name = ext.oext_type_name; otyext_params = ext.oext_type_params; otyext_constructors = exts; otyext_private = ext.oext_private } in fprintf ppf "@[%a@]" !out_type_extension te; if items <> [] then fprintf ppf "@ %a" print_items items | (tree, valopt) :: items -> begin match valopt with Some v -> fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree !out_value v | None -> fprintf ppf "@[%a@]" !out_sig_item tree end; if items <> [] then fprintf ppf "@ %a" print_items items let print_out_phrase ppf = function Ophr_eval (outv, ty) -> fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv | Ophr_signature [] -> () | Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items | Ophr_exception (exn, outv) -> print_out_exception ppf exn outv let out_phrase = ref print_out_phrase
(**************************************************************************) (* *) (* OCaml *) (* *) (* 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 Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
main.mli
open Support.Common (* This is the entry-point for the unit-tests; it avoids the exception handling. *) val main : stdout:Format.formatter -> system -> unit val start : system -> unit val start_if_not_windows : system -> unit
(* Copyright (C) 2013, Thomas Leonard * See the README file for details, or visit http://0install.net. *)
myString.ml
include BatString let count_char str char = fold_left (fun acc c -> if c = char then acc + 1 else acc ) 0 str let count_string str sub = if sub = "" then raise (Invalid_argument "String.count_string"); let m = length str in let n = length sub in let rec loop acc i = if i >= m then acc else try let j = find_from str i sub in loop (acc + 1) (j + n) with Not_found -> acc in loop 0 0
(* Copyright (C) 2018, Francois Berenger Yamanishi laboratory, Department of Bioscience and Bioinformatics, Faculty of Computer Science and Systems Engineering, Kyushu Institute of Technology, 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan. *)
parameters_repr.ml
type bootstrap_account = { public_key_hash : Signature.Public_key_hash.t ; public_key : Signature.Public_key.t option ; amount : Tez_repr.t ; } type bootstrap_contract = { delegate : Signature.Public_key_hash.t ; amount : Tez_repr.t ; script : Script_repr.t ; } type t = { bootstrap_accounts : bootstrap_account list ; bootstrap_contracts : bootstrap_contract list ; commitments : Commitment_repr.t list ; constants : Constants_repr.parametric ; security_deposit_ramp_up_cycles : int option ; no_reward_cycles : int option ; } let bootstrap_account_encoding = let open Data_encoding in union [ case (Tag 0) ~title:"Public_key_known" (tup2 Signature.Public_key.encoding Tez_repr.encoding) (function | { public_key_hash ; public_key = Some public_key ; amount } -> assert (Signature.Public_key_hash.equal (Signature.Public_key.hash public_key) public_key_hash) ; Some (public_key, amount) | { public_key = None } -> None) (fun (public_key, amount) -> { public_key = Some public_key ; public_key_hash = Signature.Public_key.hash public_key ; amount }) ; case (Tag 1) ~title:"Public_key_unknown" (tup2 Signature.Public_key_hash.encoding Tez_repr.encoding) (function | { public_key_hash ; public_key = None ; amount } -> Some (public_key_hash, amount) | { public_key = Some _ } -> None) (fun (public_key_hash, amount) -> { public_key = None ; public_key_hash ; amount }) ] let bootstrap_contract_encoding = let open Data_encoding in conv (fun { delegate ; amount ; script } -> (delegate, amount, script)) (fun (delegate, amount, script) -> { delegate ; amount ; script }) (obj3 (req "delegate" Signature.Public_key_hash.encoding) (req "amount" Tez_repr.encoding) (req "script" Script_repr.encoding)) (* This encoding is used to read configuration files (e.g. sandbox.json) where some fields can be missing, in that case they are replaced by the default. *) let constants_encoding = let open Data_encoding in conv (fun (c : Constants_repr.parametric) -> let module Compare_time_between_blocks = Compare.List (Period_repr) in let module Compare_keys = Compare.List (Ed25519.Public_key) in let opt (=) def v = if def = v then None else Some v in let default = Constants_repr.default in let preserved_cycles = opt Compare.Int.(=) default.preserved_cycles c.preserved_cycles and blocks_per_cycle = opt Compare.Int32.(=) default.blocks_per_cycle c.blocks_per_cycle and blocks_per_commitment = opt Compare.Int32.(=) default.blocks_per_commitment c.blocks_per_commitment and blocks_per_roll_snapshot = opt Compare.Int32.(=) default.blocks_per_roll_snapshot c.blocks_per_roll_snapshot and blocks_per_voting_period = opt Compare.Int32.(=) default.blocks_per_voting_period c.blocks_per_voting_period and time_between_blocks = opt Compare_time_between_blocks.(=) default.time_between_blocks c.time_between_blocks and endorsers_per_block = opt Compare.Int.(=) default.endorsers_per_block c.endorsers_per_block and hard_gas_limit_per_operation = opt Compare.Z.(=) default.hard_gas_limit_per_operation c.hard_gas_limit_per_operation and hard_gas_limit_per_block = opt Compare.Z.(=) default.hard_gas_limit_per_block c.hard_gas_limit_per_block and proof_of_work_threshold = opt Compare.Int64.(=) default.proof_of_work_threshold c.proof_of_work_threshold and tokens_per_roll = opt Tez_repr.(=) default.tokens_per_roll c.tokens_per_roll and michelson_maximum_type_size = opt Compare.Int.(=) default.michelson_maximum_type_size c.michelson_maximum_type_size and seed_nonce_revelation_tip = opt Tez_repr.(=) default.seed_nonce_revelation_tip c.seed_nonce_revelation_tip and origination_size = opt Compare.Int.(=) default.origination_size c.origination_size and block_security_deposit = opt Tez_repr.(=) default.block_security_deposit c.block_security_deposit and endorsement_security_deposit = opt Tez_repr.(=) default.endorsement_security_deposit c.endorsement_security_deposit and block_reward = opt Tez_repr.(=) default.block_reward c.block_reward and endorsement_reward = opt Tez_repr.(=) default.endorsement_reward c.endorsement_reward and cost_per_byte = opt Tez_repr.(=) default.cost_per_byte c.cost_per_byte and hard_storage_limit_per_operation = opt Compare.Z.(=) default.hard_storage_limit_per_operation c.hard_storage_limit_per_operation in (( preserved_cycles, blocks_per_cycle, blocks_per_commitment, blocks_per_roll_snapshot, blocks_per_voting_period, time_between_blocks, endorsers_per_block, hard_gas_limit_per_operation, hard_gas_limit_per_block), ((proof_of_work_threshold, tokens_per_roll, michelson_maximum_type_size, seed_nonce_revelation_tip, origination_size, block_security_deposit, endorsement_security_deposit, block_reward), (endorsement_reward, cost_per_byte, hard_storage_limit_per_operation)))) (fun (( preserved_cycles, blocks_per_cycle, blocks_per_commitment, blocks_per_roll_snapshot, blocks_per_voting_period, time_between_blocks, endorsers_per_block, hard_gas_limit_per_operation, hard_gas_limit_per_block), ((proof_of_work_threshold, tokens_per_roll, michelson_maximum_type_size, seed_nonce_revelation_tip, origination_size, block_security_deposit, endorsement_security_deposit, block_reward), (endorsement_reward, cost_per_byte, hard_storage_limit_per_operation))) -> let unopt def = function None -> def | Some v -> v in let default = Constants_repr.default in { Constants_repr.preserved_cycles = unopt default.preserved_cycles preserved_cycles ; blocks_per_cycle = unopt default.blocks_per_cycle blocks_per_cycle ; blocks_per_commitment = unopt default.blocks_per_commitment blocks_per_commitment ; blocks_per_roll_snapshot = unopt default.blocks_per_roll_snapshot blocks_per_roll_snapshot ; blocks_per_voting_period = unopt default.blocks_per_voting_period blocks_per_voting_period ; time_between_blocks = unopt default.time_between_blocks @@ time_between_blocks ; endorsers_per_block = unopt default.endorsers_per_block endorsers_per_block ; hard_gas_limit_per_operation = unopt default.hard_gas_limit_per_operation hard_gas_limit_per_operation ; hard_gas_limit_per_block = unopt default.hard_gas_limit_per_block hard_gas_limit_per_block ; proof_of_work_threshold = unopt default.proof_of_work_threshold proof_of_work_threshold ; tokens_per_roll = unopt default.tokens_per_roll tokens_per_roll ; michelson_maximum_type_size = unopt default.michelson_maximum_type_size michelson_maximum_type_size ; seed_nonce_revelation_tip = unopt default.seed_nonce_revelation_tip seed_nonce_revelation_tip ; origination_size = unopt default.origination_size origination_size ; block_security_deposit = unopt default.block_security_deposit block_security_deposit ; endorsement_security_deposit = unopt default.endorsement_security_deposit endorsement_security_deposit ; block_reward = unopt default.block_reward block_reward ; endorsement_reward = unopt default.endorsement_reward endorsement_reward ; cost_per_byte = unopt default.cost_per_byte cost_per_byte ; hard_storage_limit_per_operation = unopt default.hard_storage_limit_per_operation hard_storage_limit_per_operation ; } ) (merge_objs (obj9 (opt "preserved_cycles" uint8) (opt "blocks_per_cycle" int32) (opt "blocks_per_commitment" int32) (opt "blocks_per_roll_snapshot" int32) (opt "blocks_per_voting_period" int32) (opt "time_between_blocks" (list Period_repr.encoding)) (opt "endorsers_per_block" uint16) (opt "hard_gas_limit_per_operation" z) (opt "hard_gas_limit_per_block" z)) (merge_objs (obj8 (opt "proof_of_work_threshold" int64) (opt "tokens_per_roll" Tez_repr.encoding) (opt "michelson_maximum_type_size" uint16) (opt "seed_nonce_revelation_tip" Tez_repr.encoding) (opt "origination_size" int31) (opt "block_security_deposit" Tez_repr.encoding) (opt "endorsement_security_deposit" Tez_repr.encoding) (opt "block_reward" Tez_repr.encoding)) (obj3 (opt "endorsement_reward" Tez_repr.encoding) (opt "cost_per_byte" Tez_repr.encoding) (opt "hard_storage_limit_per_operation" z)))) let encoding = let open Data_encoding in conv (fun { bootstrap_accounts ; bootstrap_contracts ; commitments ; constants ; security_deposit_ramp_up_cycles ; no_reward_cycles } -> ((bootstrap_accounts, bootstrap_contracts, commitments, security_deposit_ramp_up_cycles, no_reward_cycles), constants)) (fun ( (bootstrap_accounts, bootstrap_contracts, commitments, security_deposit_ramp_up_cycles, no_reward_cycles), constants) -> { bootstrap_accounts ; bootstrap_contracts ; commitments ; constants ; security_deposit_ramp_up_cycles ; no_reward_cycles }) (merge_objs (obj5 (req "bootstrap_accounts" (list bootstrap_account_encoding)) (dft "bootstrap_contracts" (list bootstrap_contract_encoding) []) (dft "commitments" (list Commitment_repr.encoding) []) (opt "security_deposit_ramp_up_cycles" int31) (opt "no_reward_cycles" int31)) constants_encoding)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
settings.ml
let configure () = Config.interface_suffix := "____mli_files_are_ignored____"; Clflags.strict_value_restriction := true; Clflags.no_std_include := true (* strict_value_restriction is needed to avoid problematic over-generalization on e.g. the code "let x = r.nb in ()", where nb is a record field *)
gc.mli
type stat = { minor_words: float ; promoted_words: float ; major_words: float ; minor_collections: int ; major_collections: int ; heap_words: int ; heap_chunks: int ; live_words: int ; live_blocks: int ; free_words: int ; free_blocks: int ; largest_free: int ; fragments: int ; compactions: int ; top_heap_words: int ; stack_size: int ; forced_major_collections: int } type control = { mutable minor_heap_size: int ; mutable major_heap_increment: int ; mutable space_overhead: int ; mutable verbose: int ; mutable max_overhead: int ; mutable stack_limit: int ; mutable allocation_policy: int ; window_size: int ; custom_major_ratio: int ; custom_minor_ratio: int ; custom_minor_max_size: int } external stat : unit -> stat = "caml_gc_stat" external quick_stat : unit -> stat = "caml_gc_quick_stat" external counters : unit -> (float * float * float) = "caml_gc_counters" external minor_words : unit -> ((float)[@unboxed ]) = "caml_gc_minor_words" "caml_gc_minor_words_unboxed" external get : unit -> control = "caml_gc_get" external set : control -> unit = "caml_gc_set" external minor : unit -> unit = "caml_gc_minor" external major_slice : int -> int = "caml_gc_major_slice" external major : unit -> unit = "caml_gc_major" external full_major : unit -> unit = "caml_gc_full_major" external compact : unit -> unit = "caml_gc_compaction" val print_stat : out_channel -> unit val allocated_bytes : unit -> float external get_minor_free : unit -> int = "caml_get_minor_free" external get_bucket : int -> int = "caml_get_major_bucket"[@@noalloc ] external get_credit : unit -> int = "caml_get_major_credit"[@@noalloc ] external huge_fallback_count : unit -> int = "caml_gc_huge_fallback_count" val finalise : ('a -> unit) -> 'a -> unit val finalise_last : (unit -> unit) -> 'a -> unit val finalise_release : unit -> unit type alarm val create_alarm : (unit -> unit) -> alarm val delete_alarm : alarm -> unit external eventlog_pause : unit -> unit = "caml_eventlog_pause" external eventlog_resume : unit -> unit = "caml_eventlog_resume" module Memprof : sig type allocation_source = | Normal | Marshal | Custom type allocation = private { n_samples: int ; size: int ; source: allocation_source ; callstack: Printexc.raw_backtrace } type ('minor, 'major) tracker = { alloc_minor: allocation -> 'minor option ; alloc_major: allocation -> 'major option ; promote: 'minor -> 'major option ; dealloc_minor: 'minor -> unit ; dealloc_major: 'major -> unit } val null_tracker : ('minor, 'major) tracker val start : sampling_rate:float -> ?callstack_size:int -> ('minor, 'major) tracker -> unit val stop : unit -> unit end
syndic_rss1.mli
(** [Syndic.Rss1]: compliant with {{: http://web.resource.org/rss/1.0/spec} RSS 1.0}. *) module Error : module type of Syndic_error (** A descriptive title for the channel, image, item and textinput. See RSS 1.0 {{: http://web.resource.org/rss/1.0/spec#s5.3.1} § 5.3.1}, {{: http://web.resource.org/rss/1.0/spec#s5.4.1} § 5.4.1}, {{: http://web.resource.org/rss/1.0/spec#s5.5.1} § 5.5.1}, and {{: http://web.resource.org/rss/1.0/spec#s5.6.1} § 5.6.1}. {[ Syntax: <title>{title}</title> Requirement: Required for all Model: (#PCDATA) (Suggested) Maximum Length: 40 (characters) for channel, image and textinput (Suggested) Maximum Length: 100 for item ]} *) type title = string (** The text input field's (variable) name. {{: http://web.resource.org/rss/1.0/spec#s5.6.3} See RSS 1.0 § 5.6.3}. {[ Syntax: <name>{textinput_varname}</name> Requirement: Required if textinput Model: (#PCDATA) (Suggested) Maximum Length: 500 ]} *) type name = string (** This can be - a brief description of the channel's content, function, source, etc. {{: http://web.resource.org/rss/1.0/spec#s5.3.3} See RSS 1.0 § 5.3.3}; - or a brief description/abstract of the item. {{: http://web.resource.org/rss/1.0/spec#s5.5.3} See RSS 1.0 § 5.5.3}; - or a brief description of the textinput field's purpose. For example: "Subscribe to our newsletter for..." or "Search our site's archive of..." {{: http://web.resource.org/rss/1.0/spec#s5.6.2} See RSS 1.0 § 5.6.2}. {[ Syntax: <description>{description}</description> Requirement: Required only for channel and textinput Model: (#PCDATA) (Suggested) Maximum Length: 500 for channel and item (Suggested) Maximum Length: 100 for textinput ]} *) type description = string (** Establishes an RDF association between the optional image element [5.4] and this particular RSS channel. The rdf:resource's {image_uri} must be the same as the image element's rdf:about {image_uri}. {{: http://web.resource.org/rss/1.0/spec#s5.3.4} See RSS 1.0 § 5.3.4} {[ Syntax: <image rdf:resource="{image_uri}" /> Requirement: Required only if image element present Model: Empty ]} *) type channel_image = Uri.t (** The URL of the image to used in the "src" attribute of the channel's image tag when rendered as HTML. {{: http://web.resource.org/rss/1.0/spec#s5.4.2} See RSS 1.0 § 5.4.2} {[ Syntax: <url>{image_url}</url> Requirement: Required if the image element is present Model: (#PCDATA) (Suggested) Maximum Length: 500 ]} *) type url = Uri.t (** This can be - The URL to which an HTML rendering of the channel title will link, commonly the parent site's home or news page. {{: http://web.resource.org/rss/1.0/spec#s5.3.2} See RSS 1.0 § 5.3.2} - Or the URL to which an HTML rendering of the channel image will link. This, as with the channel's title link, is commonly the parent site's home or news page. {{: http://web.resource.org/rss/1.0/spec#s5.4.3} See RSS 1.0 § 5.4.3} - Or the item's URL. {{: http://web.resource.org/rss/1.0/spec#s5.5.2} See RSS 1.0 § 5.5.2} - Or the URL to which a textinput submission will be directed (using GET). {{: http://web.resource.org/rss/1.0/spec#s5.6.4} See RSS 1.0 § 5.6.4} {[ Syntax: <link>{link}</link> Requirement: Required for all Model: (#PCDATA) (Suggested) Maximum Length: 500 ]} *) type link = Uri.t (** An RDF table of contents, associating the document's items [5.5] with this particular RSS channel. Each item's rdf:resource {item_uri} must be the same as the associated item element's rdf:about {item_uri}. An RDF Seq (sequence) is used to contain all the items rather than an RDF Bag to denote item order for rendering and reconstruction. Note that items appearing in the document but not as members of the channel level items sequence are likely to be discarded by RDF parsers. {{: http://web.resource.org/rss/1.0/spec#s5.3.5} See RSS 1.0 § 5.3.5} {[ Syntax: <items><rdf:Seq><rdf:li resource="{item_uri}" /> ... </rdf:Seq></items> Requirement: Required ]} *) type items = Uri.t list (** Establishes an RDF association between the optional textinput element [5.6] and this particular RSS channel. The {textinput_uri} rdf:resource must be the same as the textinput element's rdf:about {textinput_uri}. {{: http://web.resource.org/rss/1.0/spec#s5.3.6} See RSS 1.0 § 5.3.6} {[ Syntax: <textinput rdf:resource="{textinput_uri}" /> Requirement: Required only if texinput element present Model: Empty ]} *) type channel_textinput = Uri.t (** The channel element contains metadata describing the channel itself, including a title, brief description, and URL link to the described resource (the channel provider's home page, for instance). The \{resource\} URL of the channel element's rdf:about attribute must be unique with respect to any other rdf:about attributes in the RSS document and is a URI which identifies the channel. Most commonly, this is either the URL of the homepage being described or a URL where the RSS file can be found. {{: http://web.resource.org/rss/1.0/spec#s5.3} See RSS 1.0 § 5.3} {[ Syntax: <channel rdf:about="{resource}"> Requirement: Required Required Attribute(s): rdf:about Model: (title, link, description, image?, items, textinput?) ]} *) type channel = { about: Uri.t (** must be unique *) ; title: title ; link: link ; description: description ; image: channel_image option ; items: items ; textinput: channel_textinput option } (** An image to be associated with an HTML rendering of the channel. This image should be of a format supported by the majority of Web browsers. While the later 0.91 specification allowed for a width of 1–144 and height of 1–400, convention (and the 0.9 specification) dictate 88×31. {{: http://web.resource.org/rss/1.0/spec#s5.4} See RSS 1.0 § 5.4} {[ Syntax: <image rdf:about="{image_uri}"> Requirement: Optional; if present, must also be present in channel element [5.3.4] Required Attribute(s): rdf:about Model: (title, url, link) ]} *) type image = {about: Uri.t; title: title; url: url; link: link} (** While commonly a news headline, with RSS 1.0's modular extensibility, this can be just about anything: discussion posting, job listing, software patch -- any object with a URI. There may be a minimum of one item per RSS document. While RSS 1.0 does not enforce an upper limit, for backward compatibility with RSS 0.9 and 0.91, a maximum of fifteen items is recommended. [about] must be unique with respect to any other rdf:about attributes in the RSS document and is a URI which identifies the item. The value of [about] should be identical to the value of the [link], if possible. {{: http://web.resource.org/rss/1.0/spec#s5.5} See RSS 1.0 § 5.5} {[ Syntax: <item rdf:about="{item_uri}"> Requirement: >= 1 Recommendation (for backward compatibility with 0.9x): 1-15 Required Attribute(s): rdf:about Model: (title, link, description?) ]} *) type item = {about: Uri.t; title: title; link: link; description: description option} (** The textinput element affords a method for submitting form data to an arbitrary URL — usually located at the parent website. The form processor at the receiving end only is assumed to handle the HTTP GET method. The field is typically used as a search box or subscription form — among others. While this is of some use when RSS documents are rendered as channels (see MNN) and accompanied by human readable title and description, the ambiguity in automatic determination of meaning of this overloaded element renders it otherwise not particularly useful. RSS 1.0 therefore suggests either deprecation or augmentation with some form of resource discovery of this element in future versions while maintaining it for backward compatiblity with RSS 0.9. [about] must be unique with respect to any other rdf:about attributes in the RSS document and is a URI which identifies the textinput. [about] should be identical to the value of the [link], if possible. {{: http://web.resource.org/rss/1.0/spec#s5.6} See RSS 1.0 § 5.6 } {[ Syntax: <textinput rdf:about="{textinput_uri}"> Requirement: Optional; if present, must also be present in channel element [5.3.6] Required Attribute(s): rdf:about Model: (title, description, name, link) ]} *) type textinput = {about: Uri.t; title: title; description: description; name: name; link: link} (** The outermost level in every RSS 1.0 compliant document is the RDF element. The opening RDF tag assocaties the rdf: namespace prefix with the RDF syntax schema and establishes the RSS 1.0 schema as the default namespace for the document. While any valid namespace prefix may be used, document creators are advised to consider "rdf:" normative. Those wishing to be strictly backward-compatible with RSS 0.9 must use "rdf:". {{: http://web.resource.org/rss/1.0/spec#s5.2} See RSS 1.0 § 5.2} {[ Syntax: <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/"> Requirement: Required exactly as shown, aside from any additional namespace declarations Model: (channel, image?, item+, textinput?) ]} *) type rdf = { channel: channel ; image: image option ; item: item list ; textinput: textinput option } val parse : ?xmlbase:Uri.t -> Xmlm.input -> rdf (** [parse xml] returns the RDF corresponding to [xml]. @raise Error.raise_expectation if [xml] is not a valid RSS1 document. @param xmlbase the base URI against which relative URIs in the XML RSS1 document are resolved. It is superseded by xml:base present in the document (if any). *) val read : ?xmlbase:Uri.t -> string -> rdf (** [read fname] reads the file name [fname] and parses it. For the optional parameters, see {!parse}. *) (**/**) (** An URI is given by (xmlbase, uri). The value of [xmlbase], if not [None], gives the base URI against which [uri] must be resolved if it is relative. *) type uri = Uri.t option * string val unsafe : ?xmlbase:Uri.t -> Xmlm.input -> [> `RDF of [> `Channel of [> `About of uri | `Description of string list | `Image of [> `URI of uri] list | `Items of [> `Seq of [> `Li of [> `URI of uri] list ] list ] list | `Link of [> `URI of uri] list | `TextInput of [> `URI of uri] list | `Title of string list ] list | `Image of [> `About of uri | `Link of [> `URI of uri] list | `Title of string list | `URL of [> `URI of uri] list ] list | `Item of [> `About of uri | `Description of string list | `Link of [> `URI of uri] list | `Title of string list ] list | `TextInput of [> `About of uri | `Description of string list | `Link of [> `URI of uri] list | `Name of string list | `Title of string list ] list ] list ] (** Analysis without verification, enjoy ! *)
(** [Syndic.Rss1]: compliant with {{: http://web.resource.org/rss/1.0/spec} RSS 1.0}. *)
socket_daemon.mli
val run : ?magic_bytes:int list -> ?timeout:Time.System.Span.t -> check_high_watermark:bool -> require_auth:bool -> #Client_context.io_wallet -> Tezos_base_unix.Socket.addr -> 'a list tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
scalar_addmul_nmod_mat_fmpz.c
#include "fmpz_mat.h" void fmpz_mat_scalar_addmul_nmod_mat_fmpz(fmpz_mat_t B, const nmod_mat_t A, const fmpz_t c) { slong i, j; for (i = 0; i < A->r; i++) for (j = 0; j < A->c; j++) fmpz_addmul_ui(fmpz_mat_entry(B,i,j), c, nmod_mat_entry(A,i,j)); }
/* Copyright (C) 2011 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/>. */
letin.ml
(* Remove nested declaration of variables *) (* Preserves the sequential order defined by a let/in *) (* declaration and, thus, possible side effects in them *) (* E.g., in [let x = e1 in e2], all side effects in [e1] are done before *) (* those of [e2] *) (* [let x = e1 in e2] has the behavior of [let x = e1 before y = e2 in y] *) open Zmisc open Zlocation open Zident open Lident open Deftypes open Zelus open Zaux (* a structure to represent nested equations before they are turned into *) (* valid Zelus equations *) type ctx = { env: Deftypes.tentry Env.t State.t; eqs: eq State.t } let empty = { env = State.empty; eqs = State.empty } let par { env = env1; eqs = eqs1 } { env = env2; eqs = eqs2 } = { env = State.par env1 env2; eqs = State.par eqs1 eqs2 } let seq { env = env1; eqs = eqs1 } { env = env2; eqs = eqs2 } = { env = State.seq env1 env2; eqs = State.seq eqs1 eqs2 } let add eq ({ eqs = eqs } as ctx) = { ctx with eqs = State.par (State.singleton eq) eqs } let optional f e_opt = match e_opt with | None -> None, { env = State.Empty; eqs = State.Empty } | Some(e) -> let e, ctx = f e in Some(e), ctx let par_fold f l = Zmisc.map_fold (fun { env = env; eqs = eqs } x -> let y, { env = env_y; eqs = eqs_y } = f x in y, { env = State.par env env_y; eqs = State.par eqs eqs_y }) { env = State.Empty; eqs = State.Empty } l (* translate a context [ctx] into an environment and an equation *) let equations eqs = (* computes the set of sequential equations *) let rec seq eqs eq_list = match eqs with | State.Empty -> eq_list | State.Cons(eq, eqs) -> eq :: seq eqs eq_list | State.Seq(eqs1, eqs2) -> seq eqs1 (seq eqs2 eq_list) | State.Par(eqs1, eqs2) -> let par_eq_list = par [] eqs1 in let par_eq_list = par par_eq_list eqs2 in Zaux.par par_eq_list :: eq_list (* and the set of parallel equations *) and par eq_list eqs = match eqs with | State.Empty -> eq_list | State.Cons(eq, eqs) -> par (eq :: eq_list) eqs | State.Seq(eqs1, eqs2) -> let seq_eq_list = seq eqs2 [] in let seq_eq_list = seq eqs1 seq_eq_list in Zaux.before seq_eq_list :: eq_list | State.Par(eqs1, eqs2) -> par (par eq_list eqs1) eqs2 in par [] eqs (* every variable from [ctx] becomes a local variable *) let add_locals n_list l_env { env = env; eqs = eqs } = let eq_list = equations eqs in let l_env = State.fold (fun env acc -> Env.append env acc) env l_env in let n_list = State.fold (fun env acc -> Env.fold (fun n entry acc -> (Zaux.vardec_from_entry n entry) :: acc) env acc) env n_list in n_list, l_env, eq_list (** Translation of expressions *) let rec expression ({ e_desc = desc } as e) = match desc with | Elocal _ | Eglobal _ | Econst _ | Econstr0 _ | Elast _ -> e, empty | Eop(op, e_list) -> let e_list, ctx = par_fold expression e_list in { e with e_desc = Eop(op, e_list) }, ctx | Eapp(app, e_op, e_list) -> let e_op, ctx_e_op = expression e_op in let e_list, ctx = par_fold expression e_list in { e with e_desc = Eapp(app, e_op, e_list) }, par ctx_e_op ctx | Etuple(e_list) -> let e_list, ctx = par_fold expression e_list in { e with e_desc = Etuple(e_list) }, ctx | Econstr1(c, e_list) -> let e_list, ctx = par_fold expression e_list in { e with e_desc = Econstr1(c, e_list) }, ctx | Erecord_access(e_record, l) -> let e_record, ctx = expression e_record in { e with e_desc = Erecord_access(e_record, l) }, ctx | Erecord(l_e_list) -> let l_e_list, ctx = par_fold (fun (l, e) -> let e, ctx = expression e in (l, e), ctx) l_e_list in { e with e_desc = Erecord(l_e_list) }, ctx | Erecord_with(e_record, l_e_list) -> let e_record, ctx_record = expression e_record in let l_e_list, ctx = par_fold (fun (l, e) -> let e, ctx = expression e in (l, e), ctx) l_e_list in { e with e_desc = Erecord_with(e_record, l_e_list) }, par ctx_record ctx | Etypeconstraint(e1, ty) -> let e1, ctx = expression e1 in { e with e_desc = Etypeconstraint(e1, ty) }, ctx | Elet(l, e_let) -> let ctx = local l in let e_let, ctx_let = expression e_let in e_let, seq ctx ctx_let | Eblock({ b_locals = l_list; b_env = b_env; b_body = eq_list }, e) -> let l_ctx = local_list l_list in let eq_list_ctx = par_equation_list eq_list in let e, ctx_e = expression e in e, seq { empty with env = State.singleton b_env } (seq l_ctx (seq eq_list_ctx ctx_e)) | Eseq(e1, e2) -> (* [e1; e2] is a short-cut for [let _ = e1 in e2] *) let e1, ctx1 = expression e1 in let e2, ctx2 = expression e2 in let _e1 = Zaux.eqmake (EQeq({ Zaux.wildpat with p_typ = e1.e_typ }, e1)) in e2, seq ctx1 (seq { empty with eqs = State.singleton _e1 } ctx2) | Epresent _ | Ematch _ | Eperiod _ -> assert false (** Translate an equation. *) and equation ({ eq_desc = desc } as eq) = match desc with | EQeq(p, e) -> let e, ctx = expression e in add { eq with eq_desc = EQeq(p, e) } ctx | EQpluseq(n, e) -> let e, ctx_e = expression e in add { eq with eq_desc = EQpluseq(n, e) } ctx_e | EQder(n, e, e0_opt, []) -> let e, ctx = expression e in let e0_opt, ctx0 = optional expression e0_opt in let eq = { eq with eq_desc = EQder(n, e, e0_opt, []) } in add eq (par ctx ctx0) | EQinit(n, e0) -> let e0, ctx_e0 = expression e0 in add { eq with eq_desc = EQinit(n, e0) } ctx_e0 | EQmatch(total, e, p_h_list) -> let e, ctx_e = expression e in let p_h_list = List.map (fun ({ m_body = b } as p_h) -> let b = block b in { p_h with m_body = b }) p_h_list in add { eq with eq_desc = EQmatch(total, e, p_h_list) } ctx_e | EQreset(res_eq_list, e) -> let e, ctx_e = expression e in let { env = env; eqs = eqs } = par_equation_list res_eq_list in let res_eq_list = equations eqs in par ctx_e (add { eq with eq_desc = EQreset(res_eq_list, e) } { empty with env = env }) | EQand(and_eq_list) -> par_equation_list and_eq_list | EQbefore(before_eq_list) -> seq_equation_list before_eq_list | EQblock { b_locals = l_list; b_env = b_env; b_body = eq_list } -> let l_ctx = local_list l_list in let eq_list_ctx = par_equation_list eq_list in par (seq l_ctx eq_list_ctx) { empty with env = State.singleton b_env } | EQforall ({ for_index = ind_list; for_init = i_list; for_body = b_eq_list } as body) -> let index ({ desc = desc } as ind) = match desc with | Einput(x, e) -> let e, ctx_e = expression e in { ind with desc = Einput(x, e) }, ctx_e | Eoutput _ -> ind, empty | Eindex(x, e1, e2) -> let e1, ctx_e1 = expression e1 in let e2, ctx_e2 = expression e2 in { ind with desc = Eindex(x, e1, e2) }, par ctx_e1 ctx_e2 in let init ({ desc = desc } as i) = match desc with | Einit_last(x, e) -> let e, ctx_e = expression e in { i with desc = Einit_last(x, e) }, ctx_e in let ind_list, ind_ctx = par_fold index ind_list in let i_list, i_ctx = par_fold init i_list in let b_eq_list = block b_eq_list in add { eq with eq_desc = EQforall { body with for_index = ind_list; for_init = i_list; for_body = b_eq_list } } (par ind_ctx i_ctx) | EQder _ | EQautomaton _ | EQpresent _ | EQemit _ | EQnext _ -> assert false and par_equation_list eq_list = List.fold_left (fun acc eq -> par (equation eq) acc) empty eq_list and seq_equation_list eq_list = List.fold_left (fun acc eq -> seq acc (equation eq)) empty eq_list (** Translating a block *) (* Once normalized, a block is of the form *) (* local x1,..., xn in do eq1 and ... and eqn *) and block ({ b_vars = n_list; b_locals = l_list; b_body = eq_list; b_env = b_env } as b) = (* first translate local declarations *) let l_ctx = local_list l_list in (* then the set of equations *) let ctx = par_equation_list eq_list in let ctx = seq l_ctx ctx in (* all local variables from [l_ctx] and [ctx] are now *) (* declared in that block *) let n_list, b_env, eq_list = add_locals n_list b_env ctx in { b with b_vars = n_list; b_locals = []; b_body = eq_list; b_env = b_env } and local { l_eq = eq_list; l_env = l_env } = let ctx = par_equation_list eq_list in seq { empty with env = State.singleton l_env } ctx and local_list = function | [] -> empty | l :: l_list -> let l_ctx = local l in let ctx = local_list l_list in seq l_ctx ctx let implementation impl = let make_let e = let e, ctx = expression e in let _, env, eq_list = add_locals [] Env.empty ctx in Zaux.make_let env eq_list e in match impl.desc with | Eopen _ | Etypedecl _ -> impl | Econstdecl(n, is_static, e) -> { impl with desc = Econstdecl(n, is_static, make_let e) } | Efundecl(n, ({ f_kind = k; f_body = e } as body)) -> { impl with desc = Efundecl(n, { body with f_body = make_let e }) } let implementation_list impl_list = Zmisc.iter implementation impl_list
(***********************************************************************) (* *) (* *) (* Zelus, a synchronous language for hybrid systems *) (* *) (* (c) 2020 Inria Paris (see the AUTHORS file) *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed under *) (* the terms of the INRIA Non-Commercial License Agreement (see the *) (* LICENSE file). *) (* *) (* *********************************************************************)
factor_squarefree.c
#include "fmpz_mpoly_factor.h" static void _fmpz_mpoly_factor_mul_mpoly_fmpz( fmpz_mpoly_factor_t f, fmpz_mpoly_t A, const fmpz_t e, const fmpz_mpoly_ctx_t ctx) { if (fmpz_mpoly_is_fmpz(A, ctx)) { fmpz_t t; fmpz_init(t); fmpz_mpoly_get_fmpz(t, A, ctx); fmpz_pow_fmpz(t, t, e); fmpz_mul(f->constant, f->constant, t); fmpz_clear(t); } else { fmpz_mpoly_factor_append_fmpz_swap(f, A, e, ctx); } } /* append factor_squarefree(A)^e to f assuming is A is primitive wrt to each variable */ int _fmpz_mpoly_factor_squarefree( fmpz_mpoly_factor_t f, fmpz_mpoly_t A, const fmpz_t e, const fmpz_mpoly_ctx_t ctx) { int success; slong v; fmpz_t k, ke; fmpz_mpoly_t S, Sp, Sm, Ss, Y, Z; if (A->length < 2) { _fmpz_mpoly_factor_mul_mpoly_fmpz(f, A, e, ctx); return 1; } fmpz_init(k); fmpz_init(ke); fmpz_mpoly_init(S, ctx); fmpz_mpoly_init(Sp, ctx); fmpz_mpoly_init(Sm, ctx); fmpz_mpoly_init(Ss, ctx); fmpz_mpoly_init(Y, ctx); fmpz_mpoly_init(Z, ctx); for (v = 0; v < ctx->minfo->nvars; v++) { fmpz_mpoly_derivative(Sp, A, v, ctx); if (fmpz_mpoly_is_zero(Sp, ctx)) continue; success = fmpz_mpoly_gcd_cofactors(Sm, Ss, Y, A, Sp, ctx); if (!success) continue; for (fmpz_set_ui(k, 1); !(fmpz_mpoly_derivative(Sp, Ss, v, ctx), fmpz_mpoly_sub(Z, Y, Sp, ctx), fmpz_mpoly_is_zero(Z, ctx)); fmpz_add_ui(k, k, 1)) { success = fmpz_mpoly_gcd_cofactors(S, Ss, Y, Ss, Z, ctx); if (!success) continue; fmpz_mul(ke, k, e); _fmpz_mpoly_factor_mul_mpoly_fmpz(f, S, k, ctx); } fmpz_mul(ke, k, e); _fmpz_mpoly_factor_mul_mpoly_fmpz(f, Ss, k, ctx); success = 1; goto cleanup; } success = 0; cleanup: fmpz_clear(k); fmpz_mpoly_clear(S, ctx); fmpz_mpoly_clear(Sp, ctx); fmpz_mpoly_clear(Sm, ctx); fmpz_mpoly_clear(Ss, ctx); fmpz_mpoly_clear(Y, ctx); fmpz_mpoly_clear(Z, ctx); return success; } int fmpz_mpoly_factor_squarefree( fmpz_mpoly_factor_t f, const fmpz_mpoly_t A, const fmpz_mpoly_ctx_t ctx) { int success; slong i; fmpz_mpoly_factor_t g; fmpz_mpoly_factor_init(g, ctx); success = fmpz_mpoly_factor_content(g, A, ctx); if (!success) goto cleanup; fmpz_swap(f->constant, g->constant); f->num = 0; for (i = 0; i < g->num; i++) { success = _fmpz_mpoly_factor_squarefree(f, g->poly + i, g->exp + i, ctx); if (!success) goto cleanup; } success = 1; cleanup: fmpz_mpoly_factor_clear(g, ctx); FLINT_ASSERT(!success || fmpz_mpoly_factor_matches(A, f, ctx)); return success; }
/* Copyright (C) 2020 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/>. */
operation_repr.mli
(** Tezos Protocol Implementation - Low level Repr. of Operations Defines kinds of operations that can be performed on chain: - preendorsement - endorsement - double baking evidence - double preendorsing evidence - double endorsing evidence - seed nonce revelation - account activation - proposal (see: [Voting_repr]) - ballot (see: [Voting_repr]) - failing noop - manager operation (which in turn has several types): - revelation - transaction - origination - delegation - set deposits limitation - tx rollup origination - tx rollup batch submission - tx rollup commit - tx rollup withdraw - tx rollup reveal withdrawals - smart contract rollup origination - zk rollup origination - zk rollup publish Each of them can be encoded as raw bytes. Operations are distinguished at type level using phantom type parameters. [packed_operation] type allows for unifying them when required, for instance to put them on a single list. *) module Kind : sig type preendorsement_consensus_kind = Preendorsement_consensus_kind type endorsement_consensus_kind = Endorsement_consensus_kind type 'a consensus = | Preendorsement_kind : preendorsement_consensus_kind consensus | Endorsement_kind : endorsement_consensus_kind consensus type preendorsement = preendorsement_consensus_kind consensus type endorsement = endorsement_consensus_kind consensus type dal_slot_availability = Dal_slot_availability_kind type seed_nonce_revelation = Seed_nonce_revelation_kind type vdf_revelation = Vdf_revelation_kind type 'a double_consensus_operation_evidence = | Double_consensus_operation_evidence type double_endorsement_evidence = endorsement_consensus_kind double_consensus_operation_evidence type double_preendorsement_evidence = preendorsement_consensus_kind double_consensus_operation_evidence type double_baking_evidence = Double_baking_evidence_kind type activate_account = Activate_account_kind type proposals = Proposals_kind type ballot = Ballot_kind type reveal = Reveal_kind type transaction = Transaction_kind type origination = Origination_kind type delegation = Delegation_kind type event = Event_kind type set_deposits_limit = Set_deposits_limit_kind type increase_paid_storage = Increase_paid_storage_kind type update_consensus_key = Update_consensus_key_kind type drain_delegate = Drain_delegate_kind type failing_noop = Failing_noop_kind type register_global_constant = Register_global_constant_kind type tx_rollup_origination = Tx_rollup_origination_kind type tx_rollup_submit_batch = Tx_rollup_submit_batch_kind type tx_rollup_commit = Tx_rollup_commit_kind type tx_rollup_return_bond = Tx_rollup_return_bond_kind type tx_rollup_finalize_commitment = Tx_rollup_finalize_commitment_kind type tx_rollup_remove_commitment = Tx_rollup_remove_commitment_kind type tx_rollup_rejection = Tx_rollup_rejection_kind type tx_rollup_dispatch_tickets = Tx_rollup_dispatch_tickets_kind type transfer_ticket = Transfer_ticket_kind type dal_publish_slot_header = Dal_publish_slot_header_kind type sc_rollup_originate = Sc_rollup_originate_kind type sc_rollup_add_messages = Sc_rollup_add_messages_kind type sc_rollup_cement = Sc_rollup_cement_kind type sc_rollup_publish = Sc_rollup_publish_kind type sc_rollup_refute = Sc_rollup_refute_kind type sc_rollup_timeout = Sc_rollup_timeout_kind type sc_rollup_execute_outbox_message = | Sc_rollup_execute_outbox_message_kind type sc_rollup_recover_bond = Sc_rollup_recover_bond_kind type sc_rollup_dal_slot_subscribe = Sc_rollup_dal_slot_subscribe_kind type zk_rollup_origination = Zk_rollup_origination_kind type zk_rollup_publish = Zk_rollup_publish_kind type 'a manager = | Reveal_manager_kind : reveal manager | Transaction_manager_kind : transaction manager | Origination_manager_kind : origination manager | Delegation_manager_kind : delegation manager | Event_manager_kind : event manager | Register_global_constant_manager_kind : register_global_constant manager | Set_deposits_limit_manager_kind : set_deposits_limit manager | Increase_paid_storage_manager_kind : increase_paid_storage manager | Update_consensus_key_manager_kind : update_consensus_key manager | Tx_rollup_origination_manager_kind : tx_rollup_origination manager | Tx_rollup_submit_batch_manager_kind : tx_rollup_submit_batch manager | Tx_rollup_commit_manager_kind : tx_rollup_commit manager | Tx_rollup_return_bond_manager_kind : tx_rollup_return_bond manager | Tx_rollup_finalize_commitment_manager_kind : tx_rollup_finalize_commitment manager | Tx_rollup_remove_commitment_manager_kind : tx_rollup_remove_commitment manager | Tx_rollup_rejection_manager_kind : tx_rollup_rejection manager | Tx_rollup_dispatch_tickets_manager_kind : tx_rollup_dispatch_tickets manager | Transfer_ticket_manager_kind : transfer_ticket manager | Dal_publish_slot_header_manager_kind : dal_publish_slot_header manager | Sc_rollup_originate_manager_kind : sc_rollup_originate manager | Sc_rollup_add_messages_manager_kind : sc_rollup_add_messages manager | Sc_rollup_cement_manager_kind : sc_rollup_cement manager | Sc_rollup_publish_manager_kind : sc_rollup_publish manager | Sc_rollup_refute_manager_kind : sc_rollup_refute manager | Sc_rollup_timeout_manager_kind : sc_rollup_timeout manager | Sc_rollup_execute_outbox_message_manager_kind : sc_rollup_execute_outbox_message manager | Sc_rollup_recover_bond_manager_kind : sc_rollup_recover_bond manager | Sc_rollup_dal_slot_subscribe_manager_kind : sc_rollup_dal_slot_subscribe manager | Zk_rollup_origination_manager_kind : zk_rollup_origination manager | Zk_rollup_publish_manager_kind : zk_rollup_publish manager end type 'a consensus_operation_type = | Endorsement : Kind.endorsement consensus_operation_type | Preendorsement : Kind.preendorsement consensus_operation_type val pp_operation_kind : Format.formatter -> 'kind consensus_operation_type -> unit type consensus_content = { slot : Slot_repr.t; (* By convention, this is the validator's first slot. *) level : Raw_level_repr.t; (* The level of (pre)endorsed block. *) round : Round_repr.t; (* The round of (pre)endorsed block. *) block_payload_hash : Block_payload_hash.t; (* The payload hash of (pre)endorsed block. *) } val consensus_content_encoding : consensus_content Data_encoding.t val pp_consensus_content : Format.formatter -> consensus_content -> unit type consensus_watermark = | Endorsement of Chain_id.t | Preendorsement of Chain_id.t | Dal_slot_availability of Chain_id.t val to_watermark : consensus_watermark -> Signature.watermark val of_watermark : Signature.watermark -> consensus_watermark option type raw = Operation.t = {shell : Operation.shell_header; proto : bytes} val raw_encoding : raw Data_encoding.t (** An [operation] contains the operation header information in [shell] and all data related to the operation itself in [protocol_data]. *) type 'kind operation = { shell : Operation.shell_header; protocol_data : 'kind protocol_data; } (** A [protocol_data] wraps together a signature for the operation and the contents of the operation itself. *) and 'kind protocol_data = { contents : 'kind contents_list; signature : Signature.t option; } (** A [contents_list] is a list of contents, the GADT guarantees two invariants: - the list is not empty, and - if the list has several elements then it only contains manager operations. *) and _ contents_list = | Single : 'kind contents -> 'kind contents_list | Cons : 'kind Kind.manager contents * 'rest Kind.manager contents_list -> ('kind * 'rest) Kind.manager contents_list (** A value of type [contents] an operation related to whether consensus, governance or contract management. *) and _ contents = (* Preendorsement: About consensus, preendorsement of a block held by a validator (specific to Tenderbake). *) | Preendorsement : consensus_content -> Kind.preendorsement contents (* Endorsement: About consensus, endorsement of a block held by a validator. *) | Endorsement : consensus_content -> Kind.endorsement contents (* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3115 Temporary operation to avoid modifying endorsement encoding. *) | Dal_slot_availability : Signature.Public_key_hash.t * Dal_endorsement_repr.t -> Kind.dal_slot_availability contents (* Seed_nonce_revelation: Nonces are created by bakers and are combined to create pseudo-random seeds. Bakers are urged to reveal their nonces after a given number of cycles to keep their block rewards from being forfeited. *) | Seed_nonce_revelation : { level : Raw_level_repr.t; nonce : Seed_repr.nonce; } -> Kind.seed_nonce_revelation contents (* Vdf_revelation: VDF are computed from the seed generated by the revealed nonces. *) | Vdf_revelation : { solution : Seed_repr.vdf_solution; } -> Kind.vdf_revelation contents (* Double_preendorsement_evidence: Double-preendorsement is a kind of malicious attack where a byzantine attempts to fork the chain by preendorsing blocks with different contents (at the same level and same round) twice. This behavior may be reported and the byzantine will have its security deposit forfeited. *) | Double_preendorsement_evidence : { op1 : Kind.preendorsement operation; op2 : Kind.preendorsement operation; } -> Kind.double_preendorsement_evidence contents (* Double_endorsement_evidence: Similar to double-preendorsement but for endorsements. *) | Double_endorsement_evidence : { op1 : Kind.endorsement operation; op2 : Kind.endorsement operation; } -> Kind.double_endorsement_evidence contents (* Double_baking_evidence: Similarly to double-endorsement but the byzantine attempts to fork by signing two different blocks at the same level. *) | Double_baking_evidence : { bh1 : Block_header_repr.t; bh2 : Block_header_repr.t; } -> Kind.double_baking_evidence contents (* Activate_account: Account activation allows to register a public key hash on the blockchain. *) | Activate_account : { id : Ed25519.Public_key_hash.t; activation_code : Blinded_public_key_hash.activation_code; } -> Kind.activate_account contents (* Proposals: A candidate protocol can be proposed for voting. *) | Proposals : { source : Signature.Public_key_hash.t; period : int32; proposals : Protocol_hash.t list; } -> Kind.proposals contents (* Ballot: The validators of the chain will then vote on proposals. *) | Ballot : { source : Signature.Public_key_hash.t; period : int32; proposal : Protocol_hash.t; ballot : Vote_repr.ballot; } -> Kind.ballot contents (* [Drain_delegate { consensus_key ; delegate ; destination }] transfers the spendable balance of the [delegate] to [destination] when [consensus_key] is the active consensus key of [delegate].. *) | Drain_delegate : { consensus_key : Signature.Public_key_hash.t; delegate : Signature.Public_key_hash.t; destination : Signature.Public_key_hash.t; } -> Kind.drain_delegate contents (* Failing_noop: An operation never considered by the state machine and which will always fail at [apply]. This allows end-users to sign arbitrary messages which have no computational semantics. *) | Failing_noop : string -> Kind.failing_noop contents (* Manager_operation: Operations, emitted and signed by a (revealed) implicit account, that describe management and interactions between contracts (whether implicit or smart). *) | Manager_operation : { source : Signature.Public_key_hash.t; fee : Tez_repr.tez; counter : counter; operation : 'kind manager_operation; gas_limit : Gas_limit_repr.Arith.integral; storage_limit : Z.t; } -> 'kind Kind.manager contents (** A [manager_operation] describes management and interactions between contracts (whether implicit or smart). *) and _ manager_operation = (* [Reveal] for the revelation of a public key, a one-time prerequisite to any signed operation, in order to be able to check the sender’s signature. *) | Reveal : Signature.Public_key.t -> Kind.reveal manager_operation (* [Transaction] of some amount to some destination contract. It can also be used to execute/call smart-contracts. *) | Transaction : { amount : Tez_repr.tez; parameters : Script_repr.lazy_expr; entrypoint : Entrypoint_repr.t; destination : Contract_repr.t; } -> Kind.transaction manager_operation (* [Origination] of a contract using a smart-contract [script] and initially credited with the amount [credit]. *) | Origination : { delegate : Signature.Public_key_hash.t option; script : Script_repr.t; credit : Tez_repr.tez; } -> Kind.origination manager_operation (* [Delegation] to some staking contract (designated by its public key hash). When this value is None, delegation is reverted as it is set to nobody. *) | Delegation : Signature.Public_key_hash.t option -> Kind.delegation manager_operation (* [Register_global_constant] allows registration and substitution of a global constant available from any contract and registered in the context. *) | Register_global_constant : { value : Script_repr.lazy_expr; } -> Kind.register_global_constant manager_operation (* [Set_deposits_limit] sets an optional limit for frozen deposits of a contract at a lower value than the maximum limit. When None, the limit in unset back to the default maximum limit. *) | Set_deposits_limit : Tez_repr.t option -> Kind.set_deposits_limit manager_operation (* [Increase_paid_storage] allows a sender to pay to increase the paid storage of some contract by some amount. *) | Increase_paid_storage : { amount_in_bytes : Z.t; destination : Contract_hash.t; } -> Kind.increase_paid_storage manager_operation (* [Update_consensus_key pk] updates the consensus key of the signing delegate to [pk]. *) | Update_consensus_key : Signature.Public_key.t -> Kind.update_consensus_key manager_operation (* [Tx_rollup_origination] allows an implicit contract to originate a new transactional rollup. *) | Tx_rollup_origination : Kind.tx_rollup_origination manager_operation (* [Tx_rollup_submit_batch] allows to submit batches of L2 operations on a transactional rollup. The content is a string, but stands for an immutable byte sequence. *) | Tx_rollup_submit_batch : { tx_rollup : Tx_rollup_repr.t; content : string; burn_limit : Tez_repr.t option; } -> Kind.tx_rollup_submit_batch manager_operation | Tx_rollup_commit : { tx_rollup : Tx_rollup_repr.t; commitment : Tx_rollup_commitment_repr.Full.t; } -> Kind.tx_rollup_commit manager_operation | Tx_rollup_return_bond : { tx_rollup : Tx_rollup_repr.t; } -> Kind.tx_rollup_return_bond manager_operation | Tx_rollup_finalize_commitment : { tx_rollup : Tx_rollup_repr.t; } -> Kind.tx_rollup_finalize_commitment manager_operation | Tx_rollup_remove_commitment : { tx_rollup : Tx_rollup_repr.t; } -> Kind.tx_rollup_remove_commitment manager_operation | Tx_rollup_rejection : { tx_rollup : Tx_rollup_repr.t; level : Tx_rollup_level_repr.t; message : Tx_rollup_message_repr.t; message_position : int; message_path : Tx_rollup_inbox_repr.Merkle.path; message_result_hash : Tx_rollup_message_result_hash_repr.t; message_result_path : Tx_rollup_commitment_repr.Merkle.path; previous_message_result : Tx_rollup_message_result_repr.t; previous_message_result_path : Tx_rollup_commitment_repr.Merkle.path; proof : Tx_rollup_l2_proof.serialized; } -> Kind.tx_rollup_rejection manager_operation | Tx_rollup_dispatch_tickets : { tx_rollup : Tx_rollup_repr.t; (** The rollup from where the tickets are retrieved *) level : Tx_rollup_level_repr.t; (** The level at which the withdrawal was enabled *) context_hash : Context_hash.t; (** The hash of the l2 context resulting from the execution of the inbox from where this withdrawal was enabled. *) message_index : int; (** Index of the message in the inbox at [level] where this withdrawal was enabled. *) message_result_path : Tx_rollup_commitment_repr.Merkle.path; tickets_info : Tx_rollup_reveal_repr.t list; } -> Kind.tx_rollup_dispatch_tickets manager_operation (** [Transfer_ticket] allows an implicit account (the "claimer") to receive [amount] tickets, pulled out of [tx_rollup], to the [entrypoint] of the smart contract [destination]. The ticket must have been addressed to the claimer, who must be the source of this operation. It must have been pulled out at [level] and from the message at [message_index]. The ticket is composed of [ticketer; ty; contents]. *) | Transfer_ticket : { contents : Script_repr.lazy_expr; (** Contents of the withdrawn ticket *) ty : Script_repr.lazy_expr; (** Type of the withdrawn ticket's contents *) ticketer : Contract_repr.t; (** Ticketer of the withdrawn ticket *) amount : Ticket_amount.t; (** Quantity of the withdrawn ticket. Must match the amount that was enabled. *) destination : Contract_repr.t; (** The smart contract address that should receive the tickets. *) entrypoint : Entrypoint_repr.t; (** The entrypoint of the smart contract address that should receive the tickets. *) } -> Kind.transfer_ticket manager_operation | Dal_publish_slot_header : { slot : Dal_slot_repr.t; } -> Kind.dal_publish_slot_header manager_operation (** [Sc_rollup_originate] allows an implicit account to originate a new smart contract rollup (initialized with a given boot sector). The [parameters_ty] field allows to provide the expected interface of the rollup being originated (i.e. its entrypoints with their associated signatures) as a Michelson type. *) | Sc_rollup_originate : { kind : Sc_rollups.Kind.t; boot_sector : string; origination_proof : string; parameters_ty : Script_repr.lazy_expr; } -> Kind.sc_rollup_originate manager_operation (* [Sc_rollup_add_messages] adds messages to a given rollup's inbox. *) | Sc_rollup_add_messages : { rollup : Sc_rollup_repr.t; messages : string list; } -> Kind.sc_rollup_add_messages manager_operation | Sc_rollup_cement : { rollup : Sc_rollup_repr.t; commitment : Sc_rollup_commitment_repr.Hash.t; } -> Kind.sc_rollup_cement manager_operation | Sc_rollup_publish : { rollup : Sc_rollup_repr.t; commitment : Sc_rollup_commitment_repr.t; } -> Kind.sc_rollup_publish manager_operation | Sc_rollup_refute : { rollup : Sc_rollup_repr.t; opponent : Sc_rollup_repr.Staker.t; refutation : Sc_rollup_game_repr.refutation option; } -> Kind.sc_rollup_refute manager_operation (** [Sc_rollup_refute { rollup; opponent; refutation }] makes a move in a refutation game between the source of the operation and the [opponent] under the given [rollup]. Both players must be stakers on commitments in conflict. When [refutation = None], the game is initialized. Next, when [refutation = Some move], [move] is the next play for the current player. See {!Sc_rollup_game_repr} for details. **) | Sc_rollup_timeout : { rollup : Sc_rollup_repr.t; stakers : Sc_rollup_game_repr.Index.t; } -> Kind.sc_rollup_timeout manager_operation (* [Sc_rollup_execute_outbox_message] executes a message from the rollup's outbox. Messages may involve transactions to smart contract accounts on Layer 1. *) | Sc_rollup_execute_outbox_message : { rollup : Sc_rollup_repr.t; (** The smart-contract rollup. *) cemented_commitment : Sc_rollup_commitment_repr.Hash.t; (** The hash of the last cemented commitment that the proof refers to. *) output_proof : string; (** A message along with a proof that it is included in the outbox at a given outbox level and message index.*) } -> Kind.sc_rollup_execute_outbox_message manager_operation | Sc_rollup_recover_bond : { sc_rollup : Sc_rollup_repr.t; } -> Kind.sc_rollup_recover_bond manager_operation | Sc_rollup_dal_slot_subscribe : { rollup : Sc_rollup_repr.t; slot_index : Dal_slot_repr.Index.t; } -> Kind.sc_rollup_dal_slot_subscribe manager_operation | Zk_rollup_origination : { public_parameters : Plonk.public_parameters; circuits_info : bool Zk_rollup_account_repr.SMap.t; (** Circuit names, alongside a boolean flag indicating if they can be used for private ops. *) init_state : Zk_rollup_state_repr.t; nb_ops : int; } -> Kind.zk_rollup_origination manager_operation | Zk_rollup_publish : { zk_rollup : Zk_rollup_repr.t; ops : (Zk_rollup_operation_repr.t * Zk_rollup_ticket_repr.t option) list; (* See {!Zk_rollup_apply} *) } -> Kind.zk_rollup_publish manager_operation (** Counters are used as anti-replay protection mechanism in manager operations: each manager account stores a counter and each manager operation declares a value for the counter. When a manager operation is applied, the value of the counter of its manager is checked and incremented. *) and counter = Z.t type packed_manager_operation = | Manager : 'kind manager_operation -> packed_manager_operation type packed_contents = Contents : 'kind contents -> packed_contents type packed_contents_list = | Contents_list : 'kind contents_list -> packed_contents_list val of_list : packed_contents list -> packed_contents_list tzresult val to_list : packed_contents_list -> packed_contents list type packed_protocol_data = | Operation_data : 'kind protocol_data -> packed_protocol_data type packed_operation = { shell : Operation.shell_header; protocol_data : packed_protocol_data; } val pack : 'kind operation -> packed_operation val manager_kind : 'kind manager_operation -> 'kind Kind.manager val encoding : packed_operation Data_encoding.t val contents_encoding : packed_contents Data_encoding.t val contents_list_encoding : packed_contents_list Data_encoding.t val protocol_data_encoding : packed_protocol_data Data_encoding.t val unsigned_operation_encoding : (Operation.shell_header * packed_contents_list) Data_encoding.t val raw : _ operation -> raw val hash_raw : raw -> Operation_hash.t val hash : _ operation -> Operation_hash.t val hash_packed : packed_operation -> Operation_hash.t (** Each operation belongs to a validation pass that is an integer abstracting its priority in a block. Except Failing_noop. *) (** The validation pass of consensus operations. *) val consensus_pass : int (** The validation pass of voting operations. *) val voting_pass : int (** The validation pass of anonymous operations. *) val anonymous_pass : int (** The validation pass of anonymous operations. *) val manager_pass : int (** [acceptable_pass op] returns either the validation_pass of [op] when defines and None when [op] is [Failing_noop]. *) val acceptable_pass : packed_operation -> int option (** [compare_by_passes] orders two operations in the reverse order of their acceptable passes. *) val compare_by_passes : packed_operation -> packed_operation -> int (** [compare (oph1,op1) (oph2,op2)] defines a total ordering relation on operations. The following requirements must be satisfied: [oph1] is the [Operation.hash op1], [oph2] is [Operation.hash op2], and that [op1] and [op2] are valid in the same context. [compare (oph1,op1) (oph2,op2) = 0] happens only if [Operation_hash.compare oph1 oph2 = 0], meaning when [op1] and [op2] are structurally identical. Two valid operations of different [validation_pass] are compared according to {!acceptable_passes}: the one with the smaller pass being the greater. Two valid operations of the same [validation_pass] are compared according to a [weight], computed thanks to their static information. The global order is as follows: {!Endorsement} and {!Preendorsement} > {!Dal_slot_availability} > {!Proposals} > {!Ballot} > {!Double_preendorsement_evidence} > {!Double_endorsement_evidence} > {!Double_baking_evidence} > {!Vdf_revelation} > {!Seed_nonce_revelation} > {!Activate_account} > {!Drain_delegate} > {!Manager_operation}. {!Endorsement} and {!Preendorsement} are compared by the pair of their [level] and [round] such as the farther to the current state [level] and [round] is greater; e.g. the greater pair in lexicographic order being the better. When equal and both operations being of the same kind, we compare their [slot]: the The smaller being the better, assuming that the more slots an endorser has, the smaller is its smallest [slot]. When the pair is equal and comparing an {!Endorsement] to a {!Preendorsement}, the {!Endorsement} is better. Two {!Dal_slot_availability} ops are compared in the lexicographic order of the pair of their number of endorsed slots as available and their endorsers. Two voting operations are compared in the lexicographic order of the pair of their [period] and [source]. A {!Proposals} is better than a {!Ballot}. Two denunciations of the same kind are compared such as the farther to the current state the better. For {!Double_baking_evidence} in the case of equality, they are compared by the hashes of their first denounced block_header. Two {!Vdf_revelation} ops are compared by their [solution]. Two {!Seed_nonce_relevation} ops are compared by their [level]. Two {!Activate_account} ops are compared by their [id]. Two {!Drain_delegate} ops are compared by their [delegate]. Two {!Manager_operation}s are compared in the lexicographic order of the pair of their [fee]/[gas_limit] ratios and [source]. *) val compare : Operation_hash.t * packed_operation -> Operation_hash.t * packed_operation -> int type error += Missing_signature (* `Permanent *) type error += Invalid_signature (* `Permanent *) val check_signature : Signature.Public_key.t -> Chain_id.t -> _ operation -> unit tzresult type ('a, 'b) eq = Eq : ('a, 'a) eq val equal : 'a operation -> 'b operation -> ('a, 'b) eq option module Encoding : sig type 'b case = | Case : { tag : int; name : string; encoding : 'a Data_encoding.t; select : packed_contents -> 'b contents option; proj : 'b contents -> 'a; inj : 'a -> 'b contents; } -> 'b case val preendorsement_case : Kind.preendorsement case val endorsement_case : Kind.endorsement case val dal_slot_availability_case : Kind.dal_slot_availability case val seed_nonce_revelation_case : Kind.seed_nonce_revelation case val vdf_revelation_case : Kind.vdf_revelation case val double_preendorsement_evidence_case : Kind.double_preendorsement_evidence case val double_endorsement_evidence_case : Kind.double_endorsement_evidence case val double_baking_evidence_case : Kind.double_baking_evidence case val activate_account_case : Kind.activate_account case val proposals_case : Kind.proposals case val ballot_case : Kind.ballot case val drain_delegate_case : Kind.drain_delegate case val failing_noop_case : Kind.failing_noop case val reveal_case : Kind.reveal Kind.manager case val transaction_case : Kind.transaction Kind.manager case val origination_case : Kind.origination Kind.manager case val delegation_case : Kind.delegation Kind.manager case val update_consensus_key_case : Kind.update_consensus_key Kind.manager case val register_global_constant_case : Kind.register_global_constant Kind.manager case val set_deposits_limit_case : Kind.set_deposits_limit Kind.manager case val increase_paid_storage_case : Kind.increase_paid_storage Kind.manager case val tx_rollup_origination_case : Kind.tx_rollup_origination Kind.manager case val tx_rollup_submit_batch_case : Kind.tx_rollup_submit_batch Kind.manager case val tx_rollup_commit_case : Kind.tx_rollup_commit Kind.manager case val tx_rollup_return_bond_case : Kind.tx_rollup_return_bond Kind.manager case val tx_rollup_finalize_commitment_case : Kind.tx_rollup_finalize_commitment Kind.manager case val tx_rollup_remove_commitment_case : Kind.tx_rollup_remove_commitment Kind.manager case val tx_rollup_rejection_case : Kind.tx_rollup_rejection Kind.manager case val tx_rollup_dispatch_tickets_case : Kind.tx_rollup_dispatch_tickets Kind.manager case val transfer_ticket_case : Kind.transfer_ticket Kind.manager case val dal_publish_slot_header_case : Kind.dal_publish_slot_header Kind.manager case val sc_rollup_originate_case : Kind.sc_rollup_originate Kind.manager case val sc_rollup_add_messages_case : Kind.sc_rollup_add_messages Kind.manager case val sc_rollup_cement_case : Kind.sc_rollup_cement Kind.manager case val sc_rollup_publish_case : Kind.sc_rollup_publish Kind.manager case val sc_rollup_refute_case : Kind.sc_rollup_refute Kind.manager case val sc_rollup_timeout_case : Kind.sc_rollup_timeout Kind.manager case val sc_rollup_execute_outbox_message_case : Kind.sc_rollup_execute_outbox_message Kind.manager case val sc_rollup_recover_bond_case : Kind.sc_rollup_recover_bond Kind.manager case val sc_rollup_dal_slot_subscribe_case : Kind.sc_rollup_dal_slot_subscribe Kind.manager case val zk_rollup_origination_case : Kind.zk_rollup_origination Kind.manager case val zk_rollup_publish_case : Kind.zk_rollup_publish Kind.manager case module Manager_operations : sig type 'b case = | MCase : { tag : int; name : string; encoding : 'a Data_encoding.t; select : packed_manager_operation -> 'kind manager_operation option; proj : 'kind manager_operation -> 'a; inj : 'a -> 'kind manager_operation; } -> 'kind case val reveal_case : Kind.reveal case val transaction_case : Kind.transaction case val origination_case : Kind.origination case val delegation_case : Kind.delegation case val update_consensus_key_tag : int val update_consensus_key_case : Kind.update_consensus_key case val register_global_constant_case : Kind.register_global_constant case val set_deposits_limit_case : Kind.set_deposits_limit case val increase_paid_storage_case : Kind.increase_paid_storage case val tx_rollup_origination_case : Kind.tx_rollup_origination case val tx_rollup_submit_batch_case : Kind.tx_rollup_submit_batch case val tx_rollup_commit_case : Kind.tx_rollup_commit case val tx_rollup_return_bond_case : Kind.tx_rollup_return_bond case val tx_rollup_finalize_commitment_case : Kind.tx_rollup_finalize_commitment case val tx_rollup_remove_commitment_case : Kind.tx_rollup_remove_commitment case val tx_rollup_rejection_case : Kind.tx_rollup_rejection case val tx_rollup_dispatch_tickets_case : Kind.tx_rollup_dispatch_tickets case val transfer_ticket_case : Kind.transfer_ticket case val dal_publish_slot_header_case : Kind.dal_publish_slot_header case val sc_rollup_originate_case : Kind.sc_rollup_originate case val sc_rollup_add_messages_case : Kind.sc_rollup_add_messages case val sc_rollup_cement_case : Kind.sc_rollup_cement case val sc_rollup_publish_case : Kind.sc_rollup_publish case val sc_rollup_refute_case : Kind.sc_rollup_refute case val sc_rollup_timeout_case : Kind.sc_rollup_timeout case val sc_rollup_execute_outbox_message_case : Kind.sc_rollup_execute_outbox_message case val sc_rollup_recover_bond_case : Kind.sc_rollup_recover_bond case val sc_rollup_dal_slot_subscribe_case : Kind.sc_rollup_dal_slot_subscribe case val zk_rollup_origination_case : Kind.zk_rollup_origination case val zk_rollup_publish_case : Kind.zk_rollup_publish case end end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
approx_inv.c
#include "acb_mat.h" int acb_mat_approx_inv(acb_mat_t X, const acb_mat_t A, slong prec) { if (X == A) { int r; acb_mat_t T; acb_mat_init(T, acb_mat_nrows(A), acb_mat_ncols(A)); r = acb_mat_approx_inv(T, A, prec); acb_mat_swap(T, X); acb_mat_clear(T); return r; } acb_mat_one(X); return acb_mat_approx_solve(X, A, X, prec); }
/* 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/>. */
sourceCode.mli
open Utility class source_code : object val lines : (int, int) Hashtbl.t val text : Buffer.t method private extract_line : int -> string method extract_line_range : int -> int -> string method private extract_substring : Lexing.position -> Lexing.position -> string method find_line : Lexing.position -> string * int method lookup : Lexing.position * Lexing.position -> Lexing.position * string * string method parse_into : (bytes -> int -> int) -> bytes -> int -> int end module Lexpos : sig type t = Lexing.position [@@deriving show] end (** A module for keeping track of source code positions. *) module Position : sig (** An unresolved source code position. Also see [Position.Resolved]. *) type t [@@deriving show] val make : start:Lexpos.t -> finish:Lexpos.t -> code:source_code option -> t (** A dummy position used for when the source code location is unknown. *) val dummy : t (** Get start position of the source code position. *) val start : t -> Lexpos.t (** Get the end position of the source code position. *) val finish : t -> Lexpos.t (** Get the source code object. *) val code : t -> source_code option val traverse_map : t -> o:'o -> f_start:('o -> Lexpos.t -> 'a * Lexpos.t) -> f_finish:('a -> Lexpos.t -> 'b * Lexpos.t ) -> f_code:('b -> source_code option -> 'c * source_code option) -> 'c * t val traverse : t -> o:'o -> f_start:('o -> Lexpos.t -> 'a) -> f_finish:('a -> Lexpos.t -> 'b) -> f_code:('b -> source_code option -> 'c) -> 'c val map_code : t -> f:(source_code option -> source_code option) -> t exception ASTSyntaxError of t * string (** Resolve the source code position to the actual contents of that position. *) module Resolved : sig type unresolved = t type t [@@deriving show] val dummy : t val start : t -> Lexpos.t val source_line : t -> string val source_expression : t -> string (** Lookup the relevant source code line. *) val resolve : unresolved -> t end (** Resolve the source code position and return the source expression. *) val resolve_expression : t -> string (** Resolve the source code position and return the start position and the source expression. *) val resolve_start_expr : t -> Lexpos.t * string end module WithPos : sig type 'a t = private { node : 'a ; pos : Position.t } [@@deriving show] (** Construct a new with_pos given a node and an optional source code position. Use the [dummy] position if none is specified. *) val make : ?pos:Position.t -> 'a -> 'a t (** Construct a new with_pos with a dummy source position *) val dummy : 'a -> 'a t (** Fetch the corresponding node. *) val node : 'a t -> 'a (** Fetch the corresponding source code position. *) val pos : 'a t -> Position.t val map : 'a t -> f:('a -> 'b) -> 'b t val map2 : 'a t -> f_pos:(Position.t -> Position.t) -> f_node:('a -> 'b) -> 'b t val with_node : 'a t -> 'b -> 'b t (** Discard positions from elements in a list **) val nodes_of_list : 'a t list -> 'a list val traverse : 'a t -> o:'o -> f_pos:('o -> Position.t -> 'b) -> f_node:('b -> 'a -> 'c) -> 'c val traverse_map : 'a t -> o:'o -> f_pos:('o -> Position.t -> 'b * Position.t) -> f_node:('b -> 'a -> 'c * 'd) -> 'c * 'd t end
client_proto_args.ml
type error += Bad_amount_param of (string * string) let msg_parameter _param = Tezos_clic.parameter (fun _ s -> return s) let amount_parameter param = Tezos_clic.parameter (fun _ s -> match Int32.of_string_opt s with | Some amount -> return amount | None -> fail (Bad_amount_param (param, s))) let amount_param ~name ~desc next = Tezos_clic.param ~name ~desc (amount_parameter name) next let msg_param ~name ~desc next = Tezos_clic.param ~name ~desc (msg_parameter name) next let () = register_error_kind `Permanent ~id:"demo.client.badAmountParam" ~title:"Bad Amount Param" ~description:"Invalid amount parameter." ~pp:(fun ppf (arg_name, literal) -> Format.fprintf ppf "Invalid literal %s for parameter %s. Should be 32-bytes integer." arg_name literal) Data_encoding.(obj2 (req "parameter" string) (req "literal" string)) (function | Bad_amount_param (parameter, literal) -> Some (parameter, literal) | _ -> None) (fun (parameter, literal) -> Bad_amount_param (parameter, literal))
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
testpreempt.ml
(* TEST * hassysthreads (* On Windows, we use Sleep(0) for triggering preemption of threads. However, this does not seem very reliable, so that this test fails on some Windows configurations. See GPR #1533. *) include systhreads ** not-windows *** bytecode *** native *) let rec generate_list n = let rec aux acc = function | 0 -> acc | n -> aux (float n :: acc) (n-1) in aux [] n let rec long_computation time0 = let long_list = generate_list 100000 in let res = List.length (List.rev_map sin long_list) in if Sys.time () -. time0 > 2. then Printf.printf "Long computation result: %d\n%!" res else long_computation time0 let interaction () = Thread.delay 0.1; Printf.printf "Interaction 1\n"; Thread.delay 0.1; Printf.printf "Interaction 2\n" let () = ignore (Thread.create interaction ()); long_computation (Sys.time ())
(* TEST * hassysthreads (* On Windows, we use Sleep(0) for triggering preemption of threads. However, this does not seem very reliable, so that this test fails on some Windows configurations. See GPR #1533. *)
warnings.mli
open Format type t = | Comment_start (* 1 *) | Comment_not_end (* 2 *) | Deprecated of string (* 3 *) | Fragile_match of string (* 4 *) | Partial_application (* 5 *) | Labels_omitted (* 6 *) | Method_override of string list (* 7 *) | Partial_match of string (* 8 *) | Non_closed_record_pattern of string (* 9 *) | Statement_type (* 10 *) | Unused_match (* 11 *) | Unused_pat (* 12 *) | Instance_variable_override of string list (* 13 *) | Illegal_backslash (* 14 *) | Implicit_public_methods of string list (* 15 *) | Unerasable_optional_argument (* 16 *) | Undeclared_virtual_method of string (* 17 *) | Not_principal of string (* 18 *) | Without_principality of string (* 19 *) | Unused_argument (* 20 *) | Nonreturning_statement (* 21 *) | Camlp4 of string (* 22 *) | Useless_record_with (* 23 *) | Bad_module_name of string (* 24 *) | All_clauses_guarded (* 25 *) | Unused_var of string (* 26 *) | Unused_var_strict of string (* 27 *) | Wildcard_arg_to_constant_constr (* 28 *) | Eol_in_string (* 29 *) | Duplicate_definitions of string * string * string * string (* 30 *) | Multiple_definition of string * string * string (* 31 *) | Unused_value_declaration of string (* 32 *) | Unused_open of string (* 33 *) | Unused_type_declaration of string (* 34 *) | Unused_for_index of string (* 35 *) | Unused_ancestor of string (* 36 *) | Unused_constructor of string * bool * bool (* 37 *) | Unused_exception of string * bool (* 38 *) | Unused_rec_flag (* 39 *) | Name_out_of_scope of string * string list * bool (* 40 *) | Ambiguous_name of string list * string list * bool (* 41 *) | Disambiguated_name of string (* 42 *) | Nonoptional_label of string (* 43 *) | Open_shadow_identifier of string * string (* 44 *) | Open_shadow_label_constructor of string * string (* 45 *) | Bad_env_variable of string * string ;; val parse_options : bool -> string -> unit;; val is_active : t -> bool;; val is_error : t -> bool;; val defaults_w : string;; val defaults_warn_error : string;; val print : formatter -> t -> int;; (* returns the number of newlines in the printed string *) exception Errors of int;; val check_fatal : unit -> unit;; val help_warnings: unit -> unit
(***********************************************************************) (* *) (* OCaml *) (* *) (* Pierre Weis && Damien Doligez, INRIA Rocquencourt *) (* *) (* Copyright 1998 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. *) (* *) (***********************************************************************)
test_constant_propagation_muxes.ml
open! Import open Signal open Test_constant_propagation.Trace let sexp_of_signal = Test_constants.sexp_of_const_signal let%expect_test "[mux]" = let sel = of_int ~width:2 2 in let width = 3 in for length = 0 to 5 do print_s [%message "" (length : int) ~_: (try_with (fun () -> mux sel (List.init length ~f:(fun i -> of_int ~width i))) : t Or_error.t)] done; [%expect {| ((length 0) (Error "[mux] got empty list")) ((length 1) (Error ("[mux] got fewer than 2 inputs" (inputs_provided 1)))) ((length 2) (Ok ( const (width 3) (value 0b001)))) ((length 3) (Ok ( const (width 3) (value 0b010)))) ((length 4) (Ok ( const (width 3) (value 0b010)))) ((length 5) (Error ( "[mux] got too many inputs" (inputs_provided 5) (maximum_expected 4)))) |}] ;; let%expect_test "mux" = let data4 = List.map ~f:(of_int ~width:5) [ 0; 10; 20; 30 ] in let mux = fn2 mux in print_s [%message "mux" ~_: (List.init 4 ~f:(fun i -> mux (of_int ~width:2 i) data4) : (signal, signal list) fn2 list)]; [%expect {| (mux ( ((2'b00 (5'b00000 5'b01010 5'b10100 5'b11110)) = 5'b00000) ((2'b01 (5'b00000 5'b01010 5'b10100 5'b11110)) = 5'b01010) ((2'b10 (5'b00000 5'b01010 5'b10100 5'b11110)) = 5'b10100) ((2'b11 (5'b00000 5'b01010 5'b10100 5'b11110)) = 5'b11110))) |}] ;; let%expect_test "mux2" = let mux2 = fn3 mux2 in print_s [%message "check all combinations with mux2" ~_: (op1 1 ~f:(fun s -> op1 1 ~f:(fun t -> op1 1 ~f:(fun f -> mux2 s t f))) : (signal, signal, signal) fn3 list list list)]; [%expect {| ("check all combinations with mux2" ( ((((1'b0 1'b0 1'b0) = 1'b0) ((1'b0 1'b0 1'b1) = 1'b1)) (((1'b0 1'b1 1'b0) = 1'b0) ((1'b0 1'b1 1'b1) = 1'b1))) ((((1'b1 1'b0 1'b0) = 1'b0) ((1'b1 1'b0 1'b1) = 1'b0)) (((1'b1 1'b1 1'b0) = 1'b1) ((1'b1 1'b1 1'b1) = 1'b1))))) |}] ;;
describeTransitGatewayVpcAttachments.mli
open Types type input = DescribeTransitGatewayVpcAttachmentsRequest.t type output = DescribeTransitGatewayVpcAttachmentsResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
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. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
raw_level_repr.mli
(** The shell's notion of a level: an integer indicating the number of blocks since genesis: genesis is 0, all other blocks have increasing levels from there. *) type t type raw_level = t module Set : Set.S with type elt = t module Map : Map.S with type key = t (** @raise Invalid_argument when the level to encode is not positive *) val encoding : raw_level Data_encoding.t val rpc_arg : raw_level RPC_arg.arg val pp : Format.formatter -> raw_level -> unit include Compare.S with type t := raw_level val to_int32 : raw_level -> int32 val to_int32_non_negative : raw_level -> Bounded.Non_negative_int32.t (** @raise Invalid_argument when the level to encode is negative *) val of_int32_exn : int32 -> raw_level (** Can trigger Unexpected_level error when the level to encode is negative *) val of_int32 : int32 -> raw_level tzresult val of_int32_non_negative : Bounded.Non_negative_int32.t -> raw_level val diff : raw_level -> raw_level -> int32 val root : raw_level val succ : raw_level -> raw_level val pred : raw_level -> raw_level option (** [add l i] i must be positive *) val add : raw_level -> int -> raw_level (** [sub l i] i must be positive *) val sub : raw_level -> int -> raw_level option module Index : Storage_description.INDEX with type t = raw_level
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
m4Printer.ml
open M4Types let string_of_token = function | SHELL s -> Printf.sprintf "SHELL %S" s | IDENT s -> Printf.sprintf "IDENT %S" s | ONE_ARG s -> Printf.sprintf "ONE_ARG %S" s | FIRST_ARG s -> Printf.sprintf "FIRST_ARG %S" s | NEXT_ARG s -> Printf.sprintf "NEXT_ARG %S" s | LAST_ARG s -> Printf.sprintf "LAST_ARG %S" s | EOF -> "EOF" let string_of_location loc = Printf.sprintf "%s:%d:%d" loc.file loc.line loc.char let string_of_arg arg = arg.arg let string_of_macro statement = match statement.kind with | Macro ( ident, args ) -> Printf.sprintf "Macro: %s ( %s )" ident ( String.concat ", " ( List.map string_of_arg args )) | Shell shell -> Printf.sprintf "Shell: %s" shell let string_of_block list = String.concat "\n" ( List.map string_of_macro list )
(**************************************************************************) (* *) (* Copyright (c) 2023 OCamlPro SAS *) (* *) (* All rights reserved. *) (* This file is distributed under the terms of the GNU General Public *) (* License version 3.0, as described in the LICENSE.md file in the root *) (* directory of this source tree. *) (* *) (* *) (**************************************************************************)
mul.c
#include "acb_poly.h" void _acb_poly_mul(acb_ptr C, acb_srcptr A, slong lenA, acb_srcptr B, slong lenB, slong prec) { _acb_poly_mullow(C, A, lenA, B, lenB, lenA + lenB - 1, prec); } void acb_poly_mul(acb_poly_t res, const acb_poly_t poly1, const acb_poly_t poly2, slong prec) { slong len_out; if ((poly1->length == 0) || (poly2->length == 0)) { acb_poly_zero(res); return; } len_out = poly1->length + poly2->length - 1; if (res == poly1 || res == poly2) { acb_poly_t temp; acb_poly_init2(temp, len_out); _acb_poly_mul(temp->coeffs, poly1->coeffs, poly1->length, poly2->coeffs, poly2->length, prec); acb_poly_swap(res, temp); acb_poly_clear(temp); } else { acb_poly_fit_length(res, len_out); _acb_poly_mul(res->coeffs, poly1->coeffs, poly1->length, poly2->coeffs, poly2->length, prec); } _acb_poly_set_length(res, len_out); _acb_poly_normalise(res); }
/* 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/>. */
profile.ml
open! Core open! Async_kernel module Start_location = struct type t = | Line_preceding_profile | End_of_profile_first_line [@@deriving compare, enumerate, sexp_of] let default = End_of_profile_first_line end let start_location = ref Start_location.default let concat = String.concat let approximate_line_length_limit = ref 1_000 let should_profile = ref false let hide_if_less_than = ref (Time_ns.Span.of_int_us 100) let hide_top_level_if_less_than = ref (Time_ns.Span.of_int_ms 10) let never_show_rendering_took = ref false let output_profile = ref print_string let sexp_of_time_ns = ref [%sexp_of: Time_ns.Alternate_sexp.t] let tag_frames_with = ref None module Time_ns = struct include Time_ns let sexp_of_t t = try !sexp_of_time_ns t with | exn -> let backtrace = Backtrace.Exn.most_recent () in [%message "[Profile.sexp_of_time_ns] raised" (exn : exn) (backtrace : Backtrace.t)] ;; end module Clock = struct type t = | Wall | Virtual of { mutable now : Time_ns.t } [@@deriving sexp_of] let create ~now = Virtual { now } let now = function | Wall -> Time_ns.now () | Virtual { now } -> now ;; let advance t ~by = match t with | Wall -> raise_s [%message "[Nested_profile.Clock.advance]"] | Virtual s -> s.now <- Time_ns.add s.now by ;; end let clock = ref Clock.Wall let now () = Clock.now !clock (* We don't support profiling for brief periods when profiler code calls user code, because doing so would be hard and could cause infinite regress, e.g. if that code in turns asks to be profiled. So, we have an internal bool ref, [profiling_is_allowed], that we use to disable profiling when calling user code. *) let profiling_is_allowed = ref true let with_profiling_disallowed f = Ref.set_temporarily profiling_is_allowed false ~f module Elide_in_test = struct type 'a t = 'a let sexp_of_t sexp_of_a a = if am_running_inline_test then [%message "<elided-in-test>"] else sexp_of_a a ;; end module Message : sig type t [@@deriving sexp_of] val create : Sexp.t Lazy.t -> t val am_forcing : unit -> bool val force : t -> Sexp.t end = struct type t = Sexp.t Lazy.t [@@deriving sexp_of] let create t = t let am_forcing_ref = ref false let am_forcing () = !am_forcing_ref let force t = Ref.set_temporarily am_forcing_ref true ~f:(fun () -> force t) end let am_forcing_message = Message.am_forcing module Record = struct type t = { start : Time_ns.t ; stop : Time_ns.t ; message : Message.t ; children : t list ; had_parallel_children : bool ; pending_children : int } let took t = Time_ns.diff t.stop t.start let rec sexp_of_t ({ start = _; stop = _; message; children; had_parallel_children; pending_children } as t) = [%sexp (took t |> Time_ns.Span.to_string_hum : string) , (if had_parallel_children then Some `parallel else None : ([ `parallel ] option[@sexp.option])) , (if pending_children <> 0 then Some (`pending_children pending_children) else None : ([ `pending_children of int ] option[@sexp.option])) , (Message.force message : Sexp.t) , (children : (t list[@sexp.omit_nil]))] ;; let sexp_to_string_on_one_line = let buffer = Buffer.create 0 in let emit string = Buffer.add_string buffer string in let over_the_limit = ref false in let can_emit additional = (not !over_the_limit) && (if Buffer.length buffer + additional > !approximate_line_length_limit then ( over_the_limit := true; emit "..."); not !over_the_limit) in let rec emit_sexp (sexp : Sexp.t) = match sexp with | Atom _ as sexp -> let string = Sexp.to_string sexp in if can_emit (String.length string) then emit string | List sexps -> if can_emit 2 then ( emit "("; (match sexps with | [] -> () | sexp :: sexps -> emit_sexp sexp; List.iter sexps ~f:(fun sexp -> if not !over_the_limit then ( emit " "; emit_sexp sexp))); emit ")") in fun sexp -> Buffer.clear buffer; over_the_limit := false; emit_sexp sexp; Buffer.contents buffer ;; let time_span_as_micros_with_two_digits_of_precision span = let span = span |> Time_ns.Span.to_int_us in let digits = String.length (span |> Int.to_string) in let precision = 2 in let microseconds = if digits <= precision then span else ( let scale = Int.pow 10 (digits - precision) in scale * ((span |> Int.to_float) /. (scale |> Int.to_float) |> Float.iround_nearest_exn)) in concat [ microseconds |> Int.to_string_hum; "us" ] ;; let pad_left string ~total_width = let n = String.length string in if n > total_width then string else concat [ String.make (total_width - n) ' '; string ] ;; let took_width t = String.length (took t |> time_span_as_micros_with_two_digits_of_precision) ;; let rec max_took_width t = Int.max (took_width t) (List.fold t.children ~init:0 ~f:(fun ac child -> Int.max ac (max_took_width child))) ;; let rec insert_gap_frames t = if List.is_empty t.children then t else ( let maybe_add_gap ts ~start ~stop = let gap_took = Time_ns.diff stop start in (* We hide the gap frame if it took less than [!hide_if_less_than], like all other frames. We also hide the gap frame if it took less than 1us, since a gap frame that says 0us would be noise. *) if Time_ns.Span.( < ) gap_took !hide_if_less_than || Time_ns.Span.( < ) gap_took Time_ns.Span.microsecond then ts else { start ; stop ; message = Message.create (lazy [%sexp "gap"]) ; children = [] ; had_parallel_children = false ; pending_children = 0 } :: ts in let last_stop, rev_children = List.fold t.children ~init:(t.start, []) ~f:(fun (last_stop, rev_children) child -> ( child.stop , insert_gap_frames child :: maybe_add_gap rev_children ~start:last_stop ~stop:child.start )) in let rev_children = maybe_add_gap rev_children ~start:last_stop ~stop:t.stop in { t with children = List.rev rev_children }) ;; let to_string_hum t = let rendering_started = now () in let start_location = !start_location in let t = insert_gap_frames t in let took_total_width = max_took_width t in let paren strings = concat [ "("; concat strings; ")" ] in let shift_right = match start_location with | End_of_profile_first_line -> 0 | Line_preceding_profile -> 1 in let start = [%sexp (t.start : Time_ns.t)] |> Sexp.to_string in let rec loop ({ message; children; had_parallel_children; pending_children; _ } as t) ~depth ~parent_took = let took = took t in let percentage = match parent_took with | None -> "" | Some parent_took -> let percentage_int = (if Time_ns.Span.equal parent_took Time_ns.Span.zero then "_" else Time_ns.Span.( // ) took parent_took *. 100. |> Float.iround_nearest_exn |> Int.to_string) |> pad_left ~total_width:3 in concat [ percentage_int; "% " ] in let message = with_profiling_disallowed (fun () -> try Message.force message with | exn -> let backtrace = Backtrace.Exn.most_recent () in [%message "[Profile.profile] message raised" (exn : exn) (backtrace : Backtrace.t)]) in concat [ String.make (shift_right + (3 * depth)) ' ' ; paren [ percentage ; took |> time_span_as_micros_with_two_digits_of_precision |> pad_left ~total_width:took_total_width ; " " ; (if had_parallel_children then "[parallel] " else "") ; (match pending_children with | 0 -> "" | 1 -> "[1 pending child] " | n -> sprintf "[%d pending children] " n) ; message |> sexp_to_string_on_one_line ; (match start_location with | Line_preceding_profile -> "" | End_of_profile_first_line -> if depth = 0 then concat [ " "; start ] else "") ; (if List.is_empty children then "" else concat [ " " ; paren [ "\n" ; concat ~sep:"\n" (List.map children ~f:(loop ~depth:(depth + 1) ~parent_took:(Some took))) ] ]) ] ] in let profile = loop t ~depth:0 ~parent_took:None in let rendering_finished = now () in let rendering_took = Time_ns.diff rendering_finished rendering_started in let rendering_took = if !never_show_rendering_took || Time_ns.Span.( < ) rendering_took !hide_top_level_if_less_than then None else Some (paren [ "rendering_took " ; rendering_took |> time_span_as_micros_with_two_digits_of_precision ]) in match start_location, rendering_took with | End_of_profile_first_line, None -> profile | End_of_profile_first_line, Some r -> paren [ r; "\n "; profile ] | Line_preceding_profile, None -> paren [ start; "\n"; profile ] | Line_preceding_profile, Some r -> paren [ start; "\n "; r; "\n"; profile ] ;; end module Frame = struct type t = { message : Message.t ; start : Time_ns.Alternate_sexp.t Elide_in_test.t ; children : Record.t Queue.t ; parent : t option ; mutable pending_children : int ; mutable max_pending_children : int } [@@deriving sexp_of] let create ~message ~parent = { message = Message.create message ; start = now () ; children = Queue.create () ; parent ; pending_children = 0 ; max_pending_children = 0 } ;; let record { message; start; children; parent = _; pending_children; max_pending_children } ~stop : Record.t = { start ; stop ; message ; children = children |> Queue.to_list ; had_parallel_children = max_pending_children > 1 ; pending_children } ;; end module Profile_context = struct let record_profile frame ~stop = let record = Frame.record frame ~stop in match frame.parent with | None -> if Time_ns.Span.( >= ) (Record.took record) !hide_top_level_if_less_than then ( let profile = concat [ record |> Record.to_string_hum; "\n" ] in with_profiling_disallowed (fun () -> try !output_profile profile with | exn -> let backtrace = Backtrace.Exn.most_recent () in eprint_s [%message "[Profile.output_profile] raised" (exn : exn) (backtrace : Backtrace.t)])) | Some parent -> Queue.enqueue parent.children record ;; let backtrace frame = let rec loop (frame : Frame.t) acc = let acc = frame.message :: acc in match frame.parent with | None -> acc | Some parent -> loop parent acc in List.rev (loop frame []) ;; end let maybe_record_frame ?hide_if_less_than:local_hide_if_less_than (frame : Frame.t) ~stop = let took = Time_ns.diff stop frame.start in let hide_if_less_than = Option.value local_hide_if_less_than ~default:!hide_if_less_than in if Time_ns.Span.( >= ) took hide_if_less_than then Profile_context.record_profile frame ~stop ;; let on_async_out_of_order = ref (fun sexp -> !output_profile (Sexp.to_string_hum (force sexp) ^ "\n")) ;; let record_profile ?hide_if_less_than (frame : Frame.t) = if frame.pending_children <> 0 then ( (* Pull this out of the record eagerly so we don't have problems with the lazy expression being evaluated later, where there might be an intervening write to [frame.pending_children]. *) let pending_children = frame.pending_children in !on_async_out_of_order (lazy [%message "Nested [profile Async] exited out-of-order." ~message:(Message.force frame.message : Sexp.t) (pending_children : int)])); maybe_record_frame ?hide_if_less_than frame ~stop:(now ()) ;; module Sync_or_async = struct type _ t = | Sync : _ t | Async : _ Deferred.t t [@@deriving sexp_of] end let profile_context_key = Univ_map.Key.create ~name:"Nested_profile.Profile.Frame" [%sexp_of: Frame.t] ;; let current_profile_context () = Async_kernel_scheduler.find_local profile_context_key let with_profile_context frame ~f = Async_kernel_scheduler.with_local profile_context_key frame ~f ;; let profile (type a) ?hide_if_less_than (sync_or_async : a Sync_or_async.t) (message : Sexp.t Lazy.t) (f : unit -> a) : a = if not (!profiling_is_allowed && !should_profile) then f () else ( let tag = with_profiling_disallowed (fun () -> try Option.bind !tag_frames_with ~f:(fun f -> f ()) with | exn -> let backtrace = Backtrace.Exn.most_recent () in Some [%message "[Profile.tag_frames_with] raised" (exn : exn) (backtrace : Backtrace.t)]) in let message = match tag with | None -> message | Some tag -> lazy (List [ force message; tag ]) in let parent = current_profile_context () in let frame = Frame.create ~message ~parent in let incr_pending_children = match parent with | None -> fun ~by:_ -> () | Some parent -> fun ~by -> parent.pending_children <- parent.pending_children + by; parent.max_pending_children <- Int.max parent.max_pending_children parent.pending_children in incr_pending_children ~by:1; let f () = with_profile_context (Some frame) ~f in match sync_or_async with | Sync -> Exn.protect ~f ~finally:(fun () -> record_profile ?hide_if_less_than frame; incr_pending_children ~by:(-1)) | Async -> Monitor.protect ~run: `Schedule ~rest:`Log f ~finally:(fun () -> record_profile ?hide_if_less_than frame; incr_pending_children ~by:(-1); return ())) ;; let backtrace () = let frame = current_profile_context () in match !should_profile with | false -> None | true -> Some (Option.value_map frame ~f:Profile_context.backtrace ~default:[] |> List.map ~f:Message.force) ;; let disown f = with_profile_context None ~f module Private = struct module Clock = Clock let clock = clock let on_async_out_of_order = on_async_out_of_order let record_frame ~start ~stop ~message = if !profiling_is_allowed && !should_profile then maybe_record_frame { message = Message.create message ; start ; children = Queue.create () ; parent = current_profile_context () ; pending_children = 0 ; max_pending_children = 0 } ~stop ;; end
dune
; File auto-generated by gentests.ml ; Auto-generated part begin ; Test for test-000.icnf ; Incremental test (rule (target test-000.incremental) (deps (:input test-000.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=incremental --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-000.expected test-000.incremental))) ; Full mode test (rule (target test-000.full) (deps (:input test-000.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=full --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-000.expected test-000.full))) ; Test for test-001.icnf ; Incremental test (rule (target test-001.incremental) (deps (:input test-001.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=incremental --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-001.expected test-001.incremental))) ; Full mode test (rule (target test-001.full) (deps (:input test-001.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=full --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-001.expected test-001.full))) ; Test for test-002.icnf ; Incremental test (rule (target test-002.incremental) (deps (:input test-002.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=incremental --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-002.expected test-002.incremental))) ; Full mode test (rule (target test-002.full) (deps (:input test-002.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=full --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff test-002.expected test-002.full))) ; Auto-generated part end
save.h
#ifndef __XEN_PUBLIC_HVM_SAVE_X86_H__ #define __XEN_PUBLIC_HVM_SAVE_X86_H__ /* * Save/restore header: general info about the save file. */ #define HVM_FILE_MAGIC 0x54381286 #define HVM_FILE_VERSION 0x00000001 struct hvm_save_header { uint32_t magic; /* Must be HVM_FILE_MAGIC */ uint32_t version; /* File format version */ uint64_t changeset; /* Version of Xen that saved this file */ uint32_t cpuid; /* CPUID[0x01][%eax] on the saving machine */ uint32_t gtsc_khz; /* Guest's TSC frequency in kHz */ }; DECLARE_HVM_SAVE_TYPE(HEADER, 1, struct hvm_save_header); /* * Processor * * Compat: * - Pre-3.4 didn't have msr_tsc_aux * - Pre-4.7 didn't have fpu_initialised */ struct hvm_hw_cpu { uint8_t fpu_regs[512]; uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rbp; uint64_t rsi; uint64_t rdi; uint64_t rsp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rip; uint64_t rflags; uint64_t cr0; uint64_t cr2; uint64_t cr3; uint64_t cr4; uint64_t dr0; uint64_t dr1; uint64_t dr2; uint64_t dr3; uint64_t dr6; uint64_t dr7; uint32_t cs_sel; uint32_t ds_sel; uint32_t es_sel; uint32_t fs_sel; uint32_t gs_sel; uint32_t ss_sel; uint32_t tr_sel; uint32_t ldtr_sel; uint32_t cs_limit; uint32_t ds_limit; uint32_t es_limit; uint32_t fs_limit; uint32_t gs_limit; uint32_t ss_limit; uint32_t tr_limit; uint32_t ldtr_limit; uint32_t idtr_limit; uint32_t gdtr_limit; uint64_t cs_base; uint64_t ds_base; uint64_t es_base; uint64_t fs_base; uint64_t gs_base; uint64_t ss_base; uint64_t tr_base; uint64_t ldtr_base; uint64_t idtr_base; uint64_t gdtr_base; uint32_t cs_arbytes; uint32_t ds_arbytes; uint32_t es_arbytes; uint32_t fs_arbytes; uint32_t gs_arbytes; uint32_t ss_arbytes; uint32_t tr_arbytes; uint32_t ldtr_arbytes; uint64_t sysenter_cs; uint64_t sysenter_esp; uint64_t sysenter_eip; /* msr for em64t */ uint64_t shadow_gs; /* msr content saved/restored. */ uint64_t msr_flags; /* Obsolete, ignored. */ uint64_t msr_lstar; uint64_t msr_star; uint64_t msr_cstar; uint64_t msr_syscall_mask; uint64_t msr_efer; uint64_t msr_tsc_aux; /* guest's idea of what rdtsc() would return */ uint64_t tsc; /* pending event, if any */ union { uint32_t pending_event; struct { uint8_t pending_vector:8; uint8_t pending_type:3; uint8_t pending_error_valid:1; uint32_t pending_reserved:19; uint8_t pending_valid:1; }; }; /* error code for pending event */ uint32_t error_code; #define _XEN_X86_FPU_INITIALISED 0 #define XEN_X86_FPU_INITIALISED (1U<<_XEN_X86_FPU_INITIALISED) uint32_t flags; uint32_t pad0; }; struct hvm_hw_cpu_compat { uint8_t fpu_regs[512]; uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rbp; uint64_t rsi; uint64_t rdi; uint64_t rsp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rip; uint64_t rflags; uint64_t cr0; uint64_t cr2; uint64_t cr3; uint64_t cr4; uint64_t dr0; uint64_t dr1; uint64_t dr2; uint64_t dr3; uint64_t dr6; uint64_t dr7; uint32_t cs_sel; uint32_t ds_sel; uint32_t es_sel; uint32_t fs_sel; uint32_t gs_sel; uint32_t ss_sel; uint32_t tr_sel; uint32_t ldtr_sel; uint32_t cs_limit; uint32_t ds_limit; uint32_t es_limit; uint32_t fs_limit; uint32_t gs_limit; uint32_t ss_limit; uint32_t tr_limit; uint32_t ldtr_limit; uint32_t idtr_limit; uint32_t gdtr_limit; uint64_t cs_base; uint64_t ds_base; uint64_t es_base; uint64_t fs_base; uint64_t gs_base; uint64_t ss_base; uint64_t tr_base; uint64_t ldtr_base; uint64_t idtr_base; uint64_t gdtr_base; uint32_t cs_arbytes; uint32_t ds_arbytes; uint32_t es_arbytes; uint32_t fs_arbytes; uint32_t gs_arbytes; uint32_t ss_arbytes; uint32_t tr_arbytes; uint32_t ldtr_arbytes; uint64_t sysenter_cs; uint64_t sysenter_esp; uint64_t sysenter_eip; /* msr for em64t */ uint64_t shadow_gs; /* msr content saved/restored. */ uint64_t msr_flags; /* Obsolete, ignored. */ uint64_t msr_lstar; uint64_t msr_star; uint64_t msr_cstar; uint64_t msr_syscall_mask; uint64_t msr_efer; /*uint64_t msr_tsc_aux; COMPAT */ /* guest's idea of what rdtsc() would return */ uint64_t tsc; /* pending event, if any */ union { uint32_t pending_event; struct { uint8_t pending_vector:8; uint8_t pending_type:3; uint8_t pending_error_valid:1; uint32_t pending_reserved:19; uint8_t pending_valid:1; }; }; /* error code for pending event */ uint32_t error_code; }; static inline int _hvm_hw_fix_cpu(void *h, uint32_t size) { union hvm_hw_cpu_union { struct hvm_hw_cpu nat; struct hvm_hw_cpu_compat cmp; } *ucpu = (union hvm_hw_cpu_union *)h; if ( size == sizeof(struct hvm_hw_cpu_compat) ) { /* * If we copy from the end backwards, we should * be able to do the modification in-place. */ ucpu->nat.error_code = ucpu->cmp.error_code; ucpu->nat.pending_event = ucpu->cmp.pending_event; ucpu->nat.tsc = ucpu->cmp.tsc; ucpu->nat.msr_tsc_aux = 0; } /* Mimic the old behaviour by unconditionally setting fpu_initialised. */ ucpu->nat.flags = XEN_X86_FPU_INITIALISED; return 0; } DECLARE_HVM_SAVE_TYPE_COMPAT(CPU, 2, struct hvm_hw_cpu, \ struct hvm_hw_cpu_compat, _hvm_hw_fix_cpu); /* * PIC */ struct hvm_hw_vpic { /* IR line bitmasks. */ uint8_t irr; uint8_t imr; uint8_t isr; /* Line IRx maps to IRQ irq_base+x */ uint8_t irq_base; /* * Where are we in ICW2-4 initialisation (0 means no init in progress)? * Bits 0-1 (=x): Next write at A=1 sets ICW(x+1). * Bit 2: ICW1.IC4 (1 == ICW4 included in init sequence) * Bit 3: ICW1.SNGL (0 == ICW3 included in init sequence) */ uint8_t init_state:4; /* IR line with highest priority. */ uint8_t priority_add:4; /* Reads from A=0 obtain ISR or IRR? */ uint8_t readsel_isr:1; /* Reads perform a polling read? */ uint8_t poll:1; /* Automatically clear IRQs from the ISR during INTA? */ uint8_t auto_eoi:1; /* Automatically rotate IRQ priorities during AEOI? */ uint8_t rotate_on_auto_eoi:1; /* Exclude slave inputs when considering in-service IRQs? */ uint8_t special_fully_nested_mode:1; /* Special mask mode excludes masked IRs from AEOI and priority checks. */ uint8_t special_mask_mode:1; /* Is this a master PIC or slave PIC? (NB. This is not programmable.) */ uint8_t is_master:1; /* Edge/trigger selection. */ uint8_t elcr; /* Virtual INT output. */ uint8_t int_output; }; DECLARE_HVM_SAVE_TYPE(PIC, 3, struct hvm_hw_vpic); /* * IO-APIC */ union vioapic_redir_entry { uint64_t bits; struct { uint8_t vector; uint8_t delivery_mode:3; uint8_t dest_mode:1; uint8_t delivery_status:1; uint8_t polarity:1; uint8_t remote_irr:1; uint8_t trig_mode:1; uint8_t mask:1; uint8_t reserve:7; uint8_t reserved[4]; uint8_t dest_id; } fields; }; #define VIOAPIC_NUM_PINS 48 /* 16 ISA IRQs, 32 non-legacy PCI IRQS. */ #define XEN_HVM_VIOAPIC(name, cnt) \ struct name { \ uint64_t base_address; \ uint32_t ioregsel; \ uint32_t id; \ union vioapic_redir_entry redirtbl[cnt]; \ } XEN_HVM_VIOAPIC(hvm_hw_vioapic, VIOAPIC_NUM_PINS); #ifndef __XEN__ #undef XEN_HVM_VIOAPIC #else #undef VIOAPIC_NUM_PINS #endif DECLARE_HVM_SAVE_TYPE(IOAPIC, 4, struct hvm_hw_vioapic); /* * LAPIC */ struct hvm_hw_lapic { uint64_t apic_base_msr; uint32_t disabled; /* VLAPIC_xx_DISABLED */ uint32_t timer_divisor; uint64_t tdt_msr; }; DECLARE_HVM_SAVE_TYPE(LAPIC, 5, struct hvm_hw_lapic); struct hvm_hw_lapic_regs { uint8_t data[1024]; }; DECLARE_HVM_SAVE_TYPE(LAPIC_REGS, 6, struct hvm_hw_lapic_regs); /* * IRQs */ struct hvm_hw_pci_irqs { /* * Virtual interrupt wires for a single PCI bus. * Indexed by: device*4 + INTx#. */ union { unsigned long i[16 / sizeof (unsigned long)]; /* DECLARE_BITMAP(i, 32*4); */ uint64_t pad[2]; }; }; DECLARE_HVM_SAVE_TYPE(PCI_IRQ, 7, struct hvm_hw_pci_irqs); struct hvm_hw_isa_irqs { /* * Virtual interrupt wires for ISA devices. * Indexed by ISA IRQ (assumes no ISA-device IRQ sharing). */ union { unsigned long i[1]; /* DECLARE_BITMAP(i, 16); */ uint64_t pad[1]; }; }; DECLARE_HVM_SAVE_TYPE(ISA_IRQ, 8, struct hvm_hw_isa_irqs); struct hvm_hw_pci_link { /* * PCI-ISA interrupt router. * Each PCI <device:INTx#> is 'wire-ORed' into one of four links using * the traditional 'barber's pole' mapping ((device + INTx#) & 3). * The router provides a programmable mapping from each link to a GSI. */ uint8_t route[4]; uint8_t pad0[4]; }; DECLARE_HVM_SAVE_TYPE(PCI_LINK, 9, struct hvm_hw_pci_link); /* * PIT */ struct hvm_hw_pit { struct hvm_hw_pit_channel { uint32_t count; /* can be 65536 */ uint16_t latched_count; uint8_t count_latched; uint8_t status_latched; uint8_t status; uint8_t read_state; uint8_t write_state; uint8_t write_latch; uint8_t rw_mode; uint8_t mode; uint8_t bcd; /* not supported */ uint8_t gate; /* timer start */ } channels[3]; /* 3 x 16 bytes */ uint32_t speaker_data_on; uint32_t pad0; }; DECLARE_HVM_SAVE_TYPE(PIT, 10, struct hvm_hw_pit); /* * RTC */ #define RTC_CMOS_SIZE 14 struct hvm_hw_rtc { /* CMOS bytes */ uint8_t cmos_data[RTC_CMOS_SIZE]; /* Index register for 2-part operations */ uint8_t cmos_index; uint8_t pad0; }; DECLARE_HVM_SAVE_TYPE(RTC, 11, struct hvm_hw_rtc); /* * HPET */ #define HPET_TIMER_NUM 3 /* 3 timers supported now */ struct hvm_hw_hpet { /* Memory-mapped, software visible registers */ uint64_t capability; /* capabilities */ uint64_t res0; /* reserved */ uint64_t config; /* configuration */ uint64_t res1; /* reserved */ uint64_t isr; /* interrupt status reg */ uint64_t res2[25]; /* reserved */ uint64_t mc64; /* main counter */ uint64_t res3; /* reserved */ struct { /* timers */ uint64_t config; /* configuration/cap */ uint64_t cmp; /* comparator */ uint64_t fsb; /* FSB route, not supported now */ uint64_t res4; /* reserved */ } timers[HPET_TIMER_NUM]; uint64_t res5[4*(24-HPET_TIMER_NUM)]; /* reserved, up to 0x3ff */ /* Hidden register state */ uint64_t period[HPET_TIMER_NUM]; /* Last value written to comparator */ }; DECLARE_HVM_SAVE_TYPE(HPET, 12, struct hvm_hw_hpet); /* * PM timer */ struct hvm_hw_pmtimer { uint32_t tmr_val; /* PM_TMR_BLK.TMR_VAL: 32bit free-running counter */ uint16_t pm1a_sts; /* PM1a_EVT_BLK.PM1a_STS: status register */ uint16_t pm1a_en; /* PM1a_EVT_BLK.PM1a_EN: enable register */ }; DECLARE_HVM_SAVE_TYPE(PMTIMER, 13, struct hvm_hw_pmtimer); /* * MTRR MSRs */ struct hvm_hw_mtrr { #define MTRR_VCNT 8 #define NUM_FIXED_MSR 11 uint64_t msr_pat_cr; /* mtrr physbase & physmask msr pair*/ uint64_t msr_mtrr_var[MTRR_VCNT*2]; uint64_t msr_mtrr_fixed[NUM_FIXED_MSR]; uint64_t msr_mtrr_cap; uint64_t msr_mtrr_def_type; }; DECLARE_HVM_SAVE_TYPE(MTRR, 14, struct hvm_hw_mtrr); /* * The save area of XSAVE/XRSTOR. */ struct hvm_hw_cpu_xsave { uint64_t xfeature_mask; /* Ignored */ uint64_t xcr0; /* Updated by XSETBV */ uint64_t xcr0_accum; /* Updated by XSETBV */ struct { struct { char x[512]; } fpu_sse; struct hvm_hw_cpu_xsave_hdr { uint64_t xstate_bv; /* Updated by XRSTOR */ uint64_t xcomp_bv; /* Updated by XRSTOR{C,S} */ uint64_t reserved[6]; } xsave_hdr; /* The 64-byte header */ } save_area; }; #define CPU_XSAVE_CODE 16 /* * Viridian hypervisor context. */ struct hvm_viridian_domain_context { uint64_t hypercall_gpa; uint64_t guest_os_id; uint64_t time_ref_count; uint64_t reference_tsc; }; DECLARE_HVM_SAVE_TYPE(VIRIDIAN_DOMAIN, 15, struct hvm_viridian_domain_context); struct hvm_viridian_vcpu_context { uint64_t vp_assist_msr; uint8_t apic_assist_pending; uint8_t _pad[7]; uint64_t simp_msr; uint64_t sint_msr[16]; uint64_t stimer_config_msr[4]; uint64_t stimer_count_msr[4]; }; DECLARE_HVM_SAVE_TYPE(VIRIDIAN_VCPU, 17, struct hvm_viridian_vcpu_context); struct hvm_vmce_vcpu { uint64_t caps; uint64_t mci_ctl2_bank0; uint64_t mci_ctl2_bank1; uint64_t mcg_ext_ctl; }; DECLARE_HVM_SAVE_TYPE(VMCE_VCPU, 18, struct hvm_vmce_vcpu); struct hvm_tsc_adjust { uint64_t tsc_adjust; }; DECLARE_HVM_SAVE_TYPE(TSC_ADJUST, 19, struct hvm_tsc_adjust); struct hvm_msr { uint32_t count; struct hvm_one_msr { uint32_t index; uint32_t _rsvd; uint64_t val; } msr[XEN_FLEX_ARRAY_DIM]; }; #define CPU_MSR_CODE 20 /* * Largest type-code in use */ #define HVM_SAVE_CODE_MAX 20 #endif /* __XEN_PUBLIC_HVM_SAVE_X86_H__ */ /* * Local variables: * mode: C * c-file-style: "BSD" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */
/* * Structure definitions for HVM state that is held by Xen and must * be saved along with the domain's memory and device-model state. * * Copyright (c) 2007 XenSource Ltd. * * 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. */
issue1116.ml
let some_int = 5 let x = "some_int"
array.mli
type 'a t = 'a array (** An alias for the type of arrays. *) (** Array operations. *) external length : 'a array -> int = "%array_length" (** Return the length (number of elements) of the given array. *) external get : 'a array -> int -> 'a = "%array_safe_get" (** [Array.get a n] returns the element number [n] of array [a]. The first element has number 0. The last element has number [Array.length a - 1]. You can also write [a.(n)] instead of [Array.get a n]. Raise [Invalid_argument] if [n] is outside the range 0 to [(Array.length a - 1)]. *) external set : 'a array -> int -> 'a -> unit = "%array_safe_set" (** [Array.set a n x] modifies array [a] in place, replacing element number [n] with [x]. You can also write [a.(n) <- x] instead of [Array.set a n x]. Raise [Invalid_argument] if [n] is outside the range 0 to [Array.length a - 1]. *) external make : int -> 'a -> 'a array = "caml_make_vect" (** [Array.make n x] returns a fresh array of length [n], initialized with [x]. All the elements of this new array are initially physically equal to [x] (in the sense of the [==] predicate). Consequently, if [x] is mutable, it is shared among all elements of the array, and modifying [x] through one of the array entries will modify all other entries at the same time. Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. If the value of [x] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2].*) external create : int -> 'a -> 'a array = "caml_make_vect" [@@ocaml.deprecated "Use Array.make instead."] (** @deprecated [Array.create] is an alias for {!Array.make}. *) external create_float: int -> float array = "caml_make_float_vect" (** [Array.create_float n] returns a fresh float array of length [n], with uninitialized data. @since 4.03 *) val make_float: int -> float array [@@ocaml.deprecated "Use Array.create_float instead."] (** @deprecated [Array.make_float] is an alias for {!Array.create_float}. *) val init : int -> (int -> 'a) -> 'a array (** [Array.init n f] returns a fresh array of length [n], with element number [i] initialized to the result of [f i]. In other terms, [Array.init n f] tabulates the results of [f] applied to the integers [0] to [n-1]. Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. If the return type of [f] is [float], then the maximum size is only [Sys.max_array_length / 2].*) val make_matrix : int -> int -> 'a -> 'a array array (** [Array.make_matrix dimx dimy e] returns a two-dimensional array (an array of arrays) with first dimension [dimx] and second dimension [dimy]. All the elements of this new matrix are initially physically equal to [e]. The element ([x,y]) of a matrix [m] is accessed with the notation [m.(x).(y)]. Raise [Invalid_argument] if [dimx] or [dimy] is negative or greater than {!Sys.max_array_length}. If the value of [e] is a floating-point number, then the maximum size is only [Sys.max_array_length / 2]. *) val create_matrix : int -> int -> 'a -> 'a array array [@@ocaml.deprecated "Use Array.make_matrix instead."] (** @deprecated [Array.create_matrix] is an alias for {!Array.make_matrix}. *) val append : 'a array -> 'a array -> 'a array (** [Array.append v1 v2] returns a fresh array containing the concatenation of the arrays [v1] and [v2]. Raise [Invalid_argument] if [Array.length v1 + Array.length v2 > Sys.max_array_length]. *) val concat : 'a array list -> 'a array (** Same as {!Array.append}, but concatenates a list of arrays. *) val sub : 'a array -> int -> int -> 'a array (** [Array.sub a start len] returns a fresh array of length [len], containing the elements number [start] to [start + len - 1] of array [a]. Raise [Invalid_argument] if [start] and [len] do not designate a valid subarray of [a]; that is, if [start < 0], or [len < 0], or [start + len > Array.length a]. *) val copy : 'a array -> 'a array (** [Array.copy a] returns a copy of [a], that is, a fresh array containing the same elements as [a]. *) val fill : 'a array -> int -> int -> 'a -> unit (** [Array.fill a ofs len x] modifies the array [a] in place, storing [x] in elements number [ofs] to [ofs + len - 1]. Raise [Invalid_argument] if [ofs] and [len] do not designate a valid subarray of [a]. *) val blit : 'a array -> int -> 'a array -> int -> int -> unit (** [Array.blit v1 o1 v2 o2 len] copies [len] elements from array [v1], starting at element number [o1], to array [v2], starting at element number [o2]. It works correctly even if [v1] and [v2] are the same array, and the source and destination chunks overlap. Raise [Invalid_argument] if [o1] and [len] do not designate a valid subarray of [v1], or if [o2] and [len] do not designate a valid subarray of [v2]. *) val to_list : 'a array -> 'a list (** [Array.to_list a] returns the list of all the elements of [a]. *) val of_list : 'a list -> 'a array (** [Array.of_list l] returns a fresh array containing the elements of [l]. Raise [Invalid_argument] if the length of [l] is greater than [Sys.max_array_length].*) (** {1 Iterators} *) val iter : ('a -> unit) -> 'a array -> unit (** [Array.iter f a] applies function [f] in turn to all the elements of [a]. It is equivalent to [f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *) val iteri : (int -> 'a -> unit) -> 'a array -> unit (** Same as {!Array.iter}, but the function is applied with the index of the element as first argument, and the element itself as second argument. *) val map : ('a -> 'b) -> 'a array -> 'b array (** [Array.map f a] applies function [f] to all the elements of [a], and builds an array with the results returned by [f]: [[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *) val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array (** Same as {!Array.map}, but the function is applied to the index of the element as first argument, and the element itself as second argument. *) val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a (** [Array.fold_left f x a] computes [f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)], where [n] is the length of the array [a]. *) val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a (** [Array.fold_right f a x] computes [f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))], where [n] is the length of the array [a]. *) (** {1 Iterators on two arrays} *) val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit (** [Array.iter2 f a b] applies function [f] to all the elements of [a] and [b]. Raise [Invalid_argument] if the arrays are not the same size. @since 4.03.0 *) val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array (** [Array.map2 f a b] applies function [f] to all the elements of [a] and [b], and builds an array with the results returned by [f]: [[| f a.(0) b.(0); ...; f a.(Array.length a - 1) b.(Array.length b - 1)|]]. Raise [Invalid_argument] if the arrays are not the same size. @since 4.03.0 *) (** {1 Array scanning} *) val for_all : ('a -> bool) -> 'a array -> bool (** [Array.for_all p [|a1; ...; an|]] checks if all elements of the array satisfy the predicate [p]. That is, it returns [(p a1) && (p a2) && ... && (p an)]. @since 4.03.0 *) val exists : ('a -> bool) -> 'a array -> bool (** [Array.exists p [|a1; ...; an|]] checks if at least one element of the array satisfies the predicate [p]. That is, it returns [(p a1) || (p a2) || ... || (p an)]. @since 4.03.0 *) val mem : 'a -> 'a array -> bool (** [mem a l] is true if and only if [a] is structurally equal to an element of [l] (i.e. there is an [x] in [l] such that [compare a x = 0]). @since 4.03.0 *) val memq : 'a -> 'a array -> bool (** Same as {!Array.mem}, but uses physical equality instead of structural equality to compare elements. @since 4.03.0 *) (** {1 Sorting} *) val sort : ('a -> 'a -> int) -> 'a array -> unit (** Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, {!Stdlib.compare} is a suitable comparison function. After calling [Array.sort], the array is sorted in place in increasing order. [Array.sort] is guaranteed to run in constant heap space and (at most) logarithmic stack space. The current implementation uses Heap Sort. It runs in constant stack space. Specification of the comparison function: Let [a] be the array and [cmp] the comparison function. The following must be true for all [x], [y], [z] in [a] : - [cmp x y] > 0 if and only if [cmp y x] < 0 - if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0 When [Array.sort] returns, [a] contains the same elements as before, reordered in such a way that for all i and j valid indices of [a] : - [cmp a.(i) a.(j)] >= 0 if and only if i >= j *) val stable_sort : ('a -> 'a -> int) -> 'a array -> unit (** Same as {!Array.sort}, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. The current implementation uses Merge Sort. It uses a temporary array of length [n/2], where [n] is the length of the array. It is usually faster than the current implementation of {!Array.sort}. *) val fast_sort : ('a -> 'a -> int) -> 'a array -> unit (** Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster on typical input. *) (** {1 Iterators} *) val to_seq : 'a array -> 'a Seq.t (** Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the iterator. @since 4.07 *) val to_seqi : 'a array -> (int * 'a) Seq.t (** Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the iterator. @since 4.07 *) val of_seq : 'a Seq.t -> 'a array (** Create an array from the generator @since 4.07 *) (**/**) (** {1 Undocumented functions} *) (* The following is for system use only. Do not call directly. *) external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set" module Floatarray : sig external create : int -> floatarray = "caml_floatarray_create" external length : floatarray -> int = "%floatarray_length" external get : floatarray -> int -> float = "%floatarray_safe_get" external set : floatarray -> int -> float -> unit = "%floatarray_safe_set" external unsafe_get : floatarray -> int -> float = "%floatarray_unsafe_get" external unsafe_set : floatarray -> int -> float -> unit = "%floatarray_unsafe_set" end
(**************************************************************************) (* *) (* OCaml *) (* *) (* 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 GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
bar.c
#include <stdio.h> #include "foo.cxx" void foo () { int n = cppfoo(); printf("n = %d\n", n); }
int_tests.mli
(*_ This signature is deliberately empty. *)
(*_ This signature is deliberately empty. *)
diffing.ml
[@@@warning "-16"] (* This module implements a modified version of Wagner-Fischer See <https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm> for preliminary reading. The main extensions is that: - State is computed based on the optimal patch so far. - The lists can be extended at each state computation. We add the constraint that extensions can only be in one side (either the left or right list). This is enforced by the external API. *) (** Shared types *) type change_kind = | Deletion | Insertion | Modification | Preservation let style = function | Preservation -> Misc.Color.[ FG Green ] | Deletion -> Misc.Color.[ FG Red; Bold] | Insertion -> Misc.Color.[ FG Red; Bold] | Modification -> Misc.Color.[ FG Magenta; Bold] let prefix ppf (pos, p) = let sty = style p in Format.pp_open_stag ppf (Misc.Color.Style sty); Format.fprintf ppf "%i. " pos; Format.pp_close_stag ppf () let (let*) = Option.bind let (let+) x f = Option.map f x let (let*!) x f = Option.iter f x module type Defs = sig type left type right type eq type diff type state end type ('left,'right,'eq,'diff) change = | Delete of 'left | Insert of 'right | Keep of 'left * 'right *' eq | Change of 'left * 'right * 'diff let classify = function | Delete _ -> Deletion | Insert _ -> Insertion | Change _ -> Modification | Keep _ -> Preservation module Define(D:Defs) = struct open D type nonrec change = (left,right,eq,diff) change type patch = change list module type S = sig val diff: state -> left array -> right array -> patch end type full_state = { line: left array; column: right array; state: state } (* The matrix supporting our dynamic programming implementation. Each cell contains: - The diff and its weight - The state computed so far - The lists, potentially extended locally. The matrix can also be reshaped. *) module Matrix : sig type shape = { l : int ; c : int } type t val make : shape -> t val reshape : shape -> t -> t (** accessor functions *) val diff : t -> int -> int -> change option val state : t -> int -> int -> full_state option val weight : t -> int -> int -> int val line : t -> int -> int -> left option val column : t -> int -> int -> right option val set : t -> int -> int -> diff:change option -> weight:int -> state:full_state -> unit (** the shape when starting filling the matrix *) val shape : t -> shape (** [shape m i j] is the shape as seen from the state at position (i,j) after some possible extensions *) val shape_at : t -> int -> int -> shape option (** the maximal shape on the whole matrix *) val real_shape : t -> shape (** debugging printer *) val[@warning "-32"] pp : Format.formatter -> t -> unit end = struct type shape = { l : int ; c : int } type t = { states: full_state option array array; weight: int array array; diff: change option array array; columns: int; lines: int; } let opt_get a n = if n < Array.length a then Some (Array.unsafe_get a n) else None let line m i j = let* st = m.states.(i).(j) in opt_get st.line i let column m i j = let* st = m.states.(i).(j) in opt_get st.column j let diff m i j = m.diff.(i).(j) let weight m i j = m.weight.(i).(j) let state m i j = m.states.(i).(j) let shape m = { l = m.lines ; c = m.columns } let set m i j ~diff ~weight ~state = m.weight.(i).(j) <- weight; m.states.(i).(j) <- Some state; m.diff.(i).(j) <- diff; () let shape_at tbl i j = let+ st = tbl.states.(i).(j) in let l = Array.length st.line in let c = Array.length st.column in { l ; c } let real_shape tbl = let lines = ref tbl.lines in let columns = ref tbl.columns in for i = 0 to tbl.lines do for j = 0 to tbl.columns do let*! {l; c} = shape_at tbl i j in if l > !lines then lines := l; if c > !columns then columns := c done; done; { l = !lines ; c = !columns } let make { l = lines ; c = columns } = { states = Array.make_matrix (lines + 1) (columns + 1) None; weight = Array.make_matrix (lines + 1) (columns + 1) max_int; diff = Array.make_matrix (lines + 1) (columns + 1) None; lines; columns; } let reshape { l = lines ; c = columns } m = let copy default a = Array.init (1+lines) (fun i -> Array.init (1+columns) (fun j -> if i <= m.lines && j <= m.columns then a.(i).(j) else default) ) in { states = copy None m.states; weight = copy max_int m.weight; diff = copy None m.diff; lines; columns } let pp ppf m = let { l ; c } = shape m in Format.eprintf "Shape : %i, %i@." l c; for i = 0 to l do for j = 0 to c do let d = diff m i j in match d with | None -> Format.fprintf ppf " " | Some diff -> let sdiff = match diff with | Insert _ -> "\u{2190}" | Delete _ -> "\u{2191}" | Keep _ -> "\u{2196}" | Change _ -> "\u{21F1}" in let w = weight m i j in Format.fprintf ppf "%s%i " sdiff w done; Format.pp_print_newline ppf () done end (* Building the patch. We first select the best final cell. A potential final cell is a cell where the local shape (i.e., the size of the strings) correspond to its position in the matrix. In other words: it's at the end of both its strings. We select the final cell with the smallest weight. We then build the patch by walking backward from the final cell to the origin. *) let select_final_state m0 = let maybe_final i j = match Matrix.shape_at m0 i j with | Some shape_here -> shape_here.l = i && shape_here.c = j | None -> false in let best_state (i0,j0,weigth0) (i,j) = let weight = Matrix.weight m0 i j in if weight < weigth0 then (i,j,weight) else (i0,j0,weigth0) in let res = ref (0,0,max_int) in let shape = Matrix.shape m0 in for i = 0 to shape.l do for j = 0 to shape.c do if maybe_final i j then res := best_state !res (i,j) done done; let i_final, j_final, _ = !res in assert (i_final <> 0 || j_final <> 0); (i_final, j_final) let construct_patch m0 = let rec aux acc (i, j) = if i = 0 && j = 0 then acc else match Matrix.diff m0 i j with | None -> assert false | Some d -> let next = match d with | Keep _ | Change _ -> (i-1, j-1) | Delete _ -> (i-1, j) | Insert _ -> (i, j-1) in aux (d::acc) next in aux [] (select_final_state m0) (* Computation of new cells *) let select_best_proposition l = let compare_proposition curr prop = match curr, prop with | None, o | o, None -> o | Some (curr_m, curr_res), Some (m, res) -> Some (if curr_m <= m then curr_m, curr_res else m,res) in List.fold_left compare_proposition None l module type Full_core = sig type update_result type update_state val weight: change -> int val test: state -> left -> right -> (eq, diff) result val update: change -> update_state -> update_result end module Generic (X: Full_core with type update_result := full_state and type update_state := full_state) = struct open X (* Boundary cell update *) let compute_column0 tbl i = let*! st = Matrix.state tbl (i-1) 0 in let*! line = Matrix.line tbl (i-1) 0 in let diff = Delete line in Matrix.set tbl i 0 ~weight:(weight diff + Matrix.weight tbl (i-1) 0) ~state:(update diff st) ~diff:(Some diff) let compute_line0 tbl j = let*! st = Matrix.state tbl 0 (j-1) in let*! column = Matrix.column tbl 0 (j-1) in let diff = Insert column in Matrix.set tbl 0 j ~weight:(weight diff + Matrix.weight tbl 0 (j-1)) ~state:(update diff st) ~diff:(Some diff) let compute_inner_cell tbl i j = let compute_proposition i j diff = let* diff = diff in let+ localstate = Matrix.state tbl i j in weight diff + Matrix.weight tbl i j, (diff, localstate) in let del = let diff = let+ x = Matrix.line tbl (i-1) j in Delete x in compute_proposition (i-1) j diff in let insert = let diff = let+ x = Matrix.column tbl i (j-1) in Insert x in compute_proposition i (j-1) diff in let diag = let diff = let* state = Matrix.state tbl (i-1) (j-1) in let* line = Matrix.line tbl (i-1) (j-1) in let* column = Matrix.column tbl (i-1) (j-1) in match test state.state line column with | Ok ok -> Some (Keep (line, column, ok)) | Error err -> Some (Change (line, column, err)) in compute_proposition (i-1) (j-1) diff in let*! newweight, (diff, localstate) = select_best_proposition [diag;del;insert] in let state = update diff localstate in Matrix.set tbl i j ~weight:newweight ~state ~diff:(Some diff) let compute_cell m i j = match i, j with | _ when Matrix.diff m i j <> None -> () | 0,0 -> () | 0,j -> compute_line0 m j | i,0 -> compute_column0 m i; | _ -> compute_inner_cell m i j (* Filling the matrix We fill the whole matrix, as in vanilla Wagner-Fischer. At this point, the lists in some states might have been extended. If any list have been extended, we need to reshape the matrix and repeat the process *) let compute_matrix state0 = let m0 = Matrix.make { l = 0 ; c = 0 } in Matrix.set m0 0 0 ~weight:0 ~state:state0 ~diff:None; let rec loop m = let shape = Matrix.shape m in let new_shape = Matrix.real_shape m in if new_shape.l > shape.l || new_shape.c > shape.c then let m = Matrix.reshape new_shape m in for i = 0 to new_shape.l do for j = 0 to new_shape.c do compute_cell m i j done done; loop m else m in loop m0 end module type Parameters = Full_core with type update_state := state module Simple(X:Parameters with type update_result := state) = struct module Internal = Generic(struct let test = X.test let weight = X.weight let update d fs = { fs with state = X.update d fs.state } end) let diff state line column = let fullstate = { line; column; state } in Internal.compute_matrix fullstate |> construct_patch end let may_append x = function | [||] -> x | y -> Array.append x y module Left_variadic (X:Parameters with type update_result := state * left array) = struct open X module Internal = Generic(struct let test = X.test let weight = X.weight let update d fs = let state, a = update d fs.state in { fs with state ; line = may_append fs.line a } end) let diff state line column = let fullstate = { line; column; state } in Internal.compute_matrix fullstate |> construct_patch end module Right_variadic (X:Parameters with type update_result := state * right array) = struct open X module Internal = Generic(struct let test = X.test let weight = X.weight let update d fs = let state, a = update d fs.state in { fs with state ; column = may_append fs.column a } end) let diff state line column = let fullstate = { line; column; state } in Internal.compute_matrix fullstate |> construct_patch end end
(**************************************************************************) (* *) (* OCaml *) (* *) (* Gabriel Radanne, projet Cambium, Inria Paris *) (* *) (* Copyright 2020 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* 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. *) (* *) (**************************************************************************)
is_zero.c
#include <stdlib.h> #include "flint.h" #include "fmpz_poly.h" #include "fmpz_poly_mat.h" int fmpz_poly_mat_is_zero(const fmpz_poly_mat_t A) { slong i, j; if (A->r == 0 || A->c == 0) return 1; for (i = 0; i < A->r; i++) for (j = 0; j < A->c; j++) if (!fmpz_poly_is_zero(fmpz_poly_mat_entry(A, i, j))) return 0; return 1; }
/* Copyright (C) 2011 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/>. */
dune
(library (name vlib) (public_name vlib_wrapped) (wrapped false) (virtual_modules vlib))
test_store.ml
let () = Printexc.record_backtrace true let ( >>?= ) = Lwt_result.( >>= ) let ( >|?= ) = Lwt_result.( >|= ) open Test_common open Lwt.Infix open Git let random_cstruct len = Mirage_crypto_rng.generate len let long_random_cstruct () = random_cstruct 1024 let long_random_string () = Cstruct.to_string (long_random_cstruct ()) module type S = sig include Git.S val v : Fpath.t -> (t, error) result Lwt.t end module Make (Store : S) = struct module Common = Make (Store) open Common module Search = Search.Make (Store) let reset t = Store.reset t >|= function | Ok () -> () | Error e -> Alcotest.failf "reset failed: %a" Store.pp_error e let check_err = function | Ok x -> Lwt.return x | Error e -> Alcotest.failf "error: %a" Store.pp_error e let run test = Lwt_main.run (test ()) let ( !! ) = Lazy.force let v0 = lazy (Store.Value.blob (Store.Value.Blob.of_cstruct (long_random_cstruct ()))) let kv0 = lazy (Store.Value.digest !!v0) let v1 = lazy (Store.Value.blob (Store.Value.Blob.of_string "hoho")) let kv1 = lazy (Store.Value.digest !!v1) let v2 = lazy (Store.Value.blob (Store.Value.Blob.of_string "")) let kv2 = lazy (Store.Value.digest !!v2) (* Create a node containing t1 -w-> v1 *) let w = "a\042bbb\047" let tree l = Store.Value.tree @@ Store.Value.Tree.of_list @@ List.map (fun (name, perm, node) -> Store.Value.Tree.entry name perm node) l let t0 = lazy (tree [w, `Normal, !!kv1]) let kt0 = lazy (Store.Value.digest !!t0) let t1 = lazy (tree ["x", `Normal, !!kv1]) let kt1 = lazy (Store.Value.digest !!t1) (* Create the tree t2 -b-> t1 -x-> v1 *) let t2 = lazy (tree ["b", `Dir, !!kt1]) let kt2 = lazy (Store.Value.digest !!t2) (* Create the tree t3 -a-> t2 -b-> t1 -x-> v1 *) let t3 = lazy (tree ["a", `Dir, !!kt2]) let kt3 = lazy (Store.Value.digest !!t3) (* Create the tree t4 -a-> t2 -b-> t1 -x-> v1 \-c-> v2 *) let t4 = lazy (tree ["c", `Exec, !!kv2; "a", `Dir, !!kt2]) let kt4 = lazy (Store.Value.digest !!t4) let t5 = lazy (tree [ ( Astring.String.map (function '\000' -> '\001' | chr -> chr) (long_random_string ()) , (* XXX(dinosaure): impossible to store an entry with \000 *) `Normal , !!kv2 ) ; "a", `Dir, !!kt2 ]) let kt5 = lazy (Store.Value.digest !!t5) let john_doe = {User.name= "John Doe"; email= "jon@doe.com"; date= 0L, None} (* c1 : t2 *) let c1 = lazy (Store.Value.commit (Store.Value.Commit.make ~author:john_doe ~committer:john_doe ~tree:!!kt2 "hello r1")) let kc1 = lazy (Store.Value.digest !!c1) (* c1 -> c2 : t4 *) let c2 = lazy (Store.Value.commit (Store.Value.Commit.make ~author:john_doe ~committer:john_doe ~parents:[!!kc1] ~tree:!!kt4 "hello r1!")) let kc2 = lazy (Store.Value.digest !!c2) let c3 = lazy (let c2 = match !!c2 with Store.Value.Commit x -> x | _ -> assert false in Store.Value.( commit (Commit.make ~author:(Commit.author c2) ~committer:(Commit.committer c2) ~parents:(Commit.parents c2) ~tree:!!kt5 (Commit.message c2)))) let kc3 = lazy (Store.Value.digest !!c3) let thomas = Git.User. { name= "Thomas Gazagnaire" ; email= "thomas.@gazagnaire.com" ; date= ( Int64.of_float @@ Unix.gettimeofday () , Some {sign= `Plus; hours= 1; minutes= 1} ) } let c4 = lazy Store.Value.( commit (Commit.make ~author:thomas ~committer:thomas ~parents:[!!kc3] ~tree:!!kt5 ~extra:["simple-key", ["simple value"]] "with extra-fields")) let kc4 = lazy (Store.Value.digest !!c4) let gpg = [ "-----BEGIN PGP SIGNATURE-----" ; "wsBcBAABCAAQBQJaV7TOCRBK7hj4Ov3rIwAAdHIIABBfj02NsDB4x2KU1uMSs8l+" ; "kTF7a7onxdgoSvWzckXmM2o+uzBtBdnHzK24Sr2uJXq+WQvuVP35io32Qc72TdmX" ; "0r8TUt6eXnqu1mlXnTNiCZZady8tL3SiWXsTwx6AFNk59bH59cQy/dF5K0RKaT+W" ; "RPCv03yBx9vEAbTVe4kj1jS+FAcYHTyd+zqKio8kjLgL1KyjIO7GRsjRW1q+VLIX" ; "ZffaDvLU6hRdHhxxsZ6tA9sLWgfHv0Z+tgpafQrAJkwZc/zRpITA4U54xxEvrKaP" ; "BwpFgFK4IlgPC7h1ZxJMJyOL6R+dXpFTtY0vK7Apat886p+nbUJho/8Pn5OuVb8=" ; "=DCpq"; "-----END PGP SIGNATURE-----" ] let c5 = lazy Store.Value.( commit (Commit.make ~author:thomas ~committer:thomas ~parents:[!!kc3] ~tree:!!kt5 ~extra:["gpgsig", gpg] "with extra-fields")) let kc5 = lazy (Store.Value.digest !!c5) (* tag1: c1 *) let tag1 = lazy Store.Value.( tag (Tag.make !!kc1 Tag.Commit ~tag:"foo" ~tagger:john_doe "Ho yeah!")) let ktag1 = lazy (Store.Value.digest !!tag1) (* tag2: c2 *) let tag2 = lazy Store.Value.( tag (Tag.make !!kc2 Tag.Commit ~tag:"bar" ~tagger:john_doe "Haha!")) let ktag2 = lazy (Store.Value.digest !!tag2) (* r1: t4 *) let r1 = Store.Reference.of_string "refs/origin/head" (* r2: c2 *) let r2 = Store.Reference.of_string "refs/upstream/head" let check_write t name k v = Store.write t v >>= check_err >>= fun (k', _) -> assert_key_equal (name ^ "-key-1") k k' ; Store.read t k >>= check_err >>= fun v' -> assert_value_equal name v v' ; Store.write t v' >>= check_err >|= fun (k'', _) -> assert_key_equal (name ^ "-key-2") k k'' let check_find t name k path e = Search.find t k path >|= fun k' -> assert_key_opt_equal (name ^ "-find") (Some e) k' let root = Fpath.v "test-git-store" let create ~root ?(index = false) () = Store.v root >>= check_err >>= fun t -> reset t >>= fun () -> Lwt_list.iter_s (fun v -> Store.write t v >|= function | Error e -> Alcotest.failf "create: %a" Store.pp_error e | Ok _ -> () ) ( if not index then [ !!v0; !!v1; !!v2; !!t0; !!t1; !!t2; !!t3; !!t4; !!c1; !!c2; !!c3; !!c4 ; !!c5 ] else [!!v1; !!v2; !!t1; !!t2; !!t4; !!c1; !!c2] ) >|= fun () -> t let is_ typ t k = Store.read t k >>= function | Error _ -> Lwt.return false | Ok v -> Lwt.return (typ = Store.Value.kind v) let check_keys t name typ expected = Store.list t >>= fun ks -> Lwt_list.filter_s (is_ typ t) ks >|= fun ks -> assert_keys_equal name expected ks let test_blobs () = let test () = create ~root () >>= fun t -> check_write t "v1" !!kv1 !!v1 >>= fun () -> check_write t "v2" !!kv2 !!v2 >>= fun () -> check_keys t "blobs" `Blob [!!kv0; !!kv1; !!kv2] in run test let test_trees () = let test () = create ~root () >>= fun t -> check_write t "t1" !!kt1 !!t1 >>= fun () -> check_write t "t2" !!kt2 !!t2 >>= fun () -> check_write t "t3" !!kt3 !!t3 >>= fun () -> check_write t "t4" !!kt4 !!t4 >>= fun () -> let p x = `Path x in check_find t "kt0:w" !!kt0 (p [w]) !!kv1 >>= fun () -> check_find t "kt1:w" !!kt1 (p ["x"]) !!kv1 >>= fun () -> check_find t "kt2:b" !!kt2 (p ["b"]) !!kt1 >>= fun () -> check_find t "kt2:b/x" !!kt2 (p ["b"; "x"]) !!kv1 >>= fun () -> check_find t "kt3:a" !!kt3 (p ["a"]) !!kt2 >>= fun () -> check_find t "kt3:a/b" !!kt3 (p ["a"; "b"]) !!kt1 >>= fun () -> check_find t "kt3:a/b/x" !!kt3 (p ["a"; "b"; "x"]) !!kv1 >>= fun () -> check_find t "kt4:c" !!kt4 (p ["c"]) !!kv2 >>= fun () -> check_keys t "trees" `Tree [!!kt0; !!kt1; !!kt2; !!kt3; !!kt4] in run test module ValueIO = Git.Value.Raw (Store.Hash) (Store.Inflate) (Store.Deflate) let head_contents = let open Store.Reference in Alcotest.testable pp_head_contents equal_head_contents let hash = Alcotest.testable Store.Hash.pp Store.Hash.equal let test_commits () = let c = let root = Store.Hash.of_hex "3aadeb4d06f2a149e06350e4dab2c7eff117addc" in let thomas = { User.name= "Thomas Gazagnaire" ; email= "thomas@gazagnaire.org" ; date= 1435873834L, Some {User.sign= `Plus; hours= 1; minutes= 0} } in let msg = "Initial commit" in Store.Value.Commit.make ~tree:root ~author:thomas ~committer:thomas msg |> Store.Value.commit in let test () = let raw = Cstruct.create 0x100 in let etmp = Cstruct.create 0x100 in match ValueIO.to_raw ~raw ~etmp c with | Error e -> Alcotest.failf "%a" ValueIO.EncoderRaw.pp_error e | Ok raw -> ( match ValueIO.of_raw_with_header (Cstruct.of_string raw) with | Error err -> Alcotest.failf "decoder: %a" Git.Error.Decoder.pp_error err | Ok c' -> assert_value_equal "commits: convert" c c' ; create ~root () >>= fun t -> check_write t "c1" !!kc1 !!c1 >>= fun () -> check_write t "c2" !!kc2 !!c2 >>= fun () -> check_write t "c4" !!kc4 !!c4 >>= fun () -> check_write t "c5" !!kc5 !!c5 >>= fun () -> let p x = `Commit (`Path x) in check_find t "c1:b" !!kc1 (p ["b"]) !!kt1 >>= fun () -> check_find t "c1:b/x" !!kc1 (p ["b"; "x"]) !!kv1 >>= fun () -> check_find t "c2:a/b/x" !!kc2 (p ["a"; "b"; "x"]) !!kv1 >>= fun () -> check_find t "c2:c" !!kc2 (p ["c"]) !!kv2 >>= fun () -> check_keys t "commits" `Commit [!!kc1; !!kc2; !!kc3; !!kc4; !!kc5] ) in run test let test_tags () = let test () = create ~root () >>= fun t -> check_write t "tag1" !!ktag1 !!tag1 >>= fun () -> check_write t "tag2" !!ktag2 !!tag2 >>= fun () -> let p l x = `Tag (l, `Commit (`Path x)) in check_find t "tag1:b" !!ktag1 (p "foo" ["b"]) !!kt1 >>= fun () -> check_find t "tag2:a" !!ktag2 (p "bar" ["a"]) !!kt2 >>= fun () -> check_find t "tag2:c" !!ktag2 (p "bar" ["c"]) !!kv2 >>= fun () -> check_keys t "tags" `Tag [!!ktag1; !!ktag2] in run test let test_refs () = let test () = create ~root () >>= fun t -> Store.Ref.write t r1 (Store.Reference.Hash !!kt4) >>= check_err >>= fun () -> Store.Ref.read t r1 >>= check_err >>= fun kt4' -> assert_head_contents_equal "r1" (Store.Reference.Hash !!kt4) kt4' ; Store.Ref.write t r2 (Store.Reference.Hash !!kc2) >>= check_err >>= fun () -> Store.Ref.read t r2 >>= check_err >>= fun kc2' -> assert_head_contents_equal "r2" (Store.Reference.Hash !!kc2) kc2' ; Store.Ref.list t >>= fun rs -> assert_refs_and_hashes_equal "refs" [r1, !!kt4; r2, !!kc2] rs ; let commit = Store.Hash.of_hex "21930ccb5f7b97e80a068371cb554b1f5ce8e55a" in Store.Ref.write t Store.Reference.head (Store.Reference.Hash commit) >>= check_err >>= fun () -> Store.Ref.read t Store.Reference.head >>= check_err >|= fun value -> Alcotest.(check head_contents) "head" (Store.Reference.Hash commit) value in run test let random_hash () = Store.Hash.of_raw_string (Cstruct.to_string (random_cstruct Store.Hash.digest_size)) let test_order_trees () = let lst = (* lexicographic order *) [ Store.Value.Tree.entry "foo.c" `Normal (random_hash ()) ; Store.Value.Tree.entry "foo" `Dir (random_hash ()) ; Store.Value.Tree.entry "foo1" `Exec (random_hash ()) ] in let equal_entry a b = a = b in (* XXX(dinosaure): lazy. *) let test () = let tree = Alcotest.testable Store.Value.Tree.pp Store.Value.Tree.equal in let entry = Alcotest.testable Store.Value.Tree.pp_entry equal_entry in let r0 = Store.Value.Tree.of_list lst in let r1 = Store.Value.Tree.to_list r0 in Alcotest.(check (list entry)) "of_list -> to_list" r1 lst ; let r2 = Store.Value.Tree.of_list [] (* empty *) in let r2 = Store.Value.Tree.add r2 (List.nth lst 0) in let r2 = Store.Value.Tree.add r2 (List.nth lst 2) in let r2 = Store.Value.Tree.add r2 (List.nth lst 1) in Alcotest.(check tree) "add" r2 r0 ; let r2 = Store.Value.Tree.of_list [] (* empty *) in let r2 = Store.Value.Tree.add r2 (List.nth lst 2) in let r2 = Store.Value.Tree.add r2 (List.nth lst 0) in let r2 = Store.Value.Tree.add r2 (List.nth lst 1) in let r2 = Store.Value.Tree.add r2 (List.nth lst 1) in Alcotest.(check tree) "add (doublon)" r2 r0 ; let empty = Store.Value.Tree.of_list [] in let r3 = List.fold_left Store.Value.Tree.add empty lst in let r4 = List.fold_left Store.Value.Tree.add empty (Store.Value.Tree.to_list r0) in Alcotest.(check tree) "add (fold)" r3 r0 ; Alcotest.(check tree) "add (fold)" r4 r0 ; Lwt.return () in run test let test_search () = let test () = create ~root () >>= fun t -> let check k path v = Search.find t k path >|= fun v' -> Alcotest.(check (option hash)) "search" (Some v) v' in check !!kt4 (`Path ["a"; "b"; "x"]) !!kv1 >>= fun () -> check !!kc2 (`Commit (`Path ["a"; "b"; "x"])) !!kv1 >>= fun () -> check !!kc2 (`Commit (`Path ["a"])) !!kt2 in run test end let suite name (module S : S) = let module T = Make (S) in ( name , [ "Operations on blobs", `Quick, T.test_blobs ; "Operations on trees", `Quick, T.test_trees ; "Operations on trees (order)", `Quick, T.test_order_trees ; "Operations on commits", `Quick, T.test_commits ; "Operations on tags", `Quick, T.test_tags ; "Operations on references", `Quick, T.test_refs ; "Search", `Quick, T.test_search ] )
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * * 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. *)
binomial_transform_convolution.c
#include <math.h> #include "acb_poly.h" void _acb_poly_binomial_transform_convolution(acb_ptr b, acb_srcptr a, slong alen, slong len, slong prec) { slong i; acb_ptr c, d; alen = FLINT_MIN(alen, len); c = _acb_vec_init(alen); d = _acb_vec_init(len); _acb_poly_borel_transform(c, a, alen, prec); for (i = 1; i < alen; i += 2) acb_neg(c + i, c + i); acb_one(d); for (i = 1; i < len; i++) acb_div_ui(d + i, d + i - 1, i, prec); _acb_poly_mullow(b, d, len, c, alen, len, prec); _acb_poly_inv_borel_transform(b, b, len, prec); _acb_vec_clear(c, alen); _acb_vec_clear(d, len); } void acb_poly_binomial_transform_convolution(acb_poly_t b, const acb_poly_t a, slong len, slong prec) { if (len == 0 || a->length == 0) { acb_poly_zero(b); return; } if (b == a) { acb_poly_t c; acb_poly_init2(c, len); _acb_poly_binomial_transform_convolution(c->coeffs, a->coeffs, a->length, len, prec); acb_poly_swap(b, c); acb_poly_clear(c); } else { acb_poly_fit_length(b, len); _acb_poly_binomial_transform_convolution(b->coeffs, a->coeffs, a->length, len, prec); } _acb_poly_set_length(b, len); _acb_poly_normalise(b); }
/* 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/>. */
Unmonad.mli
(** Effects for any monad (subject to OCaml continuations being one-shot). *) (** This is a general construction that uses effects to construct monadic expressions. Here is an alternative implementation of {!module:State} using the standard state monad: {[ module StateMonad = struct type state = int type 'a t = state -> 'a * state let ret x s = x, s let bind m f s = let x, s = m s in f x s let get s = s, s let set s _ = (), s let modify f s = (), f s end module StateUnmonad = struct type state = int module U = Algaeff.Unmonad.Make (StateMonad) let get () = U.perform StateMonad.get let set s = U.perform @@ StateMonad.set s let modify f = U.perform @@ StateMonad.modify f let run ~init f = fst @@ U.run f init end ]} Note that continuations in OCaml are one-shot, so the list monad will not work; it will quickly lead to the runtime error that the continuation is resumed twice. Also, monads do not mix well with exceptions, and thus the [bind] operation should not raise an exception unless it encounters a truly unrecoverable fatal error. Raising an exception within [bind] will skip the continuation, and thus potentially skipping exception handlers within the continuation. Those handlers might be crucial for properly releasing acquired resources. *) module type Monad = sig (** The signature of monads. *) type 'a t val ret : 'a -> 'a t val bind : 'a t -> ('a -> 'b t) -> 'b t end module type Param = Monad (** Parameters of monad effects. *) module type S = sig (** Signatures of monad effects. *) type 'a t (** The monad. *) val perform : 'a t -> 'a (** Perform an monadic operation. *) val run : (unit -> 'a) -> 'a t (** [run t] runs the thunk [t] which may perform monad effects, and then returns the corresponding monadic expression. *) end module Make (M : Monad) : S with type 'a t = 'a M.t (** The implementation of monad effects. *)
(** Effects for any monad (subject to OCaml continuations being one-shot). *)
install.mli
(** Opam install file *) open Import module Dst : sig type t val to_string : t -> string val concat_all : t -> string list -> t include Dune_lang.Conv.S with type t := t val to_dyn : t -> Dyn.t end (** Location for installation, containing the sections relative to the current package, and sites of possibly other packages *) module Section_with_site : sig type t = | Section of Dune_engine.Section.t | Site of { pkg : Dune_engine.Package.Name.t ; site : Dune_engine.Section.Site.t ; loc : Loc.t } val to_string : t -> string (* val parse_string : string -> (t, string) Result.t *) include Dune_lang.Conv.S with type t := t val to_dyn : t -> Dyn.t end module Section : sig type t = Dune_engine.Section.t include Comparable_intf.S with type key := t val to_string : t -> string val parse_string : string -> (t, string) Result.t val decode : t Dune_lang.Decoder.t val to_dyn : t -> Dyn.t module Paths : sig module Roots : sig type 'a t = { lib_root : 'a ; libexec_root : 'a ; bin : 'a ; sbin : 'a ; share_root : 'a ; etc_root : 'a ; doc_root : 'a ; man : 'a } (** Compute the opam layout from prefix. the opam layout is used for _build *) val opam_from_prefix : Path.t -> Path.t t (** Some roots (e.g. libexec) have another roots as default (e.g. lib) *) val complete : 'a option t -> 'a option t val map : f:('a -> 'b) -> 'a t -> 'b t (** return the roots of the first argument if present *) val first_has_priority : 'a option t -> 'a option t -> 'a option t end type section := t type t val make : package:Dune_engine.Package.Name.t -> roots:Path.t Roots.t -> t val install_path : t -> section -> Dst.t -> Path.t val get : t -> section -> Path.t val get_local_location : Dune_engine.Context_name.t -> section -> Dune_engine.Package.Name.t -> Path.t end end module Entry : sig type 'src t = private { src : 'src ; kind : [ `File | `Directory ] ; dst : Dst.t ; section : Section.t } module Sourced : sig type source = | User of Loc.t | Dune type entry := Path.Build.t t type nonrec t = { source : source ; entry : entry } val create : ?loc:Loc.t -> entry -> t end val adjust_dst : src:Dune_lang.String_with_vars.t -> dst:string option -> section:Section.t -> Dst.t val make : Section.t -> ?dst:string -> kind:[ `File | `Directory ] -> Path.Build.t -> Path.Build.t t val make_with_site : Section_with_site.t -> ?dst:string -> ( loc:Loc.t -> pkg:Dune_engine.Package.Name.t -> site:Dune_engine.Section.Site.t -> Section.t Memo.t) -> kind:[ `File | `Directory ] -> Path.Build.t -> Path.Build.t t Memo.t val set_src : _ t -> 'src -> 'src t val map_dst : 'a t -> f:(Dst.t -> Dst.t) -> 'a t val relative_installed_path : _ t -> paths:Section.Paths.t -> Path.t val add_install_prefix : 'a t -> paths:Section.Paths.t -> prefix:Path.t -> 'a t val compare : ('a -> 'a -> Ordering.t) -> 'a t -> 'a t -> Ordering.t end (** Same as Entry, but the destination can be in the site of a package *) module Entry_with_site : sig type 'src t = { src : 'src ; dst : Dst.t ; section : Section_with_site.t } end val gen_install_file : Path.t Entry.t list -> string (** XXX what's this function doing here? it has nothing to do with generating any rules *) val load_install_file : Path.t -> Path.t Entry.t list
(** Opam install file *) open Import
sexp_hashcons.ml
(* camlp5o *) (* hCLam.ml *) module Ploc = Sexp.Ploc [%%import: Sexp.sexp] [@@deriving hashcons { hashconsed_module_name = HC ; normal_module_name = OK ; external_types = { Ploc.vala = { preeq = (fun f x y -> match (x,y) with (Ploc.VaAnt s1, Ploc.VaAnt s2) -> s1=s2 | (Ploc.VaVal v1, Ploc.VaVal v2) -> f v1 v2 | _ -> false ) ; prehash = (fun f x -> match x with Ploc.VaAnt s -> Hashtbl.hash s | Ploc.VaVal v -> f v ) } } ; pertype_customization = { sexp = { hashcons_constructor = sexp } } }]
(* camlp5o *) (* hCLam.ml *)
accessor_float.ml
open! Base open! Import let negated = [%accessor Accessor.isomorphism ~get:Float.neg ~construct:Float.neg] let added s = Accessor.isomorphism ~get:(fun a -> a +. s) ~construct:(fun a -> a -. s) let subtracted s = Accessor.invert (added s) let multiplied s = Accessor.isomorphism ~get:(fun a -> a *. s) ~construct:(fun a -> a /. s) ;; let divided s = Accessor.invert (multiplied s)
timing.h
// // Timing helper // #ifndef wasm_support_timing_h #define wasm_support_timing_h #include <chrono> #include <iostream> #include <string> namespace wasm { class Timer { std::string name; std::chrono::steady_clock::time_point startTime; double total = 0; public: Timer(std::string name = "") : name(name) {} void start() { startTime = std::chrono::steady_clock::now(); } void stop() { total += std::chrono::duration<double>(std::chrono::steady_clock::now() - startTime) .count(); } double getTotal() { return total; } void dump() { std::cerr << "<Timer " << name << ": " << getTotal() << ">\n"; } }; } // namespace wasm #endif // wasm_support_timing_h
/* * Copyright 2016 WebAssembly Community Group participants * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
dune
(library (public_name bheap) (name binary_heap) (modules binary_heap)) (test (name test) (modules test) (libraries stdlib-shims bheap))
error_correclty_reset.ml
open Yices2 (* This error was created because of a bug: after an error thrown using the YicesError exception, any function after it would also raise the same error even though no error actually happened. This has been fixed by reseting the error state right before the exception is raised. *) let error_correclty_reset _ = try let _ = Term.bitsize (Term.Int.of_int64 64L) in OUnit2.assert_failure "an error should have been raised" with YicesError (_, _) -> (); Type.is_int (Type.bool ()); ()
cmstub.c
#include <string.h> #include <caml/mlvalues.h> #include <caml/callback.h> /* Functions callable directly from C */ int fib(int n) { value * fib_closure = caml_named_value("fib"); return Int_val(caml_callback(*fib_closure, Val_int(n))); } char * format_result(int n) { value * format_result_closure = caml_named_value("format_result"); return strdup(String_val(caml_callback(*format_result_closure, Val_int(n)))); }
/***********************************************************************/ /* */ /* OCaml */ /* */ /* 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 GNU Library General Public License, with */ /* the special exception on linking described in file ../LICENSE. */ /* */ /***********************************************************************/
operation_result.mli
open Protocol open Alpha_context val pp_internal_operation : Format.formatter -> packed_internal_operation -> unit val pp_operation_result : Format.formatter -> 'kind contents_list * 'kind Apply_results.contents_result_list -> unit
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
promoteReadReplica.mli
open Types type input = PromoteReadReplicaMessage.t type output = PromoteReadReplicaResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
approx_equal.c
#include "mpf_mat.h" int mpf_mat_approx_equal(const mpf_mat_t mat1, const mpf_mat_t mat2, flint_bitcnt_t bits) { slong j; if (mat1->r != mat2->r || mat1->c != mat2->c) { return 0; } if (mat1->r == 0 || mat1->c == 0) return 1; for (j = 0; j < mat1->r; j++) { if (!_mpf_vec_approx_equal (mat1->rows[j], mat2->rows[j], mat1->c, bits)) { return 0; } } return 1; }
/* Copyright (C) 2010 Fredrik Johansson Copyright (C) 2014 Abhinav Baid 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/>. */
l1_operation.ml
open Protocol open Alpha_context module Manager_operation = struct type t = packed_manager_operation let encoding : t Data_encoding.t = let open Data_encoding in let open Operation.Encoding.Manager_operations in let make (MCase {tag; name; encoding; select; proj; inj}) = case (Tag tag) ~title:name (merge_objs (obj1 (req "kind" (constant name))) encoding) (fun o -> match select o with None -> None | Some o -> Some ((), proj o)) (fun ((), x) -> Manager (inj x)) in def "manager_operation" @@ union [ make reveal_case; make transaction_case; make origination_case; make delegation_case; make set_deposits_limit_case; make increase_paid_storage_case; make register_global_constant_case; make tx_rollup_origination_case; make tx_rollup_submit_batch_case; make tx_rollup_commit_case; make tx_rollup_return_bond_case; make tx_rollup_finalize_commitment_case; make tx_rollup_remove_commitment_case; make tx_rollup_rejection_case; make tx_rollup_dispatch_tickets_case; make transfer_ticket_case; make dal_publish_slot_header_case; make sc_rollup_originate_case; make sc_rollup_add_messages_case; make sc_rollup_cement_case; make sc_rollup_publish_case; make sc_rollup_refute_case; make sc_rollup_timeout_case; make sc_rollup_execute_outbox_message_case; ] let get_case : type kind. kind manager_operation -> kind Operation.Encoding.Manager_operations.case = let open Operation.Encoding.Manager_operations in function | Reveal _ -> reveal_case | Transaction _ -> transaction_case | Origination _ -> origination_case | Delegation _ -> delegation_case | Register_global_constant _ -> register_global_constant_case | Set_deposits_limit _ -> set_deposits_limit_case | Increase_paid_storage _ -> increase_paid_storage_case | Tx_rollup_origination -> tx_rollup_origination_case | Tx_rollup_submit_batch _ -> tx_rollup_submit_batch_case | Tx_rollup_commit _ -> tx_rollup_commit_case | Tx_rollup_return_bond _ -> tx_rollup_return_bond_case | Tx_rollup_finalize_commitment _ -> tx_rollup_finalize_commitment_case | Tx_rollup_remove_commitment _ -> tx_rollup_remove_commitment_case | Tx_rollup_rejection _ -> tx_rollup_rejection_case | Tx_rollup_dispatch_tickets _ -> tx_rollup_dispatch_tickets_case | Transfer_ticket _ -> transfer_ticket_case | Dal_publish_slot_header _ -> dal_publish_slot_header_case | Sc_rollup_originate _ -> sc_rollup_originate_case | Sc_rollup_add_messages _ -> sc_rollup_add_messages_case | Sc_rollup_cement _ -> sc_rollup_cement_case | Sc_rollup_publish _ -> sc_rollup_publish_case | Sc_rollup_refute _ -> sc_rollup_refute_case | Sc_rollup_timeout _ -> sc_rollup_timeout_case | Sc_rollup_execute_outbox_message _ -> sc_rollup_execute_outbox_message_case | Sc_rollup_recover_bond _ -> sc_rollup_recover_bond_case | Sc_rollup_dal_slot_subscribe _ -> sc_rollup_dal_slot_subscribe_case let pp_kind ppf op = let open Operation.Encoding.Manager_operations in let (MCase {name; _}) = get_case op in Format.pp_print_string ppf name let pp ppf (Manager op) = match op with | Tx_rollup_commit {commitment = {level; _}; _} -> Format.fprintf ppf "commitment for rollup level %a" Tx_rollup_level.pp level | Tx_rollup_rejection {level; message_position; _} -> Format.fprintf ppf "rejection for commitment at level %a for message %d" Tx_rollup_level.pp level message_position | Tx_rollup_dispatch_tickets {level; tickets_info; _} -> let pp_rollup_reveal ppf Tx_rollup_reveal.{contents; ty; amount; ticketer; claimer; _} = let pp_lazy_expr ppf e = Michelson_v1_printer.print_expr_unwrapped ppf (Result.value (Script_repr.force_decode e) ~default:(Micheline.strip_locations (Micheline.Seq ((), [])))) in Format.fprintf ppf "%a tickets (%a, %a, %a) to %a" Tx_rollup_l2_qty.pp amount Contract.pp ticketer pp_lazy_expr ty pp_lazy_expr contents Tezos_crypto.Signature.V0.Public_key_hash.pp claimer in Format.fprintf ppf "@[<v 2>dispatch withdrawals at rollup level %a: %a@]" Tx_rollup_level.pp level (Format.pp_print_list pp_rollup_reveal) tickets_info | _ -> pp_kind ppf op end module Hash = Tezos_crypto.Blake2B.Make (Tezos_crypto.Base58) (struct let name = "manager_operation_hash" let title = "A manager operation hash" let b58check_prefix = "\068\160\013" (* mop(53) *) let size = None end) let () = Tezos_crypto.Base58.check_encoded_prefix Hash.b58check_encoding "mop" 53 type hash = Hash.t type t = {hash : hash; manager_operation : packed_manager_operation} let hash_manager_operation op = Hash.hash_bytes [Data_encoding.Binary.to_bytes_exn Manager_operation.encoding op] let make manager_operation = let manager_operation = Manager manager_operation in let hash = hash_manager_operation manager_operation in {hash; manager_operation} let encoding = let open Data_encoding in conv (fun {hash; manager_operation} -> (hash, manager_operation)) (fun (hash, manager_operation) -> {hash; manager_operation}) @@ obj2 (req "hash" Hash.encoding) (req "manager_operation" Manager_operation.encoding) let pp ppf {hash; manager_operation} = Format.fprintf ppf "%a (%a)" Manager_operation.pp manager_operation Hash.pp hash
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
csc_pi.c
#include "arb.h" void arb_csc_pi(arb_t res, const arb_t x, slong prec) { arb_sin_pi(res, x, prec + 4); arb_inv(res, res, prec); }
/* Copyright (C) 2017 Fredrik Johansson Copyright (C) 2017 D.H.J. Polymath 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/>. */
dune
(library (name conex_openssl) (public_name conex.openssl) (wrapped false) (libraries conex unix conex_unix))
test_gas_levels.ml
(** Testing ------- Component: Protocol (Gas levels) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/gas/main.exe \ -- test "^gas levels$" Subject: On gas consumption and exhaustion. *) open Protocol open Raw_context module S = Saturation_repr (* This value is supposed to be larger than the block gas level limit but not saturated. *) let opg = max_int / 10000 exception Gas_levels_test_error of string let err x = Exn (Gas_levels_test_error x) let succeed x = match x with Ok _ -> true | _ -> false let failed x = not (succeed x) let dummy_context () = Context.init ~consensus_threshold:0 1 >>=? fun (block, _) -> Raw_context.prepare ~level:Int32.zero ~predecessor_timestamp:Time.Protocol.epoch ~timestamp:Time.Protocol.epoch (* ~fitness:[] *) (block.context : Environment_context.Context.t) >|= Environment.wrap_tzresult let consume_gas_lwt context gas = Lwt.return (consume_gas context (S.safe_int gas)) >|= Environment.wrap_tzresult let consume_gas_limit_in_block_lwt context gas = Lwt.return (consume_gas_limit_in_block context gas) >|= Environment.wrap_tzresult let test_detect_gas_exhaustion_in_fresh_context () = dummy_context () >>=? fun context -> fail_unless (consume_gas context (S.safe_int opg) |> succeed) (err "In a fresh context, gas consumption is unlimited.") (** Create a context with a given block gas level, capped at the hard gas limit per block *) let make_context remaining_block_gas = let open Gas_limit_repr in dummy_context () >>=? fun context -> let hard_limit = Arith.fp (constants context).hard_gas_limit_per_operation in let hard_limit_block = Arith.fp (constants context).hard_gas_limit_per_block in let block_gas = Arith.(unsafe_fp (Z.of_int remaining_block_gas)) in let rec aux context to_consume = (* Because of saturated arithmetic, [to_consume] should never be negative. *) assert (Arith.(to_consume >= zero)) ; if Arith.(to_consume = zero) then return context else if Arith.(to_consume <= hard_limit) then consume_gas_limit_in_block_lwt context to_consume else consume_gas_limit_in_block_lwt context hard_limit >>=? fun context -> aux context (Arith.sub to_consume hard_limit) in aux context Arith.(sub hard_limit_block block_gas) (** Test operation gas exhaustion. Should pass when remaining gas is 0, and fail when it goes over *) let test_detect_gas_exhaustion_when_operation_gas_hits_zero () = let gas_op = 100000 in dummy_context () >>=? fun context -> set_gas_limit context (Gas_limit_repr.Arith.unsafe_fp (Z.of_int gas_op)) |> fun context -> fail_unless (consume_gas context (S.safe_int gas_op) |> succeed) (err "Succeed when consuming exactly the remaining operation gas.") >>=? fun () -> fail_unless (consume_gas context (S.safe_int (gas_op + 1)) |> failed) (err "Fail when consuming more than the remaining operation gas.") (** Test block gas exhaustion *) let test_detect_gas_exhaustion_when_block_gas_hits_zero () = let gas k = Gas_limit_repr.Arith.unsafe_fp (Z.of_int k) in let remaining_gas = gas 100000 and too_much = gas (100000 + 1) in make_context 100000 >>=? fun context -> fail_unless (consume_gas_limit_in_block context remaining_gas |> succeed) (err "Succeed when consuming exactly the remaining block gas.") >>=? fun () -> fail_unless (consume_gas_limit_in_block context too_much |> failed) (err "Fail when consuming more than the remaining block gas.") (** Test invalid gas limit. Should fail when limit is above the hard gas limit per operation *) let test_detect_gas_limit_consumption_above_hard_gas_operation_limit () = dummy_context () >>=? fun context -> fail_unless (consume_gas_limit_in_block context (Gas_limit_repr.Arith.unsafe_fp (Z.of_int opg)) |> failed) (err "Fail when consuming gas above the hard limit per operation in the \ block.") (** For a given [context], check if its levels match those given in [block_level] and [operation_level] *) let check_context_levels context block_level operation_level = let op_check = match gas_level context with | Unaccounted -> true | Limited {remaining} -> Gas_limit_repr.Arith.(unsafe_fp (Z.of_int operation_level) = remaining) in let block_check = Gas_limit_repr.Arith.( unsafe_fp (Z.of_int block_level) = block_gas_level context) in fail_unless (op_check || block_check) (err "Unexpected block and operation gas levels") >>=? fun () -> fail_unless op_check (err "Unexpected operation gas level") >>=? fun () -> fail_unless block_check (err "Unexpected block gas level") let monitor remaining_block_gas initial_operation_level consumed_gas () = let op_limit = Gas_limit_repr.Arith.unsafe_fp (Z.of_int initial_operation_level) in make_context remaining_block_gas >>=? fun context -> consume_gas_limit_in_block_lwt context op_limit >>=? fun context -> set_gas_limit context op_limit |> fun context -> consume_gas_lwt context consumed_gas >>=? fun context -> check_context_levels context (remaining_block_gas - initial_operation_level) (initial_operation_level - consumed_gas) let test_monitor_gas_level = monitor 1000 100 10 (** Test cas consumption mode switching (limited -> unlimited) *) let test_set_gas_unlimited () = let init_block_gas = 100000 in let op_limit_int = 10000 in let op_limit = Gas_limit_repr.Arith.unsafe_fp (Z.of_int op_limit_int) in make_context init_block_gas >>=? fun context -> set_gas_limit context op_limit |> set_gas_unlimited |> fun context -> consume_gas_lwt context opg >>=? fun context -> check_context_levels context init_block_gas (-1) (** Test cas consumption mode switching (unlimited -> limited) *) let test_set_gas_limited () = let init_block_gas = 100000 in let op_limit_int = 10000 in let op_limit = Gas_limit_repr.Arith.unsafe_fp (Z.of_int op_limit_int) in let op_gas = 100 in make_context init_block_gas >>=? fun context -> set_gas_unlimited context |> fun context -> set_gas_limit context op_limit |> fun context -> consume_gas_lwt context op_gas >>=? fun context -> check_context_levels context init_block_gas (op_limit_int - op_gas) (*** Tests with blocks ***) let apply_with_gas header ?(operations = []) (pred : Block.t) = let open Alpha_context in (let open Environment.Error_monad in begin_application ~chain_id:Chain_id.zero ~predecessor_context:pred.context ~predecessor_fitness:pred.header.shell.fitness ~predecessor_timestamp:pred.header.shell.timestamp header >>=? fun vstate -> List.fold_left_es (fun vstate op -> apply_operation vstate op >|=? fun (state, _result) -> state) vstate operations >>=? fun vstate -> finalize_block vstate (Some header.shell) >|=? fun (validation, result) -> (validation.context, result.consumed_gas)) >|= Environment.wrap_tzresult >|=? fun (context, consumed_gas) -> let hash = Block_header.hash header in ({Block.hash; header; operations; context}, consumed_gas) let bake_with_gas ?policy ?timestamp ?operation ?operations pred = let operations = match (operation, operations) with | (Some op, Some ops) -> Some (op :: ops) | (Some op, None) -> Some [op] | (None, Some ops) -> Some ops | (None, None) -> None in Block.Forge.forge_header ?timestamp ?policy ?operations pred >>=? fun header -> Block.Forge.sign_header header >>=? fun header -> apply_with_gas header ?operations pred let check_consumed_gas consumed expected = fail_unless Alpha_context.Gas.Arith.(consumed = expected) (err (Format.asprintf "Gas discrepancy: consumed gas : %a | expected : %a\n" Alpha_context.Gas.Arith.pp consumed Alpha_context.Gas.Arith.pp expected)) let lazy_unit = Alpha_context.Script.lazy_expr (Expr.from_string "Unit") let prepare_origination block source script = let code = Expr.toplevel_from_string script in let script = Alpha_context.Script.{code = lazy_expr code; storage = lazy_unit} in Op.contract_origination (B block) source ~script let originate_contract block source script = prepare_origination block source script >>=? fun (operation, dst) -> Block.bake ~operation block >>=? fun block -> return (block, dst) let init_block to_originate = Context.init ~consensus_threshold:0 1 >>=? fun (block, contracts) -> let src = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in (*** originate contracts ***) let rec full_originate block originated = function | [] -> return (block, List.rev originated) | h :: t -> originate_contract block src h >>=? fun (block, ct) -> full_originate block (ct :: originated) t in full_originate block [] to_originate >>=? fun (block, originated) -> return (block, src, originated) let nil_contract = "parameter unit;\n\ storage unit;\n\ code {\n\ \ DROP;\n\ \ UNIT; NIL operation; PAIR\n\ \ }\n" let fail_contract = "parameter unit; storage unit; code { FAIL }" let loop_contract = "parameter unit;\n\ storage unit;\n\ code {\n\ \ DROP;\n\ \ PUSH bool True;\n\ \ LOOP {\n\ \ PUSH string \"GASGASGAS\";\n\ \ PACK;\n\ \ SHA3;\n\ \ DROP;\n\ \ PUSH bool True\n\ \ };\n\ \ UNIT; NIL operation; PAIR\n\ \ }\n" let block_with_one_origination contract = init_block [contract] >>=? fun (block, src, originated) -> match originated with [dst] -> return (block, src, dst) | _ -> assert false let full_block () = init_block [nil_contract; fail_contract; loop_contract] >>=? fun (block, src, originated) -> let (dst_nil, dst_fail, dst_loop) = match originated with [c1; c2; c3] -> (c1, c2, c3) | _ -> assert false in return (block, src, dst_nil, dst_fail, dst_loop) (** Combine a list of operations into an operation list. Also returns the sum of their gas limits.*) let combine_operations_with_gas ?counter block src list_dst = let rec make_op_list full_gas op_list = function | [] -> return (full_gas, List.rev op_list) | (dst, gas_limit) :: t -> Op.transaction ~gas_limit (B block) src dst Alpha_context.Tez.zero >>=? fun op -> make_op_list (Alpha_context.Gas.Arith.add full_gas gas_limit) (op :: op_list) t in make_op_list Alpha_context.Gas.Arith.zero [] list_dst >>=? fun (full_gas, op_list) -> Op.combine_operations ?counter ~source:src (B block) op_list >>=? fun operation -> return (operation, full_gas) (** Applies [combine_operations_with_gas] to lists in a list, then bake a block with this list of operations. Also returns the sum of all gas limits *) let bake_operations_with_gas ?counter block src list_list_dst = let counter = Option.value ~default:Z.zero counter in let rec make_list full_gas op_list counter = function | [] -> return (full_gas, List.rev op_list) | list_dst :: t -> let n = Z.of_int (List.length list_dst) in combine_operations_with_gas ~counter block src list_dst >>=? fun (op, gas) -> make_list (Alpha_context.Gas.Arith.add full_gas gas) (op :: op_list) (Z.add counter n) t in make_list Alpha_context.Gas.Arith.zero [] counter list_list_dst >>=? fun (gas_limit_total, operations) -> bake_with_gas ~operations block >>=? fun (block, consumed_gas) -> return (block, consumed_gas, gas_limit_total) let basic_gas_sampler () = Alpha_context.Gas.Arith.integral_of_int_exn (100 + Random.int 900) let generic_test_block_one_origination contract gas_sampler structure = block_with_one_origination contract >>=? fun (block, src, dst) -> let lld = List.map (List.map (fun _ -> (dst, gas_sampler ()))) structure in bake_operations_with_gas ~counter:Z.one block src lld >>=? fun (_block, consumed_gas, gas_limit_total) -> check_consumed_gas consumed_gas gas_limit_total let make_batch_test_block_one_origination name contract gas_sampler = let test = generic_test_block_one_origination contract gas_sampler in let test_one_operation () = test [[()]] in let test_one_operation_list () = test [[(); (); ()]] in let test_many_single_operations () = test [[()]; [()]; [()]] in let test_mixed_operations () = test [[(); ()]; [()]; [(); (); ()]] in let app_n = List.map (fun (x, y) -> (x ^ " with contract " ^ name, y)) in app_n [ ("Test bake one operation", test_one_operation); ("Test bake one operation list", test_one_operation_list); ("Test multiple single operations", test_many_single_operations); ("Test both lists and single operations", test_mixed_operations); ] (** Tests the consumption of all gas in a block, should pass *) let test_consume_exactly_all_block_gas () = block_with_one_origination nil_contract >>=? fun (block, src, dst) -> (* assumptions: hard gas limit per operation = 1040000 hard gas limit per block = 5200000 *) let lld = List.map (fun _ -> [(dst, Alpha_context.Gas.Arith.integral_of_int_exn 1040000)]) [1; 1; 1; 1; 1] in bake_operations_with_gas ~counter:Z.one block src lld >>=? fun _ -> return () (** Tests the consumption of more than the block gas level with many single operations, should fail *) let test_malformed_block_max_limit_reached () = block_with_one_origination nil_contract >>=? fun (block, src, dst) -> (* assumptions: hard gas limit per operation = 1040000 hard gas limit per block = 5200000 *) let lld = [(dst, Alpha_context.Gas.Arith.integral_of_int_exn 1)] :: List.map (fun _ -> [(dst, Alpha_context.Gas.Arith.integral_of_int_exn 1040000)]) [1; 1; 1; 1; 1] in bake_operations_with_gas ~counter:Z.one block src lld >>= function | Error _ -> return_unit | Ok _ -> fail (err "Invalid block: sum of operation gas limits exceeds hard gas limit \ per block") (** Tests the consumption of more than the block gas level with one big operation list, should fail *) let test_malformed_block_max_limit_reached' () = block_with_one_origination nil_contract >>=? fun (block, src, dst) -> (* assumptions: hard gas limit per operation = 1040000 hard gas limit per block = 5200000 *) let lld = [ (dst, Alpha_context.Gas.Arith.integral_of_int_exn 1) :: List.map (fun _ -> (dst, Alpha_context.Gas.Arith.integral_of_int_exn 1040000)) [1; 1; 1; 1; 1]; ] in bake_operations_with_gas ~counter:Z.one block src lld >>= function | Error _ -> return_unit | Ok _ -> fail (err "Invalid block: sum of gas limits in operation list exceeds hard \ gas limit per block") let test_block_mixed_operations () = full_block () >>=? fun (block, src, dst_nil, dst_fail, dst_loop) -> let l = [[dst_nil]; [dst_nil; dst_fail; dst_nil]; [dst_loop]; [dst_nil]] in let lld = List.map (List.map (fun x -> (x, basic_gas_sampler ()))) l in bake_operations_with_gas ~counter:(Z.of_int 3) block src lld >>=? fun (_block, consumed_gas, gas_limit_total) -> check_consumed_gas consumed_gas gas_limit_total let quick (what, how) = Tztest.tztest what `Quick how let tests = List.map quick ([ ( "Detect gas exhaustion in fresh context", test_detect_gas_exhaustion_in_fresh_context ); ( "Detect gas exhaustion when operation gas as hits zero", test_detect_gas_exhaustion_when_operation_gas_hits_zero ); ( "Detect gas exhaustion when block gas as hits zero", test_detect_gas_exhaustion_when_block_gas_hits_zero ); ( "Detect gas limit consumption when it is above the hard gas operation \ limit", test_detect_gas_limit_consumption_above_hard_gas_operation_limit ); ( "Each new operation impacts block gas level, each gas consumption \ impacts operation gas level", test_monitor_gas_level ); ( "Switches operation gas consumption from limited to unlimited", test_set_gas_unlimited ); ( "Switches operation gas consumption from unlimited to limited", test_set_gas_limited ); ( "Accepts a block that consumes all of its gas", test_consume_exactly_all_block_gas ); ( "Detect when the sum of all operation gas limits exceeds the hard gas \ limit per block", test_malformed_block_max_limit_reached ); ( "Detect when gas limit of operation list exceeds the hard gas limit \ per block", test_malformed_block_max_limit_reached' ); ( "Test the gas consumption of various operations", test_block_mixed_operations ); ] @ make_batch_test_block_one_origination "nil" nil_contract basic_gas_sampler @ make_batch_test_block_one_origination "fail" fail_contract basic_gas_sampler @ make_batch_test_block_one_origination "infinite loop" loop_contract basic_gas_sampler)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
bootstrap_storage.mli
val init : Raw_context.t -> typecheck:(Raw_context.t -> Script_repr.t -> ( (Script_repr.t * Contract_storage.big_map_diff option) * Raw_context.t ) tzresult Lwt.t) -> ?ramp_up_cycles:int -> ?no_reward_cycles:int -> Parameters_repr.bootstrap_account list -> Parameters_repr.bootstrap_contract list -> Raw_context.t tzresult Lwt.t val cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
plain_diff.mli
(** Basic Myers diff algorithm, translated from GNU diff. **) (** [iter_matches ?cutoff ~f ~hashable a b] diffs the arrays [a] and [b] (as in /usr/bin/diff), and calls [f] on each element of the longest common subsequence in increasing order. The arguments of [f] are the indices in [a] and [b], respectively, of that element. The [cutoff] is an upper bound on the minimum edit distance between [a] and [b]. When [cutoff] is exceeded, [iter_matches] returns a correct, but not necessarily minimal diff. It defaults to about [sqrt (Array.length a + Array.length b)]. *) val iter_matches : ?cutoff:int -> f:(int * int -> unit) -> hashable:'a Base.Hashtbl.Key.t -> 'a array -> 'a array -> unit
(** Basic Myers diff algorithm, translated from GNU diff. **)
raw_level_repr.ml
type t = int32 type raw_level = t include (Compare.Int32 : Compare.S with type t := t) let pp ppf level = Format.fprintf ppf "%ld" level let rpc_arg = let construct raw_level = Int32.to_string raw_level in let destruct str = Int32.of_string_opt str |> Option.to_result ~none:"Cannot parse level" in RPC_arg.make ~descr:"A level integer" ~name:"block_level" ~construct ~destruct () let root = 0l let succ = Int32.succ let add l i = assert (Compare.Int.(i >= 0)) ; Int32.add l (Int32.of_int i) let sub l i = assert (Compare.Int.(i >= 0)) ; let res = Int32.sub l (Int32.of_int i) in if Compare.Int32.(res >= 0l) then Some res else None let pred l = if l = 0l then None else Some (Int32.pred l) let diff = Int32.sub let to_int32 l = l let of_int32_exn l = if Compare.Int32.(l >= 0l) then l else invalid_arg "Level_repr.of_int32" let encoding = Data_encoding.conv_with_guard (fun i -> i) (fun i -> try ok (of_int32_exn i) with Invalid_argument s -> Error s) Data_encoding.int32 type error += Unexpected_level of Int32.t (* `Permanent *) let () = register_error_kind `Permanent ~id:"unexpected_level" ~title:"Unexpected level" ~description:"Level must be non-negative." ~pp:(fun ppf l -> Format.fprintf ppf "The level is %s but should be non-negative." (Int32.to_string l)) Data_encoding.(obj1 (req "level" int32)) (function Unexpected_level l -> Some l | _ -> None) (fun l -> Unexpected_level l) let of_int32 l = Error_monad.catch_f (fun () -> of_int32_exn l) (fun _ -> Unexpected_level l) module Index = struct type t = raw_level let path_length = 1 let to_path level l = Int32.to_string level :: l let of_path = function [s] -> Int32.of_string_opt s | _ -> None let rpc_arg = rpc_arg let encoding = encoding let compare = compare end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
named_existentials.ml
let ok1 = function Dyn (type a) ((w, x) : a ty * a) -> ignore (x : a) let ok2 = function Dyn (type a) ((w, x) : _ * a) -> ignore (x : a) type u = C : 'a * ('a -> 'b list) -> u let f = function C (type a b) ((x, f) : _ * (a -> b list)) -> ignore (x : a) (* with GADT unification *) type _ expr = | Int : int -> int expr | Add : (int -> int -> int) expr | App : ('a -> 'b) expr * 'a expr -> 'b expr let rec eval : type t. t expr -> t = function | Int n -> n | Add -> ( + ) | App (type a) ((f, x) : _ * a expr) -> eval f (eval x : a) (* Also allow annotations on multiary constructors *) type ('a, 'b) pair = Pair of 'a * 'b let f = function Pair ((x, y) : int * _) -> x + y
bzlaelimslices.c
#include "preprocess/bzlaelimslices.h" #include "bzlacore.h" #include "bzlaexp.h" #include "bzlalog.h" #include "utils/bzlanodeiter.h" #include "utils/bzlautil.h" struct BzlaSlice { uint32_t upper; uint32_t lower; }; typedef struct BzlaSlice BzlaSlice; static BzlaSlice * new_slice(Bzla *bzla, uint32_t upper, uint32_t lower) { BzlaSlice *result; assert(bzla != NULL); assert(upper >= lower); BZLA_NEW(bzla->mm, result); result->upper = upper; result->lower = lower; return result; } static void delete_slice(Bzla *bzla, BzlaSlice *slice) { assert(bzla != NULL); assert(slice != NULL); BZLA_DELETE(bzla->mm, slice); } static uint32_t hash_slice(BzlaSlice *slice) { uint32_t result; assert(slice != NULL); assert(slice->upper >= slice->lower); result = (uint32_t) slice->upper; result += (uint32_t) slice->lower; result *= 7334147u; return result; } static int32_t compare_slices(BzlaSlice *s1, BzlaSlice *s2) { assert(s1 != NULL); assert(s2 != NULL); assert(s1->upper >= s1->lower); assert(s2->upper >= s2->lower); if (s1->upper < s2->upper) return -1; if (s1->upper > s2->upper) return 1; assert(s1->upper == s1->upper); if (s1->lower < s2->lower) return -1; if (s1->lower > s2->lower) return 1; assert(s1->upper == s2->upper && s1->lower == s2->lower); return 0; } static int32_t compare_slices_qsort(const void *p1, const void *p2) { return compare_slices(*((BzlaSlice **) p1), *((BzlaSlice **) p2)); } static int32_t compare_int_ptr(const void *p1, const void *p2) { int32_t v1 = *((int32_t *) p1); int32_t v2 = *((int32_t *) p2); if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } void bzla_eliminate_slices_on_bv_vars(Bzla *bzla) { BzlaNode *var, *cur, *result, *lambda_var, *temp; BzlaSortId sort; BzlaSlice *s1, *s2, *new_s1, *new_s2, *new_s3, **sorted_slices; BzlaPtrHashBucket *b_var, *b1, *b2; BzlaNodeIterator it; BzlaPtrHashTable *slices; int32_t i; uint32_t min, max, count; BzlaNodePtrStack vars; double start, delta; BzlaMemMgr *mm; uint32_t vals[4]; assert(bzla != NULL); start = bzla_util_time_stamp(); count = 0; BZLALOG(1, "start slice elimination"); mm = bzla->mm; BZLA_INIT_STACK(mm, vars); for (b_var = bzla->bv_vars->first; b_var != NULL; b_var = b_var->next) { if (b_var->data.flag) continue; var = (BzlaNode *) b_var->key; BZLA_PUSH_STACK(vars, var); /* mark as processed, required for non-destructive substiution */ b_var->data.flag = true; } while (!BZLA_EMPTY_STACK(vars)) { var = BZLA_POP_STACK(vars); if (!bzla_node_is_bv_var(var)) continue; BZLALOG(2, "process %s (%s)", bzla_util_node2string(var), bzla_util_node2string(bzla_node_get_simplified(bzla, var))); assert(bzla_node_is_regular(var)); slices = bzla_hashptr_table_new( mm, (BzlaHashPtr) hash_slice, (BzlaCmpPtr) compare_slices); /* find all slices on variable */ bzla_iter_parent_init(&it, var); while (bzla_iter_parent_has_next(&it)) { cur = bzla_iter_parent_next(&it); assert(bzla_node_is_regular(cur)); if (bzla_node_is_simplified(cur)) { assert(bzla_opt_get(bzla, BZLA_OPT_PP_NONDESTR_SUBST)); continue; } if (bzla_node_is_bv_slice(cur)) { s1 = new_slice(bzla, bzla_node_bv_slice_get_upper(cur), bzla_node_bv_slice_get_lower(cur)); assert(!bzla_hashptr_table_get(slices, s1)); /* full slices should have been eliminated by rewriting */ assert(s1->upper - s1->lower + 1 < bzla_node_bv_get_width(bzla, var)); bzla_hashptr_table_add(slices, s1); BZLALOG(2, " found slice %u %u", s1->upper, s1->lower); } } /* no splitting necessary? */ if (slices->count == 0u) { bzla_hashptr_table_delete(slices); continue; } /* add full slice */ s1 = new_slice(bzla, bzla_node_bv_get_width(bzla, var) - 1, 0); assert(!bzla_hashptr_table_get(slices, s1)); bzla_hashptr_table_add(slices, s1); BZLA_SPLIT_SLICES_RESTART: for (b1 = slices->last; b1 != NULL; b1 = b1->prev) { s1 = (BzlaSlice *) b1->key; for (b2 = b1->prev; b2 != NULL; b2 = b2->prev) { s2 = (BzlaSlice *) b2->key; assert(compare_slices(s1, s2)); /* not overlapping? */ if ((s1->lower > s2->upper) || (s1->upper < s2->lower) || (s2->lower > s1->upper) || (s2->upper < s1->lower)) continue; if (s1->upper == s2->upper) { assert(s1->lower != s2->lower); max = BZLA_MAX_UTIL(s1->lower, s2->lower); min = BZLA_MIN_UTIL(s1->lower, s2->lower); new_s1 = new_slice(bzla, max - 1, min); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (min == s1->lower) { bzla_hashptr_table_remove(slices, s1, 0, 0); delete_slice(bzla, s1); } else { bzla_hashptr_table_remove(slices, s2, 0, 0); delete_slice(bzla, s2); } goto BZLA_SPLIT_SLICES_RESTART; } if (s1->lower == s2->lower) { assert(s1->upper != s2->upper); max = BZLA_MAX_UTIL(s1->upper, s2->upper); min = BZLA_MIN_UTIL(s1->upper, s2->upper); new_s1 = new_slice(bzla, max, min + 1); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (max == s1->upper) { bzla_hashptr_table_remove(slices, s1, 0, 0); delete_slice(bzla, s1); } else { bzla_hashptr_table_remove(slices, s2, NULL, NULL); delete_slice(bzla, s2); } goto BZLA_SPLIT_SLICES_RESTART; } /* regular overlapping case (overlapping at both ends) */ vals[0] = s1->upper; vals[1] = s1->lower; vals[2] = s2->upper; vals[3] = s2->lower; qsort(vals, 4, sizeof(uint32_t), compare_int_ptr); new_s1 = new_slice(bzla, vals[3], vals[2] + 1); new_s2 = new_slice(bzla, vals[2], vals[1]); new_s3 = new_slice(bzla, vals[1] - 1, vals[0]); bzla_hashptr_table_remove(slices, s1, 0, 0); bzla_hashptr_table_remove(slices, s2, NULL, NULL); delete_slice(bzla, s1); delete_slice(bzla, s2); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (!bzla_hashptr_table_get(slices, new_s2)) bzla_hashptr_table_add(slices, new_s2); else delete_slice(bzla, new_s2); if (!bzla_hashptr_table_get(slices, new_s3)) bzla_hashptr_table_add(slices, new_s3); else delete_slice(bzla, new_s3); goto BZLA_SPLIT_SLICES_RESTART; } } /* copy slices to sort them */ assert(slices->count > 1u); BZLA_NEWN(mm, sorted_slices, slices->count); i = 0; for (b1 = slices->first; b1 != NULL; b1 = b1->next) { s1 = (BzlaSlice *) b1->key; sorted_slices[i++] = s1; } qsort(sorted_slices, slices->count, sizeof(BzlaSlice *), compare_slices_qsort); s1 = sorted_slices[slices->count - 1]; sort = bzla_sort_bv(bzla, s1->upper - s1->lower + 1); result = bzla_exp_var(bzla, sort, 0); bzla_sort_release(bzla, sort); delete_slice(bzla, s1); for (i = (int32_t) slices->count - 2; i >= 0; i--) { s1 = sorted_slices[i]; sort = bzla_sort_bv(bzla, s1->upper - s1->lower + 1); lambda_var = bzla_exp_var(bzla, sort, 0); bzla_sort_release(bzla, sort); temp = bzla_exp_bv_concat(bzla, result, lambda_var); bzla_node_release(bzla, result); result = temp; bzla_node_release(bzla, lambda_var); delete_slice(bzla, s1); } BZLA_DELETEN(mm, sorted_slices, slices->count); bzla_hashptr_table_delete(slices); count++; bzla->stats.eliminated_slices++; temp = bzla_exp_eq(bzla, var, result); bzla_assert_exp(bzla, temp); bzla_node_release(bzla, temp); bzla_node_release(bzla, result); } BZLA_RELEASE_STACK(vars); delta = bzla_util_time_stamp() - start; bzla->time.slicing += delta; BZLALOG(1, "end slice elimination"); BZLA_MSG(bzla->msg, 1, "sliced %u variables in %1.f seconds", count, delta); }
/*** * Bitwuzla: Satisfiability Modulo Theories (SMT) solver. * * This file is part of Bitwuzla. * * Copyright (C) 2007-2022 by the authors listed in the AUTHORS file. * * See COPYING for more information on using this software. */
quota.ml
let warn fmt = Logging.warn "quota" fmt exception Limit_reached exception Data_too_big exception Transaction_opened type domid = int (* Global defaults *) let maxent = ref (10000) let maxsize = ref (4096) let maxwatch = ref 50 let maxtransaction = ref 20 let maxwatchevent = ref 256 type overrides = (int, int) Hashtbl.t let maxent_overrides = Hashtbl.create 10 let maxwatch_overrides = Hashtbl.create 10 let maxtransaction_overrides = Hashtbl.create 10 let maxwatchevent_overrides = Hashtbl.create 10 let get_override t domid = if Hashtbl.mem t domid then Some(Hashtbl.find t domid) else None let set_override t domid override = match override with | None -> Hashtbl.remove t domid | Some override -> Hashtbl.replace t domid override let list_overrides t = Hashtbl.fold (fun domid x acc -> (domid, x) :: acc) t [] let of_domain t default domid = if Hashtbl.mem t domid then Hashtbl.find t domid else !default let maxent_of_domain = of_domain maxent_overrides maxent let maxwatch_of_domain = of_domain maxwatch_overrides maxwatch let maxtransaction_of_domain = of_domain maxtransaction_overrides maxtransaction let maxwatchevent_of_domain = of_domain maxwatchevent_overrides maxwatchevent type t = { cur: (domid, int) Hashtbl.t; (* current domains entry usage *) } let create () = { cur = Hashtbl.create 100; } let copy quota = { cur = (Hashtbl.copy quota.cur) } (*let del quota id = Hashtbl.remove quota.cur id*) let check _quota id size = if size > !maxsize then ( warn "domain %u err create entry: data too big %d" id size; raise Data_too_big ) let list quota = Hashtbl.fold (fun domid x acc -> (domid, x) :: acc) quota.cur [] let get quota id = if Hashtbl.mem quota.cur id then Hashtbl.find quota.cur id else 0 let set quota id nb = if nb = 0 then Hashtbl.remove quota.cur id else begin if Hashtbl.mem quota.cur id then Hashtbl.replace quota.cur id nb else Hashtbl.add quota.cur id nb end let decr quota id = let nb = get quota id in if nb > 0 then set quota id (nb - 1) let incr quota id = let nb = get quota id in let maxent = maxent_of_domain id in if nb >= maxent then raise Limit_reached; set quota id (nb + 1) let union quota diff = Hashtbl.iter (fun id nb -> set quota id (get quota id + nb)) diff.cur let merge orig_quota mod_quota dest_quota = Hashtbl.iter (fun id nb -> let diff = nb - (get orig_quota id) in if diff <> 0 then set dest_quota id ((get dest_quota id) + diff)) mod_quota.cur
(* * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. *)
migrate_parsetree_def.mli
(** Features which are not available in all versions of the frontend *) type missing_feature = Pexp_letexception | Ppat_open | Pexp_unreachable | PSig | Pcstr_record | Pconst_integer | Pconst_float | Pcl_open | Pcty_open | Oinherit | Pwith_typesubst_longident | Pwith_modsubst_longident | Pexp_open | Pexp_letop | Psig_typesubst | Psig_modsubst | Otyp_module | Immediate64 | Anonymous_let_module | Anonymous_unpack | Anonymous_module_binding | Anonymous_module_declaration | ExistentialsInPatternMatching | With_modtype | With_modtypesubst | Psig_modtypesubst | Extension_constructor | Pcd_vars (** Exception thrown by migration functions when a feature is not supported. *) exception Migration_error of missing_feature * Location.t (** [missing_feature_description x] is a text describing the feature [x]. *) val missing_feature_description : missing_feature -> string (** [missing_feature_minimal_version x] is the OCaml version where x was introduced. *) val missing_feature_minimal_version : missing_feature -> string (** Turn a missing feature into a reasonable error message. *) val migration_error_message : missing_feature -> string
(**************************************************************************) (* *) (* OCaml Migrate Parsetree *) (* *) (* Frédéric Bour *) (* *) (* Copyright 2017 Institut National de Recherche en Informatique et *) (* en Automatique (INRIA). *) (* *) (* 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. *) (* *) (**************************************************************************)
clb_floattrees.h
#ifndef CLB_FLOATTREES #define CLB_FLOATTREES #include <clb_dstrings.h> #include <clb_avlgeneric.h> /*---------------------------------------------------------------------*/ /* Data type declarations */ /*---------------------------------------------------------------------*/ /*---------------------------------------------------------------------*/ /* Exported Functions and Variables */ /*---------------------------------------------------------------------*/ /* General purpose data structure for indexing objects by a (double) float key. Integer values are supported directly, for all other objects pointers can be used (and need to be casted carefully by the wrapper functions). Objects pointed to by the value fields are not part of the data stucture and will not be touched by deallocating trees or tree nodes. */ typedef struct floattreecell { double key; IntOrP val1; IntOrP val2; struct floattreecell *lson; struct floattreecell *rson; }FloatTreeCell, *FloatTree_p; #define FloatTreeCellAlloc() (FloatTreeCell*)SizeMalloc(sizeof(FloatTreeCell)) #define FloatTreeCellFree(junk) SizeFree(junk, sizeof(FloatTreeCell)) FloatTree_p FloatTreeCellAllocEmpty(void); void FloatTreeFree(FloatTree_p junk); FloatTree_p FloatTreeInsert(FloatTree_p *root, FloatTree_p new); bool FloatTreeStore(FloatTree_p *root, double key, IntOrP val1, IntOrP val2); FloatTree_p FloatTreeFind(FloatTree_p *root, double key); FloatTree_p FloatTreeExtractEntry(FloatTree_p *root, double key); bool FloatTreeDeleteEntry(FloatTree_p *root, double key); long FloatTreeNodes(FloatTree_p root); AVL_TRAVERSE_DECLARATION(FloatTree, FloatTree_p) #define FloatTreeTraverseExit(stack) PStackFree(stack) #endif /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : clb_floattrees.h Author: Stephan Schulz Contents Definitions for SPLAY trees with long integer keys and up to two long or pointer values. Copied from clb_stringtrees.h Copyright 1998, 1999 by the author. This code is released under the GNU General Public Licence and the GNU Lesser General Public License. See the file COPYING in the main E directory for details.. Run "eprover -h" for contact information. Changes <1> Sat Aug 21 11:55:40 GMT 1999 Stilen from clb_numtrees.h -----------------------------------------------------------------------*/
commands.mli
val saw : int -> int -> float -> string option -> float option -> int option -> float -> string -> (unit, string) result val sine : int -> int -> float -> string option -> float option -> int option -> float -> string -> (unit, string) result val square : int -> int -> float -> string option -> float option -> int option -> float -> string -> (unit, string) result val triangle : int -> int -> float -> string option -> float option -> int option -> float -> string -> (unit, string) result val white_noise : int -> int -> float -> string option -> float option -> int option -> string -> (unit, string) result val beat : int -> int -> float -> float option -> string option -> string option -> string option -> int -> string -> (unit, string) result
compose_horner.c
#include "fq_nmod_poly.h" #ifdef T #undef T #endif #define T fq_nmod #define CAP_T FQ_NMOD #include "fq_poly_templates/compose_horner.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/>. */
test.ml
let s = "foo bar baz" let () = let lex1 = Lexing.from_string s in let lex2 = Lexing.from_string s in ignore (Test_menhir1.main Lexer1.lex lex1); ignore (Test_base.main Lexer2.lex lex2)
js-upon.ml
let f x = stop (* We don't do this as a matter of style, but the indentation reveals a common mistake. *) >>> fun () -> don't_wait_for (close fd); bind fd let f x = stop (* This is what was intended, which is indented correctly, although it's bad style on my part. *) >>> (fun () -> don't_wait_for (close fd)); bind
dune
garbage
lwt_js_events.mli
(** Programming mouse or keyboard events handlers using Lwt *) open Js_of_ocaml (** Reminder: Event capturing starts with the outer most element in the DOM and works inwards to the HTML element the event took place on (capture phase) and then out again (bubbling phase). Examples of use: Waiting for a click on [elt1] before continuing: {[let%lwt _ = Lwt_js_events.click elt1 in]} Doing some operation for each value change in input element [inp]: {[Lwt_js_events.(async (fun () -> clicks inp1 (fun ev _ -> ...) ))]} Defining a thread that waits for ESC key on an element: {[let rec esc elt = let%lwt ev = keydown elt in if ev##.keyCode = 27 then Lwt.return ev else esc elt]} Waiting for a click or escape key before continuing: {[let%lwt () = Lwt.pick [(let%lwt _ = esc Dom_html.document in Lwt.return ()); (let%lwt _ = click Dom_html.document in Lwt.return ())] in ...]} {2 Create Lwt threads for events} *) val make_event : (#Dom_html.event as 'a) Js.t Dom_html.Event.typ -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> 'a Js.t Lwt.t (** [make_event ev target] creates a Lwt thread that waits for the event [ev] to happen on [target] (once). This thread isa cancellable using [Lwt.cancel]. If you set the optional parameter [~use_capture:true], the event will be caught during the capture phase, otherwise it is caught during the bubbling phase (default). If you set the optional parameter [~passive:true], the user agent will ignore [preventDefault] calls inside the event callback. *) val seq_loop : (?use_capture:bool -> ?passive:bool -> 'target -> 'event Lwt.t) -> ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t (** [seq_loop (make_event ev) target handler] creates a looping Lwt thread that waits for the event [ev] to happen on [target], then execute handler, and start again waiting for the event. Events happening during the execution of the handler are ignored. See [async_loop] and [buffered_loop] for alternative semantics. For example, the [clicks] function below is defined by: [let clicks ?use_capture ?passive t = seq_loop click ?use_capture ?passive t] The thread returned is cancellable using [Lwt.cancel]. In order for the loop thread to be canceled from within the handler, the latter receives the former as its second parameter. By default, cancelling the loop will not cancel the potential currently running handler. This behaviour can be changed by setting the [cancel_handler] parameter to true. *) val async_loop : (?use_capture:bool -> ?passive:bool -> 'target -> 'event Lwt.t) -> ?use_capture:bool -> ?passive:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t (** [async_loop] is similar to [seq_loop], but each handler runs independently. No event is thus missed, but since several instances of the handler can be run concurrently, it is up to the programmer to ensure that they interact correctly. Cancelling the loop will not cancel the potential currently running handlers. *) val buffered_loop : (?use_capture:bool -> ?passive:bool -> 'target -> 'event Lwt.t) -> ?cancel_handler:bool -> ?cancel_queue:bool -> ?use_capture:bool -> ?passive:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t (** [buffered_loop] is similar to [seq_loop], but any event that occurs during an execution of the handler is queued instead of being ignored. No event is thus missed, but there can be a non predictable delay between its trigger and its treatment. It is thus a good idea to use this loop with handlers whose running time is short, so the memorized event still makes sense when the handler is eventually executed. It is also up to the programmer to ensure that event handlers terminate so the queue will eventually be emptied. By default, cancelling the loop will not cancel the (potential) currently running handler, but any other queued event will be dropped. This behaviour can be customized using the two optional parameters [cancel_handler] and [cancel_queue]. *) val async : (unit -> unit Lwt.t) -> unit (** [async t] records a thread to be executed later. It is implemented by calling yield, then Lwt.async. This is useful if you want to create a new event listener when you are inside an event handler. This avoids the current event to be caught by the new event handler (if it propagates). *) val func_limited_loop : (?use_capture:bool -> ?passive:bool -> 'a -> 'b Lwt.t) -> (unit -> 'a Lwt.t) -> ?use_capture:bool -> ?passive:bool -> 'a -> ('b -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t (** [func_limited_loop event delay_fun target handler] will behave like [Lwt_js_events.async_loop event target handler] but it will run [delay_fun] first, and execute [handler] only when [delay_fun] is finished and no other event occurred in the meantime. This allows to limit the number of events caught. Be careful, it is an asynchrone loop, so if you give too little time, several instances of your handler could be run in same time **) val limited_loop : (?use_capture:bool -> ?passive:bool -> 'a -> 'b Lwt.t) -> ?elapsed_time:float -> ?use_capture:bool -> ?passive:bool -> 'a -> ('b -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t (** Same as func_limited_loop but take time instead of function By default elapsed_time = 0.1s = 100ms **) (** {2 Predefined functions for some types of events} *) val click : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val copy : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.clipboardEvent Js.t Lwt.t val cut : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.clipboardEvent Js.t Lwt.t val paste : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.clipboardEvent Js.t Lwt.t val dblclick : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val mousedown : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val mouseup : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val mouseover : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val mousemove : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val mouseout : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t val keypress : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t val keydown : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t val keyup : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t val input : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val timeupdate : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val change : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val dragstart : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val dragend : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val dragenter : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val dragover : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val dragleave : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val drag : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val drop : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t val focus : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.focusEvent Js.t Lwt.t val blur : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.focusEvent Js.t Lwt.t val scroll : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val submit : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.submitEvent Js.t Lwt.t val select : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val mousewheel : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t * (int * int)) Lwt.t (** This function returns the event, together with the numbers of ticks the mouse wheel moved. Positive means down or right. This interface is compatible with all (recent) browsers. *) val wheel : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.mousewheelEvent Js.t Lwt.t val touchstart : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t val touchmove : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t val touchend : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t val touchcancel : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t val lostpointercapture : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val gotpointercapture : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerenter : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointercancel : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerdown : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerleave : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointermove : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerout : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerover : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val pointerup : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.pointerEvent Js.t Lwt.t val transitionend : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.transitionEvent Js.t Lwt.t (** Returns when a CSS transition terminates on the element. *) val transitionstart : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.transitionEvent Js.t Lwt.t val transitionrun : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.transitionEvent Js.t Lwt.t val transitioncancel : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.transitionEvent Js.t Lwt.t val load : ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t val error : ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t val abort : ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t val canplay : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val canplaythrough : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val durationchange : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val emptied : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val ended : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val loadeddata : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val loadedmetadata : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val loadstart : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val pause : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val play : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val playing : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val ratechange : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val seeked : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val seeking : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val stalled : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val suspend : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val volumechange : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val waiting : ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t val clicks : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val copies : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.clipboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val cuts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.clipboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pastes : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.clipboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dblclicks : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mousedowns : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mouseups : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mouseovers : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mousemoves : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mouseouts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val keypresses : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val keydowns : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val keyups : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val inputs : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val timeupdates : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val changes : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dragstarts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dragends : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dragenters : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dragovers : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val dragleaves : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val drags : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val drops : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val mousewheels : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mouseEvent Js.t * (int * int) -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val wheels : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.mousewheelEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val touchstarts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val touchmoves : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val touchends : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val touchcancels : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val focuses : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.focusEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val blurs : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.focusEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val scrolls : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val submits : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.submitEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val selects : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val loads : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val errors : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val aborts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.imageElement Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val canplays : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val canplaythroughs : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val durationchanges : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val emptieds : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val endeds : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val loadeddatas : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val loadedmetadatas : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val loadstarts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pauses : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val plays : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val playings : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val ratechanges : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val seekeds : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val seekings : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val stalleds : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val suspends : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val volumechanges : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val waitings : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val lostpointercaptures : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val gotpointercaptures : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerenters : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointercancels : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerdowns : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerleaves : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointermoves : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerouts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerovers : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val pointerups : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.pointerEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val transitionends : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.transitionEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val transitionstarts : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.transitionEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val transitionruns : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.transitionEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val transitioncancels : ?cancel_handler:bool -> ?use_capture:bool -> ?passive:bool -> #Dom_html.eventTarget Js.t -> (Dom_html.transitionEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val request_animation_frame : unit -> unit Lwt.t (** Returns when a repaint of the window by the browser starts. (see JS method [window.requestAnimationFrame]) *) val onload : unit -> Dom_html.event Js.t Lwt.t (** Returns when the page is loaded *) val domContentLoaded : unit -> unit Lwt.t val onunload : unit -> Dom_html.event Js.t Lwt.t val onbeforeunload : unit -> Dom_html.event Js.t Lwt.t val onresize : unit -> Dom_html.event Js.t Lwt.t val onorientationchange : unit -> Dom_html.event Js.t Lwt.t val onpopstate : unit -> Dom_html.popStateEvent Js.t Lwt.t val onhashchange : unit -> Dom_html.hashChangeEvent Js.t Lwt.t val onorientationchange_or_onresize : unit -> Dom_html.event Js.t Lwt.t val onresizes : (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val onorientationchanges : (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val onpopstates : (Dom_html.popStateEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val onhashchanges : (Dom_html.hashChangeEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val onorientationchanges_or_onresizes : (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val limited_onresizes : ?elapsed_time:float -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val limited_onorientationchanges : ?elapsed_time:float -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t val limited_onorientationchanges_or_onresizes : ?elapsed_time:float -> (Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
(* Js_of_ocaml library * http://www.ocsigen.org/js_of_ocaml/ * Copyright (C) 2010 Vincent Balat * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *)
test_sapling.ml
(** Testing ------- Component: Protocol (Sapling) Invocation: cd src/proto_alpha/lib_protocol/test dune exec ./main.exe -- test "^sapling$" Subject: On the privacy-preserving library Sapling *) open Protocol open Alpha_context open Test_tez let ( >>??= ) x y = match x with | Ok s -> y s | Error err -> Lwt.return @@ Error (Environment.wrap_tztrace err) module Raw_context_tests = struct open Sapling_helpers.Common (* This test adds to the first 100 positions in the commitments tree the constant value `uncommitted` for which we know the corresponding root and tests that the returned root is as expected. *) let commitments_add_uncommitted () = Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> let module H = Tezos_sapling.Core.Client.Hash in let cm = H.uncommitted ~height:0 in let expected_root = H.uncommitted ~height:32 in Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size:0 >>= wrap >>=? fun ctx -> List.fold_left_es (fun ctx pos -> Sapling_storage.Commitments.get_root ctx id >>= wrap >>=? fun (ctx, root) -> assert (root = expected_root) ; Sapling_storage.Commitments.add ctx id [H.to_commitment cm] (Int64.of_int pos) >>= wrap >>=? fun (ctx, _size) -> Sapling_storage.Commitments.get_root ctx id >>= wrap >|=? fun (ctx, root) -> assert (root = expected_root) ; ctx) ctx (0 -- 99) >>=? fun _ctx -> return_unit (* Nullifiers don't check for duplicates are it's done by verify_update, however committing to disk twice the same nf causes a storage error by trying to initialize the same key twice. *) let nullifier_double () = Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size:0 >>= wrap >>=? fun ctx -> let nf = gen_nf () in let open Sapling_storage in let state = {id = Some id; diff = Sapling_storage.empty_diff; memo_size = 0} in let state = nullifiers_add state nf in let state = nullifiers_add state nf in assert (Compare.List_length_with.(state.diff.nullifiers = 2)) ; Sapling_storage.Nullifiers.size ctx id >>= wrap >>=? fun disk_size -> assert (disk_size = 0L) ; Sapling_storage.apply_diff ctx id state.diff |> assert_error (* In this test we add two lists of nullifiers to the state, one is applied to the context (committed to disk) and one is kept in kept in a diff (only in memory). We then check that nullifier_mem answers true for those two lists and false for a third one. *) let nullifier_test () = Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size:0 >>= wrap >>=? fun ctx -> let nf_list_ctx = List.init ~when_negative_length:() 10 (fun _ -> gen_nf ()) |> function | Error () -> assert false (* 10 > 0 *) | Ok nf_list_ctx -> nf_list_ctx in let state = List.fold_left (fun state nf -> Sapling_storage.nullifiers_add state nf) {id = Some id; diff = Sapling_storage.empty_diff; memo_size = 0} nf_list_ctx in Sapling_storage.apply_diff ctx id state.diff >>= wrap >>=? fun (ctx, _) -> let nf_list_diff = List.init ~when_negative_length:() 10 (fun _ -> gen_nf ()) |> function | Error () -> assert false (* 10 > 0 *) | Ok nf_list_diff -> nf_list_diff in let state = List.fold_left (fun state nf -> Sapling_storage.nullifiers_add state nf) state nf_list_diff in List.iter_ep (fun nf -> Sapling_storage.nullifiers_mem ctx state nf >>= wrap >>=? fun (_, bool) -> assert bool ; return_unit) (nf_list_ctx @ nf_list_diff) >>=? fun () -> let nf_list_absent = List.init 10 ~when_negative_length:() (fun _ -> gen_nf ()) |> function | Error () -> assert false (* 10 > 0 *) | Ok nf_list_absent -> nf_list_absent in List.iter_ep (fun nf -> Sapling_storage.nullifiers_mem ctx state nf >>= wrap >>=? fun (_, bool) -> assert (not bool) ; return_unit) nf_list_absent (* This test applies a diff with tuples of ciphertext, commitment. Then it checks the result of get_from with different indexes. *) let cm_cipher_test () = Random.self_init () ; let memo_size = Random.int 200 in Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size >>= wrap >>=? fun ctx -> Sapling_storage.state_from_id ctx id >>= wrap >>=? fun (diff, ctx) -> let list_added = List.init ~when_negative_length:() 10 (fun _ -> gen_cm_cipher ~memo_size ()) |> function | Error () -> assert false (* 10 > 0 *) | Ok list_added -> list_added in let state = Sapling_storage.add diff list_added in Sapling_storage.apply_diff ctx id state.diff >>= wrap >>=? fun (ctx, _) -> let rec test_from from until expected = if from > until then return_unit else Sapling_storage.Ciphertexts.get_from ctx id from >>= wrap >>=? fun (ctx, result) -> let expected_cipher = List.map snd expected in assert (result = expected_cipher) ; Sapling_storage.Commitments.get_from ctx id from >>= wrap >>=? fun result -> let expected_cm = List.map fst expected in assert (result = expected_cm) ; test_from (Int64.succ from) until (WithExceptions.Option.get ~loc:__LOC__ @@ List.tl expected) in test_from 0L 9L list_added (* This test tests the insertion of a list vs inserting one by one. It does so by checking the equality of the roots. *) let list_insertion_test () = Random.self_init () ; let memo_size = Random.int 200 in Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id_one_by_one) -> Sapling_storage.init ctx id_one_by_one ~memo_size >>= wrap >>=? fun ctx -> let list_to_add = fst @@ List.split @@ (List.init ~when_negative_length:() 33 (fun _ -> gen_cm_cipher ~memo_size ()) |> function | Error () -> assert false (* 33 > 0 *) | Ok r -> r) in let rec test counter ctx = if counter >= 32 then return_unit else (* add a single cm to the existing tree *) Sapling_storage.Commitments.add ctx id_one_by_one [ WithExceptions.Option.get ~loc:__LOC__ @@ List.nth list_to_add counter; ] (Int64.of_int counter) >>= wrap (* create a new tree and add a list of cms *) >>=? fun (ctx, _size) -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id_all_at_once) -> Sapling_storage.init ctx id_all_at_once ~memo_size >>= wrap >>=? fun ctx -> Sapling_storage.Commitments.add ctx id_all_at_once (List.init ~when_negative_length:() (counter + 1) (fun i -> WithExceptions.Option.get ~loc:__LOC__ @@ List.nth list_to_add i) |> function | Error () -> assert false (* counter >= 0*) | Ok r -> r) 0L >>= wrap >>=? fun (ctx, _size) -> Sapling_storage.Commitments.get_root ctx id_one_by_one >>= wrap >>=? fun (ctx, root_one_by_one) -> Sapling_storage.Commitments.get_root ctx id_all_at_once >>= wrap >>=? fun (ctx, root_all_at_once) -> assert (root_all_at_once = root_one_by_one) ; test (counter + 1) ctx in test 0 ctx (* This test adds 10 more roots the maximum capacity, all at different levels, and checks that all but the first 10 are stored. Then it adds one in the diff and checks it is stored. Then it adds 10 at the same level and check that only the last one is stored. *) let root_test () = let open Tezos_sapling.Core in let gen_root () = Data_encoding.Binary.of_bytes_exn Validator.Hash.encoding (Hacl.Rand.gen 32) in let roots_ctx = List.init ~when_negative_length:() (Int32.to_int Sapling_storage.Roots.size + 10) (fun _ -> gen_root ()) |> function | Error () -> assert false (* size >= 0 *) | Ok roots_ctx -> roots_ctx in Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size:0 >>= wrap >>=? fun ctx -> (* Add one root per level to the context *) List.fold_left_es (fun (ctx, cnt) root -> Sapling_storage.Roots.add ctx id root >>= wrap >>=? fun ctx -> (* Very low level way to "bake" a block. It would be better to use the helpers functions but they complicate the access to the raw_context. *) Raw_context.prepare ~level:(Int32.add b.header.shell.level cnt) ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp (Raw_context.recover ctx) >>= wrap >|=? fun ctx -> (ctx, Int32.succ cnt)) (ctx, 0l) roots_ctx >>=? fun (ctx, _) -> (* Check mem on all the roots in the context. *) let state = Sapling_storage. {id = Some id; diff = Sapling_storage.empty_diff; memo_size = 0} in List.fold_left_es (fun i root -> Sapling_storage.root_mem ctx state root >>= wrap >|=? fun bool -> assert (if i < 10 then not bool else bool) ; i + 1) 0 roots_ctx >>=? fun _ -> (* Add roots w/o increasing the level *) let roots_same_level = List.init ~when_negative_length:() 10 (fun _ -> gen_root ()) |> function | Error () -> assert false (* 10 > 0 *) | Ok roots_same_level -> roots_same_level in List.fold_left_es (fun ctx root -> Sapling_storage.Roots.add ctx id root >>= wrap) ctx roots_same_level >>=? fun ctx -> List.fold_left_es (fun (i, ctx) root -> Sapling_storage.root_mem ctx state root >>= wrap >|=? fun bool -> assert (if i < 9 then not bool else bool) ; (i + 1, ctx)) (0, ctx) roots_same_level >>=? fun _ -> return_unit let test_get_memo_size () = Context.init 1 >>=? fun (b, _) -> Raw_context.prepare b.context ~level:b.header.shell.level ~predecessor_timestamp:b.header.shell.timestamp ~timestamp:b.header.shell.timestamp >>= wrap >>=? fun ctx -> Lazy_storage_diff.fresh Lazy_storage_kind.Sapling_state ~temporary:false ctx >>= wrap >>=? fun (ctx, id) -> Sapling_storage.init ctx id ~memo_size:0 >>= wrap >>=? fun ctx -> Sapling_storage.get_memo_size ctx id >>= wrap >|=? fun memo_size -> assert (memo_size = 0) end module Alpha_context_tests = struct open Sapling_helpers.Alpha_context_helpers (* Create a transaction with memo_size 1, test that is validates with a newly created empty_state with memo_size 1 and does not with memo_size 0. *) let test_verify_memo () = init () >>=? fun ctx -> let sk = Tezos_sapling.Core.Wallet.Spending_key.of_seed (Tezos_crypto.Hacl.Rand.gen 32) in let vt = let ps = Tezos_sapling.Storage.empty ~memo_size:0 in (* the dummy output will have memo_size 0 *) Tezos_sapling.Forge.forge_transaction ~number_dummy_outputs:1 [] [] sk "anti-replay" ps in verify_update ctx vt ~memo_size:0 |> assert_some >>=? fun _ -> verify_update ctx vt ~memo_size:1 |> assert_none (* Bench the proving and validation time of shielding and transferring several tokens. *) let test_bench_phases () = init () >>=? fun ctx -> let rounds = 5 in Printf.printf "\nrounds: %d\n" rounds ; let w = wallet_gen () in let cs = Tezos_sapling.Storage.empty ~memo_size:8 in (* one verify_update to get the id *) let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id) -> client_state_alpha ctx id >>=? fun cs -> let start = Unix.gettimeofday () in let vts = List.map (fun _ -> transfer w cs []) (1 -- rounds) in let ctime_shields = Unix.gettimeofday () -. start in Printf.printf "client_shields %f\n" ctime_shields ; let start = Unix.gettimeofday () in List.fold_left_es (fun ctx vt -> verify_update ctx ~id vt |> assert_some >|=? fun (ctx, _id) -> ctx) ctx vts >>=? fun ctx -> let vtime_shields = Unix.gettimeofday () -. start in Printf.printf "valdtr_shields %f\n" vtime_shields ; client_state_alpha ctx id >>=? fun cs -> let start = Unix.gettimeofday () in let vts = List.map (fun i -> transfer w cs [i]) (1 -- rounds) in let ctime_transfers = Unix.gettimeofday () -. start in Printf.printf "client_txs %f\n" ctime_transfers ; let start = Unix.gettimeofday () in List.fold_left_es (fun ctx vt -> verify_update ctx ~id vt |> assert_some >|=? fun (ctx, _id) -> ctx) ctx vts >|=? fun _ctx -> let vtime_transfers = Unix.gettimeofday () -. start in Printf.printf "valdtr_txs %f\n" vtime_transfers (* Transfer several times the same token. *) let test_bench_fold_over_same_token () = init () >>=? fun ctx -> let rounds = 5 in let w = wallet_gen () in let cs = Tezos_sapling.Storage.empty ~memo_size:8 in (* one verify_update to get the id *) let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id) -> let rec loop cnt ctx = if cnt >= rounds then return_unit else (* inefficient: re-synch from scratch at each round *) client_state_alpha ctx id >>=? fun cs -> let vt = transfer w cs [cnt] in verify_update ctx ~id vt |> assert_some >>=? fun (ctx, _id) -> loop (cnt + 1) ctx in loop 0 ctx (* The following tests trigger all the branches of Sapling_validator.verify_update. The function performs several checks and returns None in case of failure. During development the function was modified to throw a different exception for each of its checks so to be sure that they were reached. *) (* Test that double spending the same input fails the nf check. *) let test_double_spend_same_input () = init () >>=? fun ctx -> let w = wallet_gen () in let cs = Tezos_sapling.Storage.empty ~memo_size:8 in (* one verify_update to get the id *) let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id) -> client_state_alpha ctx id >>=? fun cs -> let vt = transfer w cs [0] in verify_update ctx ~id vt |> assert_some >>=? fun (_ctx, id) -> let vt = transfer w cs [0; 0] in verify_update ctx ~id vt |> assert_none let test_verifyupdate_one_transaction () = init () >>=? fun ctx -> let w = wallet_gen () in let cs = Tezos_sapling.Storage.empty ~memo_size:8 in let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id) -> client_state_alpha ctx id >>=? fun cs -> let vt = transfer w cs [0] in (* fails sig check because of wrong balance *) let vt_broken = Tezos_sapling.Core.Validator.UTXO. {vt with balance = Int64.(succ vt.balance)} in verify_update ctx ~id vt_broken |> assert_none >>=? fun () -> (* randomize one output to fail check outputs *) (* don't randomize the ciphertext as it is not part of the proof *) let open Tezos_sapling.Core.Client.UTXO in let o = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd vt.outputs in let o_wrong_cm = { o with cm = randomized_byte o.cm Tezos_sapling.Core.Client.Commitment.encoding; } in let vt_broken = Tezos_sapling.Core.Validator.UTXO.{vt with outputs = [o_wrong_cm]} in verify_update ctx ~id vt_broken |> assert_none >>=? fun () -> (* position inside the cv *) let pos = Random.int 32 in let o_wrong_cv = { o with ciphertext = randomized_byte ~pos o.ciphertext Tezos_sapling.Core.Client.Ciphertext.encoding; } in let vt_broken = Tezos_sapling.Core.Validator.UTXO.{vt with outputs = [o_wrong_cv]} in verify_update ctx ~id vt_broken |> assert_none let test_verifyupdate_two_transactions () = init () >>=? fun ctx -> let w = wallet_gen () in let cs = Tezos_sapling.Storage.empty ~memo_size:8 in (* generate the first storage *) let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id1) -> client_state_alpha ctx id1 >>=? fun cs1 -> let vt1 = transfer w cs1 [0] in (* generate the second storage *) let vt = transfer w cs [] in verify_update ctx vt |> assert_some >>=? fun (ctx, id2) -> client_state_alpha ctx id2 >>=? fun cs2 -> let vt2 = transfer w cs2 [0] in (* fail root check *) verify_update ctx ~id:id1 vt2 |> assert_none >>=? fun () -> (* Swap the root so that it passes the root_mem check but fails the input check *) let vt1_broken = Tezos_sapling.Core.Validator.UTXO.{vt2 with root = vt1.root} in verify_update ctx ~id:id1 vt1_broken |> assert_none >>=? fun () -> (* fail the sig check *) let vt1_broken = Tezos_sapling.Core.Validator.UTXO.{vt1 with outputs = vt2.outputs} in verify_update ctx ~id:id1 vt1_broken |> assert_none end module Interpreter_tests = struct open Sapling_helpers.Interpreter_helpers let parameters_of_list transactions = let string = "{ " ^ String.concat " ; " transactions ^ " }" in Alpha_context.Script.(lazy_expr (Expr.from_string string)) (* In this test we use a contract which takes a list of transactions, applies all of them, and assert all of them are correct. It also enforces a 1-to-1 conversion with mutez by asking an amount to shield and asking for a pkh to unshield. We create 2 keys a and b. We originate the contract, then do two lists of shield for a, then transfers several outputs to b while unshielding, then transfer all of b inputs to a while adding dummy inputs and outputs. At last we fail we make a failing transaction. *) let test_shielded_tez () = init () >>=? fun (genesis, baker, src0, src1) -> let memo_size = 8 in originate_contract "contracts/sapling_contract.tz" "{ }" src0 genesis baker >>=? fun (dst, b1, anti_replay) -> let wa = wallet_gen () in let (list_transac, total) = shield ~memo_size wa.sk 4 wa.vk (Format.sprintf "Pair 0x%s None") anti_replay in let parameters = parameters_of_list list_transac in (* a does a list of shield transaction *) transac_and_sync ~memo_size b1 parameters total src0 dst baker >>=? fun (b2, _state) -> (* we shield again on another block, forging with the empty state *) let (list_transac, total) = shield ~memo_size wa.sk 4 wa.vk (Format.sprintf "Pair 0x%s None") anti_replay in let parameters = parameters_of_list list_transac in (* a does a list of shield transaction *) transac_and_sync ~memo_size b2 parameters total src0 dst baker >>=? fun (b3, state) -> (* address that will receive an unshield *) Context.Contract.balance (B b3) src1 >>=? fun balance_before_shield -> (* address that will receive an unshield *) let wb = wallet_gen () in let list_addr = gen_addr 15 wb.vk in let list_forge_input = List.init ~when_negative_length:() 14 (fun pos_int -> let pos = Int64.of_int pos_int in let forge_input = snd (Tezos_sapling.Forge.Input.get state pos wa.vk |> WithExceptions.Option.get ~loc:__LOC__) in forge_input) |> function | Error () -> assert false (* 14 > 0 *) | Ok list_forge_input -> list_forge_input in let list_forge_output = List.map (fun addr -> Tezos_sapling.Forge.make_output addr 1L (Bytes.create 8)) list_addr in let hex_transac = to_hex (Tezos_sapling.Forge.forge_transaction ~number_dummy_inputs:0 ~number_dummy_outputs:0 list_forge_input list_forge_output wa.sk anti_replay state) Tezos_sapling.Core.Client.UTXO.transaction_encoding in let hex_pkh = to_hex (Alpha_context.Contract.is_implicit src1 |> WithExceptions.Option.get ~loc:__LOC__) Signature.Public_key_hash.encoding in let string = Format.sprintf "{Pair 0x%s (Some 0x%s) }" hex_transac hex_pkh in let parameters = Alpha_context.Script.(lazy_expr (Expr.from_string string)) in (* a transfers to b and unshield some money to src_2 (the pkh) *) transac_and_sync ~memo_size b3 parameters 0 src0 dst baker >>=? fun (b4, state) -> Context.Contract.balance (B b4) src1 >>=? fun balance_after_shield -> let diff_due_to_shield = Int64.sub (Test_tez.to_mutez balance_after_shield) (Test_tez.to_mutez balance_before_shield) in (* The balance after shield is obtained from the balance before shield by the shield specific update. *) (* The inputs total [total] mutez and 15 of those are transfered in shielded tez *) Assert.equal_int ~loc:__LOC__ (Int64.to_int diff_due_to_shield) (total - 15) >>=? fun () -> let list_forge_input = List.init ~when_negative_length:() 15 (fun i -> let pos = Int64.of_int (i + 14 + 14) in let forge_input = snd (Tezos_sapling.Forge.Input.get state pos wb.vk |> WithExceptions.Option.get ~loc:__LOC__) in forge_input) |> function | Error () -> assert false (* 14 > 0 *) | Ok list_forge_input -> list_forge_input in let addr_a = snd @@ Tezos_sapling.Core.Client.Viewing_key.new_address wa.vk Tezos_sapling.Core.Client.Viewing_key.default_index in let output = Tezos_sapling.Forge.make_output addr_a 15L (Bytes.create 8) in let hex_transac = to_hex (Tezos_sapling.Forge.forge_transaction ~number_dummy_inputs:2 ~number_dummy_outputs:2 list_forge_input [output] wb.sk anti_replay state) Tezos_sapling.Core.Client.UTXO.transaction_encoding in let string = Format.sprintf "{Pair 0x%s None }" hex_transac in let parameters = Alpha_context.Script.(lazy_expr (Expr.from_string string)) in (* b transfers to a with dummy inputs and outputs *) transac_and_sync ~memo_size b4 parameters 0 src0 dst baker >>=? fun (b, _state) -> (* Here we fail by doing the same transaction again*) Incremental.begin_construction b >>=? fun incr -> let fee = Test_tez.of_int 10 in Op.transaction ~fee (B b) src0 dst Tez.zero ~parameters >>=? fun operation -> Incremental.add_operation (* TODO make more precise *) ~expect_failure:(fun _ -> return_unit) incr operation >>=? fun _incr -> return_unit let test_push_sapling_state_should_be_forbidden () = init () (* Originating a contract to get a sapling_state with ID 0, used in the next contract *) >>=? fun (block, baker, src, _) -> originate_contract "contracts/sapling_contract.tz" "{ }" src block baker >>=? fun _ -> (* Originating the next contract should fail *) originate_contract "contracts/sapling_push_sapling_state.tz" "{ }" src block baker >>= function | Error [ Environment.Ecoproto_error (Script_tc_errors.Ill_typed_contract _); Environment.Ecoproto_error (Script_tc_errors.Unexpected_lazy_storage _); ] -> return_unit | _ -> assert false let test_use_state_from_other_contract_and_transact () = (* Attempt to use a sapling state of a contract A in a contract B *) init () (* Originating the contracts *) >>=? fun (block, baker, src, _) -> let memo_size = 8 in (* originate_contract "contracts/sapling_contract.tz" "{ }" src block baker >>=? fun (_shielded_pool_contract_address, block, _anti_replay_shielded_pool) -> *) originate_contract "contracts/sapling_use_existing_state.tz" "{ }" src block baker >>=? fun (existing_state_contract_address, block, anti_replay_2) -> (* we create one shielding transaction and transform it in Micheline to use it as a parameter *) let wa = wallet_gen () in let (transactions, _total) = shield ~memo_size wa.sk 1 wa.vk (Format.sprintf "(Pair 0x%s 0)") anti_replay_2 in let transaction = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd transactions in let parameters = Alpha_context.Script.(lazy_expr (Expr.from_string transaction)) in transac_and_sync ~memo_size block parameters 0 src existing_state_contract_address baker >|= function | Ok _ -> Alcotest.failf "Unexpected operations success" | Error errs -> assert ( List.exists (function | Environment.Ecoproto_error (Tezos_raw_protocol_alpha.Script_tc_errors .Unexpected_forged_value _) -> true | _ -> false) errs) ; Result.return_unit (* In this test we do two transactions in one block and same two in two block. We check that the sate is the same expect for roots. The second transaction is possible only if the first one is done. *) let test_transac_and_block () = init () >>=? fun (b, baker, src, _) -> let memo_size = 8 in originate_contract "contracts/sapling_contract.tz" "{ }" src b baker >>=? fun (dst, block_start, anti_replay) -> let {sk; vk} = wallet_gen () in let hex_transac_1 = hex_shield ~memo_size {sk; vk} anti_replay in let string_1 = Format.sprintf "{Pair %s None }" hex_transac_1 in let parameters_1 = Alpha_context.Script.(lazy_expr (Expr.from_string string_1)) in transac_and_sync ~memo_size block_start parameters_1 15 src dst baker >>=? fun (block_1, state) -> let intermediary_root = Tezos_sapling.Storage.get_root state in let addr = snd @@ Tezos_sapling.Core.Wallet.Viewing_key.(new_address vk default_index) in let output = Tezos_sapling.Forge.make_output addr 15L (Bytes.create 8) in let hex_transac_2 = "0x" ^ to_hex (Tezos_sapling.Forge.forge_transaction [ snd (Tezos_sapling.Forge.Input.get state 0L vk |> WithExceptions.Option.get ~loc:__LOC__); ] [output] sk anti_replay state) Tezos_sapling.Core.Client.UTXO.transaction_encoding in let string_2 = Format.sprintf "{Pair %s None }" hex_transac_2 in let parameters_2 = Alpha_context.Script.(lazy_expr (Expr.from_string string_2)) in transac_and_sync ~memo_size block_1 parameters_2 0 src dst baker >>=? fun (block_1, state_1) -> let final_root = Tezos_sapling.Storage.get_root state_1 in Alpha_services.Contract.single_sapling_get_diff Block.rpc_ctxt block_1 dst ~offset_commitment:0L ~offset_nullifier:0L () >>=? fun (_root, diff_1) -> let fee = Test_tez.of_int 10 in Tez.one_mutez *? Int64.of_int 15 >>?= fun amount_tez -> Op.transaction ~fee (B block_start) src dst amount_tez ~parameters:parameters_1 >>=? fun operation -> Incremental.begin_construction block_start >>=? fun incr -> Incremental.add_operation incr operation >>=? fun incr -> (* We need to manually get the counter here *) let ctx = Incremental.alpha_ctxt incr in let pkh = Alpha_context.Contract.is_implicit src |> WithExceptions.Option.get ~loc:__LOC__ in Alpha_context.Contract.get_counter ctx pkh >>= wrap >>=? fun counter -> Op.transaction ~counter ~fee (B block_start) src dst Tez.zero ~parameters:parameters_2 >>=? fun operation -> Incremental.add_operation incr operation >>=? fun incr -> Incremental.finalize_block incr >>=? fun block_2 -> Alpha_services.Contract.single_sapling_get_diff Block.rpc_ctxt block_2 dst ~offset_commitment:0L ~offset_nullifier:0L () >>=? fun (_root, diff_2) -> (* We check that the same transactions have passed *) assert (diff_1 = diff_2) ; let is_root_in block dst root = Incremental.begin_construction block >>=? fun incr -> let ctx_2 = Incremental.alpha_ctxt incr in Alpha_services.Contract.script Block.rpc_ctxt block dst >>=? fun script -> let ctx_without_gas_2 = Alpha_context.Gas.set_unlimited ctx_2 in Script_ir_translator.parse_script ctx_without_gas_2 ~legacy:true ~allow_forged_in_storage:true script >>= wrap >>=? fun (Ex_script script, ctxt) -> Script_ir_translator.get_single_sapling_state ctxt script.storage_type script.storage |> wrap >>=? fun (id, _ctx_2) -> let single_id = WithExceptions.Option.get ~loc:__LOC__ id in let id = Lazy_storage_kind.Sapling_state.Id.parse_z @@ Alpha_context.Sapling.Id.unparse_to_z single_id in Raw_context.prepare block.context ~level:block.header.shell.level ~predecessor_timestamp:block.header.shell.timestamp ~timestamp:block.header.shell.timestamp >>= wrap >>=? fun raw_ctx -> Sapling_storage.Roots.mem raw_ctx id root >>= wrap in (* We check that the second state did not store the root in between transactions. *) is_root_in block_2 dst intermediary_root |> assert_false >>=? fun () -> (* We check that the second state did store the final root. *) is_root_in block_2 dst final_root |> assert_true >>=? fun () -> (* We check that the first state did store the final root. *) is_root_in block_1 dst final_root |> assert_true >>=? fun () -> (* We check that the first state did store the root in between transactions. *) is_root_in block_1 dst intermediary_root |> assert_true (* In this test we try a contract which creates an empty sapling state on the fly. It then applies a list of transactions, checks they are correct and drops the result. We make several shields in the same list (since the state is drop). *) let test_drop () = init () >>=? fun (b, baker, src, _) -> originate_contract "contracts/sapling_contract_drop.tz" "Unit" src b baker >>=? fun (dst, b, anti_replay) -> let {sk; vk} = wallet_gen () in let (list_transac, _total) = shield ~memo_size:8 sk 4 vk (Format.sprintf "0x%s") anti_replay in let parameters = parameters_of_list list_transac in Op.transaction ~fee:(Test_tez.of_int 10) (B b) src dst Tez.zero ~parameters >>=? fun operation -> next_block b operation >>=? fun _b -> return_unit (* We use a contrac with two states. Its parameter is two transactions and a bool. The two transactions are tested valid against the two states, but only one state according to the bool is updated. We do two transactions shielding to different keys in the two states. At each transactions both are applied but only state is updated. We then check that the first state is updated in the correct way. *) let test_double () = init () >>=? fun (b, baker, src, _) -> let memo_size = 8 in originate_contract "contracts/sapling_contract_double.tz" "(Pair { } { })" src b baker >>=? fun (dst, b, anti_replay) -> let wa = wallet_gen () in let hex_transac_1 = hex_shield ~memo_size wa anti_replay in let wb = wallet_gen () in let hex_transac_2 = hex_shield ~memo_size wb anti_replay in let str_1 = "(Pair True (Pair " ^ hex_transac_1 ^ " " ^ hex_transac_2 ^ "))" in let str_2 = "(Pair False (Pair " ^ hex_transac_2 ^ " " ^ hex_transac_1 ^ "))" in (* transac 1 is applied to state_1*) let parameters_1 = Alpha_context.Script.(lazy_expr (Expr.from_string str_1)) in (* tranasc_2 is applied to state_2*) let parameters_2 = Alpha_context.Script.(lazy_expr (Expr.from_string str_2)) in let fee = Test_tez.of_int 10 in Op.transaction ~fee (B b) src dst Tez.zero ~parameters:parameters_1 >>=? fun operation -> next_block b operation >>=? fun b -> Op.transaction ~fee (B b) src dst Tez.zero ~parameters:parameters_2 >>=? fun operation -> next_block b operation >>=? fun b -> Incremental.begin_construction b >>=? fun incr -> let ctx = Incremental.alpha_ctxt incr in let ctx_without_gas = Alpha_context.Gas.set_unlimited ctx in Alpha_services.Contract.storage Block.rpc_ctxt b dst >>=? fun storage -> let storage_lazy_expr = Alpha_context.Script.lazy_expr storage in (let memo_size = memo_size_of_int memo_size in let open Script_typed_ir in let state_ty = sapling_state_t ~memo_size ~annot:None in pair_t (-1) (state_ty, None, None) (state_ty, None, None) ~annot:None) >>??= fun tytype -> Script_ir_translator.parse_storage ctx_without_gas ~legacy:true ~allow_forged:true tytype ~storage:storage_lazy_expr >>= wrap >>=? fun ((state_1, state_2), _ctx) -> (*Only works when diff is empty*) let local_state_from_disk disk_state ctx = let id = Alpha_context.Sapling.(disk_state.id) |> WithExceptions.Option.get ~loc:__LOC__ in Alpha_context.Sapling.get_diff ctx id ~offset_commitment:0L ~offset_nullifier:0L () >>= wrap >|=? fun diff -> client_state_of_diff ~memo_size diff in local_state_from_disk state_1 ctx >>=? fun state_1 -> local_state_from_disk state_2 ctx >|=? fun state_2 -> (* we check that first state contains 15 to addr_1 but not 15 to addr_2*) assert (Option.is_some @@ Tezos_sapling.Forge.Input.get state_1 0L wa.vk) ; assert (Option.is_some @@ Tezos_sapling.Forge.Input.get state_2 0L wa.vk) ; assert (Option.is_none @@ Tezos_sapling.Forge.Input.get state_1 0L wb.vk) ; assert (Option.is_none @@ Tezos_sapling.Forge.Input.get state_2 0L wb.vk) let test_state_as_arg () = init () >>=? fun (b, baker, src, _) -> originate_contract "contracts/sapling_contract_state_as_arg.tz" "None" src b baker >>=? fun (dst, b, anti_replay) -> originate_contract "contracts/sapling_contract_send.tz" "Unit" src b baker >>=? fun (dst_2, b, anti_replay_2) -> let w = wallet_gen () in let hex_transac_1 = hex_shield ~memo_size:8 w anti_replay in let string = "Left " ^ hex_transac_1 in let parameters = Alpha_context.Script.(lazy_expr (Expr.from_string string)) in let fee = Test_tez.of_int 10 in Op.transaction ~fee (B b) src dst Tez.zero ~parameters >>=? fun operation -> next_block b operation >>=? fun b -> let contract = "0x" ^ to_hex dst Alpha_context.Contract.encoding in let hex_transac_2 = hex_shield ~memo_size:8 w anti_replay_2 in let string = "(Pair " ^ contract ^ " " ^ hex_transac_2 ^ ")" in let parameters = Alpha_context.Script.(lazy_expr (Expr.from_string string)) in Op.transaction ~fee (B b) src dst_2 Tez.zero ~parameters >>=? fun operation -> next_block b operation >>=? fun _b -> return_unit end let tests = [ Tztest.tztest "commitments_add_uncommitted" `Quick Raw_context_tests.commitments_add_uncommitted; Tztest.tztest "nullifier_double" `Quick Raw_context_tests.nullifier_double; Tztest.tztest "nullifier_test" `Quick Raw_context_tests.nullifier_test; Tztest.tztest "cm_cipher_test" `Quick Raw_context_tests.cm_cipher_test; Tztest.tztest "list_insertion_test" `Quick Raw_context_tests.list_insertion_test; Tztest.tztest "root" `Quick Raw_context_tests.root_test; Tztest.tztest "test_get_memo_size" `Quick Raw_context_tests.test_get_memo_size; Tztest.tztest "test_verify_memo" `Quick Alpha_context_tests.test_verify_memo; Tztest.tztest "test_bench_phases" `Slow Alpha_context_tests.test_bench_phases; Tztest.tztest "test_bench_fold_over_same_token" `Slow Alpha_context_tests.test_bench_fold_over_same_token; Tztest.tztest "test_double_spend_same_input" `Quick Alpha_context_tests.test_double_spend_same_input; Tztest.tztest "test_verifyupdate_one_transaction" `Quick Alpha_context_tests.test_verifyupdate_one_transaction; Tztest.tztest "test_verifyupdate_two_transactions" `Quick Alpha_context_tests.test_verifyupdate_two_transactions; Tztest.tztest "test_shielded_tez" `Quick Interpreter_tests.test_shielded_tez; Tztest.tztest "test use state from other contract and transact" `Quick Interpreter_tests.test_use_state_from_other_contract_and_transact; Tztest.tztest "Instruction PUSH sapling_state 0 should be forbidden" `Quick Interpreter_tests.test_push_sapling_state_should_be_forbidden; Tztest.tztest "test_transac_and_block" `Quick Interpreter_tests.test_transac_and_block; Tztest.tztest "test_drop" `Quick Interpreter_tests.test_drop; Tztest.tztest "test_double" `Quick Interpreter_tests.test_double; Tztest.tztest "test_state_as_arg" `Quick Interpreter_tests.test_state_as_arg; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
shared.ml
open Core open Async include Delimited_kernel.Shared let drop_lines r lines = let rec loop n = if n = 0 then Deferred.unit else ( match%bind Reader.read_line r with | `Ok _ -> loop (n - 1) | `Eof -> failwithf "file has fewer than %i lines" lines ()) in loop lines ;;
test_tree_encoding.ml
(** Testing ------- Component: Lib_tree_encoding Invocation: dune runtest src/lib_tree_encoding/ Subject: Tests for the tree-encoding library *) let () = Alcotest_lwt.run "test lib tree encoding" [("Encodings", Test_encoding.tests); ("Proofs", Test_proofs.tests)] |> Lwt_main.run
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Trili Tech <contact@trili.tech> *) (* *) (* 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. *) (* *) (*****************************************************************************)
cycle_repr.mli
type t type cycle = t include Compare.S with type t := t val encoding : cycle Data_encoding.t val rpc_arg : cycle RPC_arg.arg val pp : Format.formatter -> cycle -> unit val root : cycle val pred : cycle -> cycle option val add : cycle -> int -> cycle val sub : cycle -> int -> cycle option val succ : cycle -> cycle val to_int32 : cycle -> int32 val of_int32_exn : int32 -> cycle module Map : S.MAP with type key = cycle module Index : Storage_description.INDEX with type t = cycle
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
zh.mli
module N : sig type encoder type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ] type ret = [ `Flush of encoder | `End ] val dst_rem : encoder -> int val dst : encoder -> Zl.bigstring -> int -> int -> encoder val encode : encoder -> ret val encoder : ?level:int -> i:Zl.bigstring -> q:De.Queue.t -> w:De.Lz77.window -> source:int -> H.bigstring -> dst -> Duff.hunk list -> encoder end module M : sig type decoder type src = [ `Channel of in_channel | `String of string | `Manual ] type decode = [ `Await of decoder | `Header of int * int * decoder | `End of decoder | `Malformed of string ] val src_len : decoder -> int val dst_len : decoder -> int val src_rem : decoder -> int val dst_rem : decoder -> int val src : decoder -> Zl.bigstring -> int -> int -> decoder val dst : decoder -> H.bigstring -> int -> int -> decoder val source : decoder -> H.bigstring -> decoder val decode : decoder -> decode val decoder : ?source:H.bigstring -> o:Zl.bigstring -> allocate:(int -> Zl.window) -> src -> decoder end
dune
(rule (targets foo%{ext_obj}) (deps foo.c) (action (run %{ocaml-config:c_compiler} -c -o %{targets} %{deps}))) (rule (targets libfoo_stubs.a) (deps foo%{ext_obj}) (action (run ar rcs %{targets} %{deps}))) (rule (targets dllfoo_stubs%{ext_dll}) (deps foo%{ext_obj}) (action (run %{ocaml-config:c_compiler} -shared -o %{targets} %{deps}))) (library (name bar) (self_build_stubs_archive (foo)) (modules bar)) (executable (name main) (libraries bar) (modules main))
init_storage.mli
(** Functions to setup storage. Used by [Alpha_context.prepare]. If you have defined a new type of storage, you should add relevant setups here. *) (* This is the genesis protocol: initialise the state *) val prepare_first_block : Context.t -> typecheck: (Raw_context.t -> Script_repr.t -> ((Script_repr.t * Lazy_storage_diff.diffs option) * Raw_context.t) Error_monad.tzresult Lwt.t) -> level:int32 -> timestamp:Time.t -> (Raw_context.t, Error_monad.error Error_monad.trace) Pervasives.result Lwt.t val prepare : Context.t -> level:Int32.t -> predecessor_timestamp:Time.t -> timestamp:Time.t -> (Raw_context.t * Receipt_repr.balance_updates * Migration_repr.origination_result list) Error_monad.tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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
(tests (names lexer printing capabilities) (libraries alcotest junit_alcotest spectrum))
dune
(library (name parsexp_prefix_test) (libraries core_kernel.composition_infix core expect_test_helpers_core parsexp parsexp_prefix parsexp_symbolic_automaton sexp_string_quickcheck tilde_f) (preprocess (pps ppx_jane)))
fpa2bv_converter.h
#pragma once #include "ast/ast.h" #include "util/obj_hashtable.h" #include "util/ref_util.h" #include "ast/fpa_decl_plugin.h" #include "ast/bv_decl_plugin.h" #include "ast/array_decl_plugin.h" #include "ast/datatype_decl_plugin.h" #include "ast/dl_decl_plugin.h" #include "ast/pb_decl_plugin.h" #include "ast/seq_decl_plugin.h" #include "ast/rewriter/bool_rewriter.h" #include "ast/rewriter/th_rewriter.h" class fpa2bv_converter { public: typedef obj_map<func_decl, std::pair<app *, app *> > special_t; typedef obj_map<func_decl, expr*> const2bv_t; typedef obj_map<func_decl, func_decl*> uf2bvuf_t; protected: ast_manager & m; bool_rewriter m_simp; bv_util m_bv_util; arith_util m_arith_util; datatype_util m_dt_util; seq_util m_seq_util; fpa_util m_util; mpf_manager & m_mpf_manager; unsynch_mpz_manager & m_mpz_manager; fpa_decl_plugin * m_plugin; bool m_hi_fp_unspecified; const2bv_t m_const2bv; const2bv_t m_rm_const2bv; uf2bvuf_t m_uf2bvuf; special_t m_min_max_ufs; friend class fpa2bv_model_converter; friend class bv2fpa_converter; public: fpa2bv_converter(ast_manager & m); virtual ~fpa2bv_converter(); fpa_util & fu() { return m_util; } bv_util & bu() { return m_bv_util; } arith_util & au() { return m_arith_util; } bool is_float(sort * s) { return m_util.is_float(s); } bool is_float(expr * e) { return is_app(e) && m_util.is_float(to_app(e)->get_decl()->get_range()); } bool is_rm(expr * e) { return is_app(e) && m_util.is_rm(e); } bool is_rm(sort * s) { return m_util.is_rm(s); } bool is_float_family(func_decl * f) { return f->get_family_id() == m_util.get_family_id(); } void mk_fp(func_decl * f, unsigned num, expr * const * args, expr_ref & result); // void split_fp(expr * e, expr * & sgn, expr * & exp, expr * & sig) const; void split_fp(expr * e, expr_ref & sgn, expr_ref & exp, expr_ref & sig) const; void join_fp(expr * e, expr_ref & res); void mk_eq(expr * a, expr * b, expr_ref & result); void mk_ite(expr * c, expr * t, expr * f, expr_ref & result); void mk_distinct(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_rounding_mode(decl_kind k, expr_ref & result); void mk_numeral(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_numeral(sort * s, mpf const & v, expr_ref & result); virtual void mk_const(func_decl * f, expr_ref & result); virtual void mk_rm_const(func_decl * f, expr_ref & result); virtual void mk_uf(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_var(unsigned base_inx, sort * srt, expr_ref & result); void mk_pinf(func_decl * f, expr_ref & result); void mk_ninf(func_decl * f, expr_ref & result); void mk_nan(func_decl * f, expr_ref & result); void mk_nzero(func_decl *f, expr_ref & result); void mk_pzero(func_decl *f, expr_ref & result); void mk_add(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_sub(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_neg(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_mul(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_div(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_rem(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_abs(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_fma(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_sqrt(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_round_to_integral(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_abs(sort * s, expr_ref & x, expr_ref & result); void mk_float_eq(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_float_lt(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_float_gt(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_float_le(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_float_ge(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_float_eq(sort * s, expr_ref & x, expr_ref & y, expr_ref & result); void mk_float_lt(sort * s, expr_ref & x, expr_ref & y, expr_ref & result); void mk_float_gt(sort *, expr_ref & x, expr_ref & y, expr_ref & result); void mk_float_le(sort * s, expr_ref & x, expr_ref & y, expr_ref & result); void mk_float_ge(sort * s, expr_ref & x, expr_ref & y, expr_ref & result); void mk_is_zero(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_nzero(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_pzero(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_negative(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_positive(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_nan(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_inf(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_normal(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_is_subnormal(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_fp(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_fp_float(func_decl * f, sort * s, expr * rm, expr * x, expr_ref & result); void mk_to_fp_signed(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_fp_unsigned(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_ieee_bv(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_ieee_bv_unspecified(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_ieee_bv_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_fp_real(func_decl * f, sort * s, expr * rm, expr * x, expr_ref & result); void mk_to_fp_real_int(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_ubv(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_sbv(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_ubv_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_sbv_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_bv_unspecified(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_real(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_real_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_to_real_unspecified(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void set_unspecified_fp_hi(bool v) { m_hi_fp_unspecified = v; } void mk_min(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_max(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_min_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); void mk_max_i(func_decl * f, unsigned num, expr * const * args, expr_ref & result); expr_ref mk_min_max_unspecified(func_decl * f, expr * x, expr * y); void reset(); void dbg_decouple(const char * prefix, expr_ref & e); expr_ref_vector m_extra_assertions; special_t const & get_min_max_specials() const { return m_min_max_ufs; }; const2bv_t const & get_const2bv() const { return m_const2bv; }; const2bv_t const & get_rm_const2bv() const { return m_rm_const2bv; }; uf2bvuf_t const & get_uf2bvuf() const { return m_uf2bvuf; }; protected: void mk_one(func_decl *f, expr_ref & sign, expr_ref & result); void mk_is_nan(expr * e, expr_ref & result); void mk_is_inf(expr * e, expr_ref & result); void mk_is_pinf(expr * e, expr_ref & result); void mk_is_ninf(expr * e, expr_ref & result); void mk_is_pos(expr * e, expr_ref & result); void mk_is_neg(expr * e, expr_ref & result); void mk_is_zero(expr * e, expr_ref & result); void mk_is_nzero(expr * e, expr_ref & result); void mk_is_pzero(expr * e, expr_ref & result); void mk_is_denormal(expr * e, expr_ref & result); void mk_is_normal(expr * e, expr_ref & result); void mk_is_rm(expr * e, BV_RM_VAL rm, expr_ref & result); void mk_top_exp(unsigned sz, expr_ref & result); void mk_bot_exp(unsigned sz, expr_ref & result); void mk_min_exp(unsigned ebits, expr_ref & result); void mk_max_exp(unsigned ebits, expr_ref & result); void mk_leading_zeros(expr * e, unsigned max_bits, expr_ref & result); void mk_bias(expr * e, expr_ref & result); void mk_unbias(expr * e, expr_ref & result); void unpack(expr * e, expr_ref & sgn, expr_ref & sig, expr_ref & exp, expr_ref & lz, bool normalize); void round(sort * s, expr_ref & rm, expr_ref & sgn, expr_ref & sig, expr_ref & exp, expr_ref & result); expr_ref mk_rounding_decision(expr * rm, expr * sgn, expr * last, expr * round, expr * sticky); void add_core(unsigned sbits, unsigned ebits, expr_ref & c_sgn, expr_ref & c_sig, expr_ref & c_exp, expr_ref & d_sgn, expr_ref & d_sig, expr_ref & d_exp, expr_ref & res_sgn, expr_ref & res_sig, expr_ref & res_exp); app * mk_fresh_const(char const * prefix, unsigned sz); void mk_to_bv(func_decl * f, unsigned num, expr * const * args, bool is_signed, expr_ref & result); private: void mk_nan(sort * s, expr_ref & result); void mk_nzero(sort * s, expr_ref & result); void mk_pzero(sort * s, expr_ref & result); void mk_zero(sort * s, expr_ref & sgn, expr_ref & result); void mk_ninf(sort * s, expr_ref & result); void mk_pinf(sort * s, expr_ref & result); void mk_one(sort * s, expr_ref & sign, expr_ref & result); void mk_neg(sort * s, expr_ref & x, expr_ref & result); void mk_add(sort * s, expr_ref & bv_rm, expr_ref & x, expr_ref & y, expr_ref & result); void mk_sub(sort * s, expr_ref & bv_rm, expr_ref & x, expr_ref & y, expr_ref & result); void mk_mul(sort * s, expr_ref & bv_rm, expr_ref & x, expr_ref & y, expr_ref & result); void mk_div(sort * s, expr_ref & bv_rm, expr_ref & x, expr_ref & y, expr_ref & result); void mk_rem(sort * s, expr_ref & x, expr_ref & y, expr_ref & result); void mk_round_to_integral(sort * s, expr_ref & rm, expr_ref & x, expr_ref & result); void mk_to_fp_float(sort * s, expr * rm, expr * x, expr_ref & result); func_decl * mk_bv_uf(func_decl * f, sort * const * domain, sort * range); expr_ref nan_wrap(expr * n); expr_ref extra_quantify(expr * e); }; class fpa2bv_converter_wrapped : public fpa2bv_converter { th_rewriter& m_rw; public: fpa2bv_converter_wrapped(ast_manager & m, th_rewriter& rw) : fpa2bv_converter(m), m_rw(rw) {} void mk_const(func_decl * f, expr_ref & result) override; void mk_rm_const(func_decl * f, expr_ref & result) override; app_ref wrap(expr * e); app_ref unwrap(expr * e, sort * s); expr* bv2rm_value(expr* b); expr* bv2fpa_value(sort* s, expr* a, expr* b = nullptr, expr* c = nullptr); };
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: fpa2bv_converter.h Abstract: Conversion routines for Floating Point -> Bit-Vector Author: Christoph (cwinter) 2012-02-09 Notes: --*/
big_form.ml
open! Core open! Bonsai_web open Bonsai.Let_syntax module Form = Bonsai_web_ui_form module E = Form.Elements module Query_box_css = [%css.raw {| .list { background: white; border: solid 1px black; width: 200px; padding: 5px; } .selected_item { background: yellow; } |}] module A_B_or_C = struct module T = struct type t = | Aaaa | Abbb | Cccc [@@deriving enumerate, compare, equal, sexp] end include T include Comparator.Make (T) end module My_variant = struct type t = | A | B of string | C of int * float [@@deriving sexp, equal, typed_variants] let form_for_variant : type a. a Typed_variant.t -> a Form.t Computation.t = function | A -> Bonsai.const (Form.return ()) | B -> E.Textbox.string [%here] | C -> Computation.map2 ~f:Form.both (E.Textbox.int [%here]) (E.Textbox.float [%here]) ;; end let my_variant_form = Form.Typed.Variant.make (module My_variant) module Nested_record = struct let checkbox = Form.Elements.Checkbox.bool ~default:false module Inner = struct type t = { b_1 : bool ; b_2 : bool } [@@deriving typed_fields, sexp] let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function | B_1 -> checkbox [%here] | B_2 -> checkbox [%here] ;; end let inner_form = Form.Typed.Record.make (module Inner) module Outer = struct type t = { a_1 : bool ; a_2 : Inner.t } [@@deriving typed_fields, sexp] let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function | A_1 -> checkbox [%here] | A_2 -> inner_form ;; end let form = Form.Typed.Record.make (module Outer) end type t = { variant : My_variant.t ; int_from_range : int ; string_from_text : string ; string_from_vert_radio : string ; string_from_horiz_radio : string ; date : Date.t ; time_ns_of_day : Time_ns.Ofday.t ; date_time : Time_ns.Stable.Alternate_sexp.V1.t ; date_from_string : Date.t ; sexp_from_string : Sexp.t ; bool_from_checkbox : bool ; bool_from_toggle : bool ; bool_from_dropdown : bool ; typeahead : A_B_or_C.t ; color_picker : [ `Hex of string ] ; string_option : string option ; a_b_or_c : A_B_or_C.t ; many : A_B_or_C.t list ; many2 : A_B_or_C.t list ; string_set : String.Set.t ; files : Bonsai_web_ui_file.t Filename.Map.t ; rank : string list ; query_box : string ; nested_record : Nested_record.Outer.t } [@@deriving typed_fields, fields, sexp_of] let ( >>|| ) a f = Bonsai.Computation.map a ~f let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function | Variant -> my_variant_form >>|| Form.tooltip "Tooltips can also be on header groups" | Int_from_range -> E.Range.int [%here] ~min:0 ~max:100 ~default:0 ~step:1 () | String_from_text -> E.Textbox.string [%here] | String_from_vert_radio -> E.Radio_buttons.list [%here] (module String) ~layout:`Vertical (Value.return [ "first"; "second"; "third" ]) | String_from_horiz_radio -> E.Radio_buttons.list [%here] (module String) ~layout:`Horizontal (Value.return [ "first"; "second"; "third" ]) | Date -> E.Date_time.date [%here] | Time_ns_of_day -> E.Date_time.time [%here] | Date_time -> E.Date_time.datetime_local [%here] | Date_from_string -> E.Textbox.string [%here] >>|| Form.project ~parse_exn:Date.of_string ~unparse:Date.to_string | Sexp_from_string -> E.Textbox.sexpable [%here] (module Sexp) | Bool_from_toggle -> E.Toggle.bool ~default:false () | Bool_from_checkbox -> E.Checkbox.bool [%here] ~default:false | Bool_from_dropdown -> E.Dropdown.enumerable [%here] (module Bool) ~to_string:Bool.to_string | Typeahead -> E.Typeahead.single [%here] (module A_B_or_C) ~placeholder:"Typeahead here!" ~all_options:(Value.return A_B_or_C.all) | String_option -> E.Dropdown.list_opt [%here] (module String) (Value.return [ "hello"; "world" ]) | A_b_or_c -> E.Dropdown.enumerable [%here] (module A_B_or_C) | Many -> let%sub multi_select = E.Multiselect.list [%here] (module A_B_or_C) (Value.return A_B_or_C.all) in Form.Dynamic.collapsible_group (Value.return "collapsible group") multi_select | Many2 -> let%sub multi_select = E.Multiselect.list [%here] (module A_B_or_C) (Value.return A_B_or_C.all) in let%sub multi_select2 = E.Multiselect.list [%here] (module A_B_or_C) (multi_select >>| Form.value_or_default ~default:[]) in let%arr multi_select = multi_select and multi_select2 = multi_select2 in Form.both multi_select multi_select2 |> Form.project ~parse_exn:snd ~unparse:(fun selected -> selected, selected) | String_set -> E.Checkbox.set [%here] (module String) (Value.return [ "first"; "second"; "third"; "fourth" ]) | Files -> E.File_select.multiple [%here] ~accept:[ `Mimetype "application/pdf"; `Extension ".csv" ] () | Rank -> let%sub rank = E.Rank.list (module String) (fun ~source item -> let%arr item = item and source = source in Vdom.Node.div ~attr:source [ Vdom.Node.text item ]) in Form.Dynamic.with_default (Value.return [ "aaaaaa"; "bbbbbb"; "cccccc" ]) rank | Query_box -> Form.Elements.Query_box.stringable (module String) ~selected_item_attr:(Value.return (Vdom.Attr.class_ Query_box_css.selected_item)) ~extra_list_container_attr:(Value.return (Vdom.Attr.class_ Query_box_css.list)) (Value.return (String.Map.of_alist_exn [ "abc", "abc"; "def", "def"; "ghi", "ghi" ])) | Nested_record -> Nested_record.form | Color_picker -> E.Color_picker.hex [%here] ;; let form = Form.Typed.Record.make (module struct module Typed_field = Typed_field let form_for_field = form_for_field end) ;; let component = let%sub form = form in let%sub editable, toggle_editable = Bonsai_extra.toggle [%here] ~default_model:true in let%arr editable = editable and toggle_editable = toggle_editable and form = form in let output = Vdom.Node.sexp_for_debugging ([%sexp_of: t Or_error.t] (Form.value form)) in let editable = if editable then `Currently_yes else `Currently_no in Vdom.Node.div [ Vdom.Node.h1 [ Vdom.Node.text "Big Form" ] ; Form.view_as_vdom ~editable form ; Vdom.Node.button ~attr:Vdom.Attr.(on_click (fun _ -> toggle_editable)) [ Vdom.Node.text "Toggle Editing" ] ; output ] ;;
Guess_lang.ml
(* Guess whether a given file is indeed written in the specified programming language. *) open Common let logger = Logging.get_logger [ __MODULE__ ] (****************************************************************************) (* Types *) (****************************************************************************) (* Evaluation will be left-to-right and lazy, using the usual (&&) and (||) operators. *) type test = | And of test * test | Or of test * test | Not of test | Test_path of (string -> bool) let eval test path = let rec eval = function | And (f, g) -> eval f && eval g | Or (f, g) -> eval f || eval g | Not f -> not (eval f) | Test_path f -> f path in eval test (****************************************************************************) (* Helpers *) (****************************************************************************) let string_chop_prefix ~pref s = let len = String.length s in let preflen = String.length pref in if len >= preflen && Str.first_chars s preflen = pref then Some (String.sub s preflen (len - preflen)) else None let has_suffix suffixes = let f path = List.exists (fun suf -> Filename.check_suffix path suf) suffixes in Test_path f let is_named valid_names = let f path = let name = Filename.basename path in List.mem name valid_names in Test_path f let prepend_period_if_needed s = match s with | "" -> "." | s -> if s.[0] <> '.' then "." ^ s else s (* Both '.d.ts' and '.ts' are considered extensions of 'hello.d.ts'. *) let has_extension extensions = has_suffix (Common.map prepend_period_if_needed extensions) let has_lang_extension lang = has_extension (Lang.ext_of_lang lang) let has_excluded_lang_extension lang = has_extension (Lang.excluded_exts_of_lang lang) let has_an_extension = let f path = Filename.extension path <> "" in Test_path f let is_executable = let f path = Sys.file_exists path && let st = Unix.stat path in match st.st_kind with | S_REG -> (* at least some user has exec permission *) st.st_perm land 0o111 <> 0 | _ -> false in (* ".exe" is intended for Windows, although this would be a binary file, not a script. *) Or (has_extension [ ".exe" ], Test_path f) let get_first_line path = Common.with_open_infile path (fun ic -> try input_line ic with | End_of_file -> (* empty file *) "") (* Get the first N bytes of the file, which is ideally obtained from a single filesystem block. *) let get_first_block ?(block_size = 4096) path = Common.with_open_infile path (fun ic -> let len = min block_size (in_channel_length ic) in really_input_string ic len) let shebang_re = lazy (SPcre.regexp "^#![ \t]*([^ \t]*)[ \t]*([^ \t].*)?$") let split_cmd_re = lazy (SPcre.regexp "[ \t]+") (* A shebang supports at most the name of the script and one argument: #!/bin/bash -e -u ^^^^^^^^^ ^^^^^ arg0 arg1 To deal with that, the '/usr/bin/env' command offer the '-S' option prefix, which will split what follows '-S' into multiple arguments. So we may find things like these: #!/usr/bin/env -S bash -e -u ^^^^^^^^^^^^ ^^^^^^^^^^^^^ arg0 arg1 It's 'env' that will parse its argument and execute the command ['bash'; '-e'; '-u'] as expected. Examples: "#!/bin/bash -e -u" -> ["/bin/bash"; "-e -u"] "#!/usr/bin/env -S bash -e -u" -> ["/usr/bin/env"; "bash"; "-e"; "-u"] *) let parse_shebang_line s = let matched = SPcre.exec_noerr ~rex:(Lazy.force shebang_re) s in match matched with | None -> None | Some matched -> ( match Pcre.get_substrings matched with | [| _; arg0; "" |] -> Some [ arg0 ] | [| _; "/usr/bin/env" as arg0; arg1 |] -> ( (* approximate emulation of 'env -S'; should work if the command contains no quotes around the arguments. *) match string_chop_prefix ~pref:"-S" arg1 with | Some packed_args -> let args = SPcre.split_noerr ~rex:(Lazy.force split_cmd_re) ~on_error:[ packed_args ] packed_args |> List.filter (fun fragment -> fragment <> "") in Some (arg0 :: args) | None -> Some [ arg0; arg1 ]) | [| _; arg0; arg1 |] -> Some [ arg0; arg1 ] | [| _ |] -> None | _ -> assert false) let get_shebang_command path = get_first_line path |> parse_shebang_line let uses_shebang_command_name cmd_names = let f path = logger#info "checking for a #! in %s" path; match get_shebang_command path with | Some ("/usr/bin/env" :: cmd_name :: _) -> List.mem cmd_name cmd_names | Some (cmd_path :: _) -> let cmd_name = Filename.basename cmd_path in List.mem cmd_name cmd_names | _ -> false in Test_path f (* PCRE regexp using the default options. In case of an error, the result is false. *) let regexp pat = let rex = SPcre.regexp pat in let f path = let s = get_first_block path in SPcre.pmatch_noerr ~rex s in Test_path f let is_executable_script cmd_names = And ( Not has_an_extension, And (is_executable, uses_shebang_command_name cmd_names) ) (* Matches if either - language has extension in Lang.ext_of_lang - language is script with shebang in Lang.shebangs_of_lang General test for a script: - must have one of the approved extensions (e.g. "bash" or "sh") - or has no extension but has executable permission and one of the approved commands occurs on the shebang line. Example: #!/bin/bash -e ^^^^ #!/usr/bin/env bash ^^^^ *) let matches_lang lang = let has_ext = And (has_lang_extension lang, Not (has_excluded_lang_extension lang)) in match Lang.shebangs_of_lang lang with | [] -> has_ext (* Prefer extensions over shebangs *) | cmd_names -> Or (has_ext, is_executable_script cmd_names) (****************************************************************************) (* Language-specific definitions *) (****************************************************************************) (* Inspect Hack files, which may use the '.php' extension in addition to the Hack-specific extensions ('.hack' etc.). See https://docs.hhvm.com/hack/source-code-fundamentals/program-structure *) let is_hack = Or ( matches_lang Lang.Hack, And ( has_extension [ ".php" ], Or ( uses_shebang_command_name [ "hhvm" ], (* optional '#!' line followed by '<?hh': *) regexp "^(?:#![^\\n]*\\n)?<\\?hh\\s" ) ) ) let inspect_file_p (lang : Lang.t) path = let test = match lang with | Hack -> is_hack | Php -> And (matches_lang lang, Not is_hack) | Dockerfile -> (* TODO: add support for exact file name to lang.json *) Or (is_named [ "Dockerfile"; "dockerfile" ], has_lang_extension lang) | Apex | Bash | C | Clojure | Cpp | Csharp | Dart | Elixir | Go | Html | Java | Js | Json | Jsonnet | Julia | Kotlin | Lisp | Lua | Ocaml | Python2 | Python3 | Python | R | Ruby | Rust | Scala | Scheme | Solidity | Swift | Terraform | Ts | Vue | Xml | Yaml -> matches_lang lang in eval test path let wrap_with_error_message lang path bool_res : (string, Output_from_core_t.skipped_target) result = match bool_res with | true -> Ok path | false -> Error { path; reason = Wrong_language; details = spf "target file doesn't look like language %s" (Lang.to_string lang); rule_id = None; } let inspect_file lang path = let bool_res = inspect_file_p lang path in wrap_with_error_message lang path bool_res let inspect_files lang paths = Common.partition_result (inspect_file lang) paths
(* Guess whether a given file is indeed written in the specified programming language. *)
strategy.mli
(** {2 User-defined strategies} *) (** A strategy is defined by a program declared under a simple assembly-like form: instructions are indexed by integers starting from 0 (the initial instruction counter). An instruction is either 1) a call to a prover, with given time and mem limits . on success, the program execution ends . on any other result, the program execution continues on the next index 2) a application of a transformation . on success, the execution continues to a explicitly given index . on failure, execution continues on the next index 3) a goto instruction. the execution halts when reaching a non-existing state *) type instruction = | Icall_prover of Whyconf.prover * float option * int option * int option (** timelimit (if none use default timelimit), memlimit (if none use default memlimit) steplimit (if none use no step limit) *) | Itransform of string * int (** successor state on success *) | Igoto of int (** goto state *) type t = instruction array
(********************************************************************) (* *) (* 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. *) (* *) (********************************************************************)
bzlaelimslices.c
#include "preprocess/bzlaelimslices.h" #include "bzlacore.h" #include "bzlaexp.h" #include "bzlalog.h" #include "utils/bzlanodeiter.h" #include "utils/bzlautil.h" struct BzlaSlice { uint32_t upper; uint32_t lower; }; typedef struct BzlaSlice BzlaSlice; static BzlaSlice * new_slice(Bzla *bzla, uint32_t upper, uint32_t lower) { BzlaSlice *result; assert(bzla != NULL); assert(upper >= lower); BZLA_NEW(bzla->mm, result); result->upper = upper; result->lower = lower; return result; } static void delete_slice(Bzla *bzla, BzlaSlice *slice) { assert(bzla != NULL); assert(slice != NULL); BZLA_DELETE(bzla->mm, slice); } static uint32_t hash_slice(BzlaSlice *slice) { uint32_t result; assert(slice != NULL); assert(slice->upper >= slice->lower); result = (uint32_t) slice->upper; result += (uint32_t) slice->lower; result *= 7334147u; return result; } static int32_t compare_slices(BzlaSlice *s1, BzlaSlice *s2) { assert(s1 != NULL); assert(s2 != NULL); assert(s1->upper >= s1->lower); assert(s2->upper >= s2->lower); if (s1->upper < s2->upper) return -1; if (s1->upper > s2->upper) return 1; assert(s1->upper == s1->upper); if (s1->lower < s2->lower) return -1; if (s1->lower > s2->lower) return 1; assert(s1->upper == s2->upper && s1->lower == s2->lower); return 0; } static int32_t compare_slices_qsort(const void *p1, const void *p2) { return compare_slices(*((BzlaSlice **) p1), *((BzlaSlice **) p2)); } static int32_t compare_int_ptr(const void *p1, const void *p2) { int32_t v1 = *((int32_t *) p1); int32_t v2 = *((int32_t *) p2); if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } void bzla_eliminate_slices_on_bv_vars(Bzla *bzla) { BzlaNode *var, *cur, *result, *lambda_var, *temp; BzlaSortId sort; BzlaSlice *s1, *s2, *new_s1, *new_s2, *new_s3, **sorted_slices; BzlaPtrHashBucket *b_var, *b1, *b2; BzlaNodeIterator it; BzlaPtrHashTable *slices; int32_t i; uint32_t min, max, count; BzlaNodePtrStack vars; double start, delta; BzlaMemMgr *mm; uint32_t vals[4]; assert(bzla != NULL); start = bzla_util_time_stamp(); count = 0; BZLALOG(1, "start slice elimination"); mm = bzla->mm; BZLA_INIT_STACK(mm, vars); for (b_var = bzla->bv_vars->first; b_var != NULL; b_var = b_var->next) { if (b_var->data.flag) continue; var = (BzlaNode *) b_var->key; BZLA_PUSH_STACK(vars, var); /* mark as processed, required for non-destructive substiution */ b_var->data.flag = true; } while (!BZLA_EMPTY_STACK(vars)) { var = BZLA_POP_STACK(vars); if (!bzla_node_is_bv_var(var)) continue; BZLALOG(2, "process %s (%s)", bzla_util_node2string(var), bzla_util_node2string(bzla_node_get_simplified(bzla, var))); assert(bzla_node_is_regular(var)); slices = bzla_hashptr_table_new( mm, (BzlaHashPtr) hash_slice, (BzlaCmpPtr) compare_slices); /* find all slices on variable */ bzla_iter_parent_init(&it, var); while (bzla_iter_parent_has_next(&it)) { cur = bzla_iter_parent_next(&it); assert(bzla_node_is_regular(cur)); if (bzla_node_is_simplified(cur)) { assert(bzla_opt_get(bzla, BZLA_OPT_PP_NONDESTR_SUBST)); continue; } if (bzla_node_is_bv_slice(cur)) { s1 = new_slice(bzla, bzla_node_bv_slice_get_upper(cur), bzla_node_bv_slice_get_lower(cur)); assert(!bzla_hashptr_table_get(slices, s1)); /* full slices should have been eliminated by rewriting */ assert(s1->upper - s1->lower + 1 < bzla_node_bv_get_width(bzla, var)); bzla_hashptr_table_add(slices, s1); BZLALOG(2, " found slice %u %u", s1->upper, s1->lower); } } /* no splitting necessary? */ if (slices->count == 0u) { bzla_hashptr_table_delete(slices); continue; } /* add full slice */ s1 = new_slice(bzla, bzla_node_bv_get_width(bzla, var) - 1, 0); assert(!bzla_hashptr_table_get(slices, s1)); bzla_hashptr_table_add(slices, s1); BZLA_SPLIT_SLICES_RESTART: for (b1 = slices->last; b1 != NULL; b1 = b1->prev) { s1 = (BzlaSlice *) b1->key; for (b2 = b1->prev; b2 != NULL; b2 = b2->prev) { s2 = (BzlaSlice *) b2->key; assert(compare_slices(s1, s2)); /* not overlapping? */ if ((s1->lower > s2->upper) || (s1->upper < s2->lower) || (s2->lower > s1->upper) || (s2->upper < s1->lower)) continue; if (s1->upper == s2->upper) { assert(s1->lower != s2->lower); max = BZLA_MAX_UTIL(s1->lower, s2->lower); min = BZLA_MIN_UTIL(s1->lower, s2->lower); new_s1 = new_slice(bzla, max - 1, min); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (min == s1->lower) { bzla_hashptr_table_remove(slices, s1, 0, 0); delete_slice(bzla, s1); } else { bzla_hashptr_table_remove(slices, s2, 0, 0); delete_slice(bzla, s2); } goto BZLA_SPLIT_SLICES_RESTART; } if (s1->lower == s2->lower) { assert(s1->upper != s2->upper); max = BZLA_MAX_UTIL(s1->upper, s2->upper); min = BZLA_MIN_UTIL(s1->upper, s2->upper); new_s1 = new_slice(bzla, max, min + 1); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (max == s1->upper) { bzla_hashptr_table_remove(slices, s1, 0, 0); delete_slice(bzla, s1); } else { bzla_hashptr_table_remove(slices, s2, NULL, NULL); delete_slice(bzla, s2); } goto BZLA_SPLIT_SLICES_RESTART; } /* regular overlapping case (overlapping at both ends) */ vals[0] = s1->upper; vals[1] = s1->lower; vals[2] = s2->upper; vals[3] = s2->lower; qsort(vals, 4, sizeof(uint32_t), compare_int_ptr); new_s1 = new_slice(bzla, vals[3], vals[2] + 1); new_s2 = new_slice(bzla, vals[2], vals[1]); new_s3 = new_slice(bzla, vals[1] - 1, vals[0]); bzla_hashptr_table_remove(slices, s1, 0, 0); bzla_hashptr_table_remove(slices, s2, NULL, NULL); delete_slice(bzla, s1); delete_slice(bzla, s2); if (!bzla_hashptr_table_get(slices, new_s1)) bzla_hashptr_table_add(slices, new_s1); else delete_slice(bzla, new_s1); if (!bzla_hashptr_table_get(slices, new_s2)) bzla_hashptr_table_add(slices, new_s2); else delete_slice(bzla, new_s2); if (!bzla_hashptr_table_get(slices, new_s3)) bzla_hashptr_table_add(slices, new_s3); else delete_slice(bzla, new_s3); goto BZLA_SPLIT_SLICES_RESTART; } } /* copy slices to sort them */ assert(slices->count > 1u); BZLA_NEWN(mm, sorted_slices, slices->count); i = 0; for (b1 = slices->first; b1 != NULL; b1 = b1->next) { s1 = (BzlaSlice *) b1->key; sorted_slices[i++] = s1; } qsort(sorted_slices, slices->count, sizeof(BzlaSlice *), compare_slices_qsort); s1 = sorted_slices[slices->count - 1]; sort = bzla_sort_bv(bzla, s1->upper - s1->lower + 1); result = bzla_exp_var(bzla, sort, 0); bzla_sort_release(bzla, sort); delete_slice(bzla, s1); for (i = (int32_t) slices->count - 2; i >= 0; i--) { s1 = sorted_slices[i]; sort = bzla_sort_bv(bzla, s1->upper - s1->lower + 1); lambda_var = bzla_exp_var(bzla, sort, 0); bzla_sort_release(bzla, sort); temp = bzla_exp_bv_concat(bzla, result, lambda_var); bzla_node_release(bzla, result); result = temp; bzla_node_release(bzla, lambda_var); delete_slice(bzla, s1); } BZLA_DELETEN(mm, sorted_slices, slices->count); bzla_hashptr_table_delete(slices); count++; bzla->stats.eliminated_slices++; temp = bzla_exp_eq(bzla, var, result); bzla_assert_exp(bzla, temp); bzla_node_release(bzla, temp); bzla_node_release(bzla, result); } BZLA_RELEASE_STACK(vars); delta = bzla_util_time_stamp() - start; bzla->time.slicing += delta; BZLALOG(1, "end slice elimination"); BZLA_MSG(bzla->msg, 1, "sliced %u variables in %1.f seconds", count, delta); }
/*** * Bitwuzla: Satisfiability Modulo Theories (SMT) solver. * * This file is part of Bitwuzla. * * Copyright (C) 2007-2021 by the authors listed in the AUTHORS file. * * See COPYING for more information on using this software. */
broadcast_services.ml
module S = struct open Data_encoding let path = RPC_path.(root / "broadcast") let dests_query = let open RPC_query in query (fun dests -> object method dests = dests end) |+ multi_field "dests" RPC_arg.int (fun t -> t#dests) |> seal (* copied from lib_shell_services/injection_services.ml *) let block_param = obj2 (req "block" (dynamic_size Block_header.encoding)) (req "operations" (list (dynamic_size (list (dynamic_size Operation.encoding))))) let block = RPC_service.post_service ~description:"Broadcast a block." ~query:dests_query ~input:block_param ~output:unit RPC_path.(path / "block") let operation = RPC_service.post_service ~description:"Broadcast an operation." ~query:dests_query ~input:Alpha_context.Operation.encoding ~output:unit RPC_path.(path / "operation") end open RPC_context let block ctxt ?(dests = []) raw operations = make_call S.block ctxt () (object method dests = dests end) (raw, operations) let operation ctxt ?(dests = []) operation = make_call S.operation ctxt () (object method dests = dests end) operation
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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.ml
type error += Cannot_pay_storage_fee (* `Temporary *) type error += Operation_quota_exceeded (* `Temporary *) type error += Storage_limit_too_high (* `Permanent *) let () = let open Data_encoding in register_error_kind `Temporary ~id:"contract.cannot_pay_storage_fee" ~title:"Cannot pay storage fee" ~description:"The storage fee is higher than the contract balance" ~pp:(fun ppf () -> Format.fprintf ppf "Cannot pay storage storage fee") Data_encoding.empty (function Cannot_pay_storage_fee -> Some () | _ -> None) (fun () -> Cannot_pay_storage_fee) ; register_error_kind `Temporary ~id:"storage_exhausted.operation" ~title:"Storage quota exceeded for the operation" ~description: "A script or one of its callee wrote more bytes than the operation said \ it would" Data_encoding.empty (function Operation_quota_exceeded -> Some () | _ -> None) (fun () -> Operation_quota_exceeded) ; register_error_kind `Permanent ~id:"storage_limit_too_high" ~title:"Storage limit out of protocol hard bounds" ~description:"A transaction tried to exceed the hard limit on storage" empty (function Storage_limit_too_high -> Some () | _ -> None) (fun () -> Storage_limit_too_high) let origination_burn c = let origination_size = Constants_storage.origination_size c in let cost_per_byte = Constants_storage.cost_per_byte c in (* the origination burn, measured in bytes *) Tez_repr.(cost_per_byte *? Int64.of_int origination_size) >|? fun to_be_paid -> (Raw_context.update_allocated_contracts_count c, to_be_paid) let record_paid_storage_space c contract = Contract_storage.used_storage_space c contract >>=? fun size -> Contract_storage.set_paid_storage_space_and_return_fees_to_pay c contract size >>=? fun (to_be_paid, c) -> let c = Raw_context.update_storage_space_to_pay c to_be_paid in let cost_per_byte = Constants_storage.cost_per_byte c in Lwt.return ( Tez_repr.(cost_per_byte *? Z.to_int64 to_be_paid) >|? fun to_burn -> (c, size, to_be_paid, to_burn) ) let burn_storage_fees c ~storage_limit ~payer = let origination_size = Constants_storage.origination_size c in let (c, storage_space_to_pay, allocated_contracts) = Raw_context.clear_storage_space_to_pay c in let storage_space_for_allocated_contracts = Z.mul (Z.of_int allocated_contracts) (Z.of_int origination_size) in let consumed = Z.add storage_space_to_pay storage_space_for_allocated_contracts in let remaining = Z.sub storage_limit consumed in if Compare.Z.(remaining < Z.zero) then fail Operation_quota_exceeded else let cost_per_byte = Constants_storage.cost_per_byte c in Tez_repr.(cost_per_byte *? Z.to_int64 consumed) >>?= fun to_burn -> (* Burning the fees... *) if Tez_repr.(to_burn = Tez_repr.zero) then (* If the payer was was deleted by transferring all its balance, and no space was used, burning zero would fail *) return c else trace Cannot_pay_storage_fee ( Contract_storage.must_exist c payer >>=? fun () -> Contract_storage.spend c payer to_burn ) let check_storage_limit c ~storage_limit = if Compare.Z.( storage_limit > (Raw_context.constants c).hard_storage_limit_per_operation) || Compare.Z.(storage_limit < Z.zero) then error Storage_limit_too_high else ok_unit let start_counting_storage_fees c = Raw_context.init_storage_space_to_pay c
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
Match_rules.mli
(* this can be raised when timeout_threshold is set *) exception File_timeout (* Return matches, errors, match time. This will run the search-mode and taint-mode rules. This can raise File_timeout. *) val check : match_hook:(string -> Pattern_match.t -> unit) -> timeout:float -> timeout_threshold:int -> Match_env.xconfig -> Rule.rules -> Xtarget.t -> Report.partial_profiling Report.match_result
(* this can be raised when timeout_threshold is set *) exception File_timeout
foo.ml
let value = "Hello, world!"
deleteSnapshot.mli
open Types type input = DeleteSnapshotRequest.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
test_p11_mechanism.ml
open OUnit2 let test_compare = let open P11_mechanism in let test a b expected ctxt = let got = P11_mechanism.compare a b in assert_equal ~ctxt ~cmp:[%eq: int] ~printer:[%show: int] expected got in "AES-CTR" >:: test (CKM_AES_CTR (P11_aes_ctr_params.make ~bits:(Unsigned.ULong.of_int 1) ~block:"")) (CKM_AES_CTR (P11_aes_ctr_params.make ~bits:(Unsigned.ULong.of_int 2) ~block:"")) (-1) let suite = "P11_mechanism" >::: [test_compare]
bench.ml
let config ~root:_ = Irmin_mem.config () module KV = Irmin_mem.KV.Make (Irmin.Contents.String) module Bench = Irmin_bench.Make (KV) let size ~root:_ = 0 let () = Bench.run ~config ~size
(* * Copyright (c) 2013-2022 Thomas Gazagnaire <thomas@gazagnaire.org> * * 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. *)
Parse_vue_tree_sitter.ml
open Common module CST = Tree_sitter_vue.CST module H = Parse_tree_sitter_helpers module PI = Parse_info open AST_generic module G = AST_generic (*****************************************************************************) (* Prelude *) (*****************************************************************************) (* Vue parser using tree-sitter-lang/semgrep-vue and converting * to ast_js.ml * * There are similarities with the code in Parse_html_tree_sitter.ml. *) (*****************************************************************************) (* Helpers *) (*****************************************************************************) type extra = { (* todo: later we should also propagate parsing errors *) parse_js_program : string wrap -> AST_generic.program; parse_js_expr : string wrap -> AST_generic.expr; } type env = extra H.env let fake = AST_generic.fake let token = H.token let str = H.str let fb = Parse_info.unsafe_fake_bracket (* val str_if_wrong_content_temporary_fix : 'a env -> Tree_sitter_run.Token.t -> string * Parse_info.t *) (* This is a temporary fix until * https://github.com/returntocorp/ocaml-tree-sitter-core/issues/5 * is fixed. *) let str_if_wrong_content_temporary_fix env (tok : Tree_sitter_run.Token.t) = let loc, _wrong_str = tok in let file = env.H.file in let h = env.H.conv in let charpos, line, column = let pos = loc.Tree_sitter_run.Loc.start in (* Parse_info is 1-line based and 0-column based, like Emacs *) let line = pos.Tree_sitter_run.Loc.row + 1 in let column = pos.Tree_sitter_run.Loc.column in try (Hashtbl.find h (line, column), line, column) with | Not_found -> failwith (spf "could not find line:%d x col:%d in %s" line column file) in let charpos2 = let pos = loc.Tree_sitter_run.Loc.end_ in (* Parse_info is 1-line based and 0-column based, like Emacs *) let line = pos.Tree_sitter_run.Loc.row + 1 in let column = pos.Tree_sitter_run.Loc.column in try Hashtbl.find h (line, column) with | Not_found -> failwith (spf "could not find line:%d x col:%d in %s" line column file) in (* Range.t is inclusive, so we need -1 to remove the char at the pos *) let charpos2 = charpos2 - 1 in let r = { Range.start = charpos; end_ = charpos2 } in let str = Range.content_at_range file r in let tok_loc = { PI.str; charpos; line; column; file } in (str, PI.mk_info_of_loc tok_loc) (*****************************************************************************) (* Boilerplate converter *) (*****************************************************************************) (* This was started by copying tree-sitter-lang/semgrep-vue/Boilerplate.ml *) (** Boilerplate to be used as a template when mapping the vue CST to another type of tree. *) let map_end_tag (env : env) ((v1, v2, v3) : CST.end_tag) : tok = let v1 = token env v1 (* "</" *) in let v2 = token env v2 (* end_tag_name *) in let v3 = token env v3 (* ">" *) in PI.combine_infos v1 [ v2; v3 ] let map_text (env : env) (x : CST.text) = match x with | `Text_frag tok -> str env tok (* text_fragment *) (* ?? not an interpolation? *) | `LCURLLCURL tok -> str env tok (* "{{" *) let map_quoted_attribute_value (env : env) (x : CST.quoted_attribute_value) : string wrap bracket = match x with | `SQUOT_opt_pat_58fbb2e_SQUOT (v1, v2, v3) -> let l = token env v1 (* "'" *) in let xs = match v2 with | Some tok -> [ str env tok ] (* pattern "[^']+" *) | None -> [] in let r = token env v3 (* "'" *) in G.string_ (l, xs, r) | `DQUOT_opt_pat_98d585a_DQUOT (v1, v2, v3) -> let l = token env v1 (* "\"" *) in let xs = match v2 with | Some tok -> [ str env tok ] (* pattern "[^\"]+" *) | None -> [] in let r = token env v3 (* "\"" *) in G.string_ (l, xs, r) let map_directive_modifiers (env : env) (xs : CST.directive_modifiers) = Common.map (fun (v1, v2) -> let v1 = token env v1 (* "." *) in let v2 = str env v2 (* pattern "[^<>\"'/=\\s.]+" *) in (v1, v2)) xs let map_anon_choice_attr_value_5986531 (env : env) (x : CST.anon_choice_attr_value_5986531) : a_xml_attr_value = match x with | `Attr_value tok -> let x = str env tok (* pattern "[^<>\"'=\\s]+" *) in N (Id (x, G.empty_id_info ())) |> G.e | `Quoted_attr_value x -> let x = map_quoted_attribute_value env x in L (String x) |> G.e let map_anon_choice_dire_arg_b33821e (env : env) (x : CST.anon_choice_dire_arg_b33821e) = match x with | `Dire_arg tok -> let id = str env tok (* pattern "[^<>\"'/=\\s.]+" *) in Left id | `Dire_dyna_arg (v1, v2, v3) -> let v1 = token env v1 (* "[" *) in let v2 = match v2 with | Some tok -> Some (str env tok) (* pattern "[^<>\"'/=\\s\\]]+" *) | None -> None in let v3 = token env v3 (* "]" *) in Right (v1, v2, v3) let map_anon_choice_attr_a1991da (env : env) (x : CST.anon_choice_attr_a1991da) : xml_attribute = match x with | `Attr (v1, v2) -> let id = str env v1 (* pattern "[^<>\"'=/\\s]+" *) in let teq, v2 = match v2 with | Some (v1, v2) -> let v1 = token env v1 (* "=" *) in let v2 = map_anon_choice_attr_value_5986531 env v2 in (v1, v2) | None -> (* <foo a /> <=> <foo a=true>? That's what we do for JSX, but should * we instead introduce a XmlAttrNoValue in AST_generic? *) let v = L (Bool (true, fake "true")) |> G.e in (fake "=", v) in XmlAttr (id, teq, v2) | `Dire_attr (v1, v2, v3) -> let id = match v1 with | `Dire_name_opt_COLON_choice_dire_arg (v1, v2) -> let v1 = str env v1 (* directive_name *) in let _v2TODO = match v2 with | Some (v1, v2) -> let v1 = token env v1 (* ":" *) in let v2 = map_anon_choice_dire_arg_b33821e env v2 in Some (v1, v2) | None -> None in v1 | `Dire_shor_choice_dire_arg (v1, v2) -> let v1 = str env v1 (* directive_shorthand *) in let _v2 = map_anon_choice_dire_arg_b33821e env v2 in v1 in let _v2TODO = match v2 with | Some x -> map_directive_modifiers env x | None -> [] in let teq, v3 = match v3 with | Some (v1, v2) -> let v1 = token env v1 (* "=" *) in let v2 = map_anon_choice_attr_value_5986531 env v2 in (v1, v2) | None -> (* <foo a /> <=> <foo a=true>? That's what we do for JSX, but should * we instead introduce a XmlAttrNoValue in AST_generic? *) let v = L (Bool (true, fake "true")) |> G.e in (fake "=", v) in (* TODO: XmlDynAttr? *) XmlAttr (id, teq, v3) let map_start_tag (env : env) ((v1, v2, v3, v4) : CST.start_tag) = let v1 = token env v1 (* "<" *) in let v2 = str env v2 (* start_tag_name *) in let v3 = Common.map (map_anon_choice_attr_a1991da env) v3 in let v4 = token env v4 (* ">" *) in (v1, v2, v3, v4) let map_template_start_tag (env : env) ((v1, v2, v3, v4) : CST.template_start_tag) = let v1 = token env v1 (* "<" *) in let v2 = str env v2 (* template_start_tag_name *) in let v3 = Common.map (map_anon_choice_attr_a1991da env) v3 in let v4 = token env v4 (* ">" *) in (v1, v2, v3, v4) let map_style_start_tag (env : env) ((v1, v2, v3, v4) : CST.style_start_tag) = let v1 = token env v1 (* "<" *) in let v2 = str env v2 (* style_start_tag_name *) in let v3 = Common.map (map_anon_choice_attr_a1991da env) v3 in let v4 = token env v4 (* ">" *) in (v1, v2, v3, v4) let map_script_start_tag (env : env) ((v1, v2, v3, v4) : CST.script_start_tag) = let v1 = token env v1 (* "<" *) in let v2 = str env v2 (* script_start_tag_name *) in let v3 = Common.map (map_anon_choice_attr_a1991da env) v3 in let v4 = token env v4 (* ">" *) in (v1, v2, v3, v4) let map_style_element (env : env) ((v1, v2, v3) : CST.style_element) : xml = let l, id, attrs, r = map_style_start_tag env v1 in let v2 = match v2 with | Some tok -> [ XmlText (str env tok) (* raw_text *) ] | None -> [] in let v3 = map_end_tag env v3 in { xml_kind = XmlClassic (l, id, r, v3); xml_attrs = attrs; xml_body = v2 } let map_script_element (env : env) ((v1, v2, v3) : CST.script_element) = let l, id, attrs, r = map_script_start_tag env v1 in let v2 = match v2 with | Some tok -> (* TODO: https://github.com/returntocorp/ocaml-tree-sitter-core/issues/5 *) let v = str_if_wrong_content_temporary_fix env tok in Some v (* raw_text *) | None -> None in let v3 = map_end_tag env v3 in (l, id, r, v3, attrs, v2) let rec map_element (env : env) (x : CST.element) : xml = match x with | `Start_tag_rep_node_choice_end_tag (v1, v2, v3) -> let l, id, attrs, r = map_start_tag env v1 in let v2 = List.concat_map (map_node env) v2 in let v3 = match v3 with | `End_tag x -> map_end_tag env x | `Impl_end_tag tok -> token env tok (* implicit_end_tag *) in { xml_kind = XmlClassic (l, id, r, v3); xml_attrs = attrs; xml_body = v2 } | `Self_clos_tag (v1, v2, v3, v4) -> let l = token env v1 (* "<" *) in let id = str env v2 (* start_tag_name *) in let attrs = Common.map (map_anon_choice_attr_a1991da env) v3 in let r = token env v4 (* "/>" *) in { xml_kind = XmlSingleton (l, id, r); xml_attrs = attrs; xml_body = [] } and map_node (env : env) (x : CST.node) : xml_body list = match x with | `Comm tok -> let _x = token env tok (* comment *) in [] | `Text x -> let x = map_text env x in [ XmlText x ] | `Interp (v1, v2, v3) -> let v1 = token env v1 (* "{{" *) in let v2 = match v2 with | Some tok -> let x = str env tok (* interpolation_text *) in (* TODO: parse as JS *) Some (L (String (fb x)) |> G.e) | None -> None in let v3 = token env v3 (* "}}" *) in [ XmlExpr (v1, v2, v3) ] | `Elem x -> let xml = map_element env x in [ XmlXml xml ] | `Temp_elem x -> let xml = map_template_element env x in [ XmlXml xml ] | `Script_elem x -> let l, id, r, rend, xml_attrs, body_opt = map_script_element env x in let xml_body = match body_opt with (* TODO: parse as JS *) | Some s -> [ XmlText s ] | None -> [] in let xml = { xml_kind = XmlClassic (l, id, r, rend); xml_attrs; xml_body } in [ XmlXml xml ] (* less: parse as CSS *) | `Style_elem x -> let xml = map_style_element env x in [ XmlXml xml ] | `Errons_end_tag (v1, v2, v3) -> let l = token env v1 (* "</" *) in let id = str env v2 (* erroneous_end_tag_name *) in let r = token env v3 (* ">" *) in (* todo? raise an exn instead? *) let xml = { xml_kind = XmlSingleton (l, id, r); xml_attrs = []; xml_body = [] } in [ XmlXml xml ] and map_template_element (env : env) ((v1, v2, v3) : CST.template_element) : xml = let l, id, attrs, r = map_template_start_tag env v1 in let v2 = List.concat_map (map_node env) v2 in let v3 = map_end_tag env v3 in { xml_kind = XmlClassic (l, id, r, v3); xml_attrs = attrs; xml_body = v2 } let map_component (env : env) (xs : CST.component) : stmt list = List.concat_map (fun x -> match x with | `Comm tok -> let _x = token env tok (* comment *) in [] | `Elem x -> let xml = map_element env x in [ G.exprstmt (Xml xml |> G.e) ] | `Temp_elem x -> let xml = map_template_element env x in [ G.exprstmt (Xml xml |> G.e) ] (* Note that right now the AST will not contain the enclosing * <script>, because XmlExpr contain single expressions, not * full programs, so it's simpler to just lift up the * program and remove the enclosing <script>. If at some point * people want to explicitly restrict their code search to * the <script> part we might revisit that. *) | `Script_elem x -> ( let _l, _id, _r, _rend, _xml_attrs, body_opt = map_script_element env x in match body_opt with | Some s -> env.extra.parse_js_program s | None -> []) (* less: parse as CSS *) | `Style_elem x -> let xml = map_style_element env x in [ G.exprstmt (Xml xml |> G.e) ]) xs (*****************************************************************************) (* Entry point *) (*****************************************************************************) (* TODO: move in Parse_tree_sitter_helpers.ml *) let parse_string_and_adjust_wrt_base content tbase fparse = Common2.with_tmp_file ~str:content ~ext:"js" (fun file -> let x = fparse file in let visitor = Map_AST.mk_visitor { Map_AST.default_visitor with Map_AST.kinfo = (fun (_, _) t -> let base_loc = PI.unsafe_token_location_of_info tbase in Parsing_helpers.adjust_info_wrt_base base_loc t); } in visitor.Map_AST.vprogram x) let parse parse_js file = H.wrap_parser (fun () -> Tree_sitter_vue.Parse.file file) (fun cst -> let extra = { parse_js_program = (fun (s, t) -> parse_string_and_adjust_wrt_base s t parse_js); parse_js_expr = (fun (s, t) -> let _xs = parse_string_and_adjust_wrt_base s t parse_js in failwith "TODO: extract expr"); } in let env = { H.file; conv = H.line_col_to_pos file; extra } in let xs = map_component env cst in xs)
(* Yoann Padioleau * * Copyright (c) 2021 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. *)