filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
bzlalsutils.h
#ifndef BZLALSUTILS_H_INCLUDED #define BZLALSUTILS_H_INCLUDED #include "bzlaslv.h" #include "bzlatypes.h" #include "utils/bzlahashint.h" /** * Update cone of incluence as a consequence of a local search move. * * Note: 'roots' will only be updated if 'update_roots' is true. * + PROP engine: always * + SLS engine: only if an actual move is performed * (not during neighborhood exploration, 'try_move') */ void bzla_lsutils_update_cone(Bzla* bzla, BzlaIntHashTable* bv_model, BzlaIntHashTable* roots, BzlaIntHashTable* score, BzlaIntHashTable* exps, bool update_roots, uint64_t* stats_updates, double* time_update_cone, double* time_update_cone_reset, double* time_update_cone_model_gen, double* time_update_cone_compute_score); bool bzla_lsutils_is_leaf_node(BzlaNode* n); void bzla_lsutils_initialize_bv_model(BzlaSolver* slv); #endif
/*** * 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. */
CCFloat.ml
(* This file is free software, part of containers. See file "license" for more details. *) open CCShims_ type t = float type fpclass = Stdlib.fpclass = | FP_normal | FP_subnormal | FP_zero | FP_infinite | FP_nan module Infix = struct let ( = ) : t -> t -> bool = Stdlib.( = ) let ( <> ) : t -> t -> bool = Stdlib.( <> ) let ( < ) : t -> t -> bool = Stdlib.( < ) let ( > ) : t -> t -> bool = Stdlib.( > ) let ( <= ) : t -> t -> bool = Stdlib.( <= ) let ( >= ) : t -> t -> bool = Stdlib.( >= ) let ( ~- ) : t -> t = Stdlib.( ~-. ) let ( + ) : t -> t -> t = Stdlib.( +. ) let ( - ) : t -> t -> t = Stdlib.( -. ) let ( * ) : t -> t -> t = Stdlib.( *. ) let ( / ) : t -> t -> t = Stdlib.( /. ) end include Infix let nan = Stdlib.nan let infinity = Stdlib.infinity let neg_infinity = Stdlib.neg_infinity let max_value = infinity let min_value = neg_infinity let max_finite_value = Stdlib.max_float let epsilon = Stdlib.epsilon_float let pi = 0x1.921fb54442d18p+1 let is_nan x = Stdlib.(classify_float x = Stdlib.FP_nan) let add = ( +. ) let sub = ( -. ) let mul = ( *. ) let div = ( /. ) let neg = ( ~-. ) let abs = Stdlib.abs_float let scale = ( *. ) let min (x : t) y = match Stdlib.classify_float x, Stdlib.classify_float y with | FP_nan, _ -> y | _, FP_nan -> x | _ -> if x < y then x else y let max (x : t) y = match Stdlib.classify_float x, Stdlib.classify_float y with | FP_nan, _ -> y | _, FP_nan -> x | _ -> if x > y then x else y let equal (a : float) b = a = b let hash : t -> int = Hashtbl.hash let compare (a : float) b = Stdlib.compare a b type 'a printer = Format.formatter -> 'a -> unit type 'a random_gen = Random.State.t -> 'a let pp = Format.pp_print_float let fsign a = if is_nan a then nan else if a = 0. then a else Stdlib.copysign 1. a exception TrapNaN of string let sign_exn (a : float) = if is_nan a then raise (TrapNaN "sign_exn") else compare a 0. let round x = let low = floor x in let high = ceil x in if x -. low > high -. x then high else low let to_int (a : float) = Stdlib.int_of_float a let of_int (a : int) = Stdlib.float_of_int a let to_string (a : float) = Stdlib.string_of_float a let of_string_exn (a : string) = Stdlib.float_of_string a let of_string_opt (a : string) = try Some (Stdlib.float_of_string a) with Failure _ -> None let random n st = Random.State.float st n let random_small = random 100.0 let random_range i j st = i +. random (j -. i) st let equal_precision ~epsilon a b = abs_float (a -. b) < epsilon let classify = Stdlib.classify_float
(* This file is free software, part of containers. See file "license" for more details. *)
type_description.ml
module Types (F : Ctypes.TYPE) = struct end
test.ml
Vlib.Foo.run ();;
pkg.ml
#!/usr/bin/env ocaml #use "topfind" #require "topkg" open Topkg let jsoo_test ~cond test = Pkg.flatten [ Pkg.test ~run:false ~cond ~auto:false (test ^ ".js"); Pkg.test ~run:false ~cond ~auto:false (test ^ ".html"); ] let () = Pkg.describe "react" @@ fun c -> Ok [ Pkg.mllib "src/react.mllib"; Pkg.mllib ~api:[] "src/react_top.mllib"; Pkg.lib "src/react_top_init.ml"; Pkg.test ~run:false "test/breakout"; Pkg.test ~run:false "test/clock"; Pkg.test "test/test"; Pkg.doc "doc/index.mld" ~dst:"odoc-pages/index.mld"; (* jsoo_test ~cond:jsoo "test/js_hisig_test"; jsoo_test ~cond:jsoo "test/js_test"; *) ]
p2p_socket.ml
(* TODO: https://gitlab.com/tezos/tezos/-/issues/4603 test `close ~wait:true`. *) module Events = P2p_events.P2p_socket module Crypto = struct (* maximal size of the buffer *) let bufsize = (1 lsl 16) - 1 let header_length = 2 (* The size of extra data added by encryption. *) let tag_length = Tezos_crypto.Crypto_box.tag_length (* The number of bytes added by encryption + header *) let extrabytes = header_length + tag_length let max_content_length = bufsize - extrabytes type data = { channel_key : Tezos_crypto.Crypto_box.channel_key; mutable local_nonce : Tezos_crypto.Crypto_box.nonce; mutable remote_nonce : Tezos_crypto.Crypto_box.nonce; } (* We do the following assumptions on the NaCl library. Note that we also make the assumption, here, that the NaCl library allows in-place boxing and unboxing, since we use the same buffer for input and output. *) let () = assert (tag_length >= header_length) (* msg is overwritten and should not be used after this invocation *) let write_chunk ?canceler fd cryptobox_data msg = let open Lwt_result_syntax in let msg_length = Bytes.length msg in let* () = fail_unless (msg_length <= max_content_length) P2p_errors.Invalid_message_size in let encrypted_length = tag_length + msg_length in let payload_length = header_length + encrypted_length in let tag = Bytes.create tag_length in let local_nonce = cryptobox_data.local_nonce in cryptobox_data.local_nonce <- Tezos_crypto.Crypto_box.increment_nonce local_nonce ; Tezos_crypto.Crypto_box.fast_box_noalloc cryptobox_data.channel_key local_nonce tag msg ; let payload = Bytes.create payload_length in TzEndian.set_uint16 payload 0 encrypted_length ; Bytes.blit tag 0 payload header_length tag_length ; Bytes.blit msg 0 payload extrabytes msg_length ; P2p_io_scheduler.write ?canceler fd payload let read_chunk ?canceler fd cryptobox_data = let open Lwt_result_syntax in let open P2p_buffer_reader in let header_buf = Bytes.create header_length in let* () = read_full ?canceler fd @@ mk_buffer_safe header_buf in let encrypted_length = TzEndian.get_uint16 header_buf 0 in let* () = fail_unless (encrypted_length >= tag_length) P2p_errors.Invalid_incoming_ciphertext_size in let tag = Bytes.create tag_length in let* () = read_full ?canceler fd @@ mk_buffer_safe tag in (* [msg_length] is [>= 0], as guaranteed by the [fail_unless] guard above. *) let msg_length = encrypted_length - tag_length in let msg = Bytes.create msg_length in let* () = read_full ?canceler fd @@ mk_buffer_safe msg in let remote_nonce = cryptobox_data.remote_nonce in cryptobox_data.remote_nonce <- Tezos_crypto.Crypto_box.increment_nonce remote_nonce ; match Tezos_crypto.Crypto_box.fast_box_open_noalloc cryptobox_data.channel_key remote_nonce tag msg with | false -> tzfail P2p_errors.Decipher_error | true -> return msg end (* Note: there is an inconsistency here, since we display an error in bytes, whereas the option is set in kbytes. Also, since the default size is 64kB-1, it is actually impossible to set the default size using the option (the max is 63 kB). *) let check_binary_chunks_size size = let value = size - Crypto.extrabytes in error_unless (value > 0 && value <= Crypto.max_content_length) (P2p_errors.Invalid_chunks_size {value = size; min = Crypto.extrabytes + 1; max = Crypto.bufsize}) module Connection_message = struct type t = { port : int option; public_key : Tezos_crypto.Crypto_box.public_key; proof_of_work_stamp : Tezos_crypto.Crypto_box.nonce; message_nonce : Tezos_crypto.Crypto_box.nonce; version : Network_version.t; } let encoding = let open Data_encoding in conv (fun {port; public_key; proof_of_work_stamp; message_nonce; version} -> let port = match port with None -> 0 | Some port -> port in (port, public_key, proof_of_work_stamp, message_nonce, version)) (fun (port, public_key, proof_of_work_stamp, message_nonce, version) -> let port = if port = 0 then None else Some port in {port; public_key; proof_of_work_stamp; message_nonce; version}) (obj5 (req "port" uint16) (req "pubkey" Tezos_crypto.Crypto_box.public_key_encoding) (req "proof_of_work_stamp" Tezos_crypto.Crypto_box.nonce_encoding) (req "message_nonce" Tezos_crypto.Crypto_box.nonce_encoding) (req "version" Network_version.encoding)) let write ~canceler fd message = let open Lwt_result_syntax in let encoded_message_len = Data_encoding.Binary.length encoding message in let* () = fail_unless (encoded_message_len < 1 lsl (Crypto.header_length * 8)) Tezos_base.Data_encoding_wrapper.Unexpected_size_of_decoded_buffer in let len = Crypto.header_length + encoded_message_len in let buf = Bytes.create len in let state = WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.make_writer_state buf ~offset:Crypto.header_length ~allowed_bytes:encoded_message_len in match Data_encoding.Binary.write encoding message state with | Error we -> tzfail (Tezos_base.Data_encoding_wrapper.Encoding_error we) | Ok last -> let* () = fail_unless (last = len) Tezos_base.Data_encoding_wrapper.Unexpected_size_of_encoded_value in TzEndian.set_int16 buf 0 encoded_message_len ; let* () = P2p_io_scheduler.write ~canceler fd buf in (* We return the raw message as it is used later to compute the nonces *) return buf let read ~canceler fd = let open Lwt_result_syntax in let open P2p_buffer_reader in let header_buf = Bytes.create Crypto.header_length in let* () = read_full ~canceler fd @@ mk_buffer_safe header_buf in let len = TzEndian.get_uint16 header_buf 0 in let pos = Crypto.header_length in let buf = Bytes.create (pos + len) in TzEndian.set_uint16 buf 0 len ; let* () = read_full ~canceler fd @@ match mk_buffer ~length_to_copy:len ~pos buf with | Error _ -> (* This call to [mk_buffer] is safe (it can't [Error] out) but we cannot use [mk_buffer_safe], because we need to specify ~len and ~pos. *) assert false | Ok buffer -> buffer in let buf = Bytes.unsafe_to_string buf in match Data_encoding.Binary.read encoding buf pos len with | Error re -> tzfail (P2p_errors.Decoding_error re) | Ok (next_pos, message) -> if next_pos <> pos + len then tzfail (P2p_errors.Decoding_error Data_encoding.Binary.Extra_bytes) else return (message, buf) end module Metadata = struct let write ~canceler metadata_config fd cryptobox_data message = let open Lwt_result_syntax in let encoded_message_len = Data_encoding.Binary.length metadata_config.P2p_params.conn_meta_encoding message in let buf = Bytes.create encoded_message_len in let state = WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.make_writer_state buf ~offset:0 ~allowed_bytes:encoded_message_len in match Data_encoding.Binary.write metadata_config.conn_meta_encoding message state with | Error we -> tzfail (Tezos_base.Data_encoding_wrapper.Encoding_error we) | Ok last -> let* () = fail_unless (last = encoded_message_len) Tezos_base.Data_encoding_wrapper.Unexpected_size_of_encoded_value in Crypto.write_chunk ~canceler fd cryptobox_data buf let read ~canceler metadata_config fd cryptobox_data = let open Lwt_result_syntax in let* buf = Crypto.read_chunk ~canceler fd cryptobox_data in let buf = Bytes.unsafe_to_string buf in let length = String.length buf in let encoding = metadata_config.P2p_params.conn_meta_encoding in match Data_encoding.Binary.read encoding buf 0 length with | Error re -> tzfail (P2p_errors.Decoding_error re) | Ok (read_len, message) -> if read_len <> length then tzfail (P2p_errors.Decoding_error Data_encoding.Binary.Extra_bytes) else return message end module Ack = struct type t = | Ack | Nack_v_0 | Nack of { motive : P2p_rejection.t; potential_peers_to_connect : P2p_point.Id.t list; } let encoding = let open Data_encoding in let ack_encoding = obj1 (req "ack" empty) in let nack_v_0_encoding = obj1 (req "nack_v_0" empty) in let nack_encoding = obj2 (req "nack_motive" P2p_rejection.encoding) (req "nack_list" (Data_encoding.list ~max_length:100 P2p_point.Id.encoding)) in let ack_case tag = case tag ack_encoding ~title:"Ack" (function Ack -> Some () | _ -> None) (fun () -> Ack) in let nack_case tag = case tag nack_encoding ~title:"Nack" (function | Nack {motive; potential_peers_to_connect} -> Some (motive, potential_peers_to_connect) | _ -> None) (fun (motive, lst) -> Nack {motive; potential_peers_to_connect = lst}) in let nack_v_0_case tag = case tag nack_v_0_encoding ~title:"Nack_v_0" (function Nack_v_0 -> Some () | _ -> None) (fun () -> Nack_v_0) in union [ack_case (Tag 0); nack_v_0_case (Tag 255); nack_case (Tag 1)] let write ?canceler fd cryptobox_data message = let open Lwt_result_syntax in let encoded_message_len = Data_encoding.Binary.length encoding message in let buf = Bytes.create encoded_message_len in let state = WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.make_writer_state buf ~offset:0 ~allowed_bytes:encoded_message_len in match Data_encoding.Binary.write encoding message state with | Error we -> tzfail (Tezos_base.Data_encoding_wrapper.Encoding_error we) | Ok last -> let* () = fail_unless (last = encoded_message_len) Tezos_base.Data_encoding_wrapper.Unexpected_size_of_encoded_value in Crypto.write_chunk ?canceler fd cryptobox_data buf let read ?canceler fd cryptobox_data = let open Lwt_result_syntax in let* buf = Crypto.read_chunk ?canceler fd cryptobox_data in let buf = Bytes.unsafe_to_string buf in let length = String.length buf in match Data_encoding.Binary.read encoding buf 0 length with | Error re -> tzfail (P2p_errors.Decoding_error re) | Ok (read_len, message) -> if read_len <> length then tzfail (P2p_errors.Decoding_error Data_encoding.Binary.Extra_bytes) else return message end type 'meta authenticated_connection = { scheduled_conn : P2p_io_scheduler.connection; info : 'meta P2p_connection.Info.t; cryptobox_data : Crypto.data; } let nack {scheduled_conn; cryptobox_data; info} motive potential_peers_to_connect = let open Lwt_syntax in let* nack = if P2p_version.feature_available P2p_version.Nack_with_list info.announced_version.p2p_version then let* () = Events.(emit nack_point_with_list) (info.id_point, potential_peers_to_connect) in Lwt.return (Ack.Nack {motive; potential_peers_to_connect}) else let* () = Events.(emit nack_point_no_point) info.id_point in Lwt.return Ack.Nack_v_0 in let* (_ : unit tzresult) = Ack.write scheduled_conn cryptobox_data nack in let* (_ : unit tzresult) = P2p_io_scheduler.close scheduled_conn in Lwt.return_unit (* First step: write and read credentials, makes no difference whether we're trying to connect to a peer or checking an incoming connection, both parties must first introduce themselves. *) let authenticate ~canceler ~proof_of_work_target ~incoming scheduled_conn ((remote_addr, remote_socket_port) as point) ?advertised_port identity announced_version metadata_config = let open Lwt_result_syntax in let local_nonce_seed = Tezos_crypto.Crypto_box.random_nonce () in let*! () = Events.(emit sending_authentication) point in let* sent_msg = Connection_message.write ~canceler scheduled_conn { public_key = identity.P2p_identity.public_key; proof_of_work_stamp = identity.proof_of_work_stamp; message_nonce = local_nonce_seed; port = advertised_port; version = announced_version; } in let* msg, recv_msg = Connection_message.read ~canceler (P2p_io_scheduler.to_readable scheduled_conn) in (* TODO: https://gitlab.com/tezos/tezos/-/issues/4604 make the below bytes-to-string copy-conversion unnecessary. This requires making the consumer of the [recv_msg] value ([Crypto_box.generate_nonces]) able to work with strings directly. *) let recv_msg = Bytes.of_string recv_msg in let remote_listening_port = if incoming then msg.port else Some remote_socket_port in let id_point = (remote_addr, remote_listening_port) in let remote_peer_id = Tezos_crypto.Crypto_box.hash msg.public_key in let* () = fail_unless (remote_peer_id <> identity.P2p_identity.peer_id) (P2p_errors.Myself id_point) in let* () = fail_unless (Tezos_crypto.Crypto_box.check_proof_of_work msg.public_key msg.proof_of_work_stamp proof_of_work_target) (P2p_errors.Not_enough_proof_of_work remote_peer_id) in let channel_key = Tezos_crypto.Crypto_box.precompute identity.P2p_identity.secret_key msg.public_key in let local_nonce, remote_nonce = Tezos_crypto.Crypto_box.generate_nonces ~incoming ~sent_msg ~recv_msg in let cryptobox_data = {Crypto.channel_key; local_nonce; remote_nonce} in let local_metadata = metadata_config.P2p_params.conn_meta_value () in let* () = Metadata.write ~canceler metadata_config scheduled_conn cryptobox_data local_metadata in let* remote_metadata = Metadata.read ~canceler metadata_config (P2p_io_scheduler.to_readable scheduled_conn) cryptobox_data in let info = { P2p_connection.Info.peer_id = remote_peer_id; announced_version = msg.version; incoming; id_point; remote_socket_port; private_node = metadata_config.private_node remote_metadata; local_metadata; remote_metadata; } in return (info, {scheduled_conn; info; cryptobox_data}) module Reader = struct type ('msg, 'meta) t = { canceler : Lwt_canceler.t; conn : 'meta authenticated_connection; encoding : 'msg Data_encoding.t; messages : (int * 'msg) tzresult Lwt_pipe.Maybe_bounded.t; mutable worker : unit Lwt.t; } let read_message st init = let rec loop status = let open Lwt_result_syntax in let*! () = Lwt.pause () in let open Data_encoding.Binary in match status with | Success {result; size; stream} -> return (result, size, stream) | Error err -> let*! () = Events.(emit read_error) () in tzfail (P2p_errors.Decoding_error err) | Await decode_next_buf -> let* buf = Crypto.read_chunk ~canceler:st.canceler (P2p_io_scheduler.to_readable st.conn.scheduled_conn) st.conn.cryptobox_data in let*! () = Events.(emit read_event) (Bytes.length buf, st.conn.info.peer_id) in loop (decode_next_buf buf) in loop (Data_encoding.Binary.read_stream ?init st.encoding) let rec worker_loop st stream = let open Lwt_syntax in let* r = let open Lwt_result_syntax in let* msg, size, stream = read_message st stream in protect ~canceler:st.canceler (fun () -> let*! () = Lwt_pipe.Maybe_bounded.push st.messages (Ok (size, msg)) in return_some stream) in match r with | Ok (Some stream) -> worker_loop st (Some stream) | Ok None -> Error_monad.cancel_with_exceptions st.canceler | Error (Canceled :: _) | Error (Exn Lwt_pipe.Closed :: _) -> Events.(emit connection_closed) st.conn.info.peer_id | Error _ as err -> if Lwt_pipe.Maybe_bounded.is_closed st.messages then () else (* best-effort push to the messages, we ignore failures *) (ignore : bool -> unit) @@ Lwt_pipe.Maybe_bounded.push_now st.messages err ; Error_monad.cancel_with_exceptions st.canceler let run ?size conn encoding canceler = let compute_size = function | Ok (size, _) -> (Sys.word_size / 8 * 11) + size + Lwt_pipe.Maybe_bounded.push_overhead | Error _ -> 0 (* we push Error only when we close the socket, we don't fear memory leaks in that case... *) in let bound = Option.map (fun max -> (max, compute_size)) size in let st = { canceler; conn; encoding; messages = Lwt_pipe.Maybe_bounded.create ?bound (); worker = Lwt.return_unit; } in Lwt_canceler.on_cancel st.canceler (fun () -> Lwt_pipe.Maybe_bounded.close st.messages ; Lwt.return_unit) ; st.worker <- Lwt_utils.worker "reader" ~on_event:Internal_event.Lwt_worker_logger.on_event ~run:(fun () -> worker_loop st None) ~cancel:(fun () -> Error_monad.cancel_with_exceptions st.canceler) ; st let shutdown st = Error_monad.cancel_with_exceptions st.canceler end type 'msg encoded_message = bytes list let copy_encoded_message = List.map Bytes.copy module Writer = struct type ('msg, 'meta) t = { canceler : Lwt_canceler.t; conn : 'meta authenticated_connection; encoding : 'msg Data_encoding.t; messages : (Bytes.t list * unit tzresult Lwt.u option) Lwt_pipe.Maybe_bounded.t; mutable worker : unit Lwt.t; binary_chunks_size : int; (* in bytes *) } let send_message st buf = let open Lwt_result_syntax in let rec loop = function | [] -> return_unit | buf :: l -> let* () = Crypto.write_chunk ~canceler:st.canceler st.conn.scheduled_conn st.conn.cryptobox_data buf in let*! () = Events.(emit write_event) (Bytes.length buf, st.conn.info.peer_id) in loop l in loop buf let encode_message (st : ('msg, _) t) msg = match Data_encoding.Binary.to_bytes st.encoding msg with | Error we -> Result_syntax.tzfail (Tezos_base.Data_encoding_wrapper.Encoding_error we) | Ok bytes -> Ok (Utils.cut st.binary_chunks_size bytes) let rec worker_loop st = let open Lwt_syntax in let* () = Lwt.pause () in let* r = protect ~canceler:st.canceler (fun () -> Lwt_result.ok @@ Lwt_pipe.Maybe_bounded.pop st.messages) in match r with | Error (Canceled :: _) | Error (Exn Lwt_pipe.Closed :: _) -> Events.(emit connection_closed) st.conn.info.peer_id | Error err -> let* () = Events.(emit write_error) (err, st.conn.info.peer_id) in Error_monad.cancel_with_exceptions st.canceler | Ok (buf, wakener) -> ( let* res = send_message st buf in match res with | Ok () -> Option.iter (fun u -> Lwt.wakeup_later u res) wakener ; worker_loop st | Error err -> ( Option.iter (fun u -> Lwt.wakeup_later u (Result_syntax.tzfail P2p_errors.Connection_closed)) wakener ; match err with | (Canceled | Exn Lwt_pipe.Closed) :: _ -> Events.(emit connection_closed) st.conn.info.peer_id | P2p_errors.Connection_closed :: _ -> let* () = Events.(emit connection_closed) st.conn.info.peer_id in Error_monad.cancel_with_exceptions st.canceler | err -> let* () = Events.(emit write_error) (err, st.conn.info.peer_id) in Error_monad.cancel_with_exceptions st.canceler)) let run ?size ?binary_chunks_size conn encoding canceler = let binary_chunks_size = match binary_chunks_size with | None -> Crypto.max_content_length | Some size -> let size = size - Crypto.extrabytes in assert (size > 0) ; assert (size <= Crypto.max_content_length) ; size in let compute_size = let buf_list_size = List.fold_left (fun sz buf -> sz + Bytes.length buf + (2 * Sys.word_size)) 0 in function | buf_l, None -> Sys.word_size + buf_list_size buf_l + Lwt_pipe.Maybe_bounded.push_overhead | buf_l, Some _ -> (2 * Sys.word_size) + buf_list_size buf_l + Lwt_pipe.Maybe_bounded.push_overhead in let bound = Option.map (fun max -> (max, compute_size)) size in let st = { canceler; conn; encoding; messages = Lwt_pipe.Maybe_bounded.create ?bound (); worker = Lwt.return_unit; binary_chunks_size; } in Lwt_canceler.on_cancel st.canceler (fun () -> Lwt_pipe.Maybe_bounded.close st.messages ; let rec loop () = match Lwt_pipe.Maybe_bounded.pop_now st.messages with | exception Lwt_pipe.Closed -> () | None -> () | Some (_, None) -> loop () | Some (_, Some w) -> Lwt.wakeup_later w (error_with_exn Lwt_pipe.Closed) ; loop () in loop () ; Lwt.return_unit) ; st.worker <- Lwt_utils.worker "writer" ~on_event:Internal_event.Lwt_worker_logger.on_event ~run:(fun () -> worker_loop st) ~cancel:(fun () -> Error_monad.cancel_with_exceptions st.canceler) ; st let shutdown st = let open Lwt_syntax in let* () = Error_monad.cancel_with_exceptions st.canceler in st.worker end type ('msg, 'meta) t = { conn : 'meta authenticated_connection; reader : ('msg, 'meta) Reader.t; writer : ('msg, 'meta) Writer.t; } let equal {conn = {scheduled_conn = conn2; _}; _} {conn = {scheduled_conn = conn1; _}; _} = P2p_io_scheduler.id conn1 = P2p_io_scheduler.id conn2 let pp ppf {conn; _} = P2p_connection.Info.pp (fun _ _ -> ()) ppf conn.info let info {conn; _} = conn.info let local_metadata {conn; _} = conn.info.local_metadata let remote_metadata {conn; _} = conn.info.remote_metadata let private_node {conn; _} = conn.info.private_node let accept ?incoming_message_queue_size ?outgoing_message_queue_size ?binary_chunks_size ~canceler conn encoding = let open Lwt_result_syntax in let* ack = protect (fun () -> let* () = Ack.write ~canceler conn.scheduled_conn conn.cryptobox_data Ack in Ack.read ~canceler (P2p_io_scheduler.to_readable conn.scheduled_conn) conn.cryptobox_data) ~on_error:(fun err -> let*! (_ : unit tzresult) = P2p_io_scheduler.close conn.scheduled_conn in match err with | [P2p_errors.Connection_closed] -> tzfail P2p_errors.Rejected_socket_connection | [P2p_errors.Decipher_error] -> tzfail P2p_errors.Invalid_auth | err -> Lwt.return_error err) in match ack with | Ack -> let canceler = Lwt_canceler.create () in let reader = Reader.run ?size:incoming_message_queue_size conn encoding canceler and writer = Writer.run ?size:outgoing_message_queue_size ?binary_chunks_size conn encoding canceler in let conn = {conn; reader; writer} in Lwt_canceler.on_cancel canceler (fun () -> let open Lwt_syntax in let* (_ : unit tzresult) = P2p_io_scheduler.close conn.conn.scheduled_conn in Lwt.return_unit) ; return conn | Nack_v_0 -> tzfail (P2p_errors.Rejected_by_nack {motive = P2p_rejection.No_motive; alternative_points = None}) | Nack {motive; potential_peers_to_connect} -> tzfail (P2p_errors.Rejected_by_nack {motive; alternative_points = Some potential_peers_to_connect}) let catch_closed_pipe f = let open Lwt_result_syntax in let*! r = Lwt.catch f (function | Lwt_pipe.Closed -> tzfail P2p_errors.Connection_closed | exn -> fail_with_exn exn) in match r with | Error (Exn Lwt_pipe.Closed :: _) -> tzfail P2p_errors.Connection_closed | (Error _ | Ok _) as v -> Lwt.return v let write {writer; _} msg = let open Lwt_result_syntax in catch_closed_pipe (fun () -> let*? buf = Writer.encode_message writer msg in let*! () = Lwt_pipe.Maybe_bounded.push writer.messages (buf, None) in return_unit) let write_sync {writer; _} msg = let open Lwt_result_syntax in catch_closed_pipe (fun () -> let waiter, wakener = Lwt.wait () in let*? buf = Writer.encode_message writer msg in let*! () = Lwt_pipe.Maybe_bounded.push writer.messages (buf, Some wakener) in waiter) let encode {writer : ('msg, _) Writer.t; _} msg = Writer.encode_message writer msg let write_encoded_now {writer; _} buf = let open Result_syntax in try Ok (Lwt_pipe.Maybe_bounded.push_now writer.messages (buf, None)) with Lwt_pipe.Closed -> tzfail P2p_errors.Connection_closed let write_now t msg = let open Result_syntax in let* buf = encode t msg in write_encoded_now t buf let rec split_bytes size bytes = if Bytes.length bytes <= size then [bytes] else Bytes.sub bytes 0 size :: split_bytes size (Bytes.sub bytes size (Bytes.length bytes - size)) let raw_write_sync {writer; _} bytes = let open Lwt_syntax in let bytes = split_bytes writer.binary_chunks_size bytes in catch_closed_pipe (fun () -> let waiter, wakener = Lwt.wait () in let* () = Lwt_pipe.Maybe_bounded.push writer.messages (bytes, Some wakener) in waiter) let read {reader; _} = catch_closed_pipe (fun () -> Lwt_pipe.Maybe_bounded.pop reader.messages) let read_now {reader; _} = try Lwt_pipe.Maybe_bounded.pop_now reader.messages with Lwt_pipe.Closed -> Some (Result_syntax.tzfail P2p_errors.Connection_closed) let stat {conn = {scheduled_conn; _}; _} = P2p_io_scheduler.stat scheduled_conn let close ?(wait = false) st = let open Lwt_syntax in let* () = if not wait then Lwt.return_unit else ( Lwt_pipe.Maybe_bounded.close st.reader.messages ; Lwt_pipe.Maybe_bounded.close st.writer.messages ; st.writer.worker) in let* () = Reader.shutdown st.reader in let* () = Writer.shutdown st.writer in let* (_ : unit tzresult) = P2p_io_scheduler.close st.conn.scheduled_conn in Lwt.return_unit module Internal_for_tests = struct let raw_write_sync = raw_write_sync let mock_authenticated_connection default_metadata = let secret_key, public_key, _pkh = Tezos_crypto.Crypto_box.random_keypair () in let cryptobox_data = Crypto. { channel_key = Tezos_crypto.Crypto_box.precompute secret_key public_key; local_nonce = Tezos_crypto.Crypto_box.zero_nonce; remote_nonce = Tezos_crypto.Crypto_box.zero_nonce; } in let scheduled_conn = let f2d_t = Lwt_main.run (P2p_fd.socket PF_INET6 SOCK_STREAM 0) in P2p_io_scheduler.register (P2p_io_scheduler.create ~read_buffer_size:0 ()) f2d_t in let info = P2p_connection.Internal_for_tests.Info.mock default_metadata in {scheduled_conn; info; cryptobox_data} let make_crashing_encoding () : 'a Data_encoding.t = Data_encoding.conv (fun _ -> assert false) (fun _ -> assert false) Data_encoding.unit let mock conn = let reader = Reader. { canceler = Lwt_canceler.create (); conn; encoding = make_crashing_encoding (); messages = Lwt_pipe.Maybe_bounded.create (); worker = Lwt.return_unit; } in let writer = Writer. { canceler = Lwt_canceler.create (); conn; encoding = make_crashing_encoding (); messages = Lwt_pipe.Maybe_bounded.create (); worker = Lwt.return_unit; binary_chunks_size = 0; } in {conn; reader; writer} end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2019-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
; This file was automatically generated, do not edit. ; Edit file manifest/main.ml instead. (library (name tezos_client_016_PtMumbai_commands) (public_name tezos-client-016-PtMumbai.commands) (instrumentation (backend bisect_ppx)) (libraries tezos-base tezos-clic tezos-protocol-016-PtMumbai tezos-protocol-016-PtMumbai.parameters tezos-stdlib-unix tezos-protocol-environment tezos-shell-services tezos-mockup tezos-mockup-registration tezos-mockup-commands tezos-client-base tezos-client-016-PtMumbai tezos-client-commands tezos-rpc tezos-client-base-unix tezos-protocol-plugin-016-PtMumbai uri) (library_flags (:standard -linkall)) (flags (:standard) -open Tezos_base.TzPervasives -open Tezos_protocol_016_PtMumbai -open Tezos_protocol_016_PtMumbai_parameters -open Tezos_stdlib_unix -open Tezos_shell_services -open Tezos_client_base -open Tezos_client_016_PtMumbai -open Tezos_client_commands -open Tezos_client_base_unix -open Tezos_protocol_plugin_016_PtMumbai) (modules (:standard \ alpha_commands_registration))) (library (name tezos_client_016_PtMumbai_commands_registration) (public_name tezos-client-016-PtMumbai.commands-registration) (instrumentation (backend bisect_ppx)) (libraries tezos-base tezos-clic tezos-protocol-016-PtMumbai tezos-protocol-016-PtMumbai.parameters tezos-protocol-environment tezos-shell-services tezos-client-base tezos-client-016-PtMumbai tezos-client-commands tezos-client-016-PtMumbai.commands tezos-client-016-PtMumbai.sapling tezos-rpc tezos-protocol-plugin-016-PtMumbai) (library_flags (:standard -linkall)) (flags (:standard) -open Tezos_base.TzPervasives -open Tezos_protocol_016_PtMumbai -open Tezos_protocol_016_PtMumbai_parameters -open Tezos_shell_services -open Tezos_client_base -open Tezos_client_016_PtMumbai -open Tezos_client_commands -open Tezos_client_016_PtMumbai_commands -open Tezos_client_sapling_016_PtMumbai -open Tezos_protocol_plugin_016_PtMumbai) (modules alpha_commands_registration))
atomic_write_intf.ml
open Store_properties type 'a diff = 'a Diff.t module type S = sig (** {1 Atomic write stores} Atomic-write stores are stores where it is possible to read, update and remove elements, with atomically guarantees. *) type t (** The type for atomic-write backend stores. *) include Read_only.S with type _ t := t (** @inline *) val set : t -> key -> value -> unit Lwt.t (** [set t k v] replaces the contents of [k] by [v] in [t]. If [k] is not already defined in [t], create a fresh binding. Raise [Invalid_argument] if [k] is the {{!Irmin.Path.S.empty} empty path}. *) val test_and_set : t -> key -> test:value option -> set:value option -> bool Lwt.t (** [test_and_set t key ~test ~set] sets [key] to [set] only if the current value of [key] is [test] and in that case returns [true]. If the current value of [key] is different, it returns [false]. [None] means that the value does not have to exist or is removed. {b Note:} The operation is guaranteed to be atomic. *) val remove : t -> key -> unit Lwt.t (** [remove t k] remove the key [k] in [t]. *) val list : t -> key list Lwt.t (** [list t] it the list of keys in [t]. *) type watch (** The type of watch handlers. *) val watch : t -> ?init:(key * value) list -> (key -> value diff -> unit Lwt.t) -> watch Lwt.t (** [watch t ?init f] adds [f] to the list of [t]'s watch handlers and returns the watch handler to be used with {!unwatch}. [init] is the optional initial values. It is more efficient to use {!watch_key} to watch only a single given key.*) val watch_key : t -> key -> ?init:value -> (value diff -> unit Lwt.t) -> watch Lwt.t (** [watch_key t k ?init f] adds [f] to the list of [t]'s watch handlers for the key [k] and returns the watch handler to be used with {!unwatch}. [init] is the optional initial value of the key. *) val unwatch : t -> watch -> unit Lwt.t (** [unwatch t w] removes [w] from [t]'s watch handlers. *) include Clearable with type _ t := t (** @inline *) include Closeable with type _ t := t (** @inline *) end module type Maker = functor (K : Type.S) (V : Type.S) -> sig include S with type key = K.t and type value = V.t include Of_config with type _ t := t (** @inline *) end module type Sigs = sig module type S = S module type Maker = Maker module Check_closed_store (AW : S) : sig include S with type key = AW.key and type value = AW.value and type watch = AW.watch val make_closeable : AW.t -> t (** [make_closeable t] returns a version of [t] that raises {!Irmin.Closed} if an operation is performed when it is already closed. *) val get_if_open_exn : t -> AW.t (** [get_if_open_exn t] returns the store (without close checks) if it is open; otherwise raises {!Irmin.Closed} *) end module Check_closed (M : Maker) : Maker end
(* * 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. *)
pecu.ml
let io_buffer_size = 65536 let invalid_arg fmt = Format.ksprintf (fun s -> invalid_arg s) fmt let invalid_encode () = invalid_arg "Expected `Await encode" let invalid_bounds off len = invalid_arg "Invalid bounds (off: %d, len: %d)" off len let malformed source off pos len = `Malformed (Bytes.sub_string source (off + pos) len) let unsafe_byte source off pos = Bytes.unsafe_get source (off + pos) let unsafe_blit = Bytes.unsafe_blit let unsafe_chr = Char.unsafe_chr let unsafe_set_chr source off chr = Bytes.unsafe_set source off chr (* Base character decoders. They assume enough data. *) let r_repr source off len = (* assert (0 <= j && 0 <= l && j + l <= String.length s); *) (* assert (l = 3); *) let a = unsafe_byte source off 1 in let b = unsafe_byte source off 2 in let of_hex = function | '0' .. '9' as chr -> Char.code chr - Char.code '0' | 'A' .. 'F' as chr -> Char.code chr - Char.code 'A' + 10 | _ -> assert false in (* (General 8bit representation) Any octet, except a CR or LF that is part of a CRLF line break of the canonical (standard) form of the data being encoded, may be represented by an "=" followed by a two digit hexadecimal representation of the octet's value. The digits of the hexadecimal alphabet, for this purpose, are "0123456789ABCDEF". Uppercase letters must be used; lowercase letters are not allowed. Thus, for example, the decimal value 12 (US-ASCII form feed) can be represented by "=0C", and the decimal value 61 (US- ASCII EQUAL SIGN) can be represented by "=3D". This rule must be followed except when the following rules allow an alternative encoding. See RFC2045 § 6.7. *) match (unsafe_byte source off 0, a, b) with | '=', ('0' .. '9' | 'A' .. 'F'), ('0' .. '9' | 'A' .. 'F') -> `Repr ((of_hex a * 16) + of_hex b) | '=', '\r', '\n' -> `Soft_line_break | _e, _a, _b -> malformed source off 0 len let r_chr chr = `Chr chr let r_wsp wsp = `Wsp wsp let r_line_break source off len = (* assert (0 <= j && 0 <= l && j + l <= String.length s); *) (* assert (l = 2); *) match Bytes.sub_string source off len with | "\r\n" -> `Line_break | _str -> malformed source off 0 len type src = [`Channel of in_channel | `String of string | `Manual] type decode = [`Await | `End | `Malformed of string | `Line of string | `Data of string] type input = [ `Malformed of string | `Soft_line_break | `Line_break | `Wsp of char | `Repr of int | `Chr of char | `End ] (* [quoted-printable] has two kind to break a line but only one is relevant: [`Line_break]. [`Soft_line_break] must be used if longer lines are to be encoded with the quoted-printable encoding. This provides a mechanism with which long lines are encoded in such a way as to be restored by the user agent. The 76 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs. [`Wsp] must not be represented at the end of the encoded line. We keep a different buffer to store them and decide if they are followed by a printable character (like "="), we decoded them as printable whitespaces. [`Repr] is a decoded 8 bits value. [`Chr] is only a printable character. *) type decoder = { src: src ; mutable i: Bytes.t ; mutable i_off: int ; mutable i_pos: int ; mutable i_len: int ; t: Buffer.t ; w: Buffer.t ; h: Bytes.t ; mutable h_len: int ; mutable h_need: int ; mutable unsafe: bool ; mutable byte_count: int ; mutable limit_count: int ; mutable pp: decoder -> input -> decode ; mutable k: decoder -> decode } (* On decodes that overlap two (or more) [d.i] buffers, we use [t_fill] to copy the input data to [d.t] and decode from there. If the [d.i] buffers are not too small this is faster than continuation based byte per byte writes. End of input is sgnaled by [d.i_pos = 0] and [d.i_len = min_int] which implies that [i_rem d < 0] is [true]. *) let i_rem decoder = decoder.i_len - decoder.i_pos + 1 let end_of_input decoder = decoder.i <- Bytes.empty ; decoder.i_off <- 0 ; decoder.i_pos <- 0 ; decoder.i_len <- min_int let src decoder source off len = if off < 0 || len < 0 || off + len > Bytes.length source then invalid_bounds off len else if len = 0 then end_of_input decoder else ( decoder.i <- source ; decoder.i_off <- off ; decoder.i_pos <- 0 ; decoder.i_len <- len - 1 ) let refill k decoder = match decoder.src with | `Manual -> decoder.k <- k ; `Await | `String _ -> end_of_input decoder ; k decoder | `Channel ic -> let len = input ic decoder.i 0 (Bytes.length decoder.i) in src decoder decoder.i 0 len ; k decoder let dangerous decoder v = decoder.unsafe <- v let reset decoder = decoder.limit_count <- 0 let ret k v byte_count decoder = decoder.k <- k ; decoder.byte_count <- decoder.byte_count + byte_count ; decoder.limit_count <- decoder.limit_count + byte_count ; if decoder.limit_count > 78 then dangerous decoder true ; decoder.pp decoder v let malformed_line source off len decoder = Buffer.add_buffer decoder.t decoder.w ; Buffer.add_subbytes decoder.t source off len ; let line = Buffer.contents decoder.t in Buffer.clear decoder.w ; Buffer.clear decoder.t ; `Malformed line let t_need decoder need = decoder.h_len <- 0 ; decoder.h_need <- need let rec t_fill k decoder = let blit decoder len = unsafe_blit decoder.i (decoder.i_off + decoder.i_pos) decoder.h decoder.h_len len ; decoder.i_pos <- decoder.i_pos + len ; decoder.h_len <- decoder.h_len + len in let rem = i_rem decoder in if rem < 0 (* end of input *) then k decoder else let need = decoder.h_need - decoder.h_len in if rem < need then ( blit decoder rem ; refill (t_fill k) decoder ) else ( blit decoder need ; k decoder ) let rec t_decode_quoted_printable decoder = if decoder.h_len < decoder.h_need then ret decode_quoted_printable (malformed_line decoder.h 0 decoder.h_len decoder) decoder.h_len decoder else ret decode_quoted_printable (r_repr decoder.h 0 decoder.h_len) decoder.h_len decoder and t_decode_line_break decoder = if decoder.h_len < decoder.h_need then ret decode_quoted_printable (malformed_line decoder.h 0 decoder.h_len decoder) decoder.h_len decoder else ret decode_quoted_printable (r_line_break decoder.h 0 decoder.h_len) decoder.h_len decoder and decode_quoted_printable decoder = let rem = i_rem decoder in if rem <= 0 then if rem < 0 then ret (fun _decoder -> `End) `End 0 decoder else refill decode_quoted_printable decoder else match unsafe_byte decoder.i decoder.i_off decoder.i_pos with | ('\009' | '\032') as wsp -> (* HT | SPACE *) decoder.i_pos <- decoder.i_pos + 1 ; ret decode_quoted_printable (r_wsp wsp) 1 decoder | '\013' -> (* CR *) (* TODO: optimize it! *) t_need decoder 2 ; t_fill t_decode_line_break decoder | '=' -> (* TODO: optimize it! *) t_need decoder 3 ; t_fill t_decode_quoted_printable decoder | ('\033' .. '\060' | '\062' .. '\126') as chr -> Buffer.add_buffer decoder.t decoder.w ; Buffer.clear decoder.w ; decoder.i_pos <- decoder.i_pos + 1 ; ret decode_quoted_printable (r_chr chr) 1 decoder | _chr -> (* XXX(dinosaure): If characters other than HT, CR, LF or octets with decimal values greater than 126 found in incoming quoted-printable data by a decoder, a robust implementation might exclude them from the decoded data and warn the user that illegal characters were discovered. See RFC2045 § 6.7. *) let j = decoder.i_pos in decoder.i_pos <- decoder.i_pos + 1 ; ret decode_quoted_printable (malformed decoder.i decoder.i_off j 1) 1 decoder let f_fill_byte byte decoder = Buffer.add_char decoder.t (unsafe_chr byte) ; decoder.k decoder let f_fill_chr chr decoder = Buffer.add_char decoder.t chr ; decoder.k decoder let pp_quoted_printable decoder = function | `Soft_line_break -> Buffer.add_buffer decoder.t decoder.w ; let data = Buffer.contents decoder.t in Buffer.clear decoder.w ; Buffer.clear decoder.t ; reset decoder ; `Data data | `Line_break -> let line = Buffer.contents decoder.t in Buffer.clear decoder.w ; Buffer.clear decoder.t ; reset decoder ; `Line line | `End -> Buffer.add_buffer decoder.t decoder.w ; let data = Buffer.contents decoder.t in Buffer.clear decoder.w ; Buffer.clear decoder.t ; `Data data | `Wsp wsp -> Buffer.add_char decoder.w wsp ; decoder.k decoder | `Repr byte -> Buffer.add_buffer decoder.t decoder.w ; Buffer.clear decoder.w ; f_fill_byte byte decoder | `Chr chr -> Buffer.add_buffer decoder.t decoder.w ; Buffer.clear decoder.w ; f_fill_chr chr decoder | `Malformed _ as v -> v let decoder src = let pp = pp_quoted_printable in let k = decode_quoted_printable in let i, i_off, i_pos, i_len = match src with | `Manual -> (Bytes.empty, 0, 1, 0) | `Channel _ -> (Bytes.create io_buffer_size, 0, 1, 0) | `String s -> (Bytes.unsafe_of_string s, 0, 0, String.length s - 1) in { src ; i_off ; i_pos ; i_len ; i ; t= Buffer.create 80 ; w= Buffer.create 80 ; h= Bytes.create 3 ; h_need= 0 ; h_len= 0 ; unsafe= false ; limit_count= 0 ; byte_count= 0 ; pp ; k } let decode decoder = decoder.k decoder let decoder_byte_count decoder = decoder.byte_count let decoder_src decoder = decoder.src let decoder_dangerous decoder = decoder.unsafe module Inline = struct (* XXX(dinosaure): I want structural typing and row polymophism on record, please. *) type unsafe_char = char type decode = [`Await | `End | `Malformed of string | `Char of unsafe_char] type input = [`Malformed of string | `Wsp | `Chr of char | `Repr of int | `End] let r_repr source off len = (* assert (0 <= j && 0 <= l && j + l <= String.length s); *) (* assert (l = 3); *) let a = unsafe_byte source off 1 in let b = unsafe_byte source off 2 in let of_hex = function | '0' .. '9' as chr -> Char.code chr - Char.code '0' | 'A' .. 'F' as chr -> Char.code chr - Char.code 'A' + 10 | 'a' .. 'f' as chr -> Char.code chr - Char.code 'a' + 10 (* RFC 2047 says: uppercase SHOULD be used for hexadecimal digits. *) | _ -> assert false in match (unsafe_byte source off 0, a, b) with | '=', ('0' .. '9' | 'A' .. 'F' | 'a' .. 'f'), ('0' .. '9' | 'A' .. 'F' | 'a' .. 'f') -> `Repr ((of_hex a * 16) + of_hex b) | _e, _a, _b -> malformed source off 0 len let r_wsp = `Wsp type decoder = { src: src ; mutable i: Bytes.t ; mutable i_off: int ; mutable i_pos: int ; mutable i_len: int ; h: Bytes.t ; mutable h_len: int ; mutable h_need: int ; mutable byte_count: int ; mutable pp: decoder -> input -> decode ; mutable k: decoder -> decode } let i_rem decoder = decoder.i_len - decoder.i_pos + 1 let end_of_input decoder = decoder.i <- Bytes.empty ; decoder.i_off <- 0 ; decoder.i_pos <- 0 ; decoder.i_len <- min_int let src decoder source off len = if off < 0 || len < 0 || off + len > Bytes.length source then invalid_bounds off len else if len = 0 then end_of_input decoder else ( decoder.i <- source ; decoder.i_off <- off ; decoder.i_pos <- 0 ; decoder.i_len <- len - 1 ) let refill k decoder = match decoder.src with | `Manual -> decoder.k <- k ; `Await | `String _ -> end_of_input decoder ; k decoder | `Channel ic -> let len = input ic decoder.i 0 (Bytes.length decoder.i) in src decoder decoder.i 0 len ; k decoder let ret k v byte_count decoder = decoder.k <- k ; decoder.byte_count <- decoder.byte_count + byte_count ; decoder.pp decoder v let t_need decoder need = decoder.h_len <- 0 ; decoder.h_need <- need let rec t_fill k decoder = let blit decoder len = unsafe_blit decoder.i (decoder.i_off + decoder.i_pos) decoder.h decoder.h_len len ; decoder.i_pos <- decoder.i_pos + len ; decoder.h_len <- decoder.h_len + len in let rem = i_rem decoder in if rem < 0 (* end of input *) then k decoder else let need = decoder.h_need - decoder.h_len in if rem < need then ( blit decoder rem ; refill (t_fill k) decoder ) else ( blit decoder need ; k decoder ) let rec t_decode_inline_quoted_printable decoder = if decoder.h_len < decoder.h_need then ret decode_inline_quoted_printable (malformed decoder.h 0 0 decoder.h_len) decoder.h_len decoder (* XXX(dinosaure): malformed line? *) else ret decode_inline_quoted_printable (r_repr decoder.h 0 decoder.h_len) decoder.h_len decoder and decode_inline_quoted_printable decoder = let rem = i_rem decoder in if rem <= 0 then if rem < 0 then ret (fun _decoder -> `End) `End 0 decoder else refill decode_inline_quoted_printable decoder else match unsafe_byte decoder.i decoder.i_off decoder.i_pos with | '_' -> decoder.i_pos <- decoder.i_pos + 1 ; ret decode_inline_quoted_printable r_wsp 1 decoder | '=' -> t_need decoder 3 ; t_fill t_decode_inline_quoted_printable decoder | ('\033' .. '\060' | '\062' .. '\126') as chr -> decoder.i_pos <- decoder.i_pos + 1 ; ret decode_inline_quoted_printable (r_chr chr) 1 decoder | _ -> let j = decoder.i_pos in decoder.i_pos <- decoder.i_pos + 1 ; ret decode_inline_quoted_printable (malformed decoder.i decoder.i_off j 1) 1 decoder let pp_inline_quoted_printable _decoder = function | `Wsp -> `Char ' ' | `Chr chr -> `Char chr | `Repr byte -> `Char (unsafe_chr byte) | `End -> `End | `Malformed _ as v -> v let decoder src = let pp = pp_inline_quoted_printable in let k = decode_inline_quoted_printable in let i, i_off, i_pos, i_len = match src with | `Manual -> (Bytes.empty, 0, 1, 0) | `Channel _ -> (Bytes.create io_buffer_size, 0, 1, 0) | `String s -> (Bytes.unsafe_of_string s, 0, 0, String.length s - 1) in { src ; i_off ; i_pos ; i_len ; i ; h= Bytes.create 3 ; h_need= 0 ; h_len= 0 ; byte_count= 0 ; pp ; k } let decode decoder = decoder.k decoder let decoder_byte_count decoder = decoder.byte_count let decoder_src decoder = decoder.src type dst = [`Channel of out_channel | `Buffer of Buffer.t | `Manual] type encode = [`Await | `End | `Char of unsafe_char] type encoder = { dst: dst ; mutable o: Bytes.t ; mutable o_off: int ; mutable o_pos: int ; mutable o_len: int ; t: Bytes.t ; mutable t_pos: int ; mutable t_len: int ; mutable k: encoder -> encode -> [`Ok | `Partial] } let o_rem encoder = encoder.o_len - encoder.o_pos + 1 let dst encoder source off len = if off < 0 || len < 0 || off + len > Bytes.length source then invalid_bounds off len ; encoder.o <- source ; encoder.o_off <- off ; encoder.o_pos <- 0 ; encoder.o_len <- len - 1 let dst_rem = o_rem let partial k encoder = function | `Await -> k encoder | `Char _ | `End -> invalid_encode () let flush k encoder = match encoder.dst with | `Manual -> encoder.k <- partial k ; `Partial | `Channel oc -> output oc encoder.o encoder.o_off encoder.o_pos ; encoder.o_pos <- 0 ; k encoder | `Buffer b -> let o = Bytes.unsafe_to_string encoder.o in Buffer.add_substring b o encoder.o_off encoder.o_pos ; encoder.o_pos <- 0 ; k encoder let t_range encoder len = encoder.t_pos <- 0 ; encoder.t_len <- len let rec t_flush k encoder = let blit encoder len = unsafe_blit encoder.t encoder.t_pos encoder.o encoder.o_pos len ; encoder.o_pos <- encoder.o_pos + len ; encoder.t_pos <- encoder.t_pos + len in let rem = o_rem encoder in let len = encoder.t_len - encoder.t_pos + 1 in if rem < len then ( blit encoder rem ; flush (t_flush k) encoder ) else ( blit encoder len ; k encoder ) let to_hex code = match Char.unsafe_chr code with | '\000' .. '\009' -> Char.chr (Char.code '0' + code) | '\010' .. '\015' -> Char.chr (Char.code 'A' + code - 10) | _ -> assert false let rec encode_quoted_printable encoder v = let k encoder = encoder.k <- encode_quoted_printable ; `Ok in match v with | `Await -> k encoder | `End -> flush k encoder | `Char chr -> let rem = o_rem encoder in if rem < 1 then flush (fun encoder -> encode_quoted_printable encoder v) encoder else match chr with | ' ' -> unsafe_set_chr encoder.o (encoder.o_off + encoder.o_pos) '_' ; encoder.o_pos <- encoder.o_pos + 1 ; k encoder | '\033' .. '\060' | '\062' .. '\126' -> unsafe_set_chr encoder.o (encoder.o_off + encoder.o_pos) chr ; encoder.o_pos <- encoder.o_pos + 1 ; k encoder | unsafe_chr -> let hi = to_hex (Char.code unsafe_chr / 16) in let lo = to_hex (Char.code unsafe_chr mod 16) in let s, j, k = if rem < 3 then ( t_range encoder 3 ; (encoder.t, 0, t_flush k) ) else let j = encoder.o_pos in encoder.o_pos <- encoder.o_pos + 3 ; (encoder.o, encoder.o_off + j, k) in unsafe_set_chr s j '=' ; unsafe_set_chr s (j + 1) hi ; unsafe_set_chr s (j + 2) lo ; k encoder let encoder dst = let o, o_off, o_pos, o_len = match dst with | `Manual -> (Bytes.empty, 1, 0, 0) | `Buffer _ | `Channel _ -> (Bytes.create io_buffer_size, 0, 0, io_buffer_size - 1) in { dst ; o_off ; o_pos ; o_len ; o ; t= Bytes.create 3 ; t_pos= 1 ; t_len= 0 ; k= encode_quoted_printable } let encode encoder v = encoder.k encoder v let encoder_dst encoder = encoder.dst end (* Encode *) type unsafe_char = char type dst = [`Channel of out_channel | `Buffer of Buffer.t | `Manual] type encode = [`Await | `End | `Char of unsafe_char | `Line_break] type encoder = { dst: dst ; mutable o: Bytes.t ; mutable o_off: int ; mutable o_pos: int ; mutable o_len: int ; t: Bytes.t ; mutable t_pos: int ; mutable t_len: int ; mutable c_col: int ; mutable k: encoder -> encode -> [`Ok | `Partial] } let o_rem encoder = encoder.o_len - encoder.o_pos + 1 let dst encoder source off len = if off < 0 || len < 0 || off + len > Bytes.length source then invalid_bounds off len ; encoder.o <- source ; encoder.o_off <- off ; encoder.o_pos <- 0 ; encoder.o_len <- len - 1 let dst_rem = o_rem let partial k encoder = function | `Await -> k encoder | `Char _ | `Line_break | `End -> invalid_encode () let flush k encoder = match encoder.dst with | `Manual -> encoder.k <- partial k ; `Partial | `Channel oc -> output oc encoder.o encoder.o_off encoder.o_pos ; encoder.o_pos <- 0 ; k encoder | `Buffer b -> let o = Bytes.unsafe_to_string encoder.o in Buffer.add_substring b o encoder.o_off encoder.o_pos ; encoder.o_pos <- 0 ; k encoder let t_range encoder len = encoder.t_pos <- 0 ; encoder.t_len <- len let rec t_flush k encoder = let blit encoder len = unsafe_blit encoder.t encoder.t_pos encoder.o encoder.o_pos len ; encoder.o_pos <- encoder.o_pos + len ; encoder.t_pos <- encoder.t_pos + len in let rem = o_rem encoder in let len = encoder.t_len - encoder.t_pos + 1 in if rem < len then ( blit encoder rem ; flush (t_flush k) encoder ) else ( blit encoder len ; k encoder ) let to_hex code = match Char.unsafe_chr code with | '\000' .. '\009' -> Char.chr (Char.code '0' + code) | '\010' .. '\015' -> Char.chr (Char.code 'A' + code - 10) | _ -> assert false let rec encode_quoted_printable encoder v = let k col_count encoder = encoder.c_col <- encoder.c_col + col_count ; encoder.k <- encode_quoted_printable ; `Ok in match v with | `Await -> k 0 encoder | `End -> flush (k 0) encoder | `Line_break -> let rem = o_rem encoder in let s, j, k = if rem < 2 then ( t_range encoder 2 ; (encoder.t, 0, t_flush (k 2)) ) else let j = encoder.o_pos in encoder.o_pos <- encoder.o_pos + 2 ; (encoder.o, encoder.o_off + j, k 2) in unsafe_set_chr s j '\r' ; unsafe_set_chr s (j + 1) '\n' ; encoder.c_col <- 0 ; flush k encoder | `Char chr -> ( let rem = o_rem encoder in if rem < 1 then flush (fun encoder -> encode_quoted_printable encoder v) encoder else if encoder.c_col = 75 then encode_soft_line_break (fun encoder -> encode_quoted_printable encoder v) encoder else match chr with | '\033' .. '\060' | '\062' .. '\126' -> unsafe_set_chr encoder.o (encoder.o_off + encoder.o_pos) chr ; encoder.o_pos <- encoder.o_pos + 1 ; k 1 encoder | unsafe_chr -> if encoder.c_col < 73 then ( let hi = to_hex (Char.code unsafe_chr / 16) in let lo = to_hex (Char.code unsafe_chr mod 16) in let s, j, k = if rem < 3 then ( t_range encoder 3 ; (encoder.t, 0, t_flush (k 3)) ) else let j = encoder.o_pos in encoder.o_pos <- encoder.o_pos + 3 ; (encoder.o, encoder.o_off + j, k 3) in unsafe_set_chr s j '=' ; unsafe_set_chr s (j + 1) hi ; unsafe_set_chr s (j + 2) lo ; k encoder ) else encode_soft_line_break (fun encoder -> encode_quoted_printable encoder v) encoder ) and encode_soft_line_break k encoder = let rem = o_rem encoder in let s, j, k = if rem < 3 then ( t_range encoder 3 ; (encoder.t, 0, t_flush k) ) else let j = encoder.o_pos in encoder.o_pos <- encoder.o_pos + 3 ; (encoder.o, encoder.o_off + j, k) in unsafe_set_chr s j '=' ; unsafe_set_chr s (j + 1) '\r' ; unsafe_set_chr s (j + 2) '\n' ; encoder.c_col <- 0 ; flush k encoder let encoder dst = let o, o_off, o_pos, o_len = match dst with | `Manual -> (Bytes.empty, 1, 0, 0) | `Buffer _ | `Channel _ -> (Bytes.create io_buffer_size, 0, 0, io_buffer_size - 1) in { dst ; o_off ; o_pos ; o_len ; o ; t= Bytes.create 3 ; t_pos= 1 ; t_len= 0 ; c_col= 0 ; k= encode_quoted_printable } let encode encoder v = encoder.k encoder v let encoder_dst encoder = encoder.dst
subdir_set.mli
(** A possibly infinite set of subdirectories *) open Import type t = | All | These of String.Set.t val to_dir_set : t -> Path.Unspecified.w Dir_set.t val of_dir_set : 'a Dir_set.t -> t val of_list : string list -> t val empty : t val is_empty : t -> bool val mem : t -> string -> bool val union : t -> t -> t val inter_set : t -> String.Set.t -> String.Set.t val union_all : t list -> t
(** A possibly infinite set of subdirectories *)
string.mli
(** String operations. A string is an immutable data structure that contains a fixed-length sequence of (single-byte) characters. Each character can be accessed in constant time through its index. Given a string [s] of length [l], we can access each of the [l] characters of [s] via its index in the sequence. Indexes start at [0], and we will call an index valid in [s] if it falls within the range [[0...l-1]] (inclusive). A position is the point between two characters or at the beginning or end of the string. We call a position valid in [s] if it falls within the range [[0...l]] (inclusive). Note that the character at index [n] is between positions [n] and [n+1]. Two parameters [start] and [len] are said to designate a valid substring of [s] if [len >= 0] and [start] and [start+len] are valid positions in [s]. Note: OCaml strings used to be modifiable in place, for instance via the {!String.set} and {!String.blit} functions described below. This usage is only possible when the compiler is put in "unsafe-string" mode by giving the [-unsafe-string] command-line option. This compatibility mode makes the types [string] and [bytes] (see module {!Bytes}) interchangeable so that functions expecting byte sequences can also accept strings as arguments and modify them. The distinction between [bytes] and [string] was introduced in OCaml 4.02, and the "unsafe-string" compatibility mode was the default until OCaml 4.05. Starting with 4.06, the compatibility mode is opt-in; we intend to remove the option in the future. *) external length : string -> int = "%string_length" (** Return the length (number of characters) of the given string. *) external get : string -> int -> char = "%string_safe_get" (** [String.get s n] returns the character at index [n] in string [s]. You can also write [s.[n]] instead of [String.get s n]. Raise [Invalid_argument] if [n] not a valid index in [s]. *) val make : int -> char -> string (** [String.make n c] returns a fresh string of length [n], filled with the character [c]. Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *) val init : int -> (int -> char) -> string (** [String.init n f] returns a string of length [n], with character [i] initialized to the result of [f i] (called in increasing index order). Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. @since 4.02.0 *) val sub : string -> int -> int -> string (** [String.sub s start len] returns a fresh string of length [len], containing the substring of [s] that starts at position [start] and has length [len]. Raise [Invalid_argument] if [start] and [len] do not designate a valid substring of [s]. *) val blit : string -> int -> bytes -> int -> int -> unit (** Same as {!Bytes.blit_string}. *) val concat : string -> string list -> string (** [String.concat sep sl] concatenates the list of strings [sl], inserting the separator string [sep] between each. Raise [Invalid_argument] if the result is longer than {!Sys.max_string_length} bytes. *) val iter : (char -> unit) -> string -> unit (** [String.iter f s] applies function [f] in turn to all the characters of [s]. It is equivalent to [f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. *) val iteri : (int -> char -> unit) -> string -> unit (** Same as {!String.iter}, but the function is applied to the index of the element as first argument (counting from 0), and the character itself as second argument. @since 4.00.0 *) val map : (char -> char) -> string -> string (** [String.map f s] applies function [f] in turn to all the characters of [s] (in increasing index order) and stores the results in a new string that is returned. @since 4.00.0 *) val mapi : (int -> char -> char) -> string -> string (** [String.mapi f s] calls [f] with each character of [s] and its index (in increasing index order) and stores the results in a new string that is returned. @since 4.02.0 *) val trim : string -> string (** Return a copy of the argument, without leading and trailing whitespace. The characters regarded as whitespace are: [' '], ['\012'], ['\n'], ['\r'], and ['\t']. If there is neither leading nor trailing whitespace character in the argument, return the original string itself, not a copy. @since 4.00.0 *) val escaped : string -> string (** Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. If there is no special character in the argument that needs escaping, return the original string itself, not a copy. Raise [Invalid_argument] if the result is longer than {!Sys.max_string_length} bytes. The function {!Scanf.unescaped} is a left inverse of [escaped], i.e. [Scanf.unescaped (escaped s) = s] for any string [s] (unless [escape s] fails). *) val index_opt: string -> char -> int option (** [String.index_opt s c] returns the index of the first occurrence of character [c] in string [s], or [None] if [c] does not occur in [s]. @since 4.05 *) val rindex_opt: string -> char -> int option (** [String.rindex_opt s c] returns the index of the last occurrence of character [c] in string [s], or [None] if [c] does not occur in [s]. @since 4.05 *) val index_from_opt: string -> int -> char -> int option (** [String.index_from_opt s i c] returns the index of the first occurrence of character [c] in string [s] after position [i] or [None] if [c] does not occur in [s] after position [i]. [String.index_opt s c] is equivalent to [String.index_from_opt s 0 c]. Raise [Invalid_argument] if [i] is not a valid position in [s]. @since 4.05 *) val rindex_from_opt: string -> int -> char -> int option (** [String.rindex_from_opt s i c] returns the index of the last occurrence of character [c] in string [s] before position [i+1] or [None] if [c] does not occur in [s] before position [i+1]. [String.rindex_opt s c] is equivalent to [String.rindex_from_opt s (String.length s - 1) c]. Raise [Invalid_argument] if [i+1] is not a valid position in [s]. @since 4.05 *) val contains : string -> char -> bool (** [String.contains s c] tests if character [c] appears in the string [s]. *) val contains_from : string -> int -> char -> bool (** [String.contains_from s start c] tests if character [c] appears in [s] after position [start]. [String.contains s c] is equivalent to [String.contains_from s 0 c]. Raise [Invalid_argument] if [start] is not a valid position in [s]. *) val rcontains_from : string -> int -> char -> bool (** [String.rcontains_from s stop c] tests if character [c] appears in [s] before position [stop+1]. Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid position in [s]. *) val uppercase_ascii : string -> string (** Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. @since 4.03.0 *) val lowercase_ascii : string -> string (** Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. @since 4.03.0 *) val capitalize_ascii : string -> string (** Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. @since 4.03.0 *) val uncapitalize_ascii : string -> string (** Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. @since 4.03.0 *) type t = string (** An alias for the type of strings. *) val compare: t -> t -> int (** The comparison function for strings, with the same specification as {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [String] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val equal: t -> t -> bool (** The equal function for strings. @since 4.03.0 *) val split_on_char: char -> string -> string list (** [String.split_on_char sep s] returns the list of all (possibly empty) substrings of [s] that are delimited by the [sep] character. The function's output is specified by the following invariants: - The list is not empty. - Concatenating its elements using [sep] as a separator returns a string equal to the input ([String.concat (String.make 1 sep) (String.split_on_char sep s) = s]). - No string in the result contains the [sep] character. @since 4.04.0 *)
(**************************************************************************) (* *) (* 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. *) (* *) (**************************************************************************)
test_graph.mli
val suite : unit Alcotest.test_case list
michelson_v1_macros.mli
open Tezos_micheline type 'l node = ('l, string) Micheline.node type error += Unexpected_macro_annotation of string type error += Sequence_expected of string type error += Invalid_arity of string * int * int val expand : 'l node -> 'l node tzresult val expand_rec : 'l node -> 'l node * error list val expand_caddadr : 'l node -> 'l node option tzresult val expand_set_caddadr : 'l node -> 'l node option tzresult val expand_map_caddadr : 'l node -> 'l node option tzresult val expand_dxiiivp : 'l node -> 'l node option tzresult val expand_pappaiir : 'l node -> 'l node option tzresult val expand_duuuuup : 'l node -> 'l node option tzresult val expand_compare : 'l node -> 'l node option tzresult val expand_asserts : 'l node -> 'l node option tzresult val expand_unpappaiir : 'l node -> 'l node option tzresult val expand_if_some : 'l node -> 'l node option tzresult val expand_if_right : 'l node -> 'l node option tzresult val unexpand : 'l node -> 'l node val unexpand_rec : 'l node -> 'l node val unexpand_caddadr : 'l node -> 'l node option val unexpand_set_caddadr : 'l node -> 'l node option val unexpand_map_caddadr : 'l node -> 'l node option val unexpand_dxiiivp : 'l node -> 'l node option val unexpand_pappaiir : 'l node -> 'l node option val unexpand_duuuuup : 'l node -> 'l node option val unexpand_compare : 'l node -> 'l node option val unexpand_asserts : 'l node -> 'l node option val unexpand_unpappaiir : 'l node -> 'l node option val unexpand_if_some : 'l node -> 'l node option val unexpand_if_right : 'l node -> 'l node option
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
memory.ml
type proc_statm = { page_size : int; size : int64; resident : int64; shared : int64; text : int64; lib : int64; data : int64; dt : int64; } type ps_stats = {page_size : int; mem : float; resident : int64} type mem_stats = Statm of proc_statm | Ps of ps_stats
(*****************************************************************************) (* Open Source License *) (* Copyright (c) 2018 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. *) (* *) (*****************************************************************************)
flexible-array-member.c
#include "testharness.h" struct s { unsigned long x; int y; char t[]; }; int main(){ struct s a = { .x = sizeof(a), .y = 2, } ; static struct s b = { .x = sizeof(b), .y = 2, .t = {1,2,3} } ; /* the previous length of t is 3 - check that we do not truncate to 3 * here as well. */ static struct s c = { .x = sizeof(b), .y = 2, .t = {1,2,3,4,5} } ; if(a.x != sizeof(struct s)) E(1); if(b.t[2] != 3) E(2); if(c.t[4] != 5) E(2); SUCCESS; }
test.ml
(* Tests to validate implemented functions/ modules *) let read_file f = let ic = open_in f in let rec loop acc = try loop (input_line ic :: acc) with End_of_file -> close_in ic; List.rev acc in let lines = try loop [] with _ -> close_in ic; failwith "Something went wrong reading file" in String.concat "\n" lines module Ezjsonm_parser = struct type t = Ezjsonm.value let catch_err f v = try Ok (f v) with Ezjsonm.Parse_error (_, s) -> Error (`Msg s) let find = Ezjsonm.find_opt let to_string t = catch_err Ezjsonm.get_string t let string = Ezjsonm.string let to_float t = catch_err Ezjsonm.get_float t let float = Ezjsonm.float let to_int t = catch_err Ezjsonm.get_int t let int = Ezjsonm.int let to_list f t = catch_err (Ezjsonm.get_list f) t let list f t = Ezjsonm.list f t let to_array f t = Result.map Array.of_list @@ to_list f t let array f t = list f (Array.to_list t) let to_obj t = catch_err Ezjsonm.get_dict t let obj = Ezjsonm.dict let null = `Null let is_null = function `Null -> true | _ -> false end module Topojson = Topojson.Make (Ezjsonm_parser) let expected_arcs = let open Topojson in let pos arr = Geometry.Position.v ~lat:arr.(1) ~lng:arr.(0) () in Array.map (Array.map pos) [| [| [| 102.; 0. |]; [| 103.; 1. |]; [| 104.; 0. |]; [| 105.; 1. |] |]; [| [| 100.; 0. |]; [| 101.; 0. |]; [| 101.; 1. |]; [| 100.; 1. |]; [| 100.; 0. |]; |]; |] let pp_position ppf t = let open Topojson.Geometry in let lat = Position.lat t in let lng = Position.lng t in Fmt.pf ppf "[%f, %f]" lat lng let position = Alcotest.testable pp_position Stdlib.( = ) let msg = Alcotest.testable (fun ppf (`Msg m) -> Fmt.pf ppf "%s" m) Stdlib.( = ) let pp_topojson ppf v = Fmt.pf ppf "%s" (Ezjsonm.value_to_string @@ Topojson.to_json v) let topojson = Alcotest.testable pp_topojson Stdlib.( = ) (* Comparing two JSON objects encoded using Ezjsonm -- might be useful to upstream this at some point. This deals with the fact that two object association lists could have a different key-value ordering. *) let rec ezjsonm_equal a b = match (a, b) with | `Null, `Null -> true | `Float a, `Float b -> Float.equal a b | `String a, `String b -> String.equal a b | `Bool a, `Bool b -> Bool.equal a b | `A xs, `A ys -> List.for_all2 ezjsonm_equal xs ys | `O [], `O [] -> true | `O ((k, v) :: xs), `O ys -> ( match List.assoc_opt k ys with | None -> false | Some v' -> ezjsonm_equal v v' && ezjsonm_equal (`O xs) (`O (remove [] k ys))) | _ -> false and remove acc k = function | [] -> List.rev acc | (k', _) :: rest when k = k' -> List.rev acc @ rest | x :: rest -> remove (x :: acc) k rest let ezjsonm = Alcotest.testable (fun ppf t -> Fmt.pf ppf "%s" (Ezjsonm.value_to_string t)) ezjsonm_equal let get_foreign_members_in_point (f : Topojson.Topology.t) = let open Topojson in let objs = List.hd (Topology.objects f) |> snd in match Geometry.geometry objs with | Geometry.Collection (point :: _) -> Geometry.foreign_members point | _ -> assert false let pp_ezjsonm ppf json = Fmt.pf ppf "%s" (Ezjsonm.value_to_string json) let pp_geometry ppf tt = Fmt.pf ppf "%s" (Ezjsonm.value_to_string (Topojson.Geometry.to_json tt)) let pp_inner_geometry ppf (g : Topojson.Geometry.geometry) = Fmt.pf ppf "%a" pp_geometry (Topojson.Geometry.v g) let inner_geometry = Alcotest.testable pp_inner_geometry Stdlib.( = ) let pp_foreign_member ppf (v : (string * Ezjsonm.value) list) = Fmt.pf ppf "%a" Fmt.(list (pair string pp_ezjsonm)) v let expected_foreign_members = [ ("arcs", `A [ `Float 0.1 ]) ] let foreign_members = Alcotest.testable pp_foreign_member Stdlib.( = ) let pp_transform ppf (t : Topojson.Topology.transform) = Fmt.pf ppf "translate: (%a), scale: (%a)" Fmt.(pair float float) t.translate Fmt.(pair float float) t.scale let transform = Alcotest.testable pp_transform Stdlib.( = ) let geometries () = let open Topojson in let s = read_file "./test_cases/topology.json" in let json = Ezjsonm.value_from_string s in let o = Topojson.of_json json |> Result.get_ok in let f = Topojson.topojson o |> function | Topology f -> f | _ -> failwith "Expected topology" in let objs = List.hd (Topology.objects f) |> snd in match Geometry.geometry objs with | Collection [ point; linestring; polygon ] -> let geo_point = Geometry.geometry point in let expected_point = Geometry.(point (Position.v ~lng:102. ~lat:0.5 ())) in Alcotest.(check inner_geometry) "same point" geo_point expected_point; let geo_linestring = Geometry.geometry linestring in let expected_linestring = Geometry.(linestring @@ Arc_index.v [ 0 ]) in Alcotest.(check inner_geometry) "same point" geo_linestring expected_linestring; let geo_polygon = Geometry.geometry polygon in let expected_polygon = Geometry.(polygon [| LineString.v @@ Arc_index.v [ -2 ] |]) in Alcotest.(check inner_geometry) "same point" geo_polygon expected_polygon | _ -> Alcotest.fail "Expected a collection of geometries" let main () = let s = read_file "./test_cases/topology.json" in let json = Ezjsonm.value_from_string s in let topojson_obj = Topojson.of_json json in match (topojson_obj, Result.map Topojson.topojson topojson_obj) with | Ok t, Ok (Topojson.Topology f) -> (* Here we check that the arcs defined in the file are the same as the ones we hardcoded above *) Alcotest.(check (array (array position))) "same arcs" (Topojson.Topology.arcs f) expected_arcs; (* Then we check that converting the Topojson OCaml value to JSON and then back again produces the same Topojson OCaml value. *) Alcotest.(check foreign_members) "same foreign_members" expected_foreign_members (get_foreign_members_in_point f); let expected_transform = Topojson.Topology.{ scale = (0.0005, 0.0001); translate = (100.0, 0.0) } in Alcotest.(check (option transform)) "same transform" (Some expected_transform) (Topojson.Topology.transform f); let output_json = Topojson.to_json t in Alcotest.(check ezjsonm) "same ezjsonm" json output_json; Alcotest.(check (result topojson msg)) "same topojson" topojson_obj (Topojson.of_json output_json) | Ok _, Ok (Topojson.Geometry _) -> assert false | Error (`Msg m), _ -> failwith m | _, Error (`Msg m) -> failwith m let properties () = let s = read_file "./test_cases/properties.json" in let json = Ezjsonm.value_from_string s in let objs = Topojson.of_json json |> Result.get_ok |> Topojson.topology_exn |> Topojson.Topology.objects in let names = List.map fst objs in Alcotest.(check (list string)) "same names" [ "point"; "points"; "collection"; "polygon" ] names; let points = List.assoc "points" objs in let props = match Topojson.Geometry.properties points with | `Obj props -> props | _ -> Alcotest.fail "exptected properties" in Alcotest.(check ezjsonm) "same props" (`O [ ("name", `String "Sir Points-a-Lot") ]) (`O props); let multipoint = Topojson.Geometry.get_multipoint_exn (Topojson.Geometry.geometry points) in let coords = Topojson.Geometry.MultiPoint.coordinates multipoint in Alcotest.(check (array @@ array (float 1.))) "same coords" [| [| 1000.; 2000. |]; [| 3000.; 4000. |] |] coords let in_and_out path () = let s = read_file path in let json = Ezjsonm.value_from_string s in let topojson = Topojson.of_json json |> Result.get_ok in let s' = Topojson.to_json topojson |> Ezjsonm.value_to_string in let json = Ezjsonm.value_from_string s' in let topojson' = Topojson.of_json json |> Result.get_ok in Alcotest.(check ezjsonm) "same topojson" (Topojson.to_json topojson) (Topojson.to_json topojson') let paths = Array.map (( ^ ) "./test_cases/") (Sys.readdir "test_cases") |> Array.to_list let () = Alcotest.run "topojson" [ ( "parsing", [ ("simple", `Quick, main); ("geometries", `Quick, geometries); ("properties", `Quick, properties); ] @ List.map (fun p -> ("read-write", `Quick, in_and_out p)) paths ); ]
(* Tests to validate implemented functions/ modules *) let read_file f =
delegate_services.ml
open Alpha_context type info = { balance: Tez.t ; frozen_balance: Tez.t ; frozen_balance_by_cycle: Delegate.frozen_balance Cycle.Map.t ; staking_balance: Tez.t ; delegated_contracts: Contract_hash.t list ; delegated_balance: Tez.t ; deactivated: bool ; grace_period: Cycle.t ; } let info_encoding = let open Data_encoding in conv (fun { balance ; frozen_balance ; frozen_balance_by_cycle ; staking_balance ; delegated_contracts ; delegated_balance ; deactivated ; grace_period } -> (balance, frozen_balance, frozen_balance_by_cycle, staking_balance, delegated_contracts, delegated_balance, deactivated, grace_period)) (fun (balance, frozen_balance, frozen_balance_by_cycle, staking_balance, delegated_contracts, delegated_balance, deactivated, grace_period) -> { balance ; frozen_balance ; frozen_balance_by_cycle ; staking_balance ; delegated_contracts ; delegated_balance ; deactivated ; grace_period }) (obj8 (req "balance" Tez.encoding) (req "frozen_balance" Tez.encoding) (req "frozen_balance_by_cycle" Delegate.frozen_balance_by_cycle_encoding) (req "staking_balance" Tez.encoding) (req "delegated_contracts" (list Contract_hash.encoding)) (req "delegated_balance" Tez.encoding) (req "deactivated" bool) (req "grace_period" Cycle.encoding)) module S = struct let path = RPC_path.(open_root / "context" / "delegates") open Data_encoding type list_query = { active: bool ; inactive: bool ; } let list_query :list_query RPC_query.t = let open RPC_query in query (fun active inactive -> { active ; inactive }) |+ flag "active" (fun t -> t.active) |+ flag "inactive" (fun t -> t.inactive) |> seal let list_delegate = RPC_service.get_service ~description: "Lists all registered delegates." ~query: list_query ~output: (list Signature.Public_key_hash.encoding) path let path = RPC_path.(path /: Signature.Public_key_hash.rpc_arg) let info = RPC_service.get_service ~description: "Everything about a delegate." ~query: RPC_query.empty ~output: info_encoding path let balance = RPC_service.get_service ~description: "Returns the full balance of a given delegate, \ including the frozen balances." ~query: RPC_query.empty ~output: Tez.encoding RPC_path.(path / "balance") let frozen_balance = RPC_service.get_service ~description: "Returns the total frozen balances of a given delegate, \ this includes the frozen deposits, rewards and fees." ~query: RPC_query.empty ~output: Tez.encoding RPC_path.(path / "frozen_balance") let frozen_balance_by_cycle = RPC_service.get_service ~description: "Returns the frozen balances of a given delegate, \ indexed by the cycle by which it will be unfrozen" ~query: RPC_query.empty ~output: Delegate.frozen_balance_by_cycle_encoding RPC_path.(path / "frozen_balance_by_cycle") let staking_balance = RPC_service.get_service ~description: "Returns the total amount of tokens delegated to a given delegate. \ This includes the balances of all the contracts that delegate \ to it, but also the balance of the delegate itself and its frozen \ fees and deposits. The rewards do not count in the delegated balance \ until they are unfrozen." ~query: RPC_query.empty ~output: Tez.encoding RPC_path.(path / "staking_balance") let delegated_contracts = RPC_service.get_service ~description: "Returns the list of contracts that delegate to a given delegate." ~query: RPC_query.empty ~output: (list Contract_hash.encoding) RPC_path.(path / "delegated_contracts") let delegated_balance = RPC_service.get_service ~description: "Returns the balances of all the contracts that delegate to a \ given delegate. This excludes the delegate's own balance and \ its frozen balances." ~query: RPC_query.empty ~output: Tez.encoding RPC_path.(path / "delegated_balance") let deactivated = RPC_service.get_service ~description: "Tells whether the delegate is currently tagged as deactivated or not." ~query: RPC_query.empty ~output: bool RPC_path.(path / "deactivated") let grace_period = RPC_service.get_service ~description: "Returns the cycle by the end of which the delegate might be \ deactivated if she fails to execute any delegate action. \ A deactivated delegate might be reactivated \ (without loosing any rolls) by simply re-registering as a delegate. \ For deactivated delegates, this value contains the cycle by which \ they were deactivated." ~query: RPC_query.empty ~output: Cycle.encoding RPC_path.(path / "grace_period") end let register () = let open Services_registration in register0 S.list_delegate begin fun ctxt q () -> Delegate.list ctxt >>= fun delegates -> if q.active && q.inactive then return delegates else if q.active then Lwt_list.filter_p (fun pkh -> Delegate.deactivated ctxt pkh >|= not) delegates >>= return else if q.inactive then Lwt_list.filter_p (fun pkh -> Delegate.deactivated ctxt pkh) delegates >>= return else return_nil end ; register1 S.info begin fun ctxt pkh () () -> Delegate.full_balance ctxt pkh >>=? fun balance -> Delegate.frozen_balance ctxt pkh >>=? fun frozen_balance -> Delegate.frozen_balance_by_cycle ctxt pkh >>= fun frozen_balance_by_cycle -> Delegate.staking_balance ctxt pkh >>=? fun staking_balance -> Delegate.delegated_contracts ctxt pkh >>= fun delegated_contracts -> Delegate.delegated_balance ctxt pkh >>=? fun delegated_balance -> Delegate.deactivated ctxt pkh >>= fun deactivated -> Delegate.grace_period ctxt pkh >>=? fun grace_period -> return { balance ; frozen_balance ; frozen_balance_by_cycle ; staking_balance ; delegated_contracts ; delegated_balance ; deactivated ; grace_period } end ; register1 S.balance begin fun ctxt pkh () () -> Delegate.full_balance ctxt pkh end ; register1 S.frozen_balance begin fun ctxt pkh () () -> Delegate.frozen_balance ctxt pkh end ; register1 S.frozen_balance_by_cycle begin fun ctxt pkh () () -> Delegate.frozen_balance_by_cycle ctxt pkh >>= return end ; register1 S.staking_balance begin fun ctxt pkh () () -> Delegate.staking_balance ctxt pkh end ; register1 S.delegated_contracts begin fun ctxt pkh () () -> Delegate.delegated_contracts ctxt pkh >>= return end ; register1 S.delegated_balance begin fun ctxt pkh () () -> Delegate.delegated_balance ctxt pkh end ; register1 S.deactivated begin fun ctxt pkh () () -> Delegate.deactivated ctxt pkh >>= return end ; register1 S.grace_period begin fun ctxt pkh () () -> Delegate.grace_period ctxt pkh end let list ctxt block ?(active = true) ?(inactive = false) () = RPC_context.make_call0 S.list_delegate ctxt block { active ; inactive } () let info ctxt block pkh = RPC_context.make_call1 S.info ctxt block pkh () () let balance ctxt block pkh = RPC_context.make_call1 S.balance ctxt block pkh () () let frozen_balance ctxt block pkh = RPC_context.make_call1 S.frozen_balance ctxt block pkh () () let frozen_balance_by_cycle ctxt block pkh = RPC_context.make_call1 S.frozen_balance_by_cycle ctxt block pkh () () let staking_balance ctxt block pkh = RPC_context.make_call1 S.staking_balance ctxt block pkh () () let delegated_contracts ctxt block pkh = RPC_context.make_call1 S.delegated_contracts ctxt block pkh () () let delegated_balance ctxt block pkh = RPC_context.make_call1 S.delegated_balance ctxt block pkh () () let deactivated ctxt block pkh = RPC_context.make_call1 S.deactivated ctxt block pkh () () let grace_period ctxt block pkh = RPC_context.make_call1 S.grace_period ctxt block pkh () () let requested_levels ~default ctxt cycles levels = match levels, cycles with | [], [] -> return [default] | levels, cycles -> (* explicitly fail when requested levels or cycle are in the past... or too far in the future... *) let levels = List.sort_uniq Level.compare (List.concat (List.map (Level.from_raw ctxt) levels :: List.map (Level.levels_in_cycle ctxt) cycles)) in map_p (fun level -> let current_level = Level.current ctxt in if Level.(level <= current_level) then return (level, None) else Baking.earlier_predecessor_timestamp ctxt level >>=? fun timestamp -> return (level, Some timestamp)) levels module Baking_rights = struct type t = { level: Raw_level.t ; delegate: Signature.Public_key_hash.t ; priority: int ; timestamp: Timestamp.t option ; } let encoding = let open Data_encoding in conv (fun { level ; delegate ; priority ; timestamp } -> (level, delegate, priority, timestamp)) (fun (level, delegate, priority, timestamp) -> { level ; delegate ; priority ; timestamp }) (obj4 (req "level" Raw_level.encoding) (req "delegate" Signature.Public_key_hash.encoding) (req "priority" uint16) (opt "estimated_time" Timestamp.encoding)) module S = struct open Data_encoding let custom_root = RPC_path.(open_root / "helpers" / "baking_rights") type baking_rights_query = { levels: Raw_level.t list ; cycles: Cycle.t list ; delegates: Signature.Public_key_hash.t list ; max_priority: int option ; all: bool ; } let baking_rights_query = let open RPC_query in query (fun levels cycles delegates max_priority all -> { levels ; cycles ; delegates ; max_priority ; all }) |+ multi_field "level" Raw_level.rpc_arg (fun t -> t.levels) |+ multi_field "cycle" Cycle.rpc_arg (fun t -> t.cycles) |+ multi_field "delegate" Signature.Public_key_hash.rpc_arg (fun t -> t.delegates) |+ opt_field "max_priority" RPC_arg.int (fun t -> t.max_priority) |+ flag "all" (fun t -> t.all) |> seal let baking_rights = RPC_service.get_service ~description: "Retrieves the list of delegates allowed to bake a block.\n\ By default, it gives the best baking priorities for bakers \ that have at least one opportunity below the 64th priority \ for the next block.\n\ Parameters `level` and `cycle` can be used to specify the \ (valid) level(s) in the past or future at which the baking \ rights have to be returned. Parameter `delegate` can be \ used to restrict the results to the given delegates. If \ parameter `all` is set, all the baking opportunities for \ each baker at each level are returned, instead of just the \ first one.\n\ Returns the list of baking slots. Also returns the minimal \ timestamps that correspond to these slots. The timestamps \ are omitted for levels in the past, and are only estimates \ for levels later that the next block, based on the \ hypothesis that all predecessor blocks were baked at the \ first priority." ~query: baking_rights_query ~output: (list encoding) custom_root end let baking_priorities ctxt max_prio (level, pred_timestamp) = Baking.baking_priorities ctxt level >>=? fun contract_list -> let rec loop l acc priority = if Compare.Int.(priority >= max_prio) then return (List.rev acc) else let Misc.LCons (pk, next) = l in let delegate = Signature.Public_key.hash pk in begin match pred_timestamp with | None -> return_none | Some pred_timestamp -> Baking.minimal_time ctxt priority pred_timestamp >>=? fun t -> return_some t end>>=? fun timestamp -> let acc = { level = level.level ; delegate ; priority ; timestamp } :: acc in next () >>=? fun l -> loop l acc (priority+1) in loop contract_list [] 0 let remove_duplicated_delegates rights = List.rev @@ fst @@ List.fold_left (fun (acc, previous) r -> if Signature.Public_key_hash.Set.mem r.delegate previous then (acc, previous) else (r :: acc, Signature.Public_key_hash.Set.add r.delegate previous)) ([], Signature.Public_key_hash.Set.empty) rights let register () = let open Services_registration in register0 S.baking_rights begin fun ctxt q () -> requested_levels ~default: (Level.succ ctxt (Level.current ctxt), Some (Timestamp.current ctxt)) ctxt q.cycles q.levels >>=? fun levels -> let max_priority = match q.max_priority with | None -> 64 | Some max -> max in map_p (baking_priorities ctxt max_priority) levels >>=? fun rights -> let rights = if q.all then rights else List.map remove_duplicated_delegates rights in let rights = List.concat rights in match q.delegates with | [] -> return rights | _ :: _ as delegates -> let is_requested p = List.exists (Signature.Public_key_hash.equal p.delegate) delegates in return (List.filter is_requested rights) end let get ctxt ?(levels = []) ?(cycles = []) ?(delegates = []) ?(all = false) ?max_priority block = RPC_context.make_call0 S.baking_rights ctxt block { levels ; cycles ; delegates ; max_priority ; all } () end module Endorsing_rights = struct type t = { level: Raw_level.t ; delegate: Signature.Public_key_hash.t ; slots: int list ; estimated_time: Time.t option ; } let encoding = let open Data_encoding in conv (fun { level ; delegate ; slots ; estimated_time } -> (level, delegate, slots, estimated_time)) (fun (level, delegate, slots, estimated_time) -> { level ; delegate ; slots ; estimated_time }) (obj4 (req "level" Raw_level.encoding) (req "delegate" Signature.Public_key_hash.encoding) (req "slots" (list uint16)) (opt "estimated_time" Timestamp.encoding)) module S = struct open Data_encoding let custom_root = RPC_path.(open_root / "helpers" / "endorsing_rights") type endorsing_rights_query = { levels: Raw_level.t list ; cycles: Cycle.t list ; delegates: Signature.Public_key_hash.t list ; } let endorsing_rights_query = let open RPC_query in query (fun levels cycles delegates -> { levels ; cycles ; delegates }) |+ multi_field "level" Raw_level.rpc_arg (fun t -> t.levels) |+ multi_field "cycle" Cycle.rpc_arg (fun t -> t.cycles) |+ multi_field "delegate" Signature.Public_key_hash.rpc_arg (fun t -> t.delegates) |> seal let endorsing_rights = RPC_service.get_service ~description: "Retrieves the delegates allowed to endorse a block.\n\ By default, it gives the endorsement slots for delegates that \ have at least one in the next block.\n\ Parameters `level` and `cycle` can be used to specify the \ (valid) level(s) in the past or future at which the \ endorsement rights have to be returned. Parameter \ `delegate` can be used to restrict the results to the given \ delegates.\n\ Returns the list of endorsement slots. Also returns the \ minimal timestamps that correspond to these slots. The \ timestamps are omitted for levels in the past, and are only \ estimates for levels later that the next block, based on \ the hypothesis that all predecessor blocks were baked at \ the first priority." ~query: endorsing_rights_query ~output: (list encoding) custom_root end let endorsement_slots ctxt (level, estimated_time) = Baking.endorsement_rights ctxt level >>=? fun rights -> return (Signature.Public_key_hash.Map.fold (fun delegate (_, slots, _) acc -> { level = level.level ; delegate ; slots ; estimated_time } :: acc) rights []) let register () = let open Services_registration in register0 S.endorsing_rights begin fun ctxt q () -> requested_levels ~default: (Level.current ctxt, Some (Timestamp.current ctxt)) ctxt q.cycles q.levels >>=? fun levels -> map_p (endorsement_slots ctxt) levels >>=? fun rights -> let rights = List.concat rights in match q.delegates with | [] -> return rights | _ :: _ as delegates -> let is_requested p = List.exists (Signature.Public_key_hash.equal p.delegate) delegates in return (List.filter is_requested rights) end let get ctxt ?(levels = []) ?(cycles = []) ?(delegates = []) block = RPC_context.make_call0 S.endorsing_rights ctxt block { levels ; cycles ; delegates } () end let register () = register () ; Baking_rights.register () ; Endorsing_rights.register () let endorsement_rights ctxt level = Endorsing_rights.endorsement_slots ctxt (level, None) >>=? fun l -> return (List.map (fun { Endorsing_rights.delegate ; _ } -> delegate) l) let baking_rights ctxt max_priority = let max = match max_priority with None -> 64 | Some m -> m in let level = Level.current ctxt in Baking_rights.baking_priorities ctxt max (level, None) >>=? fun l -> return (level.level, List.map (fun { Baking_rights.delegate ; timestamp ; _ } -> (delegate, timestamp)) l)
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
step.mli
(** Implementation of the Cucumber Step (Given, When, Then). This is mainly used by the runtime to manipulate the step. *) type t type arg = DocString of Docstring.t | Table of Table.t val string_of_arg : arg option -> string val string_of_step : t -> string (** Match a user supplied regular expression to a step. *) val find : t -> Re.re -> bool (** Extract string groups from the step to pass to a user supplied function *) val find_groups : t -> Re.re -> Re.Group.t option (** Obtain the full text string of a step *) val text : t -> string (** Extract arguments to a step *) val argument : t -> arg option
(** Implementation of the Cucumber Step (Given, When, Then). This is mainly used by the runtime to manipulate the step. *)
main.ml
(** Testing ------- Component: Protocol Invocation: dune runtest src/proto_alpha/lib_protocol/test/integration/operations Subject: Entrypoint *) let () = Alcotest_lwt.run "protocol > integration > operations" [ ("voting", Test_voting.tests); ("origination", Test_origination.tests); ("revelation", Test_reveal.tests); ("transfer", Test_transfer.tests); ("activation", Test_activation.tests); ("combined", Test_combined_operations.tests); ("failing_noop operation", Test_failing_noop.tests); ("tx rollup", Test_tx_rollup.tests); ("sc rollup", Test_sc_rollup.tests); ] |> Lwt_main.run
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
imageUtil_unix.ml
open ImageUtil (** [chop_extension' fname] is the same as [Filename.chop_extension fname] but if [fname] does not have an extension, [fname] is returned instead of raising [Invalid_argument]. *) let chop_extension' fname = try Filename.chop_extension fname with _ -> fname (** [get_extension fname] returns the extension of the file [fname]. If the file does not have an extension, [Invalid_argument] is raised. *) let get_extension fname = let baselen = String.length (chop_extension' fname) in let extlen = String.length fname - baselen - 1 in if extlen <= 0 then let err = Printf.sprintf "No extension in filename '%s'." fname in raise (Invalid_argument err) else String.sub fname (baselen + 1) extlen (** [get_extension' fname] is the same as [get_extension fname] but if [fname] does not have an extension, the empty string is returned and no exception is raised. *) let get_extension' fname = try get_extension fname with _ -> "" (* * Reads all the lines in the channel by calling input_line. * Returns a list of strings. *) let lines_from_channel ich = let lines = ref [] in let rec intfun () = try let l = input_line ich in lines := l :: !lines; intfun (); with | End_of_file -> close_in ich | e -> close_in ich; raise e in intfun (); List.rev !lines (* * Same as lines_from_channel but from a file. *) let lines_from_file fn = let ich = open_in_bin fn in let ls = lines_from_channel ich in close_in ich; ls let chunk_reader_of_in_channel ich : chunk_reader = function | `Bytes num_bytes -> begin try Ok (really_input_string ich num_bytes) with | End_of_file -> let offset = pos_in ich in close_in ich ; Error (`End_of_file offset ) | e -> close_in ich ; raise e end | `Close -> close_in ich; Ok "" let chunk_writer_of_out_channel och : chunk_writer = function | `String x -> ( try Ok (output_string och x) with | _ -> close_out och; Error `Write_error) | `Close -> close_out och; Ok () let chunk_reader_of_path fn = chunk_reader_of_in_channel (open_in_bin fn) let chunk_writer_of_path fn = chunk_writer_of_out_channel (open_out_bin fn) (** Define an output channel for the builtin buffered output on Uix. see {!ImageChannels} for more info*)
hardcaml_waveterm_interactive.ml
module Draw_notty = Draw_notty module Scroll = Scroll module Widget = Widget let run = Widget.run_interactive_viewer
UnionFind_impl__Mem.ml
type rank = int type address
(**************************************************************************) (* *) (* VOCaL -- A Verified OCaml Library *) (* *) (* Copyright (c) 2018 The VOCaL Project *) (* *) (* This software is free software, distributed under the MIT license *) (* (as described in file LICENSE enclosed). *) (**************************************************************************)
dune
(executables (names bigstring_access string_access) (libraries) (modes js)) (rule (target bigstring_access.referencejs) (deps bigstring_access.bc.js) (action (with-stdout-to %{target} (run node ./bigstring_access.bc.js)))) (rule (alias runtest) (deps bigstring_access.reference bigstring_access.referencejs) (action (diff bigstring_access.reference bigstring_access.referencejs))) (rule (target string_access.referencejs) (deps string_access.bc.js) (action (with-stdout-to %{target} (run node ./string_access.bc.js)))) (rule (alias runtest) (deps string_access.reference string_access.referencejs) (action (diff string_access.reference string_access.referencejs)))
heap.mli
(** Priority queues *) module type Ordered = sig type t val compare : t -> t -> int end exception EmptyHeap module Imperative(X: Ordered) : sig (* Type of imperative heaps. (In the following [n] refers to the number of elements in the heap) *) type t (* [create c] creates a new heap, with initial capacity of [c] *) val create : int -> t (* [is_empty h] checks the emptiness of [h] *) val is_empty : t -> bool (* [add x h] adds a new element [x] in heap [h]; size of [h] is doubled when maximum capacity is reached; complexity $O(log(n))$ *) val add : t -> X.t -> unit (* [maximum h] returns the maximum element of [h]; raises [EmptyHeap] when [h] is empty; complexity $O(1)$ *) val maximum : t -> X.t (* [remove h] removes the maximum element of [h]; raises [EmptyHeap] when [h] is empty; complexity $O(log(n))$ *) val remove : t -> unit (* [pop_maximum h] removes the maximum element of [h] and returns it; raises [EmptyHeap] when [h] is empty; complexity $O(log(n))$ *) val pop_maximum : t -> X.t (* usual iterators and combinators; elements are presented in arbitrary order *) val iter : (X.t -> unit) -> t -> unit val fold : (X.t -> 'a -> 'a) -> t -> 'a -> 'a end
(**************************************************************************) (* *) (* Ocamlgraph: a generic graph library for OCaml *) (* Copyright (C) 2004-2010 *) (* Sylvain Conchon, Jean-Christophe Filliatre and Julien Signoles *) (* *) (* This software is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Library General Public *) (* License version 2.1, with the special exception on linking *) (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************)
int40.h
#ifndef OCAML_INT40_H #define OCAML_INT40_H #define Int40_val(v) ((*((int64_t *)Data_custom_val(v))) >> 24) #define copy_int40(v) caml_copy_int64(v) #endif
dune
(test (name test_mirage) (package capnp-rpc-mirage) (libraries io-page-unix capnp-rpc-lwt capnp-rpc-mirage alcotest-lwt testlib logs.fmt testbed tcpip.ipv4 tcpip.ipv6 tcpip.stack-direct mirage-vnetif ethernet arp.mirage tcpip.tcp tcpip.icmpv4 mirage-crypto-rng-lwt))
q.ml
external q : unit -> int = "ocaml_question"
dl_mk_quantifier_abstraction.h
#pragma once #include "muz/base/dl_rule_transformer.h" #include "ast/array_decl_plugin.h" namespace datalog { class context; class mk_quantifier_abstraction : public rule_transformer::plugin { class qa_model_converter; ast_manager& m; context& m_ctx; array_util a; func_decl_ref_vector m_refs; obj_map<func_decl, func_decl*> m_new2old; obj_map<func_decl, func_decl*> m_old2new; qa_model_converter* m_mc; func_decl* declare_pred(rule_set const& rules, rule_set& dst, func_decl* old_p); app_ref mk_head(rule_set const& rules, rule_set& dst, app* p, unsigned idx); app_ref mk_tail(rule_set const& rules, rule_set& dst, app* p); expr* mk_select(expr* a, unsigned num_args, expr* const* args); public: mk_quantifier_abstraction(context & ctx, unsigned priority); ~mk_quantifier_abstraction() override; rule_set * operator()(rule_set const & source) override; }; };
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: dl_mk_quantifier_abstraction.h Abstract: Convert clauses with array arguments to predicates into Quantified Horn clauses. Author: Ken McMillan Andrey Rybalchenko Nikolaj Bjorner (nbjorner) 2013-04-02 Revision History: Based on approach suggested in SAS 2013 paper "On Solving Universally Quantified Horn Clauses" --*/
json.mli
(** Unsafe IO. (See {!Deriving_Json} for typesafe IO) *) val output : 'a -> Js.js_string Js.t (** Marshal any OCaml value into this JSON representation. *) val unsafe_input : Js.js_string Js.t -> 'a (** Unmarshal a string in JSON format as an OCaml value (unsafe but fast !). *)
(* Js_of_ocaml library * http://www.ocsigen.org/js_of_ocaml/ * Copyright Grégoire Henry 2010. * * 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. *)
dune
(env (_ (env-vars (DUNE_FOO foo-sub)))) (alias (name runtest) (action (echo "DUNE_FOO: %{env:DUNE_FOO=unset}\nDUNE_BAR: %{env:DUNE_BAR=unset}")))
dune
(rule (targets version.ml) (action (with-stdout-to version.ml (echo "let current=\"%{version:crontab}\"\n")))) (library (name cron) (public_name crontab) (libraries str))
Unit_guess_lang.ml
(* Unit tests for Guess_lang *) type exec = Exec | Nonexec type success = OK | XFAIL (* For these tests, the file doesn't need to exist. *) let name_tests : (string * Lang.t * string * success) list = [ (* name, language, file name, expected result *) ("js", Js, "foo.js", OK); ("js relative path", Js, "./a/b.c/foo.js", OK); ("js absolute path", Js, "/a/b.c/foo.js", OK); ("js double extension", Js, "foo.bar.js", OK); ("min js", Js, "foo.min.js", XFAIL); ("not js", Js, "foo.bar", XFAIL); ("jsx", Js, "foo.jsx", OK); ("typescript", Ts, "foo.ts", OK); ("typescript .d.ts", Ts, "foo.d.ts", XFAIL); ("spaces", Ruby, " a b c.rb", OK); ] let contents_tests : (string * Lang.t * string * string * exec * success) list = [ (* name, language, file name, file contents, executable?, expected result *) ("correct extension nonexec", Js, "foo1.js", "", Exec, OK); ("correct extension exec", Js, "foo2.js", "", Exec, OK); ("wrong extension exec", Js, "foo3.bar", "", Exec, XFAIL); ("bash non-executable", Bash, "hello1.bash", "", Nonexec, OK); ("bash exec", Bash, "hello2", "#!/anything/bash\n", Exec, OK); ("sh exec", Bash, "hello3", "#!/bin/sh\n# hello!", Exec, OK); ("bash exec env", Bash, "hello4", "#! /usr/bin/env bash\n", Exec, OK); ("other exec env", Bash, "hello5", "#!/usr/bin/env bashxxxx\n", Exec, XFAIL); ("env -S", Bash, "hello6", "#!/usr/bin/env -Sbash -eu\n", Exec, OK); ("hack with .hack extension", Hack, "foo.hack", "", Nonexec, OK); ( "hack without extension", Hack, "foo", "#!/usr/bin/env hhvm\nxxxx", Exec, OK ); ( "hack with .php extension and shebang", Hack, "foo.php", "#!/usr/bin/env hhvm\nxxxx", Nonexec, OK ); ( "hack with .php extension no shebang", Hack, "foo.php", "<?hh\n", Nonexec, OK ); ("php", Php, "foo.php", "", Nonexec, OK); ] let ( // ) = Filename.concat let mkdir path = if not (Sys.file_exists path) then Unix.mkdir path 0o777 (* Create a temporary file with the specified name, in a local tmp folder. We don't delete the files when we're done because it's easier when troubleshooting tests. *) let with_file name contents exec f = let dir = "tmp" in mkdir dir; let path = dir // name in let oc = open_out_bin path in (match exec with | Exec -> Unix.chmod path 0o755 | Nonexec -> ()); Fun.protect ~finally:(fun () -> close_out oc) (fun () -> output_string oc contents; close_out oc; f path) let test_name_only lang path expectation = match (expectation, Guess_lang.inspect_file lang path) with | OK, Ok _ | XFAIL, Error _ -> () | _ -> assert false let test_with_contents lang name contents exec expectation = with_file name contents exec (fun path -> match (expectation, Guess_lang.inspect_file lang path) with | OK, Ok _ | XFAIL, Error _ -> () | _ -> assert false) (* This is necessary when running the tests on Windows. *) let fix_path s = match Sys.os_type with | "Win32" -> String.map (function | '/' -> '\\' | c -> c) s | _ -> s let test_inspect_file = Common.map (fun (test_name, lang, path, expectation) -> (test_name, fun () -> test_name_only lang (fix_path path) expectation)) name_tests @ Common.map (fun (test_name, lang, file_name, contents, exec, expectation) -> ( test_name, fun () -> test_with_contents lang file_name contents exec expectation )) contents_tests let tests = Testutil.pack_suites "Guess_lang" [ Testutil.pack_tests "inspect_file" test_inspect_file ]
(* Unit tests for Guess_lang *)
describePrefixLists.mli
open Types type input = DescribePrefixListsRequest.t type output = DescribePrefixListsResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
tx_rollup_hash_builder.ml
let message : Raw_context.t -> Tx_rollup_message_repr.t -> (Raw_context.t * Tx_rollup_message_hash_repr.t) tzresult = fun ctxt input -> Tx_rollup_gas.hash ~hash_f:Tx_rollup_message_hash_repr.hash_bytes ctxt Tx_rollup_message_repr.encoding input let message_result : Raw_context.t -> Tx_rollup_message_result_repr.t -> (Raw_context.t * Tx_rollup_message_result_hash_repr.t) tzresult = fun ctxt input -> Tx_rollup_gas.hash ~hash_f:Tx_rollup_message_result_hash_repr.hash_bytes ctxt Tx_rollup_message_result_repr.encoding input let compact_commitment : Raw_context.t -> Tx_rollup_commitment_repr.Compact.t -> (Raw_context.t * Tx_rollup_commitment_repr.Hash.t) tzresult = fun ctxt input -> Tx_rollup_gas.hash ~hash_f:Tx_rollup_commitment_repr.Hash.hash_bytes ctxt Tx_rollup_commitment_repr.Compact.encoding input let withdraw_list : Raw_context.t -> Tx_rollup_withdraw_repr.t list -> (Raw_context.t * Tx_rollup_withdraw_list_hash_repr.t) tzresult = fun ctxt input -> Tx_rollup_gas.hash ~hash_f:Tx_rollup_withdraw_list_hash_repr.hash_bytes ctxt (Data_encoding.list Tx_rollup_withdraw_repr.encoding) input
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
daemon.ml
(** Functor for the common parts of all Tezos daemons: node, baker, endorser and accuser. Handles event handling in particular. *) module type PARAMETERS = sig type persistent_state type session_state val base_default_name : string val default_colors : Log.Color.t array end module Level = struct type default_level = [`Debug | `Info | `Notice] type level = [default_level | `Warning | `Error | `Fatal] let to_string = function | `Debug -> "debug" | `Info -> "info" | `Notice -> "notice" | `Warning -> "warning" | `Error -> "error" | `Fatal -> "fatal" end module Make (X : PARAMETERS) = struct exception Terminated_before_event of { daemon : string; event : string; where : string option; } let () = Printexc.register_printer @@ function | Terminated_before_event {daemon; event; where = None} -> Some (sf "%s terminated before event occurred: %s" daemon event) | Terminated_before_event {daemon; event; where = Some where} -> Some (sf "%s terminated before event occurred: %s where %s" daemon event where) | _ -> None type session_status = { process : Process.t; session_state : X.session_state; mutable event_loop_promise : unit Lwt.t option; } type status = Not_running | Running of session_status type event_handler = | Event_handler : { filter : JSON.t -> 'a option; resolver : 'a option Lwt.u; } -> event_handler type event = {name : string; value : JSON.t} type t = { name : string; color : Tezt.Log.Color.t; path : string; persistent_state : X.persistent_state; mutable status : status; event_pipe : string; mutable stdout_handlers : (string -> unit) list; mutable persistent_event_handlers : (event -> unit) list; mutable one_shot_event_handlers : event_handler list String_map.t; } let name daemon = daemon.name let terminate ?(kill = false) daemon = match daemon.status with | Not_running -> unit | Running {event_loop_promise = None; _} -> invalid_arg "you cannot call Daemon.terminate before Daemon.run returns" | Running {process; event_loop_promise = Some event_loop_promise; _} -> if kill then Process.kill process else Process.terminate process ; event_loop_promise let next_name = ref 1 let fresh_name () = let index = !next_name in incr next_name ; X.base_default_name ^ string_of_int index let next_color = ref 0 let get_next_color () = let color = X.default_colors.(!next_color mod Array.length X.default_colors) in incr next_color ; color let () = Test.declare_reset_function @@ fun () -> next_name := 1 ; next_color := 0 let create ~path ?runner ?name ?color ?event_pipe persistent_state = let name = match name with None -> fresh_name () | Some name -> name in let color = match color with None -> get_next_color () | Some color -> color in let event_pipe = match event_pipe with | None -> Temp.file ?runner (name ^ "-event-pipe") | Some file -> file in { name; color; path; persistent_state; status = Not_running; event_pipe; stdout_handlers = []; persistent_event_handlers = []; one_shot_event_handlers = String_map.empty; } (** Takes the given JSON full event of the following form and evaluates in an event using [<name>] and [<value>]: {[{ "fd-sink-item.v0": { [...] "event": { <name>:<value> } } }]} If the given JSON does not match the right structure, and in particular if the value of the field ["event"] is not a one-field object, the function evaluates in None. *) let get_event_from_full_event json = let event = JSON.(json |-> "fd-sink-item.v0" |-> "event") in match JSON.as_object_opt event with | None | Some ([] | _ :: _ :: _) -> None | Some [(name, value)] -> Some {name; value} let handle_raw_event daemon line = let json = JSON.parse ~origin:("event from " ^ daemon.name) line in match get_event_from_full_event json with | None -> () | Some (raw_event : event) -> ( let name = raw_event.name in List.iter (fun handler -> handler raw_event) daemon.persistent_event_handlers ; (* Trigger one-shot events. *) match String_map.find_opt name daemon.one_shot_event_handlers with | None -> () | Some events -> (* Trigger matching events and accumulate others in [acc]. *) let rec loop acc = function | [] -> daemon.one_shot_event_handlers <- String_map.add name (List.rev acc) daemon.one_shot_event_handlers | (Event_handler {filter; resolver} as head) :: tail -> let acc = match filter json with | exception exn -> Test.fail "uncaught exception in filter for event %s of daemon \ %s: %s" name daemon.name (Printexc.to_string exn) | None -> head :: acc | Some value -> Lwt.wakeup_later resolver (Some value) ; acc in loop acc tail in loop [] events) let run ?runner ?(on_terminate = fun _ -> unit) ?(event_level = `Info) ?(event_sections_levels = []) daemon session_state arguments = ignore (event_level : Level.default_level) ; (match daemon.status with | Not_running -> () | Running _ -> Test.fail "daemon %s is already running" daemon.name) ; (* Create the named pipe where the daemon will send its internal events in JSON. *) if Runner.Sys.file_exists ?runner daemon.event_pipe then Runner.Sys.remove ?runner daemon.event_pipe ; Runner.Sys.mkfifo ?runner ~perms:0o640 daemon.event_pipe ; (* Note: in the CI, it seems that if the daemon tries to open the FIFO for writing before we opened it for reading, the [Lwt.openfile] call (of the daemon, for writing) blocks forever. So we need to make sure that we open the file before we spawn the daemon. *) let event_process = match runner with | None -> None | Some runner -> let cmd = "cat" in let arguments = [daemon.event_pipe] in let name = Filename.basename daemon.event_pipe in let process = Process.spawn ~name ~runner ~log_output:false cmd arguments in Some process in (* The input is either the local pipe or the remote pipe. *) let* event_input = match event_process with | None -> Lwt_io.(open_file ~mode:input) daemon.event_pipe | Some process -> Lwt.return @@ Process.stdout process in let env = let args = List.fold_right (fun (prefix, level) args -> sf "section-prefix=%s:%s" prefix (Level.to_string level) :: args) (("", (event_level :> Level.level)) :: event_sections_levels) [] in let args_str = "?" ^ String.concat "&" (List.rev args) in String_map.singleton "TEZOS_EVENTS_CONFIG" ("file-descriptor-path://" ^ daemon.event_pipe ^ args_str) in let process = Process.spawn ?runner ~name:daemon.name ~color:daemon.color ~env daemon.path arguments in (* Make sure the daemon status is [Running], otherwise [event_loop_promise] would stop immediately thinking the daemon has been terminated. *) let running_status = {process; session_state; event_loop_promise = None} in daemon.status <- Running running_status ; let event_loop_promise = let rec event_loop () = let* line = Lwt_io.read_line_opt event_input in match line with | Some line -> handle_raw_event daemon line ; event_loop () | None -> ( match daemon.status with | Not_running -> ( match event_process with | None -> Lwt_io.close event_input | Some process -> Lwt.return @@ Process.kill process) | Running _ -> (* It can take a little while before the pipe is opened by the daemon, and before that, reading from it yields end of file for some reason. *) let* () = Lwt_unix.sleep 0.01 in event_loop ()) in let rec stdout_loop () = let* stdout_line = Lwt_io.read_line_opt (Process.stdout process) in match stdout_line with | Some line -> List.iter (fun handler -> handler line) daemon.stdout_handlers ; stdout_loop () | None -> ( match daemon.status with | Not_running -> Lwt.return_unit | Running _ -> (* TODO: is the sleep necessary here? *) let* () = Lwt_unix.sleep 0.01 in stdout_loop ()) in let ( and*!! ) = lwt_both_fail_early in let* () = event_loop () and*!! () = stdout_loop () and*!! () = let* process_status = Process.wait process in (* Setting [daemon.status] to [Not_running] stops the event loop cleanly. *) daemon.status <- Not_running ; (* Cancel one-shot event handlers. *) let pending = daemon.one_shot_event_handlers in daemon.one_shot_event_handlers <- String_map.empty ; String_map.iter (fun _ -> List.iter (fun (Event_handler {resolver; _}) -> Lwt.wakeup_later resolver None)) pending ; on_terminate process_status in unit in running_status.event_loop_promise <- Some event_loop_promise ; Background.register event_loop_promise ; unit let wait_for_full ?where daemon name filter = let (promise, resolver) = Lwt.task () in let current_events = String_map.find_opt name daemon.one_shot_event_handlers |> Option.value ~default:[] in daemon.one_shot_event_handlers <- String_map.add name (Event_handler {filter; resolver} :: current_events) daemon.one_shot_event_handlers ; let* result = promise in match result with | None -> raise (Terminated_before_event {daemon = daemon.name; event = name; where}) | Some x -> return x let event_from_full_event_filter filter json = let raw = get_event_from_full_event json in (* If [json] does not match the correct JSON structure, it will be filtered out, which will result in ignoring the current event. @see raw_event_from_event *) Option.bind raw (fun {value; _} -> filter value) let wait_for ?where daemon name filter = wait_for_full ?where daemon name (event_from_full_event_filter filter) let on_event daemon handler = daemon.persistent_event_handlers <- handler :: daemon.persistent_event_handlers let on_stdout daemon handler = daemon.stdout_handlers <- handler :: daemon.stdout_handlers let log_events daemon = on_event daemon @@ fun event -> Log.info "Received event: %s = %s" event.name (JSON.encode event.value) type observe_memory_consumption = Observe of (unit -> int option Lwt.t) let memory_consumption daemon = let from_command ~cmd ~args ~expect_failure r = let p = Process.spawn ~log_output:true cmd args in fun () -> let* output = Process.check_and_read_stdout ~expect_failure p in match output =~* rex r with | None -> Test.fail "Unable to find `%s' in process stdout" r | Some v -> return v in let cannot_observe = return @@ Observe (fun () -> return None) in match daemon.status with | Not_running -> cannot_observe | Running {process; _} -> ( let* perf = Process.program_path "perf" in let* heaptrack_print = Process.program_path "heaptrack_print" in match (perf, heaptrack_print) with | (None, _) | (_, None) -> cannot_observe | (Some perf, Some heaptrack_print) -> ( try let pid = Process.pid process |> string_of_int in let get_trace = from_command ~cmd:perf ~args:["stat"; "-r"; "5"; "heaptrack"; "-p"; pid] ~expect_failure:true ".* heaptrack --analyze \"(.*)\"" in return @@ Observe (fun () -> let* dump = get_trace () in let* peak = from_command ~cmd:heaptrack_print ~args:[dump] ~expect_failure:false "peak heap memory consumption: (\\d+\\.?\\d*\\w)" () in match peak =~** rex "(\\d+\\.?\\d*)(\\w)" with | None -> Test.fail "Invalid memory consumption format: %s\n" peak | Some (size, unit) -> let factor_of_unit = match unit with | "K" -> 1024 | "M" -> 1024 * 1024 | "G" -> 1024 * 1024 * 1024 | _ -> 1 in let size = int_of_float @@ float_of_string size *. float_of_int factor_of_unit in return @@ Some size) with exn -> Test.fail "failed to set up memory consumption measurement: %s" (Printexc.to_string exn))) end let n_events_rev n filter = if n <= 0 then invalid_arg "Base.n_events_rev: n must be > 0." ; let acc = ref [] in let size = ref 0 in let accumulation_threshold value = acc := value :: !acc ; incr size ; if !size >= n then Some !acc else None in let accumulating_filter json = Option.bind (filter json) accumulation_threshold in accumulating_filter let n_events n filter = let accumulating_filter = n_events_rev n filter in let inverting_filter json = Option.map List.rev @@ accumulating_filter json in inverting_filter let nth_event n filter = let accumulating_filter = n_events_rev n filter in let nth_filter json = Option.map List.hd @@ accumulating_filter json in nth_filter
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
TestModifier.mli
(* This file is intentionally blank to detect unused declarations. *)
(* This file is intentionally blank to detect unused declarations. *)
sc_rollup_proof_repr.ml
type t = { pvm_step : Sc_rollups.wrapped_proof; inbox : Sc_rollup_inbox_repr.Proof.t option; } let encoding = let open Data_encoding in conv (fun {pvm_step; inbox} -> (pvm_step, inbox)) (fun (pvm_step, inbox) -> {pvm_step; inbox}) (obj2 (req "pvm_step" Sc_rollups.wrapped_proof_encoding) (req "inbox" (option Sc_rollup_inbox_repr.Proof.encoding))) let pp ppf _ = Format.fprintf ppf "Refutation game proof" let start proof = let (module P) = Sc_rollups.wrapped_proof_module proof.pvm_step in P.proof_start_state P.proof let stop proof = let (module P) = Sc_rollups.wrapped_proof_module proof.pvm_step in P.proof_stop_state P.proof (* This takes an [input] and checks if it is at or above the given level. It returns [None] if this is the case. We use this to check that the PVM proof is obeying [commit_level] correctly---if the message obtained from the inbox proof is at or above [commit_level] the [input_given] in the PVM proof should be [None]. *) let cut_at_level level input = let input_level = Sc_rollup_PVM_sem.(input.inbox_level) in if Raw_level_repr.(level <= input_level) then None else Some input type error += Sc_rollup_proof_check of string let proof_error reason = let open Lwt_result_syntax in fail (Sc_rollup_proof_check reason) let check p reason = let open Lwt_result_syntax in if p then return () else proof_error reason let valid snapshot commit_level ~pvm_name proof = let (module P) = Sc_rollups.wrapped_proof_module proof.pvm_step in let open Lwt_result_syntax in let* _ = check (String.equal P.name pvm_name) "Incorrect PVM kind" in let input_requested = P.proof_input_requested P.proof in let input_given = P.proof_input_given P.proof in let* input = match (input_requested, proof.inbox) with | Sc_rollup_PVM_sem.No_input_required, None -> return None | Sc_rollup_PVM_sem.Initial, Some inbox_proof -> Sc_rollup_inbox_repr.Proof.valid {inbox_level = Raw_level_repr.root; message_counter = Z.zero} snapshot inbox_proof | Sc_rollup_PVM_sem.First_after (level, counter), Some inbox_proof -> Sc_rollup_inbox_repr.Proof.valid {inbox_level = level; message_counter = Z.succ counter} snapshot inbox_proof | _ -> proof_error (Format.asprintf "input_requested is %a, inbox proof is %a" Sc_rollup_PVM_sem.pp_input_request input_requested (Format.pp_print_option Sc_rollup_inbox_repr.Proof.pp) proof.inbox) in let* _ = check (Option.equal Sc_rollup_PVM_sem.input_equal (Option.bind input (cut_at_level commit_level)) input_given) "Input given is not what inbox proof expects" in Lwt.map Result.ok (P.verify_proof P.proof) module type PVM_with_context_and_state = sig include Sc_rollups.PVM.S val context : context val state : state end type error += Proof_cannot_be_wrapped let produce pvm_and_state inbox commit_level = let open Lwt_result_syntax in let (module P : PVM_with_context_and_state) = pvm_and_state in let*! request = P.is_input_state P.state in let* inbox, input_given = match request with | Sc_rollup_PVM_sem.No_input_required -> return (None, None) | Sc_rollup_PVM_sem.Initial -> let* p, i = Sc_rollup_inbox_repr.Proof.produce_proof inbox (Raw_level_repr.root, Z.zero) in return (Some p, i) | Sc_rollup_PVM_sem.First_after (l, n) -> let* p, i = Sc_rollup_inbox_repr.Proof.produce_proof inbox (l, n) in return (Some p, i) in let input_given = Option.bind input_given (cut_at_level commit_level) in let* pvm_step_proof = P.produce_proof P.context input_given P.state in let module P_with_proof = struct include P let proof = pvm_step_proof end in match Sc_rollups.wrap_proof (module P_with_proof) with | Some pvm_step -> return {pvm_step; inbox} | None -> fail Proof_cannot_be_wrapped
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* 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. *) (* *) (*****************************************************************************)
main.ml
let backoff_benchmarks = let open Backoff in [ bench_basic ~with_backoff:true; bench_basic ~with_backoff:false; bench_artificial ~with_backoff:true; bench_artificial ~with_backoff:false; ] let benchmark_list = [ Bench_spsc_queue.bench; Mpmc_queue.bench ~takers:4 ~pushers:4; Mpmc_queue.bench ~takers:1 ~pushers:8; Mpmc_queue.bench ~takers:8 ~pushers:1; Mpmc_queue.bench ~use_cas:true ~takers:4 ~pushers:4; Mpmc_queue.bench ~use_cas:true ~takers:1 ~pushers:8; Mpmc_queue.bench ~use_cas:true ~takers:8 ~pushers:1; ] @ backoff_benchmarks let () = let results = (* todo: should assert no stranded domains between tests. *) List.map (fun f -> f ()) benchmark_list |> List.map Benchmark_result.to_json |> String.concat ", " in let output = Printf.sprintf {| {"name": "lockfree", "results": [%s]}|} results (* Cannot use Yojson rewriters as of today none works on OCaml 5.1.0. This at least verifies that the manually crafted JSON is well-formed. If the type grow, we could switch to running ppx manually on 5.0.0 and pasting in its output. *) |> Yojson.Basic.prettify in Printf.printf "%s" output
michelson_v1_macros.mli
open Tezos_micheline type 'l node = ('l, string) Micheline.node type error += Unexpected_macro_annotation of string type error += Sequence_expected of string type error += Invalid_arity of string * int * int val expand : 'l node -> 'l node tzresult val expand_rec : 'l node -> 'l node * error list val expand_caddadr : 'l node -> 'l node option tzresult val expand_set_caddadr : 'l node -> 'l node option tzresult val expand_map_caddadr : 'l node -> 'l node option tzresult val expand_deprecated_dxiiivp : 'l node -> 'l node option tzresult val expand_pappaiir : 'l node -> 'l node option tzresult val expand_deprecated_duuuuup : 'l node -> 'l node option tzresult val expand_compare : 'l node -> 'l node option tzresult val expand_asserts : 'l node -> 'l node option tzresult val expand_unpappaiir : 'l node -> 'l node option tzresult val expand_if_some : 'l node -> 'l node option tzresult val expand_if_right : 'l node -> 'l node option tzresult val unexpand : 'l node -> 'l node val unexpand_rec : 'l node -> 'l node val unexpand_caddadr : 'l node -> 'l node option val unexpand_set_caddadr : 'l node -> 'l node option val unexpand_map_caddadr : 'l node -> 'l node option val unexpand_deprecated_dxiiivp : 'l node -> 'l node option val unexpand_pappaiir : 'l node -> 'l node option val unexpand_deprecated_duuuuup : 'l node -> 'l node option val unexpand_compare : 'l node -> 'l node option val unexpand_asserts : 'l node -> 'l node option val unexpand_unpappaiir : 'l node -> 'l node option val unexpand_if_some : 'l node -> 'l node option val unexpand_if_right : 'l node -> 'l node option
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
test_michael_scott_queue.ml
module Atomic = Dscheck.TracedAtomic let drain queue = let remaining = ref 0 in while not (Michael_scott_queue.is_empty queue) do remaining := !remaining + 1; assert (Option.is_some (Michael_scott_queue.pop queue)) done; !remaining let producer_consumer () = Atomic.trace (fun () -> let queue = Michael_scott_queue.create () in let items_total = 4 in Atomic.spawn (fun () -> for _ = 1 to items_total do Michael_scott_queue.push queue 0 done); (* consumer *) let popped = ref 0 in Atomic.spawn (fun () -> for _ = 1 to items_total do match Michael_scott_queue.pop queue with | None -> () | Some _ -> popped := !popped + 1 done); (* checks*) Atomic.final (fun () -> Atomic.check (fun () -> let remaining = drain queue in !popped + remaining = items_total))) let () = let open Alcotest in run "michael_scott_queue_dscheck" [ ("basic", [ test_case "1-producer-1-consumer" `Slow producer_consumer ]) ]
opamRepositoryName.ml
include OpamStd.AbstractString let default = of_string "default"
(**************************************************************************) (* *) (* Copyright 2012-2016 OCamlPro *) (* Copyright 2012 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. *) (* *) (**************************************************************************)
glyphs.ml
open Gg open Vg ;; (** Test images for glyphs. *) let open_sans_xbold = { Font.name = "Open Sans"; size = 1.0; weight = `W800; slant = `Normal} (* Font info for the string "Revolt!" as found in Open_sans.extra_bold. *) let glyphs = [ 53; 72; 89; 82; 79; 87; 4 ] let advances = [1386.; 1266.; 1251.; 1305.; 662.; 942.; 594.;] let u_to_em = 2048. ;; Db.image "glyph-revolt" __POS__ ~author:Db.dbuenzli ~title:"Revolt in black" ~tags:["glyph"] ~note:"Black characters “Revolt!”, approximatively centered \ in the image." ~size:(Size2.v 135. 45.) ~view:(Box2.v P2.o (Size2.v 3. 1.)) begin fun _ -> let font = { open_sans_xbold with Font.size = 0.7 } in let text = "Revolt!" in I.const Color.black |> I.cut_glyphs ~text font glyphs |> I.move (V2.v 0.23 0.25) end; Db.image "glyph-revolt-outline" __POS__ ~author:Db.dbuenzli ~title:"Revolt outline in black" ~tags:["glyph"] ~note:"Black outlined characters “Revolt!”, approximatively centered \ in the image with bevel path joins." ~size:(Size2.v 135. 45.) ~view:(Box2.v P2.o (Size2.v 3. 1.)) begin fun _ -> let font = { open_sans_xbold with Font.size = 0.7 } in let area = `O { P.o with P.width = 0.03; join = `Bevel } in let text = "Revolt!" in I.const Color.black |> I.cut_glyphs ~area ~text font glyphs |> I.move (V2.v 0.23 0.25) end; Db.image "glyph-revolt-fade" __POS__ ~author:Db.dbuenzli ~title:"Revolt from black to white" ~tags:["glyph"; "gradient" ] ~note:"Characters “Revolt!”, approximatively centered \ in the image and fading from black to white" ~size:(Size2.v 135. 45.) ~view:(Box2.v P2.o (Size2.v 3. 1.)) begin fun _ -> let font = { open_sans_xbold with Font.size = 0.7 } in let text = "Revolt!" in let stops = [0.0, Color.black; 1.0, Color.white] in I.axial stops P2.o (P2.v 3. 0.) |> I.cut_glyphs ~text font glyphs |> I.move (V2.v 0.23 0.25) end; Db.image "glyph-aspect" __POS__ ~author:Db.dbuenzli ~title:"Glyph aspect" ~tags:["glyph"] ~note:"The character should read “R”, without distortion." ~size:(Size2.v 25. 50.) ~view:(Box2.v P2.o (Size2.v 2. 1.)) begin fun _ -> let font = { open_sans_xbold with Font.size = 0.5 } in let text = "R" in let sq = P.empty |> P.rect (Box2.v (P2.v 0. 0.75) (P2.v 0.25 0.25)) in I.const Color.black |> I.cut sq |> I.blend (I.const Color.black |> I.cut_glyphs ~text font [53;]) |> I.scale (V2.v 4.0 1.0) end; Db.image "glyph-multi" __POS__ ~author:Db.dbuenzli ~title:"Multiple revolts" ~tags:["glyph"] ~note:"Rectangle filled with revolts rotated by 30°." ~size:(Size2.v 108. 135.) ~view:(Box2.v P2.o (P2.v 0.8 1.0)) begin fun view -> let font = { open_sans_xbold with Font.size = 0.025 } in let text = "Revolt!" in let angle = Float.rad_of_deg 30. in let revolt pos = I.const Color.black |> I.cut_glyphs ~text font glyphs |> I.move pos in let next max dv pt = if V2.x pt < V2.x max then Some (V2.v (V2.x pt +. V2.x dv) (V2.y pt)) else let y = V2.y pt +. V2.y dv in if y > V2.y max then None else Some (V2.v 0. y) in let max = V2.v 1.3 1.3 in let dv = V2.v 0.11 0.03 in let rec blend_revolt acc = function | None -> acc | Some pt -> blend_revolt (acc |> I.blend (revolt pt)) (next max dv pt) in let margin = let area = `O { P.o with P.width = 0.1 } in I.const Color.white |> I.cut ~area (P.empty |> P.rect view) in blend_revolt (I.const Color.white) (Some P2.o) |> I.rot angle |> I.move (P2.v 0.2 (-. sin (angle))) |> I.blend margin end; Db.image "glyph-advances" __POS__ ~author:Db.dbuenzli ~title:"Advancing revolt" ~tags:["glyph"] ~note:"First line, no advances specified. Second line advances with glyph advances, should render same as first line. Third line, funky glyph advances with up and down." ~size:(Size2.v 135. (45. *. 3.)) ~view:(Box2.v P2.o (Size2.v 3. 3.)) begin fun _ -> let fsize = 0.7 in let font = { open_sans_xbold with Font.size = fsize } in let text = "Revolt!" in let black = I.const Color.black in let ypos n = V2.v 0.23 (0.25 +. n *. 0.98) in let no_advances = I.cut_glyphs ~text font glyphs in let adv_advances = let adv a = V2.v ((a *. fsize) /. u_to_em) 0. in I.cut_glyphs ~text ~advances:(List.map adv advances) font glyphs in let funky_advances = let adv i a = V2.v ((a *. fsize) /. u_to_em) (if i mod 2 = 0 then 0.2 else -0.2) in I.cut_glyphs ~text ~advances:(List.mapi adv advances) font glyphs in black |> funky_advances |> I.move (ypos 0.) |> I.blend (black |> adv_advances |> I.move (ypos 1.)) |> I.blend (black |> no_advances |> I.move (ypos 2.)) end ;; Db.image "glyph-affiche-blocks" __POS__ ~author:Db.dbuenzli ~title:"Affiché with ligature and text to glyph correspondence" ~tags:["glyph"] ~note:"The ffi is a single glyph and the é glyph is encoded as the sequence <U+0065, U+0301> in the text string." ~size:(Size2.v 135. 45.) ~view:(Box2.v P2.o (Size2.v 3. 1.)) begin fun _ -> let font = { open_sans_xbold with Font.size = 0.7 } in let glyphs = [ 36; 605; 70; 75; 171 ] in let text = "Affiche\xCC\x81" in let blocks = false, [(1,1); (3,1); (1,1); (1,1); (2,1)] in I.const Color.black |> I.cut_glyphs ~text ~blocks font glyphs |> I.move (V2.v 0.23 0.25) end ;; (*--------------------------------------------------------------------------- Copyright (c) 2013 The vg programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
(*--------------------------------------------------------------------------- Copyright (c) 2013 The vg programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. vg v0.9.4 ---------------------------------------------------------------------------*)
node.ml
open Import module Make (G : Git.S) (P : Irmin.Path.S) = struct module Hash = Irmin.Hash.Make (G.Hash) module Key = Irmin.Key.Of_hash (Hash) module Raw = Git.Value.Make (G.Hash) module Path = P module Metadata = Metadata type t = G.Value.Tree.t type metadata = Metadata.t [@@deriving irmin] type hash = Hash.t [@@deriving irmin] type step = Path.step [@@deriving irmin] type node_key = hash [@@deriving irmin] type contents_key = hash [@@deriving irmin] type value = [ `Node of hash | `Contents of hash * metadata ] [@@deriving irmin] let of_step = Irmin.Type.to_string P.step_t let to_step str = match Irmin.Type.of_string P.step_t str with | Ok x -> x | Error (`Msg e) -> failwith e exception Exit of (step * value) list let list ?(offset = 0) ?length ?cache:_ t = let t = G.Value.Tree.to_list t in let length = match length with None -> List.length t | Some n -> n in try List.fold_left (fun (i, acc) { Git.Tree.perm; name; node } -> if i < offset then (i + 1, acc) else if i >= offset + length then raise (Exit acc) else let name = to_step name in match perm with | `Dir -> (i + 1, (name, `Node node) :: acc) | `Commit -> (i + 1, acc) (* FIXME *) | #Metadata.t as p -> (i + 1, (name, `Contents (node, p)) :: acc)) (0, []) t |> fun (_, acc) -> List.rev acc with Exit acc -> List.rev acc let find ?cache:_ t s = let s = of_step s in let rec aux = function | [] -> None | x :: xs when x.Git.Tree.name <> s -> aux xs | { Git.Tree.perm; node; _ } :: _ -> ( match perm with | `Dir -> Some (`Node node) | `Commit -> None (* FIXME *) | #Metadata.t as p -> Some (`Contents (node, p))) in aux (Git.Tree.to_list t) let remove t step = G.Value.Tree.remove ~name:(of_step step) t let is_empty = G.Value.Tree.is_empty let length t = G.Value.Tree.length t |> Int64.to_int let add t name value = let name = of_step name in let entry = match value with | `Node node -> Git.Tree.entry ~name `Dir node | `Contents (node, perm) -> Git.Tree.entry ~name (perm :> Git.Tree.perm) node in (* FIXME(samoht): issue in G.Value.Tree.add *) let entries = G.Value.Tree.to_list t in match List.find (fun e -> e.Git.Tree.name = name) entries with | exception Not_found -> Git.Tree.of_list (entry :: entries) | e -> let equal x y = x.Git.Tree.perm = y.Git.Tree.perm && x.name = y.name && G.Hash.equal x.node y.node in if equal e entry then t else let entries = List.filter (fun e -> e.Git.Tree.name <> name) entries in Git.Tree.of_list (entry :: entries) let empty : unit -> t = (* [Git.Tree.t] is immutable, so sharing a singleton empty tree is safe *) Fun.const (Git.Tree.of_list []) let to_git perm (name, node) = G.Value.Tree.entry ~name:(of_step name) perm node let v alist = let alist = List.rev_map (fun (l, x) -> let v k = (l, k) in match x with | `Node n -> to_git `Dir (v n) | `Contents (c, perm) -> to_git (perm :> Git.Tree.perm) (v c)) alist in (* Tree.of_list will sort the list in the right order *) G.Value.Tree.of_list alist let alist t = let mk_n k = `Node k in let mk_c k metadata = `Contents (k, metadata) in List.fold_left (fun acc -> function | { Git.Tree.perm = `Dir; name; node } -> (to_step name, mk_n node) :: acc | { Git.Tree.perm = `Commit; name; _ } -> (* Irmin does not support Git submodules; do not follow them, just consider *) [%log.warn "skipping Git submodule: %s" name]; acc | { Git.Tree.perm = #Metadata.t as perm; name; node; _ } -> (to_step name, mk_c node perm) :: acc) [] (G.Value.Tree.to_list t) |> List.rev module N = Irmin.Node.Make (Hash) (P) (Metadata) let to_n t = N.of_list (alist t) let of_n n = v (N.list n) let to_bin t = Raw.to_raw (G.Value.tree t) let of_list = v let of_seq seq = List.of_seq seq |> v let seq ?offset ?length ?cache t = list ?offset ?length ?cache t |> List.to_seq let clear _ = () let encode_bin (t : t) k = [%log.debug "Tree.encode_bin"]; k (to_bin t) let decode_bin buf pos_ref = [%log.debug "Tree.decode_bin"]; let off = !pos_ref in match Raw.of_raw_with_header buf ~off with | Ok (Git.Value.Tree t) -> pos_ref := String.length buf; t | Ok _ -> failwith "wrong object kind" | Error _ -> failwith "wrong object" let size_of = Irmin.Type.Size.custom_dynamic () let t = Irmin.Type.map ~bin:(encode_bin, decode_bin, size_of) N.t of_n to_n let merge ~contents ~node = let merge = N.merge ~contents ~node in Irmin.Merge.like t merge to_n of_n exception Dangling_hash of { context : string; hash : hash } let with_handler _ n = n let head t = `Node (list t) module Ht = Irmin.Hash.Typed (Hash) (struct type nonrec t = t [@@deriving irmin] end) let hash_exn ?force:_ = Ht.hash end module Store (G : Git.S) (P : Irmin.Path.S) = struct module Key = Irmin.Hash.Make (G.Hash) module Val = Make (G) (P) module V = struct type t = G.Value.Tree.t let type_eq = function `Tree -> true | _ -> false let to_git t = G.Value.tree t let of_git = function Git.Value.Tree t -> Some t | _ -> None end include Content_addressable.Check_closed (Content_addressable.Make (G) (V)) end
(* * 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. *)
main.ml
open! Core open! Bonsai_web let (_ : _ Start.Handle.t) = Start.start Start.Result_spec.just_the_view ~bind_to_element_with_id:"app" Bonsai_drag_and_drop_example.app ;;
EulerSystem.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2015 Tal Hadad <tal_hd@hotmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_EULERSYSTEM_H #define EIGEN_EULERSYSTEM_H namespace Eigen { // Forward declerations template <typename _Scalar, class _System> class EulerAngles; namespace internal { // TODO: Check if already exists on the rest API template <int Num, bool IsPositive = (Num > 0)> struct Abs { enum { value = Num }; }; template <int Num> struct Abs<Num, false> { enum { value = -Num }; }; template <int Axis> struct IsValidAxis { enum { value = Axis != 0 && Abs<Axis>::value <= 3 }; }; } #define EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1] /** \brief Representation of a fixed signed rotation axis for EulerSystem. * * \ingroup EulerAngles_Module * * Values here represent: * - The axis of the rotation: X, Y or Z. * - The sign (i.e. direction of the rotation along the axis): positive(+) or negative(-) * * Therefore, this could express all the axes {+X,+Y,+Z,-X,-Y,-Z} * * For positive axis, use +EULER_{axis}, and for negative axis use -EULER_{axis}. */ enum EulerAxis { EULER_X = 1, /*!< the X axis */ EULER_Y = 2, /*!< the Y axis */ EULER_Z = 3 /*!< the Z axis */ }; /** \class EulerSystem * * \ingroup EulerAngles_Module * * \brief Represents a fixed Euler rotation system. * * This meta-class goal is to represent the Euler system in compilation time, for EulerAngles. * * You can use this class to get two things: * - Build an Euler system, and then pass it as a template parameter to EulerAngles. * - Query some compile time data about an Euler system. (e.g. Whether it's tait bryan) * * Euler rotation is a set of three rotation on fixed axes. (see \ref EulerAngles) * This meta-class store constantly those signed axes. (see \ref EulerAxis) * * ### Types of Euler systems ### * * All and only valid 3 dimension Euler rotation over standard * signed axes{+X,+Y,+Z,-X,-Y,-Z} are supported: * - all axes X, Y, Z in each valid order (see below what order is valid) * - rotation over the axis is supported both over the positive and negative directions. * - both tait bryan and proper/classic Euler angles (i.e. the opposite). * * Since EulerSystem support both positive and negative directions, * you may call this rotation distinction in other names: * - _right handed_ or _left handed_ * - _counterclockwise_ or _clockwise_ * * Notice all axed combination are valid, and would trigger a static assertion. * Same unsigned axes can't be neighbors, e.g. {X,X,Y} is invalid. * This yield two and only two classes: * - _tait bryan_ - all unsigned axes are distinct, e.g. {X,Y,Z} * - _proper/classic Euler angles_ - The first and the third unsigned axes is equal, * and the second is different, e.g. {X,Y,X} * * ### Intrinsic vs extrinsic Euler systems ### * * Only intrinsic Euler systems are supported for simplicity. * If you want to use extrinsic Euler systems, * just use the equal intrinsic opposite order for axes and angles. * I.e axes (A,B,C) becomes (C,B,A), and angles (a,b,c) becomes (c,b,a). * * ### Convenient user typedefs ### * * Convenient typedefs for EulerSystem exist (only for positive axes Euler systems), * in a form of EulerSystem{A}{B}{C}, e.g. \ref EulerSystemXYZ. * * ### Additional reading ### * * More information about Euler angles: https://en.wikipedia.org/wiki/Euler_angles * * \tparam _AlphaAxis the first fixed EulerAxis * * \tparam _AlphaAxis the second fixed EulerAxis * * \tparam _AlphaAxis the third fixed EulerAxis */ template <int _AlphaAxis, int _BetaAxis, int _GammaAxis> class EulerSystem { public: // It's defined this way and not as enum, because I think // that enum is not guerantee to support negative numbers /** The first rotation axis */ static const int AlphaAxis = _AlphaAxis; /** The second rotation axis */ static const int BetaAxis = _BetaAxis; /** The third rotation axis */ static const int GammaAxis = _GammaAxis; enum { AlphaAxisAbs = internal::Abs<AlphaAxis>::value, /*!< the first rotation axis unsigned */ BetaAxisAbs = internal::Abs<BetaAxis>::value, /*!< the second rotation axis unsigned */ GammaAxisAbs = internal::Abs<GammaAxis>::value, /*!< the third rotation axis unsigned */ IsAlphaOpposite = (AlphaAxis < 0) ? 1 : 0, /*!< weather alpha axis is negative */ IsBetaOpposite = (BetaAxis < 0) ? 1 : 0, /*!< weather beta axis is negative */ IsGammaOpposite = (GammaAxis < 0) ? 1 : 0, /*!< weather gamma axis is negative */ IsOdd = ((AlphaAxisAbs)%3 == (BetaAxisAbs - 1)%3) ? 0 : 1, /*!< weather the Euler system is odd */ IsEven = IsOdd ? 0 : 1, /*!< weather the Euler system is even */ IsTaitBryan = ((unsigned)AlphaAxisAbs != (unsigned)GammaAxisAbs) ? 1 : 0 /*!< weather the Euler system is tait bryan */ }; private: EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis<AlphaAxis>::value, ALPHA_AXIS_IS_INVALID); EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis<BetaAxis>::value, BETA_AXIS_IS_INVALID); EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis<GammaAxis>::value, GAMMA_AXIS_IS_INVALID); EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT((unsigned)AlphaAxisAbs != (unsigned)BetaAxisAbs, ALPHA_AXIS_CANT_BE_EQUAL_TO_BETA_AXIS); EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT((unsigned)BetaAxisAbs != (unsigned)GammaAxisAbs, BETA_AXIS_CANT_BE_EQUAL_TO_GAMMA_AXIS); enum { // I, J, K are the pivot indexes permutation for the rotation matrix, that match this Euler system. // They are used in this class converters. // They are always different from each other, and their possible values are: 0, 1, or 2. I = AlphaAxisAbs - 1, J = (AlphaAxisAbs - 1 + 1 + IsOdd)%3, K = (AlphaAxisAbs - 1 + 2 - IsOdd)%3 }; // TODO: Get @mat parameter in form that avoids double evaluation. template <typename Derived> static void CalcEulerAngles_imp(Matrix<typename MatrixBase<Derived>::Scalar, 3, 1>& res, const MatrixBase<Derived>& mat, internal::true_type /*isTaitBryan*/) { using std::atan2; using std::sin; using std::cos; typedef typename Derived::Scalar Scalar; typedef Matrix<Scalar,2,1> Vector2; res[0] = atan2(mat(J,K), mat(K,K)); Scalar c2 = Vector2(mat(I,I), mat(I,J)).norm(); if((IsOdd && res[0]<Scalar(0)) || ((!IsOdd) && res[0]>Scalar(0))) { if(res[0] > Scalar(0)) { res[0] -= Scalar(EIGEN_PI); } else { res[0] += Scalar(EIGEN_PI); } res[1] = atan2(-mat(I,K), -c2); } else res[1] = atan2(-mat(I,K), c2); Scalar s1 = sin(res[0]); Scalar c1 = cos(res[0]); res[2] = atan2(s1*mat(K,I)-c1*mat(J,I), c1*mat(J,J) - s1 * mat(K,J)); } template <typename Derived> static void CalcEulerAngles_imp(Matrix<typename MatrixBase<Derived>::Scalar,3,1>& res, const MatrixBase<Derived>& mat, internal::false_type /*isTaitBryan*/) { using std::atan2; using std::sin; using std::cos; typedef typename Derived::Scalar Scalar; typedef Matrix<Scalar,2,1> Vector2; res[0] = atan2(mat(J,I), mat(K,I)); if((IsOdd && res[0]<Scalar(0)) || ((!IsOdd) && res[0]>Scalar(0))) { if(res[0] > Scalar(0)) { res[0] -= Scalar(EIGEN_PI); } else { res[0] += Scalar(EIGEN_PI); } Scalar s2 = Vector2(mat(J,I), mat(K,I)).norm(); res[1] = -atan2(s2, mat(I,I)); } else { Scalar s2 = Vector2(mat(J,I), mat(K,I)).norm(); res[1] = atan2(s2, mat(I,I)); } // With a=(0,1,0), we have i=0; j=1; k=2, and after computing the first two angles, // we can compute their respective rotation, and apply its inverse to M. Since the result must // be a rotation around x, we have: // // c2 s1.s2 c1.s2 1 0 0 // 0 c1 -s1 * M = 0 c3 s3 // -s2 s1.c2 c1.c2 0 -s3 c3 // // Thus: m11.c1 - m21.s1 = c3 & m12.c1 - m22.s1 = s3 Scalar s1 = sin(res[0]); Scalar c1 = cos(res[0]); res[2] = atan2(c1*mat(J,K)-s1*mat(K,K), c1*mat(J,J) - s1 * mat(K,J)); } template<typename Scalar> static void CalcEulerAngles( EulerAngles<Scalar, EulerSystem>& res, const typename EulerAngles<Scalar, EulerSystem>::Matrix3& mat) { CalcEulerAngles(res, mat, false, false, false); } template< bool PositiveRangeAlpha, bool PositiveRangeBeta, bool PositiveRangeGamma, typename Scalar> static void CalcEulerAngles( EulerAngles<Scalar, EulerSystem>& res, const typename EulerAngles<Scalar, EulerSystem>::Matrix3& mat) { CalcEulerAngles(res, mat, PositiveRangeAlpha, PositiveRangeBeta, PositiveRangeGamma); } template<typename Scalar> static void CalcEulerAngles( EulerAngles<Scalar, EulerSystem>& res, const typename EulerAngles<Scalar, EulerSystem>::Matrix3& mat, bool PositiveRangeAlpha, bool PositiveRangeBeta, bool PositiveRangeGamma) { CalcEulerAngles_imp( res.angles(), mat, typename internal::conditional<IsTaitBryan, internal::true_type, internal::false_type>::type()); if (IsAlphaOpposite == IsOdd) res.alpha() = -res.alpha(); if (IsBetaOpposite == IsOdd) res.beta() = -res.beta(); if (IsGammaOpposite == IsOdd) res.gamma() = -res.gamma(); // Saturate results to the requested range if (PositiveRangeAlpha && (res.alpha() < 0)) res.alpha() += Scalar(2 * EIGEN_PI); if (PositiveRangeBeta && (res.beta() < 0)) res.beta() += Scalar(2 * EIGEN_PI); if (PositiveRangeGamma && (res.gamma() < 0)) res.gamma() += Scalar(2 * EIGEN_PI); } template <typename _Scalar, class _System> friend class Eigen::EulerAngles; }; #define EIGEN_EULER_SYSTEM_TYPEDEF(A, B, C) \ /** \ingroup EulerAngles_Module */ \ typedef EulerSystem<EULER_##A, EULER_##B, EULER_##C> EulerSystem##A##B##C; EIGEN_EULER_SYSTEM_TYPEDEF(X,Y,Z) EIGEN_EULER_SYSTEM_TYPEDEF(X,Y,X) EIGEN_EULER_SYSTEM_TYPEDEF(X,Z,Y) EIGEN_EULER_SYSTEM_TYPEDEF(X,Z,X) EIGEN_EULER_SYSTEM_TYPEDEF(Y,Z,X) EIGEN_EULER_SYSTEM_TYPEDEF(Y,Z,Y) EIGEN_EULER_SYSTEM_TYPEDEF(Y,X,Z) EIGEN_EULER_SYSTEM_TYPEDEF(Y,X,Y) EIGEN_EULER_SYSTEM_TYPEDEF(Z,X,Y) EIGEN_EULER_SYSTEM_TYPEDEF(Z,X,Z) EIGEN_EULER_SYSTEM_TYPEDEF(Z,Y,X) EIGEN_EULER_SYSTEM_TYPEDEF(Z,Y,Z) } #endif // EIGEN_EULERSYSTEM_H
graphe.ml
open Common (*****************************************************************************) (* Prelude *) (*****************************************************************************) (* * There are multiple libraries for graphs in OCaml, incorporating each * different graph algorithms: * * - OCamlGraph, by Filliatre, Signoles, et al. It has transitive closure, * Kruskal, Floyd, topological sort, CFC, etc. Probably the best. But it is * heavily functorized. I thought it was too complicated because of all * those functors but they also provide an easy interface without functor * in pack.mli and sig_pack.mli which makes it almost usable * (see paper from jfla05 on ocamlgraph). * * - A small graph library in ocamldot by Trevor Jim to compute the * transitive reduction of a graph, aka its kernel. * * - A small library in ocamldoc by Guesdon, who ported into ocamldoc * the functionality of ocamldot, and apparently uses the opportunity * to rewrite too his own graph library. Has also the transitive * reduction. * * - Camllib by jeannet ? * * - probably more on the caml hump. * * I have also developed a few graph libraries in commons/, but really just * to have a data type with successors/predecessors accessors: * * - common.ml type 'a graph. No algorithm, just builder/accessors. * - ograph.ml object version of Common.graph, just the interface. * * - ograph2way.ml a generic version, inherit ograph. * - ograph_extended.ml, implicit nodei = int for key. * - ograph_simple.ml, key can be specified, for instance can be a string, * so dont have to pass through the intermediate nodei for everything. * * I have also included in commons/ the small code from ocamldot/ocamldoc in: * - ocamlextra/graph_ocamldot.ml * - ocamlextra/graph_ocamldoc.ml * * ograph_simple and ograph_extended and ograph2way show that there is not * a single graph that can accomodate all needs while still being convenient. * ograph_extended is more generic, but you pay a little for that by * forcing the user to have this intermediate 'nodei'. The people * from ocamlgraph have well realized that and made it possible * to have different graph interface (imperative/pure, directed/undirected, * with/witout nodes, parametrized vertex or not, ...) and reuse * lots of code for the algorithm. Unfortunately, just like for the C++ * STL, it comes at a price: lots of functors. The sig_pack.mli and pack.ml * tries to solve this pb, but they made some choices about what should * be the default that are not always good, and they do not allow * polymorphic nodes, which I think is quite useful (especially when * you want to display your graph with dot, you want to see the label * of the nodes, and not just integers. * * * So, this module is a small wrapper around ocamlgraph, to have * more polymorphic graphs with some defaults that makes sense most * of the time (Directed graph, Imperative, vertex ints with mapping * to node information), and which can use algorithms defined in * other libraries by making some small converters from one representation * to the other (e.g. from my ograph_simple to ocamlgraph, and vice versa). * * Note that even if ocamlgraph is really good and even if this file is useful, * for quick and dirty trivial graph stuff then ograph_simple * should be simpler (less dependencies). You can * use it directly from common.cma. Then with the converter to ocamlgraph, * you can start with ograph_simple, and if in a few places you need * to use the graph algorithm provided by ocamlgraph or ocamldot, then * use the adapters. * * Alternatives in other languages: * - boost C++ BGL, * http://www.boost.org/doc/libs/1_45_0/libs/graph/doc/index.html * - quickGraph for .NET, http://quickgraph.codeplex.com/ * apparently inspired by the boost one * - c++ GTL, graph template library * - c++ ASTL, automata library * - See the book by Skienna "Algorithm Design Manual" which gives many * resources related to graph libraries. *) (*****************************************************************************) (* Types *) (*****************************************************************************) (* OG for ocamlgraph. * * todo: maybe time to use the non generic implementation and * use something more efficient, especially for G.pred, * see Imperative.ConcreteBidirectional for instance *) module OG = Graph.Pack.Digraph (* Polymorphic graph *) type 'key graph = { og : OG.t; (* Note that OG.V.t is not even an integer. It's an abstract data type * from which one can get its 'label' which is an int. It's a little * bit tedious because to create such a 't' you also have to use * yet another function: OG.V.create that takes an int ... *) key_of_vertex : (OG.V.t, 'key) Hashtbl.t; vertex_of_key : ('key, OG.V.t) Hashtbl.t; (* used to create vertexes (OG.V.create n) *) cnt : int ref; } (* module OG : sig type t = Ocamlgraph.Pack.Digraph.t module V : sig type t = Ocamlgraph.Pack.Digraph.V.t val compare : t -> t -> int val hash : t -> int val equal : t -> t -> bool type label = int val create : label -> t val label : t -> label end type vertex = V.t module E : sig type t = Ocamlgraph.Pack.Digraph.E.t val compare : t -> t -> int val src : t -> V.t val dst : t -> V.t type label = int val create : V.t -> label -> V.t -> t val label : t -> label type vertex = V.t end type edge = E.t NA val is_directed : bool DONE val create : ?size:int -> unit -> t val copy : t -> t DONE val add_vertex : t -> V.t -> unit DONE val remove_vertex : t -> V.t -> unit DONE val add_edge : t -> V.t -> V.t -> unit val add_edge_e : t -> E.t -> unit DONE val remove_edge : t -> V.t -> V.t -> unit val remove_edge_e : t -> E.t -> unit module Mark : sig type graph = t type vertex = V.t val clear : t -> unit val get : V.t -> int val set : V.t -> int -> unit end val is_empty : t -> bool DONE val nb_vertex : t -> int DONE val nb_edges : t -> int DONE val out_degree : t -> V.t -> int DONE val in_degree : t -> V.t -> int val mem_vertex : t -> V.t -> bool val mem_edge : t -> V.t -> V.t -> bool val mem_edge_e : t -> E.t -> bool val find_edge : t -> V.t -> V.t -> E.t DONE val succ : t -> V.t -> V.t list DONE val pred : t -> V.t -> V.t list val succ_e : t -> V.t -> E.t list val pred_e : t -> V.t -> E.t list DONE val iter_vertex : (V.t -> unit) -> t -> unit val iter_edges : (V.t -> V.t -> unit) -> t -> unit val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a val fold_edges : (V.t -> V.t -> 'a -> 'a) -> t -> 'a -> 'a val map_vertex : (V.t -> V.t) -> t -> t val iter_edges_e : (E.t -> unit) -> t -> unit val fold_edges_e : (E.t -> 'a -> 'a) -> t -> 'a -> 'a val iter_succ : (V.t -> unit) -> t -> V.t -> unit val iter_pred : (V.t -> unit) -> t -> V.t -> unit val fold_succ : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val fold_pred : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val iter_succ_e : (E.t -> unit) -> t -> V.t -> unit val fold_succ_e : (E.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val iter_pred_e : (E.t -> unit) -> t -> V.t -> unit val fold_pred_e : (E.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val find_vertex : t -> int -> V.t DONE val transitive_closure : ?reflexive:bool -> t -> t val add_transitive_closure : ?reflexive:bool -> t -> t DONE val mirror : t -> t val complement : t -> t val intersect : t -> t -> t val union : t -> t -> t module Dfs : sig val iter : ?pre:(V.t -> unit) -> ?post:(V.t -> unit) -> t -> unit val prefix : (V.t -> unit) -> t -> unit val postfix : (V.t -> unit) -> t -> unit val iter_component : ?pre:(V.t -> unit) -> ?post:(V.t -> unit) -> t -> V.t -> unit val prefix_component : (V.t -> unit) -> t -> V.t -> unit val postfix_component : (V.t -> unit) -> t -> V.t -> unit val has_cycle : t -> bool end module Bfs : sig val iter : (V.t -> unit) -> t -> unit val iter_component : (V.t -> unit) -> t -> V.t -> unit end module Marking : sig val dfs : t -> unit val has_cycle : t -> bool end module Classic : sig val divisors : int -> t val de_bruijn : int -> t val vertex_only : int -> t val full : ?self:bool -> int -> t end module Rand : sig val graph : ?loops:bool -> v:int -> e:int -> unit -> t val labeled : (V.t -> V.t -> E.label) -> ?loops:bool -> v:int -> e:int -> unit -> t end module Components : sig val scc : t -> int * (V.t -> int) val scc_array : t -> V.t list array val scc_list : t -> V.t list list end DONE val shortest_path : t -> V.t -> V.t -> E.t list * int val ford_fulkerson : t -> V.t -> V.t -> (E.t -> int) * int val goldberg : t -> V.t -> V.t -> (E.t -> int) * int module PathCheck : sig type path_checker = Ocamlgraph.Pack.Digraph.PathCheck.path_checker val create : t -> path_checker val check_path : path_checker -> V.t -> V.t -> bool end module Topological : sig val fold : (V.t -> 'a -> 'a) -> t -> 'a -> 'a val iter : (V.t -> unit) -> t -> unit end val spanningtree : t -> E.t list val dot_output : t -> string -> unit DONE val display_with_gv : t -> unit val parse_gml_file : string -> t val parse_dot_file : string -> t val print_gml_file : t -> string -> unit end *) (*****************************************************************************) (* Graph construction *) (*****************************************************************************) let create () = { og = OG.create (); key_of_vertex = Hashtbl.create 101; vertex_of_key = Hashtbl.create 101; cnt = ref 0; } let add_vertex_if_not_present key g = if Hashtbl.mem g.vertex_of_key key then () else ( incr g.cnt; let v = OG.V.create !(g.cnt) in Hashtbl.replace g.key_of_vertex v key; Hashtbl.replace g.vertex_of_key key v; (* not necessary as add_edge automatically do that *) OG.add_vertex g.og v) let vertex_of_key key g = Hashtbl.find g.vertex_of_key key let key_of_vertex v g = Hashtbl.find g.key_of_vertex v let add_edge k1 k2 g = let vx = g |> vertex_of_key k1 in let vy = g |> vertex_of_key k2 in OG.add_edge g.og vx vy; () (*****************************************************************************) (* Graph access *) (*****************************************************************************) let nodes g = Common2.hkeys g.vertex_of_key let out_degree k g = OG.out_degree g.og (g |> vertex_of_key k) let in_degree k g = OG.in_degree g.og (g |> vertex_of_key k) let nb_nodes g = OG.nb_vertex g.og let nb_edges g = OG.nb_edges g.og let succ k g = OG.succ g.og (g |> vertex_of_key k) |> List.map (fun k -> key_of_vertex k g) (* this seems slow on the version of ocamlgraph I currently have *) let pred k g = OG.pred g.og (g |> vertex_of_key k) |> List.map (fun k -> key_of_vertex k g) let ivertex k g = let v = vertex_of_key k g in OG.V.label v let has_node k g = try let _ = ivertex k g in true with | Not_found -> false let entry_nodes g = (* old: slow: nodes g +> List.filter (fun n -> pred n g = []) * Once I use a better underlying graph implementation maybe I * will not need this kind of things. *) let res = ref [] in let hdone = Hashtbl.create 101 in let finished = ref false in g.og |> OG.Topological.iter (fun v -> if !finished || Hashtbl.mem hdone v then finished := true else let xs = OG.succ g.og v in xs |> List.iter (fun n -> Hashtbl.replace hdone n true); Common.push v res); !res |> List.map (fun i -> key_of_vertex i g) |> List.rev [@@profiling] (*****************************************************************************) (* Iteration *) (*****************************************************************************) let iter_edges f g = g.og |> OG.iter_edges (fun v1 v2 -> let k1 = key_of_vertex v1 g in let k2 = key_of_vertex v2 g in f k1 k2) let iter_nodes f g = g.og |> OG.iter_vertex (fun v -> let k = key_of_vertex v g in f k) (*****************************************************************************) (* Graph deletion *) (*****************************************************************************) let remove_vertex k g = let vk = g |> vertex_of_key k in OG.remove_vertex g.og vk; Hashtbl.remove g.vertex_of_key k; Hashtbl.remove g.key_of_vertex vk; () let remove_edge k1 k2 g = let vx = g |> vertex_of_key k1 in let vy = g |> vertex_of_key k2 in (* todo? assert edge exists? *) OG.remove_edge g.og vx vy; () (*****************************************************************************) (* Misc *) (*****************************************************************************) (* todo? make the graph more functional ? it's very imperative right now * which forces the caller to write in an imperative way and use functions * like this 'copy()'. Look at launchbary haskell paper? *) let copy oldg = (* * bugfix: we can't just OG.copy the graph and Hashtbl.copy the vertex because * the vertex will actually be different in the copied graph, and so the * vertex_of_key will return a vertex in the original graph, not in * the new copied graph. *) (* { og = OG.copy g.og; key_of_vertex = Hashtbl.copy g.key_of_vertex; vertex_of_key = Hashtbl.copy g.vertex_of_key; cnt = ref !(g.cnt); } *) (* naive way, enough? optimize? all those iter are ugly ... *) let g = create () in let nodes = nodes oldg in nodes |> List.iter (fun n -> add_vertex_if_not_present n g); nodes |> List.iter (fun n -> (* bugfix: it's oldg, not 'g', wow, copying stuff is error prone *) let succ = succ n oldg in succ |> List.iter (fun n2 -> add_edge n n2 g)); g (*****************************************************************************) (* Graph algorithms *) (*****************************************************************************) let shortest_path k1 k2 g = let vx = g |> vertex_of_key k1 in let vy = g |> vertex_of_key k2 in let edges, _len = OG.shortest_path g.og vx vy in let vertexes = vx :: (edges |> List.map (fun edge -> OG.E.dst edge)) in vertexes |> List.map (fun v -> key_of_vertex v g) (* todo? this works? I get some * Fatal error: exception Invalid_argument("[ocamlgraph] fold_succ") * when doing: * let g = ... * let node = whatever g in * let g2 = transitive_closure g in * let succ = succ node g2 * is it because node references something from g? Is is the same * issue that for copy? * *) let transitive_closure g = let label_to_vertex = Hashtbl.create 101 in g.og |> OG.iter_vertex (fun v -> let lbl = OG.V.label v in Hashtbl.replace label_to_vertex lbl v); let og' = OG.transitive_closure ~reflexive:true g.og in let g' = create () in og' |> OG.iter_vertex (fun v -> let lbl = OG.V.label v in let vertex_in_g = Hashtbl.find label_to_vertex lbl in let key_in_g = Hashtbl.find g.key_of_vertex vertex_in_g in Hashtbl.replace g'.key_of_vertex v key_in_g; Hashtbl.replace g'.vertex_of_key key_in_g v); { g' with og = og' } let mirror g = let og' = OG.mirror g.og in (* todo: have probably to do the same gymnastic than for transitive_closure*) { g with og = og' } (* http://en.wikipedia.org/wiki/Strongly_connected_component *) let strongly_connected_components g = let scc_array_vt = OG.Components.scc_array g.og in let scc_array = scc_array_vt |> Array.map (fun xs -> xs |> List.map (fun vt -> key_of_vertex vt g)) in let h = Hashtbl.create 101 in scc_array |> Array.iteri (fun i xs -> xs |> List.iter (fun k -> if Hashtbl.mem h k then failwith "the strongly connected components should be disjoint"; Hashtbl.add h k i)); (scc_array, h) [@@profiling] (* http://en.wikipedia.org/wiki/Strongly_connected_component *) let strongly_connected_components_condensation g (scc, hscc) = let g2 = create () in let n = Array.length scc in for i = 0 to n - 1 do g2 |> add_vertex_if_not_present i done; g |> iter_edges (fun n1 n2 -> let k1 = Hashtbl.find hscc n1 in let k2 = Hashtbl.find hscc n2 in if k1 <> k2 then g2 |> add_edge k1 k2); g2 [@@profiling] let depth_nodes g = if OG.Dfs.has_cycle g.og then failwith "not a DAG"; let hres = Hashtbl.create 101 in (* do in toplogical order *) g.og |> OG.Topological.iter (fun v -> let ncurrent = if not (Hashtbl.mem hres v) then 0 else Hashtbl.find hres v in Hashtbl.replace hres v ncurrent; let xs = OG.succ g.og v in xs |> List.iter (fun v2 -> let nchild = if not (Hashtbl.mem hres v2) then ncurrent + 1 (* todo: max or min? can lead to different metrics, * either to know the longest path from the top, or to know some * possible shortest path from the top. *) else max (Hashtbl.find hres v2) (ncurrent + 1) in Hashtbl.replace hres v2 nchild; ())); let hfinalres = Hashtbl.create 101 in hres |> Hashtbl.iter (fun v n -> Hashtbl.add hfinalres (key_of_vertex v g) n); hfinalres [@@profiling] (*****************************************************************************) (* Graph visualization and debugging *) (*****************************************************************************) let display_with_gv g = OG.display_with_gv g.og let print_graph_generic ?(launch_gv = true) ?(extra_string = "") ~str_of_key filename g = Common.with_open_outfile filename (fun (pr, _) -> pr "digraph misc {\n"; (* pr "size = \"10,10\";\n" ; *) pr extra_string; pr "\n"; g.og |> OG.iter_vertex (fun v -> let k = key_of_vertex v g in (* todo? could also use the str_of_key to represent the node *) pr (spf "%d [label=\"%s\"];\n" (OG.V.label v) (str_of_key k))); g.og |> OG.iter_vertex (fun v -> let succ = OG.succ g.og v in succ |> List.iter (fun v2 -> pr (spf "%d -> %d;\n" (OG.V.label v) (OG.V.label v2)))); pr "}\n"); if launch_gv then failwith "TODO: Ograph_extended.launch_gv_cmd filename"; (* Ograph_extended.launch_gv_cmd filename; *) () (* nosemgrep *) let tmpfile = "/tmp/graph_ml.dot" let display_strongly_connected_components ~str_of_key hscc g = print_graph_generic ~str_of_key:(fun k -> let s = str_of_key k in spf "%s (scc=%d)" s (Hashtbl.find hscc k)) tmpfile g (*****************************************************************************) (* stat *) (*****************************************************************************) let stat g = pr2_gen ("cnt = ", g.cnt); ()
(* Yoann Padioleau * * Copyright (C) 2010, 2013 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *)
lifted.ml
open! Base open Ppxlib open Ast_builder.Default type 'a t = { value_bindings : value_binding list ; body : 'a } include Monad.Make (struct type nonrec 'a t = 'a t let return body = { value_bindings = []; body } let bind a ~f = let b = f a.body in { value_bindings = a.value_bindings @ b.value_bindings; body = b.body } ;; let map = `Define_using_bind end) let create ~loc ~prefix ~ty rhs = let name = gen_symbol ~prefix () in let lhs = pvar ~loc name in let body = evar ~loc name in let ty, rhs, body = if Helpers.is_value_expression rhs then ty, rhs, body else ( (* Thunkify the value to evaluate when referred to. *) let ty = [%type: Stdlib.Unit.t -> [%t ty]] in let rhs = [%expr fun () -> [%e rhs]] in let body = [%expr [%e body] ()] in ty, rhs, body) in { value_bindings = [ value_binding ~loc ~pat:(ppat_constraint ~loc lhs ty) ~expr:rhs ] ; body } ;; let let_bind_user_expressions { value_bindings; body } ~loc = if List.is_empty value_bindings then body else pexp_let ~loc Nonrecursive value_bindings body ;;
plugin.ml
(* Original author: Nicolas Pouillard *) open My_std open Format open Log open Pathname.Operators open Tags.Operators open Rule open Tools open Command ;; let plugin = "myocamlbuild" let plugin_file = plugin^".ml" let plugin_config_file = plugin^"_config.ml" let plugin_config_file_interface = plugin^"_config.mli" let we_have_a_plugin_source () = sys_file_exists plugin_file let we_need_a_plugin_binary () = !Options.plugin && we_have_a_plugin_source () let we_have_a_plugin_binary () = sys_file_exists ((!Options.build_dir/plugin)^(!Options.exe)) let we_have_a_config_file () = sys_file_exists plugin_config_file let we_have_a_config_file_interface () = sys_file_exists plugin_config_file_interface (* exported through plugin.mli *) let we_need_a_plugin () = we_need_a_plugin_binary () module Make(U:sig end) = struct let we_need_a_plugin_binary = we_need_a_plugin_binary () let we_have_a_plugin_source = we_have_a_plugin_source () let we_have_a_config_file = we_have_a_config_file () let we_have_a_config_file_interface = we_have_a_config_file_interface () let we_have_a_plugin_binary () = (* this remains a function as it will change during the build *) we_have_a_plugin_binary () let up_to_date_or_copy fn = let fn' = !Options.build_dir/fn in Pathname.exists fn && begin Pathname.exists fn' && Pathname.same_contents fn fn' || begin Shell.cp fn fn'; false end end let rebuild_plugin () = let a = up_to_date_or_copy plugin_file in let b = (not we_have_a_config_file) || up_to_date_or_copy plugin_config_file in let c = (not we_have_a_config_file_interface) || up_to_date_or_copy plugin_config_file_interface in if a && b && c && we_have_a_plugin_binary () then () (* Up to date *) (* FIXME: remove ocamlbuild_config.ml in _build/ if removed in parent *) else begin if !Options.native_plugin && not (sys_file_exists ((!Ocamlbuild_where.libdir)/"ocamlbuildlib.cmxa")) then begin Options.native_plugin := false; eprintf "Warning: Won't be able to compile a native plugin" end; let plugin_config = if we_have_a_config_file then if we_have_a_config_file_interface then S[P plugin_config_file_interface; P plugin_config_file] else P plugin_config_file else N in let cma, cmo, compiler, byte_or_native = if !Options.native_plugin then "cmxa", "cmx", !Options.plugin_ocamlopt, "native" else "cma", "cmo", !Options.plugin_ocamlc, "byte" in let (unix_spec, ocamlbuild_lib_spec, ocamlbuild_module_spec) = let use_light_mode = not !Options.native_plugin && !*My_unix.is_degraded in let use_ocamlfind_pkgs = !Options.plugin_use_ocamlfind && !Options.plugin_tags <> [] in (* The plugin has the following dependencies that must be included during compilation: - unix.cmxa, if it is available - ocamlbuildlib.cm{a,xa}, the library part of ocamlbuild - ocamlbuild.cm{o,x}, the module that performs the initialization work of the ocamlbuild executable, using modules of ocamlbuildlib.cmxa We pass all this stuff to the compilation command for the plugin, with two independent important details to handle: (1) ocamlbuild is designed to still work in environments where Unix is not available for some reason; in this case, we should not link unix, and use the "ocamlbuildlight.cmo" initialization module, which runs a "light" version of ocamlbuild without unix. There is also an ocamlbuildlightlib.cma archive to be used in that case. The boolean variable [use_light_mode] tells us whether we are in this unix-deprived scenario. (2) there are risks of compilation error due to double-linking of native modules when the user passes its own tags to the plugin compilation process (as was added to support modular construction of ocamlbuild plugins). Indeed, if we hard-code linking to unix.cmxa in all cases, and the user enables -plugin-use-ocamlfind and passes -plugin-tag "package(unix)" (or package(foo) for any foo which depends on unix), the command-line finally executed will be ocamlfind ocamlopt unix.cmxa -package unix myocamlbuild.ml which fails with a compilation error due to doubly-passed native modules. To sanest way to solve this problem at the ocamlbuild level is to pass "-package unix" instead of unix.cmxa when we detect that such a situation may happen. OCamlfind will see that the same package is demanded twice, and only request it once to the compiler. Similarly, we use "-package ocamlbuild" instead of linking ocamlbuildlib.cmxa[1]. We switch to this behavior when two conditions, embodied in the boolean variable [use_ocamlfind_pkgs], are met: (a) plugin-use-ocamlfind is enabled (b) the user is passing some plugin tags Condition (a) is overly conservative as the double-linking issue may also happen in non-ocamlfind situations, such as "-plugin-tags use_unix" -- but it's unclear how one would avoid the issue in that case, except by documenting that people should not do that, or getting rid of the hard-linking logic entirely, with the corresponding risks of regression. Condition (b) should not be necessary (we expect using ocamlfind packages to work whenever ocamlfind is available), but allows the behavior in absence of -plugin-tags to be completely unchanged, to reassure us about potential regressions introduced by this option. [1]: we may wonder whether to use "-package ocamlbuildlight" in unix-deprived situations, but currently ocamlfind doesn't know about the ocamlbuildlight library. As a compromise we always use "-package ocamlbuild" when use_ocamlfind_pkgs is set. An ocamlfind and -plugin-tags user in unix-deprived environment may want to mutate the META of ocamlbuild to point to ocamlbuildlightlib instead of ocamlbuildlib. *) let unix_lib = if use_ocamlfind_pkgs then `Package "unix" else if use_light_mode then `Nothing else `Lib "unix" in let ocamlbuild_lib = if use_ocamlfind_pkgs then `Package "ocamlbuild" else if use_light_mode then `Local_lib "ocamlbuildlightlib" else `Local_lib "ocamlbuildlib" in let ocamlbuild_module = if use_light_mode then `Local_mod "ocamlbuildlight" else `Local_mod "ocamlbuild" in let dir = !Ocamlbuild_where.libdir in let dir = if Pathname.is_implicit dir then Pathname.pwd/dir else dir in let in_dir file = let path = dir/file in if not (sys_file_exists path) then failwith (sprintf "Cannot find %S in ocamlbuild -where directory" file); path in let spec = function | `Nothing -> N | `Package pkg -> S[A "-package"; A pkg] | `Lib lib -> P (lib -.- cma) | `Local_lib llib -> S [A "-I"; A dir; P (in_dir (llib -.- cma))] | `Local_mod lmod -> P (in_dir (lmod -.- cmo)) in (spec unix_lib, spec ocamlbuild_lib, spec ocamlbuild_module) in let plugin_tags = Tags.of_list !Options.plugin_tags ++ "ocaml" ++ "program" ++ "link" ++ byte_or_native in (* The plugin is compiled before [Param_tags.init()] is called globally, which means that parametrized tags have not been made effective yet. The [partial_init] calls below initializes precisely those that will be used during the compilation of the plugin, and no more. *) Param_tags.partial_init Const.Source.plugin_tag plugin_tags; let cmd = (* The argument order is important: we carefully put the plugin source files before the ocamlbuild.cm{o,x} module doing the main initialization, so that user global side-effects (setting options, installing flags..) are performed brefore ocamlbuild's main routine. This is a fragile thing to rely upon and we insist that our users use the more robust [dispatch] registration instead, but we still aren't going to break that now. For the same reason we place the user plugin-tags after the plugin libraries (in case a tag would, say, inject a .cmo that also relies on them), but before the main plugin source file and ocamlbuild's initialization. *) Cmd(S[compiler; unix_spec; ocamlbuild_lib_spec; T plugin_tags; plugin_config; P plugin_file; ocamlbuild_module_spec; A"-o"; Px (plugin^(!Options.exe))]) in Shell.chdir !Options.build_dir; Shell.rm_f (plugin^(!Options.exe)); Command.execute cmd; end let execute_plugin () = Shell.chdir Pathname.pwd; let runner = if !Options.native_plugin then N else !Options.ocamlrun in let argv = List.tl (Array.to_list Sys.argv) in let passed_argv = List.filter (fun s -> s <> "-plugin-option") argv in let spec = S[runner; P(!Options.build_dir/plugin^(!Options.exe)); A"-no-plugin"; atomize passed_argv] in Log.finish (); let rc = sys_command (Command.string_of_command_spec spec) in raise (Exit_silently_with_code rc) let main () = if we_need_a_plugin_binary then begin rebuild_plugin (); if not (we_have_a_plugin_binary ()) then begin Log.eprintf "Error: we failed to build the plugin"; raise (Exit_with_code Exit_codes.rc_build_error); end end; (* if -just-plugin is passed by there is no plugin, nothing happens, and we decided not to emit a warning: this lets people that write ocamlbuild-driver scripts always run a first phase (ocamlbuild -just-plugin ...) if they want to, without having to test for the existence of a plugin first. *) if !Options.just_plugin then begin Log.finish (); raise Exit_OK; end; (* On the contrary, not having a plugin yet passing -plugin-tags is probably caused by a user error that we should warn about; for example people may incorrectly think that -plugin-tag foo.ocamlbuild will enable foo's rules: they have to explicitly use Foo in their plugin and it's best to warn if they don't. *) if not we_have_a_plugin_source && !Options.plugin_tags <> [] then eprintf "Warning: option -plugin-tag(s) has no effect \ in absence of plugin file %S" plugin_file; if we_need_a_plugin_binary && we_have_a_plugin_binary () then execute_plugin () end ;; let execute_plugin_if_needed () = let module P = Make(struct end) in P.main () ;;
(***********************************************************************) (* *) (* ocamlbuild *) (* *) (* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *) (* *) (* Copyright 2007 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. *) (* *) (***********************************************************************)
resource_pool.mli
(** External resource pools. This module provides an abstraction for managing collections of resources. One example use case is for managing a pool of database connections, where instead of establishing a new connection each time you need one (which is expensive), you can keep a pool of opened connections and reuse ones that are free. It also provides the capability of: - specifying the maximum number of resources that the pool can manage simultaneously, - checking whether a resource is still valid before/after use, and - performing cleanup logic before dropping a resource. The following example illustrates how it is used with an imaginary [Db] module: {[ let uri = "postgresql://localhost:5432" (* Create a database connection pool with max size of 10. *) let pool = Resource_pool.create 10 ~dispose:(fun connection -> Db.close connection |> Lwt.return) (fun () -> Db.connect uri |> Lwt.return) (* Use the pool in queries. *) let create_user name = Resource_pool.use pool (fun connection -> connection |> Db.insert "users" [("name", name)] |> Lwt.return ) ]} Note that this is {e not} intended to keep a pool of system threads. If you want to have such pool, consider using {!Lwt_preemptive}. *) type 'a t (** A pool containing elements of type ['a]. *) val create : ?validate : ('a -> bool Lwt.t) -> ?check : (exn -> 'a -> bool Lwt.t) -> ?dispose : ('a -> unit Lwt.t) -> int -> (unit -> 'a Lwt.t) -> 'a t (** [create n ?check ?validate ?dispose f] creates a new pool with at most [n] elements. [f] is used to create a new pool element. Elements are created on demand and re-used until disposed of. [f] may raise the exception [Resource_invalid] to signal a failed resource creation. In this case [use] will re-attempt to create the resource (according to [creation_attempts]). @param validate is called each time a pool element is accessed by {!use}, before the element is provided to {!use}'s callback. If [validate element] resolves to [true] the element is considered valid and is passed to the callback for use as-is. If [validate element] resolves to [false] the tested pool element is passed to [dispose] then dropped, with a new one is created to take [element]'s place in the pool. @param check is called after the resolution of {!use}'s callback when the resolution is a failed promise. [check element is_ok] must call [is_ok] exactly once with [true] if [element] is still valid and [false] otherwise. If [check] calls [is_ok false] then [dispose] will be run on [element] and the element will not be returned to the pool. @param dispose is used as described above and by {!clear} to dispose of all elements in a pool. [dispose] is {b not} guaranteed to be called on the elements in a pool when the pool is garbage collected. {!clear} should be used if the elements of the pool need to be explicitly disposed of. *) (** set the maximum size of the pool *) val set_max : 'a t -> int -> unit (** exception to be thrown by the function supplied to [use] when a resource is no longer valid and therefore to be disposed of; [safe] determines whether it is safe to relaunch the function supplied to [use]. Typically this refers to whether side-effects (that should not occur a second time) have been effectuated before the exception was raised. *) exception Resource_invalid of {safe : bool} val use : ?creation_attempts:int -> ?usage_attempts:int -> 'a t -> ('a -> 'b Lwt.t) -> 'b Lwt.t (** [use p f] requests one free element of the pool [p] and gives it to the function [f]. The element is put back into the pool after the promise created by [f] completes. In case the resource supplied to [f] is no longer valid, [f] can throw a [Resource_invalid] exception in which case the resource is disposed of. The parameter [creation_attempts] (default: [1]) controls the number of resource creation attempts that are made in case the creation function raises the [Resource_invalid] exception. The parameter [usage_attempts] (default: [1]) controls the number of attempts that are made in case [f] raises the [Resource_invalid] exception with [safe] set to true. After each attempt the resource is disposed of. In the case that [p] is exhausted and the maximum number of elements is reached, [use] will wait until one becomes free. *) val clear : 'a t -> unit Lwt.t (** [clear p] will clear all elements in [p], calling the [dispose] function associated with [p] on each of the cleared elements. Any elements from [p] which are currently in use will be disposed of once they are released. The next call to [use p] after [clear p] guarantees a freshly created pool element. Disposals are performed sequentially in an undefined order. *) exception Resource_limit_exceeded val add : ?omit_max_check:bool -> 'a t -> 'a -> unit (** By [add p c] you can add an existing resource element [c] to pool [p]. This function may raise a [Resource_limit_exceeded] exception. If [omit_max_check] is [true] (default: [false]), then this exception will not be raised. Instead the maximum number of resources might be exceeded and more than [p.max] elements will be available to the user. *) val wait_queue_length : _ t -> int (** [wait_queue_length p] returns the number of {!use} requests currently waiting for an element of the pool [p] to become available. *) val wait_queue_delay : _ t -> float (** [wait_queue_length p] returns the age of the oldest {!use} request currently waiting for an element of the pool [p] to become available. *)
(** External resource pools. This module provides an abstraction for managing collections of resources. One example use case is for managing a pool of database connections, where instead of establishing a new connection each time you need one (which is expensive), you can keep a pool of opened connections and reuse ones that are free. It also provides the capability of: - specifying the maximum number of resources that the pool can manage simultaneously, - checking whether a resource is still valid before/after use, and - performing cleanup logic before dropping a resource. The following example illustrates how it is used with an imaginary [Db] module: {[ let uri = "postgresql://localhost:5432" (* Create a database connection pool with max size of 10. *) let pool =
dune_fsevents.ml
let paths, latency = let latency = ref 0. in let paths = ref [] in let anon p = paths := p :: !paths in Arg.parse [ ("--latency", Arg.Set_float latency, "latency") ] anon "dune_fsevents [--latency float] [path]+"; (!paths, !latency) let fsevents = Fsevents.create ~paths ~latency ~f:(fun events -> ListLabels.iter events ~f:(fun evt -> Printf.printf "%s\n%!" (Dyn.to_string (Fsevents.Event.to_dyn_raw evt)))) let () = let runloop = Fsevents.RunLoop.in_current_thread () in Fsevents.start fsevents runloop; match Fsevents.RunLoop.run_current_thread runloop with | Ok () -> () | Error e -> raise e
encrypted.ml
type Tezos_crypto.Base58.data += Encrypted_ed25519 of Bytes.t type Tezos_crypto.Base58.data += Encrypted_secp256k1 of Bytes.t type Tezos_crypto.Base58.data += Encrypted_p256 of Bytes.t type Tezos_crypto.Base58.data += Encrypted_secp256k1_element of Bytes.t type Tezos_crypto.Base58.data += Encrypted_bls12_381 of Bytes.t type encrypted_sk = Encrypted_aggregate_sk | Encrypted_sk of Signature.algo type decrypted_sk = | Decrypted_aggregate_sk of Tezos_crypto.Aggregate_signature.Secret_key.t | Decrypted_sk of Signature.Secret_key.t open Client_keys let scheme = "encrypted" let aggregate_scheme = "aggregate_encrypted" module Raw = struct (* https://tools.ietf.org/html/rfc2898#section-4.1 *) let salt_len = 8 (* Fixed zero nonce *) let nonce = Tezos_crypto.Crypto_box.zero_nonce (* Secret keys for Ed25519, secp256k1, P256 have the same size. *) let encrypted_size = Tezos_crypto.Crypto_box.tag_length + Tezos_crypto.Hacl.Ed25519.sk_size let pbkdf ~salt ~password = Pbkdf.SHA512.pbkdf2 ~count:32768 ~dk_len:32l ~salt ~password let encrypt ~password sk = let salt = Tezos_crypto.Hacl.Rand.gen salt_len in let key = Tezos_crypto.Crypto_box.Secretbox.unsafe_of_bytes (pbkdf ~salt ~password) in let msg = match (sk : decrypted_sk) with | Decrypted_sk (Ed25519 sk) -> Data_encoding.Binary.to_bytes_exn Signature.Ed25519.Secret_key.encoding sk | Decrypted_sk (Secp256k1 sk) -> Data_encoding.Binary.to_bytes_exn Signature.Secp256k1.Secret_key.encoding sk | Decrypted_sk (P256 sk) -> Data_encoding.Binary.to_bytes_exn Signature.P256.Secret_key.encoding sk | Decrypted_sk (Bls sk) | Decrypted_aggregate_sk (Bls12_381 sk) -> Data_encoding.Binary.to_bytes_exn Signature.Bls.Secret_key.encoding sk in Bytes.cat salt (Tezos_crypto.Crypto_box.Secretbox.secretbox key msg nonce) let decrypt algo ~password ~encrypted_sk = let open Lwt_result_syntax in let salt = Bytes.sub encrypted_sk 0 salt_len in let encrypted_sk = Bytes.sub encrypted_sk salt_len encrypted_size in let key = Tezos_crypto.Crypto_box.Secretbox.unsafe_of_bytes (pbkdf ~salt ~password) in match ( Tezos_crypto.Crypto_box.Secretbox.secretbox_open key encrypted_sk nonce, algo ) with | None, _ -> return_none | Some bytes, Encrypted_sk Signature.Ed25519 -> ( match Data_encoding.Binary.of_bytes_opt Signature.Ed25519.Secret_key.encoding bytes with | Some sk -> return_some (Decrypted_sk (Ed25519 sk : Signature.Secret_key.t)) | None -> failwith "Corrupted wallet, deciphered key is not a valid Ed25519 secret \ key") | Some bytes, Encrypted_sk Signature.Secp256k1 -> ( match Data_encoding.Binary.of_bytes_opt Signature.Secp256k1.Secret_key.encoding bytes with | Some sk -> return_some (Decrypted_sk (Secp256k1 sk : Signature.Secret_key.t)) | None -> failwith "Corrupted wallet, deciphered key is not a valid Secp256k1 \ secret key") | Some bytes, Encrypted_sk Signature.P256 -> ( match Data_encoding.Binary.of_bytes_opt Signature.P256.Secret_key.encoding bytes with | Some sk -> return_some (Decrypted_sk (P256 sk : Signature.Secret_key.t)) | None -> failwith "Corrupted wallet, deciphered key is not a valid P256 secret key") | Some bytes, (Encrypted_aggregate_sk | Encrypted_sk Signature.Bls) -> ( match Data_encoding.Binary.of_bytes_opt Signature.Bls.Secret_key.encoding bytes with | Some sk -> return_some (Decrypted_aggregate_sk (Bls12_381 sk : Tezos_crypto.Aggregate_signature.Secret_key.t)) | None -> failwith "Corrupted wallet, deciphered key is not a valid BLS12_381 \ secret key") end module Encodings = struct let ed25519 = let length = Tezos_crypto.Hacl.Ed25519.sk_size + Tezos_crypto.Crypto_box.tag_length + Raw.salt_len in Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.ed25519_encrypted_seed ~length ~to_raw:(fun sk -> Bytes.to_string sk) ~of_raw:(fun buf -> if String.length buf <> length then None else Some (Bytes.of_string buf)) ~wrap:(fun sk -> Encrypted_ed25519 sk) let secp256k1 = let open Libsecp256k1.External in let length = Key.secret_bytes + Tezos_crypto.Crypto_box.tag_length + Raw.salt_len in Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.secp256k1_encrypted_secret_key ~length ~to_raw:(fun sk -> Bytes.to_string sk) ~of_raw:(fun buf -> if String.length buf <> length then None else Some (Bytes.of_string buf)) ~wrap:(fun sk -> Encrypted_secp256k1 sk) let p256 = let length = Tezos_crypto.Hacl.P256.sk_size + Tezos_crypto.Crypto_box.tag_length + Raw.salt_len in Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.p256_encrypted_secret_key ~length ~to_raw:(fun sk -> Bytes.to_string sk) ~of_raw:(fun buf -> if String.length buf <> length then None else Some (Bytes.of_string buf)) ~wrap:(fun sk -> Encrypted_p256 sk) let bls12_381 = let length = (* 32 + 16 + 8 = 56 *) Bls12_381_signature.sk_size_in_bytes + Tezos_crypto.Crypto_box.tag_length + Raw.salt_len in Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.bls12_381_encrypted_secret_key ~length ~to_raw:(fun sk -> Bytes.to_string sk) ~of_raw:(fun buf -> if String.length buf <> length then None else Some (Bytes.of_string buf)) ~wrap:(fun sk -> Encrypted_bls12_381 sk) let secp256k1_scalar = let length = 36 + Tezos_crypto.Crypto_box.tag_length + Raw.salt_len in Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.secp256k1_encrypted_scalar ~length ~to_raw:(fun sk -> Bytes.to_string sk) ~of_raw:(fun buf -> if String.length buf <> length then None else Some (Bytes.of_string buf)) ~wrap:(fun sk -> Encrypted_secp256k1_element sk) let () = Tezos_crypto.Base58.check_encoded_prefix ed25519 "edesk" 88 ; Tezos_crypto.Base58.check_encoded_prefix secp256k1 "spesk" 88 ; Tezos_crypto.Base58.check_encoded_prefix p256 "p2esk" 88 ; Tezos_crypto.Base58.check_encoded_prefix bls12_381 "BLesk" 88 ; Tezos_crypto.Base58.check_encoded_prefix secp256k1_scalar "seesk" 93 end (* we cache the password in this list to avoid asking the user all the time *) let passwords = ref [] (* Loop asking the user to give their password. Fails if a wrong password is given more than `retries_left` *) let interactive_decrypt_loop (cctxt : #Client_context.io) ?name ~retries_left ~encrypted_sk algo = let open Lwt_result_syntax in let rec interactive_decrypt_loop (cctxt : #Client_context.io) name ~current_retries ~retries ~encrypted_sk algo = match current_retries with | n when n >= retries -> failwith "%d incorrect password attempts" current_retries | _ -> ( let* password = cctxt#prompt_password "Enter password for encrypted key%s: " name in let* o = Raw.decrypt algo ~password ~encrypted_sk in match o with | Some sk -> passwords := password :: !passwords ; return sk | None -> let*! () = if retries_left == 1 then Lwt.return_unit else cctxt#message "Sorry, try again." in interactive_decrypt_loop cctxt name ~current_retries:(current_retries + 1) ~retries ~encrypted_sk algo) in let name = Option.fold name ~some:(fun s -> Format.sprintf " \"%s\"" s) ~none:"" in interactive_decrypt_loop cctxt name ~current_retries:0 ~retries:retries_left ~encrypted_sk algo (* add all passwords obtained by [ctxt#load_passwords] to the list of known passwords *) let password_file_load ctxt = let open Lwt_syntax in match ctxt#load_passwords with | Some stream -> let* () = Lwt_stream.iter (fun p -> passwords := Bytes.of_string p :: !passwords) stream in return_ok_unit | None -> return_ok_unit let rec noninteractive_decrypt_loop algo ~encrypted_sk = let open Lwt_result_syntax in function | [] -> return_none | password :: passwords -> ( let* o = Raw.decrypt algo ~password ~encrypted_sk in match o with | None -> noninteractive_decrypt_loop algo ~encrypted_sk passwords | Some sk -> return_some sk) let decrypt_payload cctxt ?name encrypted_sk = let open Lwt_result_syntax in let* algo, encrypted_sk = match Tezos_crypto.Base58.decode encrypted_sk with | Some (Encrypted_ed25519 encrypted_sk) -> return (Encrypted_sk Signature.Ed25519, encrypted_sk) | Some (Encrypted_secp256k1 encrypted_sk) -> return (Encrypted_sk Signature.Secp256k1, encrypted_sk) | Some (Encrypted_p256 encrypted_sk) -> return (Encrypted_sk Signature.P256, encrypted_sk) | Some (Encrypted_bls12_381 encrypted_sk) -> return (Encrypted_aggregate_sk, encrypted_sk) | _ -> failwith "Not a Base58Check-encoded encrypted key" in let* o = noninteractive_decrypt_loop algo ~encrypted_sk !passwords in match o with | Some sk -> return sk | None -> let retries_left = if cctxt#multiple_password_retries then 3 else 1 in interactive_decrypt_loop cctxt ?name ~retries_left ~encrypted_sk algo let internal_decrypt_simple (cctxt : #Client_context.prompter) ?name sk_uri = let open Lwt_result_syntax in let payload = Uri.path (sk_uri : sk_uri :> Uri.t) in let* decrypted_sk = decrypt_payload cctxt ?name payload in match decrypted_sk with | Decrypted_sk sk -> return sk | Decrypted_aggregate_sk _sk -> failwith "Found an aggregate secret key where a non-aggregate one was expected." let internal_decrypt_aggregate (cctxt : #Client_context.prompter) ?name aggregate_sk_uri = let open Lwt_result_syntax in let payload = Uri.path (aggregate_sk_uri : aggregate_sk_uri :> Uri.t) in let* decrypted_sk = decrypt_payload cctxt ?name payload in match decrypted_sk with | Decrypted_aggregate_sk sk -> return sk | Decrypted_sk _sk -> failwith "Found a non-aggregate secret key where an aggregate one was expected." let decrypt (cctxt : #Client_context.prompter) ?name sk_uri = let open Lwt_result_syntax in let* () = password_file_load cctxt in internal_decrypt_simple (cctxt : #Client_context.prompter) ?name sk_uri let decrypt_aggregate (cctxt : #Client_context.prompter) ?name aggregate_sk_uri = let open Lwt_result_syntax in let* () = password_file_load cctxt in internal_decrypt_aggregate (cctxt : #Client_context.prompter) ?name aggregate_sk_uri let decrypt_all (cctxt : #Client_context.io_wallet) = let open Lwt_result_syntax in let* sks = Secret_key.load cctxt in let* () = password_file_load cctxt in List.iter_es (fun (name, sk_uri) -> if Uri.scheme (sk_uri : sk_uri :> Uri.t) <> Some scheme then return_unit else let* _ = internal_decrypt_simple cctxt ~name sk_uri in return_unit) sks let decrypt_list (cctxt : #Client_context.io_wallet) keys = let open Lwt_result_syntax in let* sks = Secret_key.load cctxt in let* () = password_file_load cctxt in List.iter_es (fun (name, sk_uri) -> if Uri.scheme (sk_uri : sk_uri :> Uri.t) = Some scheme && (keys = [] || List.mem ~equal:String.equal name keys) then let* _ = internal_decrypt_simple cctxt ~name sk_uri in return_unit else return_unit) sks let rec read_password (cctxt : #Client_context.io) = let open Lwt_result_syntax in let* password = cctxt#prompt_password "Enter password to encrypt your key: " in let* confirm = cctxt#prompt_password "Confirm password: " in if not (Bytes.equal password confirm) then let*! () = cctxt#message "Passwords do not match." in read_password cctxt else return password let common_encrypt sk password = let payload = Raw.encrypt ~password sk in let encoding = match sk with | Decrypted_sk (Ed25519 _) -> Encodings.ed25519 | Decrypted_sk (Secp256k1 _) -> Encodings.secp256k1 | Decrypted_sk (P256 _) -> Encodings.p256 | Decrypted_sk (Bls _) | Decrypted_aggregate_sk (Bls12_381 _) -> Encodings.bls12_381 in Tezos_crypto.Base58.simple_encode encoding payload let internal_encrypt_simple sk password = let open Lwt_result_syntax in let path = common_encrypt sk password in let*? v = Client_keys.make_sk_uri (Uri.make ~scheme ~path ()) in return v let internal_encrypt_aggregate sk password = let open Lwt_result_syntax in let path = common_encrypt sk password in let*? v = Client_keys.make_aggregate_sk_uri (Uri.make ~scheme:aggregate_scheme ~path ()) in return v let encrypt sk password = internal_encrypt_simple (Decrypted_sk sk) password let encrypt_aggregate sk password = internal_encrypt_aggregate (Decrypted_aggregate_sk sk) password let prompt_twice_and_encrypt cctxt sk = let open Lwt_result_syntax in let* password = read_password cctxt in encrypt sk password let prompt_twice_and_encrypt_aggregate cctxt sk = let open Lwt_result_syntax in let* password = read_password cctxt in encrypt_aggregate sk password module Sapling_raw = struct let salt_len = 8 (* 193 *) let encrypted_size = Tezos_crypto.Crypto_box.tag_length + salt_len + 169 let nonce = Tezos_crypto.Crypto_box.zero_nonce let pbkdf ~salt ~password = Pbkdf.SHA512.pbkdf2 ~count:32768 ~dk_len:32l ~salt ~password let encrypt ~password msg = let msg = Tezos_sapling.Core.Wallet.Spending_key.to_bytes msg in let salt = Tezos_crypto.Hacl.Rand.gen salt_len in let key = Tezos_crypto.Crypto_box.Secretbox.unsafe_of_bytes (pbkdf ~salt ~password) in Bytes.( to_string (cat salt (Tezos_crypto.Crypto_box.Secretbox.secretbox key msg nonce))) let decrypt ~password payload = let ebytes = Bytes.of_string payload in let salt = Bytes.sub ebytes 0 salt_len in let encrypted_sk = Bytes.sub ebytes salt_len (encrypted_size - salt_len) in let key = Tezos_crypto.Crypto_box.Secretbox.unsafe_of_bytes (pbkdf ~salt ~password) in Option.bind (Tezos_crypto.Crypto_box.Secretbox.secretbox_open key encrypted_sk nonce) Tezos_sapling.Core.Wallet.Spending_key.of_bytes type Tezos_crypto.Base58.data += | Data of Tezos_sapling.Core.Wallet.Spending_key.t let encrypted_b58_encoding password = Tezos_crypto.Base58.register_encoding ~prefix:Tezos_crypto.Base58.Prefix.sapling_spending_key ~length:encrypted_size ~to_raw:(encrypt ~password) ~of_raw:(decrypt ~password) ~wrap:(fun x -> Data x) end let encrypt_sapling_key cctxt sk = let open Lwt_result_syntax in let* password = read_password cctxt in let path = Tezos_crypto.Base58.simple_encode (Sapling_raw.encrypted_b58_encoding password) sk in let*? v = Client_keys.make_sapling_uri (Uri.make ~scheme ~path ()) in return v let decrypt_sapling_key (cctxt : #Client_context.io) (sk_uri : sapling_uri) = let open Lwt_result_syntax in let uri = (sk_uri :> Uri.t) in let payload = Uri.path uri in if Uri.scheme uri = Some scheme then let* password = cctxt#prompt_password "Enter password to decrypt your key: " in match Tezos_crypto.Base58.simple_decode (Sapling_raw.encrypted_b58_encoding password) payload with | None -> failwith "Password incorrect or corrupted wallet, could not decipher \ encrypted Sapling spending key." | Some sapling_key -> return sapling_key else match Tezos_crypto.Base58.simple_decode Tezos_sapling.Core.Wallet.Spending_key.b58check_encoding payload with | None -> failwith "Corrupted wallet, could not read unencrypted Sapling spending key." | Some sapling_key -> return sapling_key module Make (C : sig val cctxt : Client_context.io_wallet end) = struct let scheme = "encrypted" let title = "Built-in signer using encrypted keys." let description = "Valid secret key URIs are of the form\n\ \ - encrypted:<encrypted_key>\n\ where <encrypted_key> is the encrypted (password protected using Nacl's \ cryptobox and pbkdf) secret key, formatted in unprefixed \ Tezos_crypto.Base58.\n\ Valid public key URIs are of the form\n\ \ - encrypted:<public_key>\n\ where <public_key> is the public key in Tezos_crypto.Base58." include Client_keys.Signature_type let public_key = Unencrypted.public_key let public_key_hash = Unencrypted.public_key_hash let import_secret_key = Unencrypted.import_secret_key let neuterize sk_uri = let open Lwt_result_syntax in let* sk = decrypt C.cctxt sk_uri in let*? v = Unencrypted.make_pk (Signature.Secret_key.to_public_key sk) in return v let sign ?watermark sk_uri buf = let open Lwt_result_syntax in let* sk = decrypt C.cctxt sk_uri in return (Signature.sign ?watermark sk buf) let deterministic_nonce sk_uri buf = let open Lwt_result_syntax in let* sk = decrypt C.cctxt sk_uri in return (Signature.deterministic_nonce sk buf) let deterministic_nonce_hash sk_uri buf = let open Lwt_result_syntax in let* sk = decrypt C.cctxt sk_uri in return (Signature.deterministic_nonce_hash sk buf) let supports_deterministic_nonces _ = Lwt_result_syntax.return_true end module Make_aggregate (C : sig val cctxt : Client_context.io_wallet end) = struct let scheme = "aggregate_encrypted" let title = "Built-in signer using encrypted aggregate keys." let description = "Valid aggregate secret key URIs are of the form\n\ \ - aggregate_encrypted:<encrypted_aggregate_key>\n\ where <encrypted_key> is the encrypted (password protected using Nacl's \ cryptobox and pbkdf) secret key, formatted in unprefixed \ Tezos_crypto.Base58.\n\ Valid aggregate public key URIs are of the form\n\ \ - aggregate_encrypted:<public_aggregate_key>\n\ where <public_aggregate_key> is the public key in Tezos_crypto.Base58." include Client_keys.Aggregate_type let public_key = Unencrypted.Aggregate.public_key let public_key_hash = Unencrypted.Aggregate.public_key_hash let import_secret_key = Unencrypted.Aggregate.import_secret_key let neuterize sk_uri = let open Lwt_result_syntax in let* sk = decrypt_aggregate C.cctxt sk_uri in let*? v = Unencrypted.Aggregate.make_pk (Tezos_crypto.Aggregate_signature.Secret_key.to_public_key sk) in return v let sign sk_uri buf = let open Lwt_result_syntax in let* sk = decrypt_aggregate C.cctxt sk_uri in return (Tezos_crypto.Aggregate_signature.sign sk buf) end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2018 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. *) (* *) (*****************************************************************************)
binaryen_stubs_globals.c
#define CAML_NAME_SPACE #include <caml/mlvalues.h> #include <caml/fail.h> #include <caml/memory.h> #include <caml/alloc.h> #include "binaryen-c.h" #include "ocaml_helpers.h" /* Allocating an OCaml custom block to hold the given BinaryenGlobalRef */ static value alloc_BinaryenGlobalRef(BinaryenGlobalRef exp) { value v = caml_alloc_custom(&binaryen_ops, sizeof(BinaryenGlobalRef), 0, 1); BinaryenGlobalRef_val(v) = exp; return v; } /* Allocating an OCaml custom block to hold the given BinaryenType */ static value alloc_BinaryenType(BinaryenType typ) { value v = caml_alloc_custom(&binaryen_ops, sizeof(BinaryenType), 0, 1); BinaryenType_val(v) = typ; return v; } /* Allocating an OCaml custom block to hold the given BinaryenExpressionRef */ static value alloc_BinaryenExpressionRef(BinaryenExpressionRef exp) { value v = caml_alloc_custom(&binaryen_ops, sizeof(BinaryenExpressionRef), 0, 1); BinaryenExpressionRef_val(v) = exp; return v; } CAMLprim value caml_binaryen_add_global(value _module, value _name, value _ty, value _mutable_, value _init) { CAMLparam5(_module, _name, _ty, _mutable_, _init); BinaryenModuleRef module = BinaryenModuleRef_val(_module); char* name = Safe_String_val(_name); BinaryenType ty = BinaryenType_val(_ty); int8_t mutable_ = Bool_val(_mutable_); BinaryenExpressionRef init = BinaryenExpressionRef_val(_init); BinaryenGlobalRef glob = BinaryenAddGlobal(module, name, ty, mutable_, init); CAMLreturn(alloc_BinaryenGlobalRef(glob)); } CAMLprim value caml_binaryen_get_global(value _module, value _name) { CAMLparam2(_module, _name); BinaryenModuleRef module = BinaryenModuleRef_val(_module); char* name = Safe_String_val(_name); BinaryenGlobalRef glob = BinaryenGetGlobal(module, name); CAMLreturn(alloc_BinaryenGlobalRef(glob)); } CAMLprim value caml_binaryen_remove_global(value _module, value _name) { CAMLparam2(_module, _name); BinaryenModuleRef module = BinaryenModuleRef_val(_module); char* name = Safe_String_val(_name); BinaryenRemoveGlobal(module, name); CAMLreturn(Val_unit); } CAMLprim value caml_binaryen_get_num_globals(value _module) { CAMLparam1(_module); BinaryenModuleRef module = BinaryenModuleRef_val(_module); CAMLreturn(Val_int(BinaryenGetNumGlobals(module))); } CAMLprim value caml_binaryen_get_global_by_index(value _module, value _index) { CAMLparam2(_module, _index); BinaryenModuleRef module = BinaryenModuleRef_val(_module); BinaryenIndex index = Int_val(_index); CAMLreturn(alloc_BinaryenGlobalRef(BinaryenGetGlobalByIndex(module, index))); } CAMLprim value caml_binaryen_global_get_name(value _global) { CAMLparam1(_global); BinaryenGlobalRef global = BinaryenGlobalRef_val(_global); const char* name = BinaryenGlobalGetName(global); CAMLreturn(caml_copy_string(name)); } CAMLprim value caml_binaryen_global_get_type(value _global) { CAMLparam1(_global); BinaryenGlobalRef global = BinaryenGlobalRef_val(_global); BinaryenType ty = BinaryenGlobalGetType(global); CAMLreturn(alloc_BinaryenType(ty)); } CAMLprim value caml_binaryen_global_is_mutable(value _global) { CAMLparam1(_global); BinaryenGlobalRef global = BinaryenGlobalRef_val(_global); CAMLreturn(Val_bool(BinaryenGlobalIsMutable(global))); } CAMLprim value caml_binaryen_global_get_init_expr(value _global) { CAMLparam1(_global); BinaryenGlobalRef global = BinaryenGlobalRef_val(_global); BinaryenExpressionRef exp = BinaryenGlobalGetInitExpr(global); CAMLreturn(alloc_BinaryenExpressionRef(exp)); }
salsa20_core.mli
(** {{:http://cr.yp.to/snuffle/spec.pdf} The Salsa20 specification} specifies a Salsa20/20 Core function as well as a set of reduced Salsa20/8 Core and Salsa20/12 Core functions *) (** [salsa20_8_core input] is [output], the Salsa20/8 Core function. [input] must be 16 blocks of 32 bits. @raise Invalid_argument if [input] is not of the correct size *) val salsa20_8_core : Cstruct.t -> Cstruct.t (** [salsa20_12_core input] is [output], the Salsa20/12 Core function. [input] must be 16 blocks of 32 bits. @raise Invalid_argument if [input] is not of the correct size *) val salsa20_12_core : Cstruct.t -> Cstruct.t (** [salsa20_20_core input] is [output], the Salsa20/20 Core function. [input] must be 16 blocks of 32 bits. @raise Invalid_argument if [input] is not of the correct size *) val salsa20_20_core : Cstruct.t -> Cstruct.t
(** {{:http://cr.yp.to/snuffle/spec.pdf} The Salsa20 specification} specifies a Salsa20/20 Core function as well as a set of reduced Salsa20/8 Core and Salsa20/12 Core functions *)
seed_storage.mli
type error += | Unknown of { oldest : Cycle_repr.t ; cycle : Cycle_repr.t ; latest : Cycle_repr.t } (* `Permanent *) (** Generates the first [preserved_cycles+2] seeds for which there are no nonces. *) val init: Raw_context.t -> Raw_context.t tzresult Lwt.t val for_cycle: Raw_context.t -> Cycle_repr.t -> Seed_repr.seed tzresult Lwt.t (** If it is the end of the cycle, computes and stores the seed of cycle at distance [preserved_cycle+2] in the future using the seed of the previous cycle and the revelations of the current one. *) val cycle_end: Raw_context.t -> Cycle_repr.t -> (Raw_context.t * Nonce_storage.unrevealed 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. *) (* *) (*****************************************************************************)
storage_functors.mli
(** Tezos Protocol Implementation - Typed storage builders. *) open Storage_sigs module Make_subcontext (C : Raw_context.T) (N : NAME) : Raw_context.T with type t = C.t module Make_single_data_storage (C : Raw_context.T) (N : NAME) (V : VALUE) : Single_data_storage with type t = C.t and type value = V.t module type INDEX = sig type t val path_length: int val to_path: t -> string list -> string list val of_path: string list -> t option type 'a ipath val args: ('a, t, 'a ipath) Storage_description.args end module Pair(I1 : INDEX)(I2 : INDEX) : INDEX with type t = I1.t * I2.t module Make_data_set_storage (C : Raw_context.T) (I : INDEX) : Data_set_storage with type t = C.t and type elt = I.t module Make_indexed_data_storage (C : Raw_context.T) (I : INDEX) (V : VALUE) : Indexed_data_storage with type t = C.t and type key = I.t and type value = V.t module Make_indexed_carbonated_data_storage (C : Raw_context.T) (I : INDEX) (V : VALUE) : Non_iterable_indexed_carbonated_data_storage with type t = C.t and type key = I.t and type value = V.t module Make_indexed_data_snapshotable_storage (C : Raw_context.T) (Snapshot : INDEX) (I : INDEX) (V : VALUE) : Indexed_data_snapshotable_storage with type t = C.t and type snapshot = Snapshot.t and type key = I.t and type value = V.t module Make_indexed_subcontext (C : Raw_context.T) (I : INDEX) : Indexed_raw_context with type t = C.t and type key = I.t and type 'a ipath = 'a I.ipath module Wrap_indexed_data_storage (C : Indexed_data_storage) (K : sig type t val wrap: t -> C.key val unwrap: C.key -> t option end) : Indexed_data_storage with type t = C.t and type key = K.t and type value = C.value
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
roll_storage.mli
(** Basic roll manipulation. The storage related to roll (i.e. `Storage.Roll`) is not used outside of this module. And, this interface enforces the invariant that a roll is always either in the limbo list or owned by a delegate. *) type error += | (* `Permanent *) Consume_roll_change | (* `Permanent *) No_roll_for_delegate | (* `Permanent *) No_roll_snapshot_for_cycle of Cycle_repr.t | (* `Permanent *) Unregistered_delegate of Signature.Public_key_hash.t (** [init ctxt] returns a new context initialized from [ctxt] where the next roll to be allocated is the first roll, i.e. [(Storage.Roll.Next.get ctxt) = Roll_repr.first]. This function returns a [{!Storage_error Existing_key}] error if the context has already been initialized. *) val init : Raw_context.t -> Raw_context.t tzresult Lwt.t (** [init_first_cycles ctxt] computes a new context from [ctxt] where the store has been prepared to save roll snapshots for all cycles from [0] to [Constants.preserved_cycles + 2]: 1. rolls for all cycles in the interval [(0, preserved_cycles)] are frozen (after taking a snapshot), 2. a snapshot is taken for rolls of cycle [preserved_cycles + 1], 3. rolls for cycle [preserved_cycles + 2] are ready for a snapshot, i.e. the necessary storage has been prepared. *) val init_first_cycles : Raw_context.t -> Raw_context.t tzresult Lwt.t (** [cycle_end ctxt last_cycle] returns a new context after applying the end-of-cycle bookkeeping to [ctxt]: 1. clears cycle [c = (last_cycle - preserved_cycles)] if [last_cycle >= preserved_cycles] (this amounts to deleting the only snapshot left after the freezing of [c]), 2. freezes snapshot rolls for the cycle [(last_cycle + preserved_cycles + 1)] (this amounts to removing all snapshots for the cycle, except one randomly selected for computing baking rights), 3. makes cycle [(last_cycle + preserved_cycles + 2)] ready for snapshot. *) val cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t (** [snapshot_rolls ctxt] creates roll snapshots for cycle [c = level + preserved_cycles + 2]. The returned context is such that: 1. the snapshot index associated to cycle [c] is incremented, 2. the rolls' owners are copied and associated to the snapshot id [(c,index)] (where [index] is the current snapshot index of cycle [c]), 3. the last roll for cycle [c], and snapshot [index] is set to be the next roll of [ctxt]. *) val snapshot_rolls : Raw_context.t -> Raw_context.t tzresult Lwt.t (** [fold ctxt f init] folds [f] on the list of all rolls from [Roll_repr.first] to [Storage.Next.Roll] of the context [ctxt]. Only rolls which have owners are considered, rolls without owners are skipped. The first parameter of [f] is a roll [r], the second parameter of [f] is the owner of [r], and the last parameter is the initial value of the accumulator. *) val fold : Raw_context.t -> f:(Roll_repr.roll -> Signature.Public_key.t -> 'a -> 'a tzresult Lwt.t) -> 'a -> 'a tzresult Lwt.t (** May return a [No_roll_snapshot_for_cycle] error. *) val baking_rights_owner : Raw_context.t -> Level_repr.t -> priority:int -> Signature.Public_key.t tzresult Lwt.t (** May return a [No_roll_snapshot_for_cycle] error. *) val endorsement_rights_owner : Raw_context.t -> Level_repr.t -> slot:int -> Signature.Public_key.t tzresult Lwt.t module Delegate : sig val is_inactive : Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t (** [add_amount ctxt dlg am] performs the following actions: 1. if the delegate [dlg] is inactive, increase its change [chg] by [am], 2. if the [dlg] is active, update [dlg]'s number of rolls [nr], and change [chg] so that [dlg]'s number of tokens is increased by [am], and equal to [nr * tokens_per_roll + chg], where [chg < tokens_per_roll]. *) val add_amount : Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t (** [remove_amount ctxt dlg am] performs the following actions: 1. if the delegate [dlg] is inactive, decrease its change [chg] by [am], 2. if the [dlg] is active, update [dlg]'s number of rolls [nr], and change [chg] so that [dlg]'s number of tokens is decreased by [am], and equal to [nr * tokens_per_roll + chg], where [chg < tokens_per_roll]. *) val remove_amount : Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t (** [set_inactive ctxt dlg] renders delegate [dlg] inactive and performs the following actions: 1. empty the list of rolls of [dlg], 2. increase the change of [dlg] by [nr * tokens_per_roll], where [nr] is [dlg]'s number of rolls prior to inactivation. *) val set_inactive : Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t (** If the delegate [dlg] is already active then [set_active ctxt dlg] performs the following sequence of actions: 1. if the delegate is not scheduled to become inactive, then schedule the delegate to become inactive after [(preserved_cycles * 2) + 1] cycles, 2. if the delegate is already scheduled to become inactive at cycle [ic], then re-schedule it to become inactive at cycle [max ic (cc + preserved_cycles + 1)], where [cc] is the current cycle. If [dlg] is inactive then this function puts [dlg] in active state and performs the following actions: 1. if [dlg] is not scheduled to become inactive, schedule [dlg] to become inactive after [(preserved_cycles * 2) + 1] cycles, 2. if the [dlg] is already scheduled to become inactive at cycle [ic], then re-schedule it to become inactive at cycle [max ic (cc + (preserved_cycles * 2) + 1)], where [cc] is the current cycle, 3. dispatch [dlg]'s change [chg] into [nr] rolls of size [tokens_per_roll] so that the total amount managed by [dlg] is unchanged and equal to [(nr * tokens_per_roll) + chg], where [chg < tokens_per_roll]. *) val set_active : Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t end module Contract : sig (** Calls [Delegate.add_amount ctxt contract am] if a delegate is associated to [contract], or returns unchanged [ctxt] otherwise. *) val add_amount : Raw_context.t -> Contract_repr.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t (** Calls [Delegate.remove_amount ctxt contract am] if a delegate is associated to [contract], or returns unchanged [ctxt] otherwise. *) val remove_amount : Raw_context.t -> Contract_repr.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t end (** [delegate_pubkey ctxt delegate] returns the public key of [delegate] found in context [ctxt] if there exists a registered contract. *) val delegate_pubkey : Raw_context.t -> Signature.Public_key_hash.t -> Signature.Public_key.t tzresult Lwt.t (** [count_rolls ctxt delegate] returns the number of rolls held by [delegate] in context [ctxt]. *) val count_rolls : Raw_context.t -> Signature.Public_key_hash.t -> int tzresult Lwt.t (** [get_change ctxt delegate] returns the amount of change held by [delegate] in context [ctxt]. The change is the part of the staking balance of a delegate that is not part of a roll, i.e., the amount of staking balance (smaller than the value of a roll) not being taken into account for baking rights computation. *) val get_change : Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t (** [update_tokens_per_roll ctxt am] performs the following actions: 1. set the constant [tokens_per_roll] to [am], 2. if the constant was increased by [tpram], then add the amount [nr * tpram] to each delegate, where [nr] is the delegate's number of rolls, 3. if the constant was instead decreased by [tpram], then remove the amount [nr * tpram] from all delegates. *) val update_tokens_per_roll : Raw_context.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t (** [get_contract_delegate ctxt contract] returns the public key hash of the delegate whose contract is [contract] in context [ctxt]. *) val get_contract_delegate : Raw_context.t -> Contract_repr.t -> Signature.Public_key_hash.t option tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2019 Metastate AG <contact@metastate.ch> *) (* *) (* 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. *) (* *) (*****************************************************************************)
compose_mod_brent_kung_precomp_preinv.c
#ifdef T #include "templates.h" #include <gmp.h> #include "flint.h" #include "ulong_extras.h" void _TEMPLATE(T, poly_reduce_matrix_mod_poly) (TEMPLATE(T, mat_t) A, const TEMPLATE(T, mat_t) B, const TEMPLATE(T, poly_t) f, const TEMPLATE(T, ctx_t) ctx) { slong n = f->length - 1; slong i, m = n_sqrt(n) + 1; TEMPLATE(T, t) invf; TEMPLATE(T, mat_init) (A, m, n, ctx); TEMPLATE(T, one) (TEMPLATE(T, mat_entry) (A, 0, 0), ctx); TEMPLATE(T, init) (invf, ctx); TEMPLATE(T, inv) (invf, f->coeffs + (f->length - 1), ctx); for (i = 1; i < m; i++) _TEMPLATE(T, poly_rem) (A->rows[i], B->rows[i], B->c, f->coeffs, f->length, invf, ctx); TEMPLATE(T, clear) (invf, ctx); } void _TEMPLATE(T, poly_precompute_matrix) ( TEMPLATE(T, mat_t) A, const TEMPLATE(T, struct) * poly1, const TEMPLATE(T, struct) * poly2, slong len2, const TEMPLATE(T, struct) * poly2inv, slong len2inv, const TEMPLATE(T, ctx_t) ctx) { /* Set rows of A to powers of poly1 */ slong i, n, m; n = len2 - 1; m = n_sqrt(n) + 1; TEMPLATE(T, one) (TEMPLATE(T, mat_entry) (A, 0, 0), ctx); _TEMPLATE(T, vec_set) (A->rows[1], poly1, n, ctx); for (i = 2; i < m; i++) _TEMPLATE(T, poly_mulmod_preinv) (A->rows[i], A->rows[i - 1], n, poly1, n, poly2, len2, poly2inv, len2inv, ctx); } void TEMPLATE(T, poly_precompute_matrix) (TEMPLATE(T, mat_t) A, const TEMPLATE(T, poly_t) poly1, const TEMPLATE(T, poly_t) poly2, const TEMPLATE(T, poly_t) poly2inv, const TEMPLATE(T, ctx_t) ctx) { slong len1 = poly1->length; slong len2 = poly2->length; slong len = len2 - 1; slong m = n_sqrt(len) + 1; TEMPLATE(T, struct) * ptr1; if (len2 == 0) { flint_printf ("Exception (nmod_poly_compose_mod_brent_kung). Division by zero.\n"); flint_abort(); } if (A->r != m || A->c != len) { flint_printf ("Exception (nmod_poly_compose_mod_brent_kung). Wrong dimensions.\n"); flint_abort(); } if (len2 == 1) { TEMPLATE(T, mat_zero) (A, ctx); return; } ptr1 = _TEMPLATE(T, vec_init) (len, ctx); if (len1 <= len) { _TEMPLATE(T, vec_set) (ptr1, poly1->coeffs, len1, ctx); _TEMPLATE(T, vec_zero) (ptr1 + len1, len - len1, ctx); } else { TEMPLATE(T, t) inv2; TEMPLATE(T, init) (inv2, ctx); TEMPLATE(T, inv) (inv2, poly2->coeffs + len2 - 1, ctx); _TEMPLATE(T, poly_rem) (ptr1, poly1->coeffs, len1, poly2->coeffs, len2, inv2, ctx); TEMPLATE(T, clear) (inv2, ctx); } _TEMPLATE(T, poly_precompute_matrix) (A, ptr1, poly2->coeffs, len2, poly2inv->coeffs, poly2inv->length, ctx); _TEMPLATE(T, vec_clear) (ptr1, len, ctx); } void _TEMPLATE(T, poly_compose_mod_brent_kung_precomp_preinv) ( TEMPLATE(T, struct) * res, const TEMPLATE(T, struct) * poly1, slong len1, const TEMPLATE(T, mat_t) A, const TEMPLATE(T, struct) * poly3, slong len3, const TEMPLATE(T, struct) * poly3inv, slong len3inv, const TEMPLATE(T, ctx_t) ctx) { TEMPLATE(T, mat_t) B, C; TEMPLATE(T, struct) * t, *h; slong i, n, m; n = len3 - 1; if (len3 == 1) return; if (len1 == 1) { TEMPLATE(T, set) (res, poly1, ctx); return; } if (len3 == 2) { _TEMPLATE3(T, poly_evaluate, T) (res, poly1, len1, TEMPLATE(T, mat_entry) (A, 1, 0), ctx); return; } m = n_sqrt(n) + 1; /* TODO check A */ TEMPLATE(T, mat_init) (B, m, m, ctx); TEMPLATE(T, mat_init) (C, m, n, ctx); h = _TEMPLATE(T, vec_init) (n, ctx); t = _TEMPLATE(T, vec_init) (n, ctx); /* Set rows of B to the segments of poly1 */ for (i = 0; i < len1 / m; i++) _TEMPLATE(T, vec_set) (B->rows[i], poly1 + i * m, m, ctx); _TEMPLATE(T, vec_set) (B->rows[i], poly1 + i * m, len1 % m, ctx); TEMPLATE(T, mat_mul) (C, B, A, ctx); /* Evaluate block composition using the Horner scheme */ _TEMPLATE(T, vec_set) (res, C->rows[m - 1], n, ctx); _TEMPLATE(T, poly_mulmod_preinv) (h, A->rows[m - 1], n, A->rows[1], n, poly3, len3, poly3inv, len3inv, ctx); for (i = m - 2; i >= 0; i--) { _TEMPLATE(T, poly_mulmod_preinv) (t, res, n, h, n, poly3, len3, poly3inv, len3inv, ctx); _TEMPLATE(T, poly_add) (res, t, n, C->rows[i], n, ctx); } _TEMPLATE(T, vec_clear) (h, n, ctx); _TEMPLATE(T, vec_clear) (t, n, ctx); TEMPLATE(T, mat_clear) (B, ctx); TEMPLATE(T, mat_clear) (C, ctx); } void TEMPLATE(T, poly_compose_mod_brent_kung_precomp_preinv) ( TEMPLATE(T, poly_t) res, const TEMPLATE(T, poly_t) poly1, const TEMPLATE(T, mat_t) A, const TEMPLATE(T, poly_t) poly3, const TEMPLATE(T, poly_t) poly3inv, const TEMPLATE(T, ctx_t) ctx) { slong len1 = poly1->length; slong len3 = poly3->length; slong len = len3 - 1; if (len3 == 0) { TEMPLATE_PRINTF ("Exception (%s_poly_compose_mod_brent_kung). Division by zero.\n", T); flint_abort(); } if (len1 >= len3) { TEMPLATE_PRINTF ("Exception (%s_poly_compose_brent_kung). The degree of the \n", T); flint_printf ("first polynomial must be smaller than that of the modulus.\n"); flint_abort(); } if (len1 == 0 || len3 == 1) { TEMPLATE(T, poly_zero) (res, ctx); return; } if (len1 == 1) { TEMPLATE(T, poly_set) (res, poly1, ctx); return; } if (res == poly3 || res == poly1 || res == poly3inv) { TEMPLATE(T, poly_t) tmp; TEMPLATE(T, poly_init) (tmp, ctx); TEMPLATE(T, poly_compose_mod_brent_kung_precomp_preinv) (tmp, poly1, A, poly3, poly3inv, ctx); TEMPLATE(T, poly_swap) (tmp, res, ctx); TEMPLATE(T, poly_clear) (tmp, ctx); return; } TEMPLATE(T, poly_fit_length) (res, len, ctx); _TEMPLATE(T, poly_compose_mod_brent_kung_precomp_preinv) (res->coeffs, poly1->coeffs, len1, A, poly3->coeffs, len3, poly3inv->coeffs, poly3inv->length, ctx); res->length = len; _TEMPLATE(T, poly_normalise) (res, ctx); } #endif
/* Copyright (C) 2011 Fredrik Johansson Copyright (C) 2013 Martin Lee 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/>. */
services.ml
open Capnp_direct.Core_types module Msg = Capnp_direct.String_content module RO_array = Capnp_rpc.RO_array class virtual test_service = object inherit service as super val mutable released = false val virtual name : string val id = Capnp_rpc.Debug.OID.next () method released = released method! release = assert (not released); released <- true; method! pp f = Fmt.pf f "%s(%a, %t)" name Capnp_rpc.Debug.OID.pp id super#pp_refcount end let echo_service () = object inherit test_service as super val name = "echo-service" method call results msg = super#check_refcount; resolve_ok results {msg with Msg.data = "got:" ^ msg.Msg.data} end (* A service which just queues incoming messages and lets the test driver handle them. *) let manual () = object (self) inherit test_service as super val queue = Queue.create () val name = "manual" method call results x = super#check_refcount; Queue.add (x, results) queue method pop_n msg = match Queue.pop queue with | exception Queue.Empty -> Capnp_rpc.Debug.failf "Empty queue (expecting %S)" msg | actual, answer -> Alcotest.(check string) ("Expecting " ^ msg) msg actual.Msg.data; let args = Request_payload.snapshot_caps actual in args, answer (* Expect a message with no caps *) method pop0 msg = let args, answer = self#pop_n msg in Alcotest.(check int) "Has no args" 0 @@ RO_array.length args; answer (* Expect a message with one cap *) method pop1 msg = let args, answer = self#pop_n msg in Alcotest.(check int) "Has one arg" 1 @@ RO_array.length args; RO_array.get_exn args 0, answer end (* Callers can swap their arguments for the slot's contents. *) let swap_service slot = object inherit test_service as super val name = "swap" method call results x = super#check_refcount; let old_msg = !slot in slot := x; resolve_ok results old_msg end let logger () = object inherit test_service as super val name = "logger" val log = Queue.create () method call results x = super#check_refcount; let caps = Request_payload.snapshot_caps x in assert (RO_array.length caps = 0); Queue.add x.Msg.data log; resolve_ok results (Msg.Response.v "logged") method pop = try Queue.pop log with Queue.Empty -> "(queue empty)" end
sail_lib.ml
module Big_int = Nat_big_num (* for ToFromInterp_lib_foo *) module type BitType = sig type t val b0 : t val b1 : t end type 'a return = { return : 'b . 'a -> 'b } type 'za zoption = | ZNone of unit | ZSome of 'za;; let zint_forwards i = string_of_int (Big_int.to_int i) let opt_trace = ref false let trace_depth = ref 0 let random = ref false let opt_cycle_limit = ref 0 let cycle_count = ref 0 let cycle_limit_reached () = cycle_count := !cycle_count + 1; !opt_cycle_limit != 0 && !cycle_count >= !opt_cycle_limit let sail_call (type t) (f : _ -> t) = let module M = struct exception Return of t end in let return = { return = (fun x -> raise (M.Return x)) } in try f return with M.Return x -> x let trace str = if !opt_trace then begin if !trace_depth < 0 then trace_depth := 0 else (); prerr_endline (String.make (!trace_depth * 2) ' ' ^ str) end else () let trace_write name str = trace ("Write: " ^ name ^ " " ^ str) let trace_read name str = trace ("Read: " ^ name ^ " " ^ str) let sail_trace_call (type t) (name : string) (in_string : string) (string_of_out : t -> string) (f : _ -> t) = let module M = struct exception Return of t end in let return = { return = (fun x -> raise (M.Return x)) } in trace ("Call: " ^ name ^ " " ^ in_string); incr trace_depth; let result = try f return with M.Return x -> x in decr trace_depth; trace ("Return: " ^ string_of_out result); result let trace_call str = trace str; incr trace_depth type bit = B0 | B1 let eq_anything (a, b) = a = b let eq_bit (a, b) = a = b let and_bit = function | B1, B1 -> B1 | _, _ -> B0 let or_bit = function | B0, B0 -> B0 | _, _ -> B1 let xor_bit = function | B1, B0 -> B1 | B0, B1 -> B1 | _, _ -> B0 let and_vec (xs, ys) = assert (List.length xs = List.length ys); List.map2 (fun x y -> and_bit (x, y)) xs ys let and_bool (b1, b2) = b1 && b2 let or_vec (xs, ys) = assert (List.length xs = List.length ys); List.map2 (fun x y -> or_bit (x, y)) xs ys let or_bool (b1, b2) = b1 || b2 let xor_vec (xs, ys) = assert (List.length xs = List.length ys); List.map2 (fun x y -> xor_bit (x, y)) xs ys let xor_bool (b1, b2) = (b1 || b2) && (b1 != b2) let undefined_bit () = if !random then (if Random.bool () then B0 else B1) else B0 let undefined_bool () = if !random then Random.bool () else false let rec undefined_vector (len, item) = if Big_int.equal len Big_int.zero then [] else item :: undefined_vector (Big_int.sub len (Big_int.of_int 1), item) let undefined_list _ = [] let undefined_bitvector len = if Big_int.equal len Big_int.zero then [] else B0 :: undefined_vector (Big_int.sub len (Big_int.of_int 1), B0) let undefined_string () = "" let undefined_unit () = () let undefined_int () = if !random then Big_int.of_int (Random.int 0xFFFF) else Big_int.zero let undefined_nat () = Big_int.zero let undefined_range (lo, _) = lo let internal_pick list = if !random then List.nth list (Random.int (List.length list)) else List.nth list 0 let eq_int (n, m) = Big_int.equal n m let eq_bool ((x : bool), (y : bool)) : bool = x = y let rec drop n xs = match n, xs with | 0, xs -> xs | _, [] -> [] | n, (_ :: xs) -> drop (n -1) xs let rec take n xs = match n, xs with | 0, _ -> [] | n, (x :: xs) -> x :: take (n - 1) xs | _, [] -> [] let count_leading_zeros xs = let rec aux bs acc = match bs with | (B0 :: bs') -> aux bs' (acc + 1) | _ -> acc in Big_int.of_int (aux xs 0) let subrange (list, n, m) = let n = Big_int.to_int n in let m = Big_int.to_int m in List.rev (take (n - (m - 1)) (drop m (List.rev list))) let slice (list, n, m) = let n = Big_int.to_int n in let m = Big_int.to_int m in List.rev (take m (drop n (List.rev list))) let eq_list (xs, ys) = List.for_all2 (fun x y -> x = y) xs ys let access (xs, n) = List.nth (List.rev xs) (Big_int.to_int n) let append (xs, ys) = xs @ ys let update (xs, n, x) = let n = (List.length xs - Big_int.to_int n) - 1 in take n xs @ [x] @ drop (n + 1) xs let update_subrange (xs, n, _, ys) = let rec aux xs o = function | [] -> xs | (y :: ys) -> aux (update (xs, o, y)) (Big_int.sub o (Big_int.of_int 1)) ys in aux xs n ys let vector_truncate (xs, n) = List.rev (take (Big_int.to_int n) (List.rev xs)) let vector_truncateLSB (xs, n) = take (Big_int.to_int n) xs let length xs = Big_int.of_int (List.length xs) let big_int_of_bit = function | B0 -> Big_int.zero | B1 -> (Big_int.of_int 1) let uint xs = let uint_bit x (n, pos) = Big_int.add n (Big_int.mul (Big_int.pow_int_positive 2 pos) (big_int_of_bit x)), pos + 1 in fst (List.fold_right uint_bit xs (Big_int.zero, 0)) let sint = function | [] -> Big_int.zero | [msb] -> Big_int.negate (big_int_of_bit msb) | msb :: xs -> let msb_pos = List.length xs in let complement = Big_int.negate (Big_int.mul (Big_int.pow_int_positive 2 msb_pos) (big_int_of_bit msb)) in Big_int.add complement (uint xs) let add_int (x, y) = Big_int.add x y let sub_int (x, y) = Big_int.sub x y let sub_nat (x, y) = let z = Big_int.sub x y in if Big_int.less z Big_int.zero then Big_int.zero else z let mult (x, y) = Big_int.mul x y (* This is euclidian division from lem *) let quotient (x, y) = Big_int.div x y (* This is the same as tdiv_int, kept for compatibility with old preludes *) let quot_round_zero (x, y) = Big_int.integerDiv_t x y (* The corresponding remainder function for above just respects the sign of x *) let rem_round_zero (x, y) = Big_int.integerRem_t x y (* Lem provides euclidian modulo by default *) let modulus (x, y) = Big_int.modulus x y let negate x = Big_int.negate x let tdiv_int (x, y) = Big_int.integerDiv_t x y let tmod_int (x, y) = Big_int.integerRem_t x y let add_bit_with_carry (x, y, carry) = match x, y, carry with | B0, B0, B0 -> B0, B0 | B0, B1, B0 -> B1, B0 | B1, B0, B0 -> B1, B0 | B1, B1, B0 -> B0, B1 | B0, B0, B1 -> B1, B0 | B0, B1, B1 -> B0, B1 | B1, B0, B1 -> B0, B1 | B1, B1, B1 -> B1, B1 let sub_bit_with_carry (x, y, carry) = match x, y, carry with | B0, B0, B0 -> B0, B0 | B0, B1, B0 -> B0, B1 | B1, B0, B0 -> B1, B0 | B1, B1, B0 -> B0, B0 | B0, B0, B1 -> B1, B0 | B0, B1, B1 -> B0, B0 | B1, B0, B1 -> B1, B1 | B1, B1, B1 -> B1, B0 let not_bit = function | B0 -> B1 | B1 -> B0 let not_vec xs = List.map not_bit xs let add_vec_carry (xs, ys) = assert (List.length xs = List.length ys); let (carry, result) = List.fold_right2 (fun x y (c, result) -> let (z, c) = add_bit_with_carry (x, y, c) in (c, z :: result)) xs ys (B0, []) in carry, result let add_vec (xs, ys) = snd (add_vec_carry (xs, ys)) let rec replicate_bits (bits, n) = if Big_int.less_equal n Big_int.zero then [] else bits @ replicate_bits (bits, Big_int.sub n (Big_int.of_int 1)) let identity x = x (* Returns list of n bits of integer m starting from offset o >= 0 (bits numbered from least significant). Uses twos-complement representation for m<0 and pads most significant bits in sign-extended way. Most significant bit is head of returned list. *) let rec get_slice_int' (n, m, o) = if n <= 0 then [] else let bit = if (Big_int.extract_num m (n + o - 1) 1) == Big_int.zero then B0 else B1 in bit :: get_slice_int' (n-1, m, o) (* as above but taking Big_int for all arguments *) let get_slice_int (n, m, o) = get_slice_int' (Big_int.to_int n, m, Big_int.to_int o) (* as above but omitting offset, len is ocaml int *) let to_bits' (len, n) = get_slice_int' (len, n, 0) (* as above but taking big_int for length *) let to_bits (len, n) = get_slice_int' (Big_int.to_int len, n, 0) (* unsigned multiplication of two n bit lists producing a list of 2n bits *) let mult_vec (x, y) = let xi = uint(x) in let yi = uint(y) in let len = List.length x in let prod = Big_int.mul xi yi in to_bits' (2*len, prod) (* signed multiplication of two n bit lists producing a list of 2n bits. *) let mults_vec (x, y) = let xi = sint(x) in let yi = sint(y) in let len = List.length x in let prod = Big_int.mul xi yi in to_bits' (2*len, prod) let add_vec_int (v, n) = let n_bits = to_bits'(List.length v, n) in add_vec(v, n_bits) let sub_vec (xs, ys) = add_vec (xs, add_vec_int (not_vec ys, (Big_int.of_int 1))) let sub_vec_int (v, n) = let n_bits = to_bits'(List.length v, n) in sub_vec(v, n_bits) let bin_char = function | '0' -> B0 | '1' -> B1 | _ -> failwith "Invalid binary character" let hex_char = function | '0' -> [B0; B0; B0; B0] | '1' -> [B0; B0; B0; B1] | '2' -> [B0; B0; B1; B0] | '3' -> [B0; B0; B1; B1] | '4' -> [B0; B1; B0; B0] | '5' -> [B0; B1; B0; B1] | '6' -> [B0; B1; B1; B0] | '7' -> [B0; B1; B1; B1] | '8' -> [B1; B0; B0; B0] | '9' -> [B1; B0; B0; B1] | 'A' | 'a' -> [B1; B0; B1; B0] | 'B' | 'b' -> [B1; B0; B1; B1] | 'C' | 'c' -> [B1; B1; B0; B0] | 'D' | 'd' -> [B1; B1; B0; B1] | 'E' | 'e' -> [B1; B1; B1; B0] | 'F' | 'f' -> [B1; B1; B1; B1] | _ -> failwith "Invalid hex character" let list_of_string s = let rec aux i acc = if i < 0 then acc else aux (i-1) (s.[i] :: acc) in aux (String.length s - 1) [] let bits_of_string str = List.concat (List.map hex_char (list_of_string str)) let concat_str (str1, str2) = str1 ^ str2 let rec break n = function | [] -> [] | (_ :: _ as xs) -> [take n xs] @ break n (drop n xs) let string_of_bit = function | B0 -> "0" | B1 -> "1" let char_of_bit = function | B0 -> '0' | B1 -> '1' let int_of_bit = function | B0 -> 0 | B1 -> 1 let bool_of_bit = function | B0 -> false | B1 -> true let bit_of_bool = function | false -> B0 | true -> B1 let bigint_of_bit b = Big_int.of_int (int_of_bit b) let string_of_hex = function | [B0; B0; B0; B0] -> "0" | [B0; B0; B0; B1] -> "1" | [B0; B0; B1; B0] -> "2" | [B0; B0; B1; B1] -> "3" | [B0; B1; B0; B0] -> "4" | [B0; B1; B0; B1] -> "5" | [B0; B1; B1; B0] -> "6" | [B0; B1; B1; B1] -> "7" | [B1; B0; B0; B0] -> "8" | [B1; B0; B0; B1] -> "9" | [B1; B0; B1; B0] -> "A" | [B1; B0; B1; B1] -> "B" | [B1; B1; B0; B0] -> "C" | [B1; B1; B0; B1] -> "D" | [B1; B1; B1; B0] -> "E" | [B1; B1; B1; B1] -> "F" | _ -> failwith "Cannot convert binary sequence to hex" let string_of_bits bits = if List.length bits mod 4 == 0 then "0x" ^ String.concat "" (List.map string_of_hex (break 4 bits)) else "0b" ^ String.concat "" (List.map string_of_bit bits) let decimal_string_of_bits bits = let place_values = List.mapi (fun i b -> (Big_int.mul (bigint_of_bit b) (Big_int.pow_int_positive 2 i))) (List.rev bits) in let sum = List.fold_left Big_int.add Big_int.zero place_values in Big_int.to_string sum let hex_slice (str, n, m) = let bits = List.concat (List.map hex_char (list_of_string (String.sub str 2 (String.length str - 2)))) in let padding = replicate_bits([B0], n) in let bits = padding @ bits in let slice = List.rev (take (Big_int.to_int n) (drop (Big_int.to_int m) (List.rev bits))) in slice let putchar n = print_char (char_of_int (Big_int.to_int n)); flush stdout let rec bits_of_int bit n = if bit <> 0 then begin if n / bit > 0 then B1 :: bits_of_int (bit / 2) (n - bit) else B0 :: bits_of_int (bit / 2) n end else [] let rec bits_of_big_int pow n = if pow < 1 then [] else begin let bit = (Big_int.pow_int_positive 2 (pow - 1)) in if Big_int.greater (Big_int.div n bit) Big_int.zero then B1 :: bits_of_big_int (pow - 1) (Big_int.sub n bit) else B0 :: bits_of_big_int (pow - 1) n end let byte_of_int n = bits_of_int 128 n module Mem = struct include Map.Make(struct type t = Big_int.num let compare = Big_int.compare end) end let mem_pages = (ref Mem.empty : (Bytes.t Mem.t) ref);; let page_shift_bits = 20 (* 1M page *) let page_size_bytes = 1 lsl page_shift_bits;; let page_no_of_addr a = Big_int.shift_right a page_shift_bits let bottom_addr_of_page p = Big_int.shift_left p page_shift_bits let top_addr_of_page p = Big_int.shift_left (Big_int.succ p) page_shift_bits let get_mem_page p = try Mem.find p !mem_pages with Not_found -> let new_page = Bytes.make page_size_bytes '\000' in mem_pages := Mem.add p new_page !mem_pages; new_page let rec add_mem_bytes addr buf off len = let page_no = page_no_of_addr addr in let page_bot = bottom_addr_of_page page_no in let page_top = top_addr_of_page page_no in let page_off = Big_int.to_int (Big_int.sub addr page_bot) in let page = get_mem_page page_no in let bytes_left_in_page = Big_int.sub page_top addr in let to_copy = min (Big_int.to_int bytes_left_in_page) len in Bytes.blit buf off page page_off to_copy; if (to_copy < len) then add_mem_bytes page_top buf (off + to_copy) (len - to_copy) let rec read_mem_bytes addr len = let page_no = page_no_of_addr addr in let page_bot = bottom_addr_of_page page_no in let page_top = top_addr_of_page page_no in let page_off = Big_int.to_int (Big_int.sub addr page_bot) in let page = get_mem_page page_no in let bytes_left_in_page = Big_int.sub page_top addr in let to_get = min (Big_int.to_int bytes_left_in_page) len in let bytes = Bytes.sub page page_off to_get in if to_get >= len then bytes else Bytes.cat bytes (read_mem_bytes page_top (len - to_get)) let write_ram' (data_size, addr, data) = let len = Big_int.to_int data_size in let bytes = Bytes.create len in begin List.iteri (fun i byte -> Bytes.set bytes (len - i - 1) (char_of_int (Big_int.to_int (uint byte)))) (break 8 data); add_mem_bytes addr bytes 0 len end let write_ram (_addr_size, data_size, _hex_ram, addr, data) = write_ram' (data_size, uint addr, data); true let wram addr byte = let bytes = Bytes.make 1 (char_of_int byte) in add_mem_bytes addr bytes 0 1 let read_ram (_addr_size, data_size, _hex_ram, addr) = let addr = uint addr in let bytes = read_mem_bytes addr (Big_int.to_int data_size) in let vector = ref [] in Bytes.iter (fun byte -> vector := (byte_of_int (int_of_char byte)) @ !vector) bytes; !vector let fast_read_ram (data_size, addr) = let addr = uint addr in let bytes = read_mem_bytes addr (Big_int.to_int data_size) in let vector = ref [] in Bytes.iter (fun byte -> vector := (byte_of_int (int_of_char byte)) @ !vector) bytes; !vector let tag_ram = (ref Mem.empty : (bool Mem.t) ref);; let write_tag_bool (addr, tag) = let addri = uint addr in tag_ram := Mem.add addri tag !tag_ram let read_tag_bool addr = let addri = uint addr in try Mem.find addri !tag_ram with Not_found -> false let rec reverse_endianness bits = if List.length bits <= 8 then bits else reverse_endianness (drop 8 bits) @ (take 8 bits) (* FIXME: Casts can't be externed *) let zcast_unit_vec x = [x] let shl_int (n, m) = Big_int.shift_left n (Big_int.to_int m) let shr_int (n, m) = Big_int.shift_right n (Big_int.to_int m) let lor_int (n, m) = Big_int.bitwise_or n m let land_int (n, m) = Big_int.bitwise_and n m let lxor_int (n, m) = Big_int.bitwise_xor n m let debug (str1, n, str2, v) = prerr_endline (str1 ^ Big_int.to_string n ^ str2 ^ string_of_bits v) let eq_string (str1, str2) = String.compare str1 str2 == 0 let string_startswith (str1, str2) = String.length str1 >= String.length str2 && String.compare (String.sub str1 0 (String.length str2)) str2 == 0 let string_drop (str, n) = if (Big_int.less_equal (Big_int.of_int (String.length str)) n) then "" else let n = Big_int.to_int n in String.sub str n (String.length str - n) let string_take (str, n) = let n = Big_int.to_int n in if String.length str <= n then str else String.sub str 0 n let string_length str = Big_int.of_int (String.length str) let string_append (s1, s2) = s1 ^ s2 let int_of_string_opt s = try Some (Big_int.of_string s) with | Invalid_argument _ -> None (* highly inefficient recursive implementation *) let rec maybe_int_of_prefix = function | "" -> ZNone () | str -> let len = String.length str in match int_of_string_opt str with | Some n -> ZSome (n, Big_int.of_int len) | None -> maybe_int_of_prefix (String.sub str 0 (len - 1)) let maybe_int_of_string str = match int_of_string_opt str with | None -> ZNone () | Some n -> ZSome n let lt_int (x, y) = Big_int.less x y let set_slice (out_len, _slice_len, out, n, slice) = let out = update_subrange(out, Big_int.add n (Big_int.of_int (List.length slice - 1)), n, slice) in assert (List.length out = Big_int.to_int out_len); out (* Set slice_len bits in the integer m, starting from index n *) let set_slice_int (slice_len, m, n, slice) = assert (Big_int.to_int slice_len == List.length slice); let shifted_slice = Big_int.shift_left (uint slice) (Big_int.to_int n) in let mask = uint (replicate_bits ([B1], slice_len) @ replicate_bits ([B0], n)) in Big_int.bitwise_or (Big_int.bitwise_xor (Big_int.bitwise_or mask m) mask) shifted_slice let eq_real (x, y) = Rational.equal x y let lt_real (x, y) = Rational.lt x y let gt_real (x, y) = Rational.gt x y let lteq_real (x, y) = Rational.leq x y let gteq_real (x, y) = Rational.geq x y let to_real x = Rational.of_int (Big_int.to_int x) (* FIXME *) let negate_real x = Rational.neg x let neg_real x = Rational.neg x let string_of_real x = if Big_int.equal (Rational.den x) (Big_int.of_int 1) then Big_int.to_string (Rational.num x) else Big_int.to_string (Rational.num x) ^ "/" ^ Big_int.to_string (Rational.den x) let print_real (str, r) = print_endline (str ^ string_of_real r) let prerr_real (str, r) = prerr_endline (str ^ string_of_real r) let round_down x = Rational.floor x let round_up x = Rational.ceiling x let quotient_real (x, y) = Rational.div x y let div_real (x, y) = Rational.div x y let mult_real (x, y) = Rational.mul x y let real_power (_, _) = failwith "real_power" let int_power (x, y) = Big_int.pow_int x (Big_int.to_int y) let add_real (x, y) = Rational.add x y let sub_real (x, y) = Rational.sub x y let abs_real x = Rational.abs x let sqrt_real x = let precision = 30 in let s = Big_int.sqrt (Rational.num x) in if Big_int.equal (Rational.den x) (Big_int.of_int 1) && Big_int.equal (Big_int.mul s s) (Rational.num x) then to_real s else let p = ref (to_real (Big_int.sqrt (Big_int.div (Rational.num x) (Rational.den x)))) in let n = ref (Rational.of_int 0) in let convergence = ref (Rational.div (Rational.of_int 1) (Rational.of_big_int (Big_int.pow_int_positive 10 precision))) in let quit_loop = ref false in while not !quit_loop do n := Rational.div (Rational.add !p (Rational.div x !p)) (Rational.of_int 2); if Rational.lt (Rational.abs (Rational.sub !p !n)) !convergence then quit_loop := true else p := !n done; !n let random_real () = Rational.div (Rational.of_int (Random.bits ())) (Rational.of_int (Random.bits())) let lt (x, y) = Big_int.less x y let gt (x, y) = Big_int.greater x y let lteq (x, y) = Big_int.less_equal x y let gteq (x, y) = Big_int.greater_equal x y let pow2 x = Big_int.pow_int (Big_int.of_int 2) (Big_int.to_int x) let max_int (x, y) = Big_int.max x y let min_int (x, y) = Big_int.min x y let abs_int x = Big_int.abs x let string_of_int x = Big_int.to_string x let undefined_real () = Rational.of_int 0 let rec pow x = function | 0 -> 1 | n -> x * pow x (n - 1) let real_of_string str = match Util.split_on_char '.' str with | [whole; frac] -> let whole = Rational.of_int (int_of_string whole) in let frac = Rational.div (Rational.of_int (int_of_string frac)) (Rational.of_int (pow 10 (String.length frac))) in Rational.add whole frac | [_] -> Rational.of_int (int_of_string str) | _ -> failwith "invalid real literal" let print str = Stdlib.print_string str let prerr str = Stdlib.prerr_string str let print_int (str, x) = print_endline (str ^ Big_int.to_string x) let prerr_int (str, x) = prerr_endline (str ^ Big_int.to_string x) let print_bits (str, xs) = print_endline (str ^ string_of_bits xs) let prerr_bits (str, xs) = prerr_endline (str ^ string_of_bits xs) let print_string(str, msg) = print_endline (str ^ msg) let prerr_string(str, msg) = prerr_endline (str ^ msg) let reg_deref r = !r let string_of_zbit = function | B0 -> "0" | B1 -> "1" let string_of_znat n = Big_int.to_string n let string_of_zint n = Big_int.to_string n let string_of_zimplicit n = Big_int.to_string n let string_of_zunit () = "()" let string_of_zbool = function | true -> "true" | false -> "false" let string_of_zreal _ = "REAL" let string_of_zstring str = "\"" ^ String.escaped str ^ "\"" let rec string_of_list sep string_of = function | [] -> "" | [x] -> string_of x | x::ls -> (string_of x) ^ sep ^ (string_of_list sep string_of ls) let skip () = () let memea (_, _) = () let zero_extend (vec, n) = let m = Big_int.to_int n in if m <= List.length vec then take m vec else replicate_bits ([B0], Big_int.of_int (m - List.length vec)) @ vec let sign_extend (vec, n) = let m = Big_int.to_int n in match vec with | B0 :: _ as vec -> replicate_bits ([B0], Big_int.of_int (m - List.length vec)) @ vec | [] -> replicate_bits ([B0], Big_int.of_int (m - List.length vec)) @ vec | B1 :: _ as vec -> replicate_bits ([B1], Big_int.of_int (m - List.length vec)) @ vec let zeros n = replicate_bits ([B0], n) let ones n = replicate_bits ([B1], n) let shift_bits_right_arith (x, y) = let ybi = uint(y) in let msbs = replicate_bits (take 1 x, ybi) in let rbits = msbs @ x in take (List.length x) rbits let shiftr (x, y) = let zeros = zeros y in let rbits = zeros @ x in take (List.length x) rbits let arith_shiftr (x, y) = let msbs = replicate_bits (take 1 x, y) in let rbits = msbs @ x in take (List.length x) rbits let shift_bits_right (x, y) = shiftr (x, uint(y)) let shiftl (x, y) = let yi = Big_int.to_int y in let zeros = zeros y in let rbits = x @ zeros in drop yi rbits let shift_bits_left (x, y) = shiftl (x, uint(y)) let speculate_conditional_success () = true (* Return nanoseconds since epoch. Truncates to ocaml int but will be OK for next 100 years or so... *) let get_time_ns () = Big_int.of_int (int_of_float (1e9 *. Unix.gettimeofday ())) (* Python: f = """let hex_bits_{0}_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 {0}) then ZSome ((bits_of_big_int {0} n, len)) else ZNone () """ for i in list(range(1, 34)) + [48, 64]: print(f.format(i)) *) let hex_bits_1_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 1) then ZSome ((bits_of_big_int 1 n, len)) else ZNone () let hex_bits_2_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 2) then ZSome ((bits_of_big_int 2 n, len)) else ZNone () let hex_bits_3_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 3) then ZSome ((bits_of_big_int 3 n, len)) else ZNone () let hex_bits_4_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 4) then ZSome ((bits_of_big_int 4 n, len)) else ZNone () let hex_bits_5_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 5) then ZSome ((bits_of_big_int 5 n, len)) else ZNone () let hex_bits_6_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 6) then ZSome ((bits_of_big_int 6 n, len)) else ZNone () let hex_bits_7_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 7) then ZSome ((bits_of_big_int 7 n, len)) else ZNone () let hex_bits_8_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 8) then ZSome ((bits_of_big_int 8 n, len)) else ZNone () let hex_bits_9_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 9) then ZSome ((bits_of_big_int 9 n, len)) else ZNone () let hex_bits_10_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 10) then ZSome ((bits_of_big_int 10 n, len)) else ZNone () let hex_bits_11_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 11) then ZSome ((bits_of_big_int 11 n, len)) else ZNone () let hex_bits_12_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 12) then ZSome ((bits_of_big_int 12 n, len)) else ZNone () let hex_bits_13_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 13) then ZSome ((bits_of_big_int 13 n, len)) else ZNone () let hex_bits_14_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 14) then ZSome ((bits_of_big_int 14 n, len)) else ZNone () let hex_bits_15_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 15) then ZSome ((bits_of_big_int 15 n, len)) else ZNone () let hex_bits_16_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 16) then ZSome ((bits_of_big_int 16 n, len)) else ZNone () let hex_bits_17_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 17) then ZSome ((bits_of_big_int 17 n, len)) else ZNone () let hex_bits_18_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 18) then ZSome ((bits_of_big_int 18 n, len)) else ZNone () let hex_bits_19_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 19) then ZSome ((bits_of_big_int 19 n, len)) else ZNone () let hex_bits_20_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 20) then ZSome ((bits_of_big_int 20 n, len)) else ZNone () let hex_bits_21_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 21) then ZSome ((bits_of_big_int 21 n, len)) else ZNone () let hex_bits_22_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 22) then ZSome ((bits_of_big_int 22 n, len)) else ZNone () let hex_bits_23_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 23) then ZSome ((bits_of_big_int 23 n, len)) else ZNone () let hex_bits_24_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 24) then ZSome ((bits_of_big_int 24 n, len)) else ZNone () let hex_bits_25_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 25) then ZSome ((bits_of_big_int 25 n, len)) else ZNone () let hex_bits_26_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 26) then ZSome ((bits_of_big_int 26 n, len)) else ZNone () let hex_bits_27_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 27) then ZSome ((bits_of_big_int 27 n, len)) else ZNone () let hex_bits_28_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 28) then ZSome ((bits_of_big_int 28 n, len)) else ZNone () let hex_bits_29_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 29) then ZSome ((bits_of_big_int 29 n, len)) else ZNone () let hex_bits_30_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 30) then ZSome ((bits_of_big_int 30 n, len)) else ZNone () let hex_bits_31_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 31) then ZSome ((bits_of_big_int 31 n, len)) else ZNone () let hex_bits_32_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 32) then ZSome ((bits_of_big_int 32 n, len)) else ZNone () let hex_bits_33_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 33) then ZSome ((bits_of_big_int 33 n, len)) else ZNone () let hex_bits_48_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 48) then ZSome ((bits_of_big_int 48 n, len)) else ZNone () let hex_bits_64_matches_prefix s = match maybe_int_of_prefix s with | ZNone () -> ZNone () | ZSome (n, len) -> if Big_int.less_equal Big_int.zero n && Big_int.less n (Big_int.pow_int_positive 2 64) then ZSome ((bits_of_big_int 64 n, len)) else ZNone () let string_of_bool = function | true -> "true" | false -> "false" let dec_str x = Big_int.to_string x let hex_str x = Big_int.to_string x let trace_memory_write (_, _, _) = () let trace_memory_read (_, _, _) = () let sleep_request () = () let wakeup_request () = () let reset_registers () = () let load_raw (paddr, file) = let i = ref 0 in let paddr = uint paddr in let in_chan = open_in file in try while true do let byte = input_char in_chan |> Char.code in wram (Big_int.add paddr (Big_int.of_int !i)) byte; incr i done with | End_of_file -> () (* XXX this could count cycles and exit after given limit *) let cycle_count () = () (* TODO range, atom, register(?), int, nat, bool, real(!), list, string, itself(?) *) let rand_zvector (g : 'generators) (size : int) (_order : bool) (elem_gen : 'generators -> 'a) : 'a list = Util.list_init size (fun _ -> elem_gen g) let rand_zbit (_ : 'generators) : bit = bit_of_bool (Random.bool()) let rand_zbitvector (g : 'generators) (size : int) (_order : bool) : bit list = Util.list_init size (fun _ -> rand_zbit g) let rand_zbool (_ : 'generators) : bool = Random.bool() let rand_zunit (_ : 'generators) : unit = () let rand_choice l = let n = List.length l in List.nth l (Random.int n)
(****************************************************************************) (* Sail *) (* *) (* Sail and the Sail architecture models here, comprising all files and *) (* directories except the ASL-derived Sail code in the aarch64 directory, *) (* are subject to the BSD two-clause licence below. *) (* *) (* The ASL derived parts of the ARMv8.3 specification in *) (* aarch64/no_vector and aarch64/full are copyright ARM Ltd. *) (* *) (* Copyright (c) 2013-2021 *) (* Kathyrn Gray *) (* Shaked Flur *) (* Stephen Kell *) (* Gabriel Kerneis *) (* Robert Norton-Wright *) (* Christopher Pulte *) (* Peter Sewell *) (* Alasdair Armstrong *) (* Brian Campbell *) (* Thomas Bauereiss *) (* Anthony Fox *) (* Jon French *) (* Dominic Mulligan *) (* Stephen Kell *) (* Mark Wassell *) (* Alastair Reid (Arm Ltd) *) (* *) (* All rights reserved. *) (* *) (* This work was partially supported by EPSRC grant EP/K008528/1 <a *) (* href="http://www.cl.cam.ac.uk/users/pes20/rems">REMS: Rigorous *) (* Engineering for Mainstream Systems</a>, an ARM iCASE award, EPSRC IAA *) (* KTF funding, and donations from Arm. This project has received *) (* funding from the European Research Council (ERC) under the European *) (* Union’s Horizon 2020 research and innovation programme (grant *) (* agreement No 789108, ELVER). *) (* *) (* This software was developed by SRI International and the University of *) (* Cambridge Computer Laboratory (Department of Computer Science and *) (* Technology) under DARPA/AFRL contracts FA8650-18-C-7809 ("CIFV") *) (* and FA8750-10-C-0237 ("CTSRD"). *) (* *) (* Redistribution and use in source and binary forms, with or without *) (* modification, are permitted provided that the following conditions *) (* are met: *) (* 1. Redistributions of source code must retain the above copyright *) (* notice, this list of conditions and the following disclaimer. *) (* 2. Redistributions in binary form must reproduce the above copyright *) (* notice, this list of conditions and the following disclaimer in *) (* the documentation and/or other materials provided with the *) (* distribution. *) (* *) (* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' *) (* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *) (* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *) (* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR *) (* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *) (* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *) (* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF *) (* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *) (* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *) (* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT *) (* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *) (* SUCH DAMAGE. *) (****************************************************************************)
File_type.mli
type file_type = | PL of pl_type | Obj of string | Binary of string | Text of string | Doc of string | Config of config_type | Media of media_type | Archive of string | Other of string and pl_type = | OCaml of string | FSharp of string | MLOther of string | Haskell of string | Lisp of lisp_type | Skip | Scala | Prolog of string | Script of string | C of string | Cplusplus of string | Java | Kotlin | Csharp | ObjectiveC of string | Swift | Perl | Python | Ruby | Lua | R | Erlang | Go | Rust | Beta | Pascal | Web of webpl_type | Haxe | Opa | Flash | Bytecode of string | Asm | Thrift | MiscPL of string and config_type = Makefile | Json | Jsonnet | Yaml | HCL and lisp_type = CommonLisp | Elisp | Scheme | Clojure and webpl_type = | Php of string | Hack | Js | TypeScript (* JSX/TSX are converted in Js/Typescript *) | Coffee | Vue | Css | Html | Xml | Sql and media_type = Sound of string | Picture of string | Video of string val file_type_of_file : Common.filename -> file_type val is_textual_file : Common.filename -> bool val is_syncweb_obj_file : Common.filename -> bool val is_json_filename : Common.filename -> bool val files_of_dirs_or_files : (file_type -> bool) -> Common.filename list -> Common.filename list (* specialisations *) val webpl_type_of_file : Common.filename -> webpl_type option (* val string_of_pl: pl_kind -> string *)
backend.ml
open! Import open Store_properties open struct module type Node_portable = Node.Portable.S module type Commit_portable = Commit.Portable.S end (** [S] is what a backend must define in order to be made an irmin store. *) module type S = sig module Schema : Schema.S (** A store schema, meant to be provided by the user. *) module Hash : Hash.S with type t = Schema.Hash.t (** Hashing implementation. *) (** A contents store. *) module Contents : Contents.Store with type hash = Hash.t and type value = Schema.Contents.t (** A node store. *) module Node : Node.Store with type hash = Hash.t and type Val.contents_key = Contents.key and module Path = Schema.Path and module Metadata = Schema.Metadata (** A node abstraction that is portable from different repos. Similar to [Node.Val]. *) module Node_portable : Node_portable with type node := Node.value and type hash := Hash.t and type metadata := Schema.Metadata.t and type step := Schema.Path.step (** A commit store. *) module Commit : Commit.Store with type hash = Hash.t and type Val.node_key = Node.key and module Info = Schema.Info (** A commit abstraction that is portable from different repos. Similar to [Commit.Val]. *) module Commit_portable : Commit_portable with type commit := Commit.value and type hash := Hash.t and module Info = Schema.Info (** A branch store. *) module Branch : Branch.Store with type key = Schema.Branch.t and type value = Commit.key (** A slice abstraction. *) module Slice : Slice.S with type contents = Contents.hash * Contents.value and type node = Node.hash * Node.value and type commit = Commit.hash * Commit.value (** A repo abstraction. *) module Repo : sig type t (** Repo opening and closing functions *) include Of_config with type _ t := t (** @inline *) include Closeable with type _ t := t (** @inline *) (** Getters from repo to backend store in ro mode *) val contents_t : t -> read Contents.t val node_t : t -> read Node.t val commit_t : t -> read Commit.t val config : t -> Conf.t val batch : t -> (read_write Contents.t -> read_write Node.t -> read_write Commit.t -> 'a Lwt.t) -> 'a Lwt.t (** A getter from repo to backend stores in rw mode. *) val branch_t : t -> Branch.t (** A branch store getter from repo *) end (** URI-based low-level remote synchronisation. *) module Remote : sig include Remote.S with type commit = Commit.key and type branch = Branch.key val v : Repo.t -> t Lwt.t end end
(* * Copyright (c) 2021 Craig Ferguson <craig@tarides.com> * * 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_protobuf.c
#include <pg_query.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "parse_tests.c" int main() { size_t i; bool ret_code = 0; for (i = 0; i < testsLength; i += 2) { PgQueryProtobufParseResult result = pg_query_parse_protobuf(tests[i]); if (result.error) { ret_code = -1; printf("%s\n", result.error->message); } else { printf("."); } //} else if (strcmp(result.parse_tree, tests[i + 1]) == 0) { // printf("."); //} else { // ret_code = -1; // printf("INVALID result for \"%s\"\nexpected: %s\nactual: %s\n", tests[i], tests[i + 1], result.parse_tree); //} pg_query_free_protobuf_parse_result(result); } printf("\n"); pg_query_exit(); return ret_code; }
bench_async_ecaml.ml
open! Core open! Async let () = Command_unix.run (Command.async ~summary:"Run ecaml_async benchmarks with the normal async_unix scheduler" (let%map_open.Command () = return () in fun () -> let%bind time_per_ping = Ecaml_bench.Bench_async_ecaml.benchmark_small_pings () in let%map bytes_per_second = Ecaml_bench.Bench_async_ecaml.benchmark_throughput () in print_s [%message (time_per_ping : Sexp.t) (bytes_per_second : Sexp.t)])) ;;
trace_stat_summary_utils.mli
(** Utilities to summarise data. This file is NOT meant to be used from Tezos, as opposed to some other "trace_*" files. *) type histo = (float * int) list [@@deriving repr] type curve = float list [@@deriving repr] val snap_to_integer : significant_digits:int -> float -> float (** [snap_to_integer ~significant_digits v] is [Float.round v] if [v] is close to [Float.round v], otherwise the result is [v]. [significant_digits] defines how close things are. Examples: When [significant_digits] is [4] and [v] is [42.00001], [snap_to_integer v] is [42.]. When [significant_digits] is [4] and [v] is [42.001], [snap_to_integer v] is [v]. *) val create_pp_real : ?significant_digits:int -> float list -> Format.formatter -> float -> unit (** [create_pp_real examples] is [pp_real], a float pretty-printer that adapts to the [examples] shown to it. It is highly recommended, but not mandatory, for all the numbers passed to [pp_real] to be included in [examples]. When all the [examples] are integers, the display may be different. The examples that aren't integer, but that are very close to be a integers are counted as integers. [significant_digits] is used internally to snap the examples to integers. *) val create_pp_seconds : float list -> Format.formatter -> float -> unit (** [create_pp_seconds examples] is [pp_seconds], a time span pretty-printer that adapts to the [examples] shown to it. It is highly recommended, but not mandatory, for all the numbers passed to [pp_seconds] to be included in [examples]. *) val pp_percent : Format.formatter -> float -> unit (** Pretty prints a percent in a way that always takes 4 chars. Examples: [0.] is [" 0%"], [0.00001] is ["0.0%"], [0.003] is ["0.3%"], [0.15] is [" 15%"], [9.0] is [900%], [700.] is [700x], [410_000.0] is ["4e6x"] and [1e100] is ["++++"]. Negative inputs are undefined. *) val approx_transaction_count_of_block_count : ?first_block_idx:int -> int -> int val approx_operation_count_of_block_count : ?first_block_idx:int -> int -> int (** Functional Exponential Moving Average (EMA). *) module Exponential_moving_average : sig type t val create : ?relevance_threshold:float -> float -> t (** [create ?relevance_threshold m] is [ema], a functional exponential moving average. [1. -. m] is the fraction of what's forgotten of the past during each [update]. The value represented by [ema] can be retrieved using [peek_exn ema] or [peek_or_nan ema]. When [m = 0.], all the past is forgotten on each update and each forget. [peek_exn ema] is either the latest sample fed to an update function or [nan]. When [m] approaches [1.], [peek_exn ema] tends to be the mean of all the samples seen in the past. See https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average {3 Relevance} The value represented by [ema] is built from the {e history} of samples shown through [update(_batch)]. When that history is empty, the value can't be calculated, and when the history is too small, or too distant because of calls to [forget(_batch)], the represented value is very noisy. [relevance_threshold] is a threshold on [ema]'s inner [void_fraction], below which the represented value should be considered relevant, i.e. [peek_or_nan ema] is not NaN. Before any call to [update(_batch)], the represented value is always irrelevant. After a sufficient number of updates (e.g. 1 update in general), the represented value gets relevant. After a sufficient number of forgets, the represented value gets irrelevant again. A good value for [relevance_threshold] is between [momentum] and [1.], so that right after a call to [update], the value is always relevant. {3 Commutativity} Adding together two curves independently built with an EMA, is equivalent to adding the samples beforehand, and using a single EMA. In a more more formal way: Let [a], [b] be vectors of real values of similar length. Let [ema(x)] be the [Exponential_moving_average.map momentum] function ([float list -> float list]); Let [*], [+] and [/] be the element-wise vector multiplication, addition and division. Then [ema(a + b)] is [ema(a) + ema(b)]. The same is not true for multiplication and division, [ema(a * b)] is not [ema(a) * ema(b)], but [exp(ema(log(a * b)))] is [exp(ema(log(a))) * exp(ema(log(b)))] when all values in [a] and [b] are strictly greater than 0. *) val from_half_life : ?relevance_threshold:float -> float -> t (** [from_half_life hl] is [ema], a functional exponential moving average. After [hl] calls to [update], half of the past is forgotten. *) val from_half_life_ratio : ?relevance_threshold:float -> float -> float -> t (** [from_half_life_ratio hl_ratio step_count] is [ema], a functional exponential moving average. After [hl_ratio * step_count] calls to [update], half of the past is forgotten. *) val map : ?relevance_threshold:float -> float -> float list -> float list (** [map momentum vec0] is [vec1], a list of float with the same length as [vec0], where the values have been locally averaged. The first element of [vec1] is also the first element of [vec0]. *) val update : t -> float -> t (** Feed a new sample to the EMA. If the sample is not finite (i.e., NaN or infinite), the represented won't be either. *) val update_batch : t -> float -> float -> t (** [update_batch ema p s] is equivalent to calling [update] [s] times. Modulo floating point errors. *) val forget : t -> t (** [forget ema] forgets some of the past without the need for samples. The represented value doesn't change. *) val forget_batch : t -> float -> t (** [forget_batch ema s] is equivalent to calling [forget] [s] times. Modulo floating point errors.*) val is_relevant : t -> bool (** Indicates whether or not [peek_exn] can be called without raising an exception. *) val peek_exn : t -> float (** Read the EMA value. *) val peek_or_nan : t -> float (** Read the EMA value. *) val momentum : t -> float val hidden_state : t -> float val void_fraction : t -> float end (** This [Resample] module offers 3 ways to resample a 1d vector: - At the lowest level, using [should_sample]. - Using [create_acc] / [accumulate] / [finalise]. - At the highest level, using [resample_vector]. Both downsampling and upsampling are possible: {v > upsampling vec0: | | | | (len0:4) vec1: | | | | | | (len1:6) > identity vec0: | | | | (len0:4) vec1: | | | | (len1:4) > downsampling vec0: | | | | | | (len0:6) vec1: | | | | (len1:4) v} The first and last point of the input and output sequences are always equal. *) module Resample : sig val should_sample : i0:int -> len0:int -> i1:int -> len1:int -> [ `After | `Before | `Inside of float | `Out_of_bounds ] (** When resampling a 1d vector from [len0] to [len1], this function locates a destination point with index [i1] relative to the range [i0 - 1] excluded and [i0] included. When both [i0] and [i1] equal [0], the result is [`Inside 1.]. [len0] and [len1] should be greater or equal to 2. *) type acc val create_acc : [ `Interpolate | `Next_neighbor ] -> len0:int -> len1:int -> v00:float -> acc (** Creates a resampling accumulator. Requires the first point of vec0. *) val accumulate : acc -> float -> acc val finalise : acc -> curve val resample_vector : [< `Interpolate | `Next_neighbor ] -> curve -> int -> curve (** [resample_vector mode vec0 len1] is [vec1], a curve of length [len1], created by resampling [vec0]. It internally relies on the [should_sample] function. *) end (** Functional summary for a variable that has zero or more occurences per period. [accumulate] is expected to be called [in_period_count] times before [finalise] is. {3 Stats Gathered} - Global (non-nan) max, argmax, min, argmin and mean of the variable. - The very last non-nan sample encountered minus the very first non-nan sample encountered. - Global histogram made of [distribution_bin_count] bins. Option: [distribution_scale] to control the spreading scale of the bins, either on a linear or a log scale. Computed using Bentov. - A curve made of [out_sample_count] points. Options: [evolution_smoothing] to control the smoothing, either using EMA, or no smoothing at all. {3 Histograms} The histograms are all computed using https://github.com/barko/bentov. [Bentov] computes dynamic histograms without the need for a priori informations on the distributions, while maintaining a constant memory space and a marginal CPU footprint. The implementation of that library is pretty straightforward, but not perfect; the CPU footprint doesn't scale well with the number of bins. The computed histograms depend on the order of the operations, some marginal unsabilities are to be expected. [Bentov] is good at spreading the bins on the input space. Since some histograms will be shown on a log plot, the log10 of those values is passed to [Bentov] instead, but the json will store real seconds. {3 Log Scale} When a variable has to be displayed on a log scale, the [scale] option can be set to [`Log] in order for some adjustments to be made. In the histogram, the bins have to spread on a log scale. When smoothing the evolution, the EMA decay has to be calculated on a log scale. Gotcha: All the input samples should be strictly greater than 0, so that they don't fail their conversion to log. {3 Periods are Decoupled from Samples} When a [Variable_summary] ([vs]) is created, the number of periods has to be declared right away through the [in_period_count] parameter, but [vs] is very flexible when it comes to the number of samples shown to it on each period. The simplest use case of [vs] is when there is exactly one sample for each period. In that case, [accumulate acc samples] is called using a list of length 1. For example: when a period corresponds to a cycle of an algorithm, and the variable is a timestamp. The more advanced use case of [vs] is when there are a varying number a samples for each period. For example: when a period corresponds to a cycle of an algorithm, and the variable is the time taken by a buffer flush that may happen 0, 1 or more times per cycle. In that later case, the [evolution] curve may contain NaNs before and after sample points. {3 Possible Future Evolutions} - A period-wise histogram, similar to Grafana's heatmaps: "A heatmap is like a histogram, but over time where each time slice represents its own histogram.". - Variance evolution. Either without smoothing or using exponential moving variance (see wikipedia). - Global variance. - Quantile evolution. *) module Variable_summary : sig type t = { max_value : float * int; min_value : float * int; mean : float; diff : float; distribution : histo; evolution : curve; } [@@deriving repr] type acc val create_acc : evolution_smoothing:[ `Ema of float * float | `None ] -> evolution_resampling_mode:[ `Interpolate | `Next_neighbor | `Prev_neighbor ] -> distribution_bin_count:int -> scale:[ `Linear | `Log ] -> in_period_count:int -> out_sample_count:int -> acc val accumulate : acc -> float list -> acc val finalise : acc -> t end (** See [Trace_stat_summary] for an explanation and an example. Heavily inspired by the "repr" library. Type parameters: - ['res] is the output of [finalise]. - ['f] is the full contructor that creates a ['res]. - ['v] is the output of [folder.finalise], one parameter of ['f]. - ['rest] is ['f] or ['res] or somewhere in between. - ['acc] is the accumulator of one folder. - ['row] is what needs to be fed to all [folder.accumulate]. Typical use case: {[ let pf = open_ (fun res_a res_b -> my_constructor res_a res_b) |+ folder my_acc_a my_accumulate_a my_finalise_a |+ folder my_acc_b my_accumulate_b my_finalise_b |> seal in let res = my_row_sequence |> Seq.fold_left accumulate pf |> finalise in ]} *) module Parallel_folders : sig (** Section 1/3 - Individual folders *) type ('row, 'acc, 'v) folder val folder : 'acc -> ('acc -> 'row -> 'acc) -> ('acc -> 'v) -> ('row, 'acc, 'v) folder (** Create one folder to be passed to an open parallel folder using [|+]. *) (** Section 2/3 - Open parallel folder *) type ('res, 'row, 'v) folders type ('res, 'row, 'f, 'rest) open_t val open_ : 'f -> ('res, 'row, 'f, 'f) open_t (** Start building a parallel folder. *) val app : ('res, 'row, 'f, 'v -> 'rest) open_t -> ('row, 'acc, 'v) folder -> ('res, 'row, 'f, 'rest) open_t (** Add a folder to an open parallel folder. *) val ( |+ ) : ('res, 'row, 'f, 'v -> 'rest) open_t -> ('row, 'acc, 'v) folder -> ('res, 'row, 'f, 'rest) open_t (** Alias for [app]. *) (** Section 3/3 - Closed parallel folder *) type ('res, 'row) t val seal : ('res, 'row, 'f, 'res) open_t -> ('res, 'row) t (** Stop building a parallel folder. Gotcha: It may seal a partially applied [f]. *) val accumulate : ('res, 'row) t -> 'row -> ('res, 'row) t (** Forward a row to all registered functional folders. *) val finalise : ('res, 'row) t -> 'res (** Finalise all folders and pass their result to the user-defined function provided to [open_]. *) end
(** Utilities to summarise data. This file is NOT meant to be used from Tezos, as opposed to some other "trace_*" files. *)
lpize_pfff.ml
open Common (* CONFIG *) let lang = ref "ml" let verbose = ref false (*****************************************************************************) (* LPizer *) (*****************************************************************************) (* In this file because it can't be put in syncweb/ (it uses graph_code_c), * and it's a form of code slicing ... *) (* for lpification, to get a list of files and handling the skip list *) let find_source xs = let root = Common2.common_prefix_of_files_or_dirs xs in let root = Common.fullpath root |> Common2.chop_dirsymbol in let files = Find_source.files_of_dir_or_files ~lang:!lang xs in files |> List.iter (fun file -> pr (Common.readable root file) ) (* syncweb does not like tabs *) let untabify s = Str.global_substitute (Str.regexp "^\\([\t]+\\)") (fun _wholestr -> let substr = Str.matched_string s in let n = String.length substr in Common2.n_space (4 * n) ) s (* todo: could generalize this in graph_code.ml! have a range * property there! *) type entity = { name: string; kind: Entity_code.entity_kind; range: int * int; } type env = { current_file: Common.filename; cnt: int ref; hentities: (Graph_code.node, bool) Hashtbl.t; } let uniquify env kind s = let sfinal = if Hashtbl.mem env.hentities (s, kind) then let s2 = spf "%s (%s)" s env.current_file in if Hashtbl.mem env.hentities (s2, kind) then begin incr env.cnt; let s3 = spf "%s (%s)%d" s env.current_file !(env.cnt) in if Hashtbl.mem env.hentities (s3, kind) then failwith "impossible" else s3 end else s2 else s in Hashtbl.replace env.hentities (sfinal, kind) true; sfinal let count_dollar s = let cnt = ref 0 in for i = 0 to String.length s - 1 do if String.get s i = '$' then incr cnt done; !cnt (*--------------------------------------------------*) (* C *) (*--------------------------------------------------*) open Cst_cpp module Ast = Cst_cpp module E = Entity_code module PI = Parse_info let hooks_for_comment_cpp = { Comment_code. kind = Token_helpers_cpp.token_kind_of_tok; tokf = Token_helpers_cpp.info_of_tok; } let range_of_any_with_comment_cpp any toks = let ii = Lib_parsing_cpp.ii_of_any any in let (min, max) = PI.min_max_ii_by_pos ii in match Comment_code.comment_before hooks_for_comment_cpp min toks with | None -> min, max | Some ii -> ii, max (* todo: % - could do that in graph_code_c, with a range * - if have functions like this * asize_t fl_cur_size = 0; /* How many free words were added since * the latest fl_init_merge. */ * then the comment is splitted in two which leads to parse error * in the generated file * - do not create chunk entity for #define XXx when just after a ifndef XXx * at the top of the file. *) let extract_entities_cpp env xs = xs |> Common.map_filter (fun (top, toks) -> match top with | CppDirectiveDecl decl -> (match decl with | Define (_, ident, kind_define, _val) -> let kind = match kind_define with | DefineVar -> E.Constant | DefineFunc _ -> E.Macro in let (min, max) = range_of_any_with_comment_cpp (Toplevel top) toks in Some { name = fst ident |> uniquify env kind; kind = kind; range = (PI.line_of_info min, PI.line_of_info max); } | _ -> None ) | DeclElem decl -> (match decl with | Func (FunctionOrMethod def) -> let (min, max) = range_of_any_with_comment_cpp (Toplevel top) toks in Some { name = Ast.string_of_name_tmp def.f_name |> uniquify env E.Function; kind = E.Function; range = (PI.line_of_info min, PI.line_of_info max); } | BlockDecl decl -> let (min, max) = range_of_any_with_comment_cpp (Toplevel top) toks in (match decl with | DeclList ([x, _], _) -> (match x with (* prototype, don't care *) | { v_namei = Some (_name, None); v_type = (_, (FunctionType _)); _ } -> None (* typedef struct X { } X *) | { v_namei = _; v_type = (_, (StructDef { c_name = Some name; _})); v_storage = StoTypedef _; _ } -> Some { name = Ast.string_of_name_tmp name |> uniquify env E.Class; kind = E.Class; range = (PI.line_of_info min, PI.line_of_info max); } (* other typedefs, don't care *) | { v_namei = Some (_name, None); v_storage = StoTypedef _; _ } -> None (* global decl, don't care *) | { v_namei = Some (_name, None); v_storage = (Sto (Extern, _)); _ } -> None (* global def *) | { v_namei = Some (name, _); v_storage = _; _ } -> Some { name = Ast.string_of_name_tmp name |> uniquify env E.Global; kind = E.Global; range = (PI.line_of_info min, PI.line_of_info max); } (* struct def *) | { v_namei = _; v_type = (_, (StructDef { c_name = Some name; _})); _ } -> Some { name = Ast.string_of_name_tmp name |> uniquify env E.Class; kind = E.Class; range = (PI.line_of_info min, PI.line_of_info max); } (* enum def *) | { v_namei = _; v_type = (_, (EnumDef (_, Some ident, _))); _ } -> Some { name = Ast.string_of_name_tmp (None, [], IdIdent ident) |> uniquify env E.Type; kind = E.Type; range = (PI.line_of_info min, PI.line_of_info max); } (* enum anon *) | { v_namei = _; v_type = (_, (EnumDef (_, None, _))); _ } -> Some { name = "_anon_" |> uniquify env E.Type; kind = E.Type; range = (PI.line_of_info min, PI.line_of_info max); } | _ -> None ) | _ -> None ) | _ -> None ) | _ -> None ) (*--------------------------------------------------*) (* OCaml *) (*--------------------------------------------------*) let hooks_for_comment_ml = { Comment_code. kind = Token_helpers_ml.token_kind_of_tok; tokf = Token_helpers_ml.info_of_tok; } let is_estet_comment ii = let s = PI.str_of_info ii in (s =~ ".*\\*\\*\\*\\*") || (s =~ ".*------") || (s =~ ".*####") let range_of_any_with_comment_ml any toks = let ii = Lib_parsing_ml.ii_of_any any in let (min, max) = PI.min_max_ii_by_pos ii in let if_not_estet_comment ii otherwise = if (not (is_estet_comment ii)) then ii else otherwise in match Comment_code.comment_before hooks_for_comment_ml min toks, Comment_code.comment_after hooks_for_comment_ml max toks with | None, None -> min, max | Some ii, None -> if_not_estet_comment ii min, max | None, Some ii -> min, if_not_estet_comment ii max | Some i1, Some i2 -> if_not_estet_comment i1 min, if_not_estet_comment i2 max open Cst_ml let nb_newlines info = let str = PI.str_of_info info in if str =~ ".*\n" then (Str.split_delim (Str.regexp "\n") str |> List.length) - 1 else 0 (* TODO: * - let f = function ... leads to constant!! should be function! *) let (extract_entities_ml: env -> Parse_ml.program_and_tokens -> entity list) = fun env (top_opt, toks) -> let qualify x = Module_ml.module_name_of_filename env.current_file ^ "." ^ x in let range any = let (min, max) = range_of_any_with_comment_ml any toks in let nblines = nb_newlines max in (PI.line_of_info min, PI.line_of_info max + nblines) in let cnt = ref 0 in match top_opt with | None -> [] | Some xs -> xs |> List.map (fun top -> match top with | TopItem Let(_i1, _,[Left(LetClassic( {l_name=Name (name, _); l_params=[]; l_body=[Left(Function(_, _))]; _ }))]) -> let kind = E.Function in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem Let(_i1, _,[Left(LetClassic( {l_name=Name (name, _); l_params=[]; _}))]) -> let kind = E.Constant in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem Let(_i1, _, [Left(LetClassic( {l_name=Name (name, _); l_params=_::_; _}))]) -> let kind = E.Function in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem(Exception(_, Name((name, _)), _)) -> let kind = E.Exception in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem Let(_i1, _, [Left(LetPattern(PatUnderscore _, _, _))]) -> incr cnt; [{ name = qualify (spf "_%d" !cnt); kind = E.TopStmts; range = range (Toplevel top); }] | TopItem(Type(_, [Left(TyDef(_, Name((name, _)), _, _ ))])) -> let kind = E.Type in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem(Val(_, Name((name, _)), _, _)) -> let kind = E.Prototype in [{ name = qualify name |> uniquify env kind; kind; range = range (Toplevel top); }] | TopItem(Type(t1, xs)) -> let (xs, ys) = Common.partition_either (fun x -> x) xs in let zipped = Common2.zip xs (t1::ys) in zipped |> Common.map_filter (fun (x, _tok1) -> match x with | (TyDef(_, Name((name, _)), _, _)) -> let kind = E.Type in Some { name = qualify name |> uniquify env kind; kind = E.Type; range = range (TypeDeclaration x); } | _ -> None ) | _ -> [] ) |> List.flatten (*--------------------------------------------------*) (* Generic part *) (*--------------------------------------------------*) let sanity_check _xs = (* let group_by_basename = xs |> List.map (fun file -> Filename.basename file, file) |> Common.group_assoc_bykey_eff in group_by_basename |> List.iter (fun (_base, xs) -> if List.length xs > 1 then pr2 (spf "multiple files with same name: %s" (xs |> Common.join "\n")) ); *) () let string_of_entity_kind kind = match kind with | E.Function -> "function" | E.Global -> "global" | E.Type -> if !lang = "c" then "enum" else "type" | E.Class -> if !lang = "c" then "struct" else "class" | E.Constant -> "constant" (* old: was "function", because in C people sometimes use macro * where it could be a function (if C supported inline keywords), * so this is a low-level detail I wanted to hide. * But if you put "function" here then you destroy the work done * by uniquify and you can get a macro and function with the same * chunkname. So either put macro here, or change the call * to uniquify. *) | E.Macro -> "macro" | E.Exception -> "exception" | E.TopStmts -> "toplevel" | E.Prototype -> "signature" | _ -> failwith (spf "not handled kind: %s" (E.string_of_entity_kind kind)) (* main entry point *) let lpize xs = Parse_cpp.init_defs !Flag_parsing_cpp.macros_h; let root = Sys.getcwd () in let local = Filename.concat root "pfff_macros.h" in if Sys.file_exists local then Parse_cpp.add_defs local; sanity_check xs; let current_dir = ref "" in (* to avoid duped entities *) let hentities = Hashtbl.create 101 in xs |> List.iter (fun file -> let dir = Filename.dirname file in if dir <> !current_dir then begin pr (spf "\\section{[[%s/]]}" dir); pr ""; current_dir := dir; end; pr (spf "\\subsection*{[[%s]]}" file); pr ""; let (xs, _stat) = (* CONFIG *) Parse_ml.parse file (* Parse_cpp.parse file *) in let env = { current_file = file; hentities = hentities; (* starts at 1 so that first have no int, just the filename * e.g. function foo (foo.h), and then the second one have * function foo (foo.h)2 *) cnt = ref 1; } in let entities = (* CONFIG *) extract_entities_ml env xs (* extract_entities_cpp env xs *) in let hstart = entities |> List.map (fun e -> fst e.range, e) |> Common.hash_of_list in let hcovered = entities |> List.map (fun e -> let (lstart, lend) = e.range in Common2.enum_safe lstart lend ) |> List.flatten |> Common.hashset_of_list in let lines = Common.cat file in let arr = Array.of_list lines in (* CONFIG *) let suffix = "" in (* "arm" *) (* the chunks *) entities |> List.iter (fun e -> let (lstart, lend) = e.range in pr (spf "<<%s [[%s]]%s>>=" (string_of_entity_kind e.kind) e.name suffix); let nbdollars = ref 0 in Common2.enum_safe lstart lend |> List.iter (fun line -> let idx = line - 1 in if idx >= Array.length arr || idx < 0 then failwith (spf "out of range for %s, line %d" file line); pr (untabify (arr.(line - 1))); nbdollars := !nbdollars + (count_dollar arr.(line - 1)); ); pr "@"; if !nbdollars mod 2 = 1 then pr "%$"; pr ""; ); pr ""; pr "%-------------------------------------------------------------"; pr ""; (* we don't use the basename (even though 'make sync' ' used to make * this assumption because) because we would have too many dupes. *) pr (spf "<<%s>>=" file); Common.cat file |> Common.index_list_1 |> List.iter (fun (s, idx) -> match Common2.hfind_option idx hstart with | None -> if Hashtbl.mem hcovered idx then () else pr (untabify s) | Some e -> pr (spf "<<%s [[%s]]%s>>" (string_of_entity_kind e.kind) e.name suffix); ); pr "@"; pr ""; pr ""; (* CONFIG *) (* for the initial 'make sync' to work *) Sys.command (spf "rm -f %s" file) |> ignore; ); () (* "-lpize", " <files>", Common.mk_action_n_arg lpize; "-find_source", " <dirs>", Common.mk_action_n_arg find_source; "-lang", Arg.Set_string lang, (spf " <str> choose language (default = %s)" !lang); "-verbose", Arg.Set verbose, " "; *)
dune
(executable (name mylib) (public_name mylib) (modes shared_object))
interval_base.h
#ifndef _INTERVAL_BASE_H #define _INTERVAL_BASE_H /* We work with _RD (round down) and _RU (round up) version of arithmetic functions. Extreme care must be taken regarding inline assembly. As setting the mode of the processor has to be done before any computation, we have to prevent instructions reordering. This is also true for setting back the mode to nearest. The result has to be stored in the stack before setting the mode to nearest: computation is done in 80 bits mode and casting the result to 64 bits has to be done before changing rounding mode because the casting itself introduces errors. This is why some (artificial) variables dependencies have to be used, along with the "volatile" keyword and the "memory" keyword in the clobber list. It is extremely wise to check the assembly code generated... */ #if defined _MSC_BUILD #error "MSVC inline assembly is not supported at the moment. Please contribute." #elif !(defined __GNUC__) #define asm __asm__ #define __volatile__ #endif /* Set the processor to different rounding modes */ #define SET_RD(ref) "fstcw "#ref"\n\t andw $0xf3ff,"#ref"\n\t orw $0x0400,"#ref"\n\t fldcw "#ref"\n\t" #define SET_RU(ref) "fstcw "#ref"\n\t andw $0xf3ff,"#ref"\n\t orw $0x0800,"#ref"\n\t fldcw "#ref"\n\t" #define SET_NEAREST(ref) "fstcw "#ref"\n\t andw $0xf3ff,"#ref"\n\t fldcw "#ref"\n\t" static short int cw; static long long int tmp; #define FILDQ(ref) "fildq "#ref"\n\t" #endif /* interval_base.h included */
/* Copyright 2011 Jean-Marc Alliot / Jean-Baptiste Gotteland Copyright 2018 Christophe Troestler This file is part of the ocaml interval library. The ocaml interval library 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, either version 3 of the License, or (at your option) any later version. The ocaml interval 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 GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the ocaml interval library. If not, see <http://www.gnu.org/licenses/>. */
scheme.mli
(** A collection of rules for one or multiple directories. *) open Import type 'rules t = | Empty (** [Empty] is a scheme that has no rules *) | Union of 'rules t * 'rules t (** [Union (a, b)] produces all the rules produced by a and b *) | Approximation of Path.Build.w Dir_set.t * 'rules t (** [Approximation (dirs, x)] produces the same rules as [x] in [dirs] and produces no rules outside of [dirs]. It is an error if [x] produces any rules outside of [dirs]. This error is not always going to be detected, especially if it's hidden by an occurrence of [Thunk]. If the error is undetected, the violating rules are just silently ignored. *) | Finite of 'rules Path.Build.Map.t (** [Finite rules] just produces a fixed set of rules known in advance. The keys in the map are the directory paths. *) | Thunk of (unit -> 'rules t Memo.t) (** [Thunk f] is a "lazy" collection of rules. This is normally used with [Approximation (dirs, Thunk f)] such that the work of [f] can be delayed (or avoided entirely) until (or unless) the rules for [dirs] become necessary. The thunk will be called at most once per [evaluate]. *) module Evaluated : sig type 'a t (** returns the rules and the set of child directories that could have rules defined in this scheme *) val get_rules : 'a t -> dir:Path.Build.t -> ('a option * String.Set.t) Memo.t end (** [Evaluated.t] shares the work of scheme evaluation between multiple [get_rules] requests. This consists of: - Sharing the work of scheme data structure traversal. For example, if a scheme consists of a many nested [Union]s, a naive scheme lookup would have to look at them all at every [get_rules] query. [evaluate] will collapse them to a directory-keyed trie for faster lookup. - Sharing the work done by user thunks. Every thunk will only be called at most once per [evaluate]. *) val evaluate : 'a t -> union:('a -> 'a -> 'a) -> 'a Evaluated.t Memo.t val all : 'a t list -> 'a t
(** A collection of rules for one or multiple directories. *)
Parse.mli
(** Functions for parsing typescript programs into a CST. Generated by ocaml-tree-sitter. *) (** Parse a typescript program from a string into a typed OCaml CST. The resulting CST is [None] if parsing failed completely, otherwise some tree is returned even if some parsing errors occurred, in which case the error list is not empty. *) val string : ?src_file:string -> string -> CST.program Tree_sitter_run.Parsing_result.t (** Parse a typescript program from a file into a typed OCaml CST. See the [string] function above for details. *) val file : string -> CST.program Tree_sitter_run.Parsing_result.t (** Whether to print debugging information. Default: false. *) val debug : bool ref (** The original tree-sitter parser. *) val ts_parser : Tree_sitter_bindings.Tree_sitter_API.ts_parser (** Parse a program into a tree-sitter CST. *) val parse_source_string : ?src_file:string -> string -> Tree_sitter_run.Tree_sitter_parsing.t (** Parse a source file into a tree-sitter CST. *) val parse_source_file : string -> Tree_sitter_run.Tree_sitter_parsing.t (** Parse a tree-sitter CST into an OCaml typed CST. *) val parse_input_tree : Tree_sitter_run.Tree_sitter_parsing.t -> CST.program Tree_sitter_run.Parsing_result.t
generic_parser.mli
open Module_types module type ERROR = sig type t type semantic type expect val is_semantic: t -> bool val semantic: t -> semantic val expectations: t -> expect list val make_semantic: semantic -> t val make_expectations: expect list -> t end module type COMBINATORS = sig type 'a t type semantic val return: 'a -> 'a t val succeed: 'a -> 'a t val fail: semantic -> 'a t val consumer: 'a t -> 'a t val map: ('a -> 'b) -> 'a t -> 'b t val (>>=): 'a t -> ('a -> 'b t) -> 'b t val (<|>): 'a t -> 'a t -> 'a t val optional: 'a t -> 'a option t val one_of: 'a t list -> 'a t val zero_or_more: 'a t -> 'a list t val one_or_more: 'a t -> 'a list t val one_or_more_separated: 'a t -> _ t -> 'a list t val zero_or_more_separated: 'a t -> _ t -> 'a list t val skip_zero_or_more: 'a t -> int t val skip_one_or_more: 'a t -> int t val (|=): ('a -> 'b) t -> 'a t -> 'b t val (|.): 'a t -> _ t -> 'a t val (|==): ('a -> 'b) t -> (unit -> 'a t) -> 'b t val (|..): 'a t -> (unit -> _ t) -> 'a t end module Make (T:ANY) (S:ANY) (Expect:ANY) (Semantic:ANY) (F:ANY): sig type token = T.t type final = F.t type parser include COMBINATORS with type semantic = Semantic.t module Error: ERROR with type semantic = Semantic.t and type expect = Expect.t val unexpected: Expect.t -> 'a t val (<?>): 'a t -> Expect.t -> 'a t val backtrackable: 'a t -> Expect.t -> 'a t val followed_by: 'a t -> Expect.t -> unit t (** [followed_by p expect] Parses [p] and backtracks (i.e. all tokens of [p] will be pushed back to the lookahead). In case [p] succeeds, the [followed_by] parser succeeds without consuming tokens. Otherwise it fails without consuming tokens. *) val not_followed_by: 'a t -> Expect.t -> unit t (** [not_followed_by p expect] Parses [p] and backtracks (i.e. all tokens of [p] will be pushed back to the lookahead). In case [p] succeeds, the [not_followed_by] parser fails without consuming tokens. Otherwise it succeeds without consuming tokens. *) val needs_more: parser -> bool val has_ended: parser -> bool val put_token: parser -> token -> parser val state: parser -> S.t val result: parser -> final option val error: parser -> Error.t val error_string: parser -> (Expect.t -> string) -> (Semantic.t -> string) -> string val lookahead: parser -> token list val has_succeeded: parser -> bool val has_failed: parser -> bool val make_parser: S.t -> final t -> parser val get: S.t t val update: (S.t -> S.t) -> unit t val get_and_update: (S.t -> S.t) -> S.t t val token: (S.t -> token -> ('a * S.t, Expect.t) result) -> 'a t end
ounit_myList.ml
open OUnit open MyList (* UNIT TEST : [collapse_first : ('a * 'b) list -> ('a * ('b list)) list] *) let test_collapse_first_00 () = let l = [] in let r = collapse_first l in error_assert "r = []" (r = []); () let _ = push_test "test_collapse_first_00" test_collapse_first_00 let test_collapse_first_01 () = let l = [(1, 2); (1, 3); (2, 4); (1, 5); (1, 2)] in let r = collapse_first l in error_assert "r = [(1, [2; 3]); (2, [4]); (1, [5; 2])]" (r = [(1, [2; 3]); (2, [4]); (1, [5; 2])]); () let _ = push_test "test_collapse_first_01" test_collapse_first_01 let indexes_true_tests_len12 = [| ([true; false; false; true; false; false; false; false; false; false; false; false], [0; 3]); ([true; false; false; false; true; false; false; false; false; false; false; false], [0; 4]); ([false; false; false; true; true; false; false; false; false; false; false; false], [3; 4]); ([false; true; false; true; true; false; false; false; false; false; false; false], [1; 3; 4]); ([false; true; false; true; false; false; false; false; false; false; false; false], [1; 3]); ([false; false; true; true; true; false; false; false; false; false; false; false], [2; 3; 4]); ([false; false; true; false; true; true; false; false; false; false; false; false], [2; 4; 5]); ([false; false; false; false; false; true; false; false; true; true; false; false], [5; 8; 9]); ([false; false; false; false; false; false; false; false; true; true; true; false], [8; 9; 10]); ([false; false; false; false; false; false; false; false; true; false; true; true], [8; 10; 11]); ([false; false; false; false; false; false; false; true; true; false; false; true], [7; 8; 11]); ([false; false; false; false; false; true; true; false; false; false; false; false], [5; 6]); ([false; false; false; false; false; false; true; true; false; false; false; false], [6; 7]); ([true; false; false; true; true; false; false; false; false; false; false; false], [0; 3; 4]); ([false; false; false; false; false; false; false; false; false; false; false; false], []); |] let test_indexes_gen bl il () = let il' = indexes (fun x -> x) bl in error_assert "il' = il" (il' = il); () let test_indexes_true_gen bl il () = let il' = indexes_true bl in error_assert "il' = il" (il' = il); () let test_of_sorted_indexes_gen bl il () = let len = List.length bl in let bl' = of_sorted_indexes len il in error_assert "bl' = bl" (bl' = bl); () let test_of_indexes_true_gen bl il () = let len = List.length bl in let bl' = of_indexes ~sorted:true len il in error_assert "bl' = bl" (bl' = bl); () let test_of_indexes_false_gen bl il () = let len = List.length bl in let bl' = of_indexes ~sorted:false len il in error_assert "bl' = bl" (bl' = bl); () let test_poll_indexes = [| (test_indexes_gen, "test_indexes_gen"); (test_indexes_true_gen, "test_indexes_true_gen"); (test_of_sorted_indexes_gen, "test_of_sorted_indexes_gen"); (test_of_indexes_true_gen, "test_of_indexes_true_gen"); (test_of_indexes_false_gen, "test_of_indexes_false_gen"); |] let _ = Array.iteri (fun i (bl, il) -> Array.iteri (fun j (compute, compute_name) -> let tag = OUnit.ToS.("["^(int i)^","^(int j)^"]") in push_test ("test_"^tag^"_"^compute_name) (compute bl il) ) test_poll_indexes ) indexes_true_tests_len12 (* UNIT TEST [of_sorted_indexes : int -> int list -> bool list] *) (* UNIT TEST [of_indexes : ?sorted:bool -> int -> int list -> bool list] *) (* UNIT TEST [lexsort : ... ] *) let test_lexsort_00 () = let input = [([1; 2; 3; 4; 5; 10; 11; 12; 14; 15; 16; 17], 2)] in let expected_output = [[2]] in let output = lexsort Stdlib.compare input in error_assert "output = expected_output" (output = expected_output) let _ = push_test "test_lexsort_00" test_lexsort_00 let _ = run_tests()
batcher.mli
open Alpha_context (** Initialize the internal state of the batcher. *) val init : rollup:Tx_rollup.t -> signer:Signature.public_key_hash -> Context.index -> Constants.t -> unit tzresult Lwt.t (** Returns [true] if the batcher was started for this node. *) val active : unit -> bool (** Retrieve an L2 transaction from the queue. *) val find_transaction : L2_transaction.hash -> L2_transaction.t option tzresult (** List all queued transactions in the order they appear in the queue, i.e. the message that were added first to the queue are at the end of list. *) val get_queue : unit -> L2_transaction.t list tzresult (** [register_transaction ?apply state tx] registers a new L2 transaction [tx] in the queue of the batcher for future injection on L1. If [apply] is [true] (defaults to [true]), the transaction is applied on the batcher's incremental context. In this case, when the application fails, the transaction is not queued. A batch is injected asynchronously if a full batch can be constructed and [eager_batch] is [true]. *) val register_transaction : ?eager_batch:bool -> ?apply:bool -> L2_transaction.t -> L2_transaction.hash tzresult Lwt.t (** Create L2 batches of operations from the queue and pack them in an L1 batch operation. The batch operation is queued in the injector for injection on the Tezos node. *) val batch : unit -> unit tzresult Lwt.t (** Notifies a new L2 head to the batcher worker. *) val new_head : L2block.t -> unit tzresult Lwt.t
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************) open Protocol
test_sampling_data.ml
open Tezos_benchmark (* Input parameter parsing *) let verbose = if Array.length Sys.argv < 2 then ( Format.eprintf "Executable expects random seed on input\n%!" ; exit 1) else (Random.init (int_of_string Sys.argv.(1)) ; List.exists (( = ) "-v")) (Array.to_list Sys.argv) (* ------------------------------------------------------------------------- *) (* MCMC instantiation *) let state = Random.State.make [|42; 987897; 54120|] module Crypto_samplers = Crypto_samplers.Make_finite_key_pool (struct let algo = `Default let size = 16 end) module Michelson_base_samplers = Michelson_samplers_base.Make (struct let parameters = let size = {Base_samplers.min = 4; max = 32} in { Michelson_samplers_base.int_size = size; string_size = size; bytes_size = size; } end) module Data = Michelson_mcmc_samplers.Make_data_sampler (Michelson_base_samplers) (Crypto_samplers) (struct let rng_state = state let target_size = 500 let verbosity = if verbose then `Trace else `Silent end) let start = Unix.gettimeofday () let generator = Data.generator ~burn_in:(200 * 7) state let stop = Unix.gettimeofday () let () = Format.printf "Burn in time: %f seconds@." (stop -. start) let _ = for _i = 0 to 1000 do let Michelson_mcmc_samplers.{term = michelson; typ} = generator state in if verbose then ( Format.eprintf "result:@." ; Format.eprintf "type: %a@." Test_helpers.print_script_expr typ ; Format.eprintf "%a@." Test_helpers.print_script_expr michelson) done
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
constants_services.mli
open Alpha_context val errors: 'a #RPC_context.simple -> 'a -> Data_encoding.json_schema shell_tzresult Lwt.t (** Returns all the constants of the protocol *) val all: 'a #RPC_context.simple -> 'a -> Constants.t shell_tzresult Lwt.t val register: unit -> 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. *) (* *) (*****************************************************************************)
dune
(documentation (package guile))
desc.ml
open Bechamel type t = Benchmark.stats let sampling_witness : Benchmark.sampling Json_encoding.encoding = let open Json_encoding in let a = case float (function `Geometric x -> Some x | _ -> None) (fun x -> `Geometric x) in let b = case int (function `Linear x -> Some x | _ -> None) (fun x -> `Linear x) in union [ a; b ] let mtime_witness : Time.span Json_encoding.encoding = let open Json_encoding in conv Time.span_to_uint64_ns Time.span_of_uint64_ns int53 (* XXX(dinosaure): fix [int53]. *) let label_witness : string Json_encoding.encoding = Json_encoding.string let witness : t Json_encoding.encoding = let open Json_encoding in let start = req "start" int in let sampling = req "sampling" sampling_witness in let stabilize = req "stabilize" bool in let quota = req "quota" mtime_witness in let limit = req "limit" int in let instances = req "instances" (list label_witness) in let samples = req "samples" int in let time = req "time" mtime_witness in conv (fun (t : t) -> let open Benchmark in ( t.start, t.sampling, t.stabilize, t.quota, t.limit, t.instances, t.samples, t.time )) (fun (start, sampling, stabilize, quota, limit, instances, samples, time) -> let open Benchmark in { start; sampling; stabilize; quota; limit; instances; samples; time }) (obj8 start sampling stabilize quota limit instances samples time)
menhirLib.mli
module General : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This module offers general-purpose functions on lists and streams. *) (* As of 2017/03/31, this module is DEPRECATED. It might be removed in the future. *) (* --------------------------------------------------------------------------- *) (* Lists. *) (* [take n xs] returns the [n] first elements of the list [xs]. It is acceptable for the list [xs] to have length less than [n], in which case [xs] itself is returned. *) val take: int -> 'a list -> 'a list (* [drop n xs] returns the list [xs], deprived of its [n] first elements. It is acceptable for the list [xs] to have length less than [n], in which case an empty list is returned. *) val drop: int -> 'a list -> 'a list (* [uniq cmp xs] assumes that the list [xs] is sorted according to the ordering [cmp] and returns the list [xs] deprived of any duplicate elements. *) val uniq: ('a -> 'a -> int) -> 'a list -> 'a list (* [weed cmp xs] returns the list [xs] deprived of any duplicate elements. *) val weed: ('a -> 'a -> int) -> 'a list -> 'a list (* --------------------------------------------------------------------------- *) (* A stream is a list whose elements are produced on demand. *) type 'a stream = 'a head Lazy.t and 'a head = | Nil | Cons of 'a * 'a stream (* The length of a stream. *) val length: 'a stream -> int (* Folding over a stream. *) val foldr: ('a -> 'b -> 'b) -> 'a stream -> 'b -> 'b end module Convert : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* An ocamlyacc-style, or Menhir-style, parser requires access to the lexer, which must be parameterized with a lexing buffer, and to the lexing buffer itself, where it reads position information. *) (* This traditional API is convenient when used with ocamllex, but inelegant when used with other lexer generators. *) type ('token, 'semantic_value) traditional = (Lexing.lexbuf -> 'token) -> Lexing.lexbuf -> 'semantic_value (* This revised API is independent of any lexer generator. Here, the parser only requires access to the lexer, and the lexer takes no parameters. The tokens returned by the lexer may contain position information. *) type ('token, 'semantic_value) revised = (unit -> 'token) -> 'semantic_value (* --------------------------------------------------------------------------- *) (* Converting a traditional parser, produced by ocamlyacc or Menhir, into a revised parser. *) (* A token of the revised lexer is essentially a triple of a token of the traditional lexer (or raw token), a start position, and and end position. The three [get] functions are accessors. *) (* We do not require the type ['token] to actually be a triple type. This enables complex applications where it is a record type with more than three fields. It also enables simple applications where positions are of no interest, so ['token] is just ['raw_token] and [get_startp] and [get_endp] return dummy positions. *) val traditional2revised: ('token -> 'raw_token) -> ('token -> Lexing.position) -> ('token -> Lexing.position) -> ('raw_token, 'semantic_value) traditional -> ('token, 'semantic_value) revised (* --------------------------------------------------------------------------- *) (* Converting a revised parser back to a traditional parser. *) val revised2traditional: ('raw_token -> Lexing.position -> Lexing.position -> 'token) -> ('token, 'semantic_value) revised -> ('raw_token, 'semantic_value) traditional (* --------------------------------------------------------------------------- *) (* Simplified versions of the above, where concrete triples are used. *) module Simplified : sig val traditional2revised: ('token, 'semantic_value) traditional -> ('token * Lexing.position * Lexing.position, 'semantic_value) revised val revised2traditional: ('token * Lexing.position * Lexing.position, 'semantic_value) revised -> ('token, 'semantic_value) traditional end end module IncrementalEngine : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) type position = Lexing.position open General (* This signature describes the incremental LR engine. *) (* In this mode, the user controls the lexer, and the parser suspends itself when it needs to read a new token. *) module type INCREMENTAL_ENGINE = sig type token (* A value of type [production] is (an index for) a production. The start productions (which do not exist in an \mly file, but are constructed by Menhir internally) are not part of this type. *) type production (* The type ['a checkpoint] represents an intermediate or final state of the parser. An intermediate checkpoint is a suspension: it records the parser's current state, and allows parsing to be resumed. The parameter ['a] is the type of the semantic value that will eventually be produced if the parser succeeds. *) (* [Accepted] and [Rejected] are final checkpoints. [Accepted] carries a semantic value. *) (* [InputNeeded] is an intermediate checkpoint. It means that the parser wishes to read one token before continuing. *) (* [Shifting] is an intermediate checkpoint. It means that the parser is taking a shift transition. It exposes the state of the parser before and after the transition. The Boolean parameter tells whether the parser intends to request a new token after this transition. (It always does, except when it is about to accept.) *) (* [AboutToReduce] is an intermediate checkpoint. It means that the parser is about to perform a reduction step. It exposes the parser's current state as well as the production that is about to be reduced. *) (* [HandlingError] is an intermediate checkpoint. It means that the parser has detected an error and is currently handling it, in several steps. *) (* A value of type ['a env] represents a configuration of the automaton: current state, stack, lookahead token, etc. The parameter ['a] is the type of the semantic value that will eventually be produced if the parser succeeds. *) (* In normal operation, the parser works with checkpoints: see the functions [offer] and [resume]. However, it is also possible to work directly with environments (see the functions [pop], [force_reduction], and [feed]) and to reconstruct a checkpoint out of an environment (see [input_needed]). This is considered advanced functionality; its purpose is to allow error recovery strategies to be programmed by the user. *) type 'a env type 'a checkpoint = private | InputNeeded of 'a env | Shifting of 'a env * 'a env * bool | AboutToReduce of 'a env * production | HandlingError of 'a env | Accepted of 'a | Rejected (* [offer] allows the user to resume the parser after it has suspended itself with a checkpoint of the form [InputNeeded env]. [offer] expects the old checkpoint as well as a new token and produces a new checkpoint. It does not raise any exception. *) val offer: 'a checkpoint -> token * position * position -> 'a checkpoint (* [resume] allows the user to resume the parser after it has suspended itself with a checkpoint of the form [AboutToReduce (env, prod)] or [HandlingError env]. [resume] expects the old checkpoint and produces a new checkpoint. It does not raise any exception. *) val resume: 'a checkpoint -> 'a checkpoint (* A token supplier is a function of no arguments which delivers a new token (together with its start and end positions) every time it is called. *) type supplier = unit -> token * position * position (* A pair of a lexer and a lexing buffer can be easily turned into a supplier. *) val lexer_lexbuf_to_supplier: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> supplier (* The functions [offer] and [resume] are sufficient to write a parser loop. One can imagine many variations (which is why we expose these functions in the first place!). Here, we expose a few variations of the main loop, ready for use. *) (* [loop supplier checkpoint] begins parsing from [checkpoint], reading tokens from [supplier]. It continues parsing until it reaches a checkpoint of the form [Accepted v] or [Rejected]. In the former case, it returns [v]. In the latter case, it raises the exception [Error]. *) val loop: supplier -> 'a checkpoint -> 'a (* [loop_handle succeed fail supplier checkpoint] begins parsing from [checkpoint], reading tokens from [supplier]. It continues parsing until it reaches a checkpoint of the form [Accepted v] or [HandlingError env] (or [Rejected], but that should not happen, as [HandlingError _] will be observed first). In the former case, it calls [succeed v]. In the latter case, it calls [fail] with this checkpoint. It cannot raise [Error]. This means that Menhir's traditional error-handling procedure (which pops the stack until a state that can act on the [error] token is found) does not get a chance to run. Instead, the user can implement her own error handling code, in the [fail] continuation. *) val loop_handle: ('a -> 'answer) -> ('a checkpoint -> 'answer) -> supplier -> 'a checkpoint -> 'answer (* [loop_handle_undo] is analogous to [loop_handle], except it passes a pair of checkpoints to the failure continuation. The first (and oldest) checkpoint is the last [InputNeeded] checkpoint that was encountered before the error was detected. The second (and newest) checkpoint is where the error was detected, as in [loop_handle]. Going back to the first checkpoint can be thought of as undoing any reductions that were performed after seeing the problematic token. (These reductions must be default reductions or spurious reductions.) [loop_handle_undo] must initially be applied to an [InputNeeded] checkpoint. The parser's initial checkpoints satisfy this constraint. *) val loop_handle_undo: ('a -> 'answer) -> ('a checkpoint -> 'a checkpoint -> 'answer) -> supplier -> 'a checkpoint -> 'answer (* [shifts checkpoint] assumes that [checkpoint] has been obtained by submitting a token to the parser. It runs the parser from [checkpoint], through an arbitrary number of reductions, until the parser either accepts this token (i.e., shifts) or rejects it (i.e., signals an error). If the parser decides to shift, then [Some env] is returned, where [env] is the parser's state just before shifting. Otherwise, [None] is returned. *) (* It is desirable that the semantic actions be side-effect free, or that their side-effects be harmless (replayable). *) val shifts: 'a checkpoint -> 'a env option (* The function [acceptable] allows testing, after an error has been detected, which tokens would have been accepted at this point. It is implemented using [shifts]. Its argument should be an [InputNeeded] checkpoint. *) (* For completeness, one must undo any spurious reductions before carrying out this test -- that is, one must apply [acceptable] to the FIRST checkpoint that is passed by [loop_handle_undo] to its failure continuation. *) (* This test causes some semantic actions to be run! The semantic actions should be side-effect free, or their side-effects should be harmless. *) (* The position [pos] is used as the start and end positions of the hypothetical token, and may be picked up by the semantic actions. We suggest using the position where the error was detected. *) val acceptable: 'a checkpoint -> token -> position -> bool (* The abstract type ['a lr1state] describes the non-initial states of the LR(1) automaton. The index ['a] represents the type of the semantic value associated with this state's incoming symbol. *) type 'a lr1state (* The states of the LR(1) automaton are numbered (from 0 and up). *) val number: _ lr1state -> int (* Productions are numbered. *) (* [find_production i] requires the index [i] to be valid. Use with care. *) val production_index: production -> int val find_production: int -> production (* An element is a pair of a non-initial state [s] and a semantic value [v] associated with the incoming symbol of this state. The idea is, the value [v] was pushed onto the stack just before the state [s] was entered. Thus, for some type ['a], the state [s] has type ['a lr1state] and the value [v] has type ['a]. In other words, the type [element] is an existential type. *) type element = | Element: 'a lr1state * 'a * position * position -> element (* The parser's stack is (or, more precisely, can be viewed as) a stream of elements. The type [stream] is defined by the module [General]. *) (* As of 2017/03/31, the types [stream] and [stack] and the function [stack] are DEPRECATED. They might be removed in the future. An alternative way of inspecting the stack is via the functions [top] and [pop]. *) type stack = (* DEPRECATED *) element stream (* This is the parser's stack, a stream of elements. This stream is empty if the parser is in an initial state; otherwise, it is non-empty. The LR(1) automaton's current state is the one found in the top element of the stack. *) val stack: 'a env -> stack (* DEPRECATED *) (* [top env] returns the parser's top stack element. The state contained in this stack element is the current state of the automaton. If the stack is empty, [None] is returned. In that case, the current state of the automaton must be an initial state. *) val top: 'a env -> element option (* [pop_many i env] pops [i] cells off the automaton's stack. This is done via [i] successive invocations of [pop]. Thus, [pop_many 1] is [pop]. The index [i] must be nonnegative. The time complexity is O(i). *) val pop_many: int -> 'a env -> 'a env option (* [get i env] returns the parser's [i]-th stack element. The index [i] is 0-based: thus, [get 0] is [top]. If [i] is greater than or equal to the number of elements in the stack, [None] is returned. The time complexity is O(i). *) val get: int -> 'a env -> element option (* [current_state_number env] is (the integer number of) the automaton's current state. This works even if the automaton's stack is empty, in which case the current state is an initial state. This number can be passed as an argument to a [message] function generated by [menhir --compile-errors]. *) val current_state_number: 'a env -> int (* [equal env1 env2] tells whether the parser configurations [env1] and [env2] are equal in the sense that the automaton's current state is the same in [env1] and [env2] and the stack is *physically* the same in [env1] and [env2]. If [equal env1 env2] is [true], then the sequence of the stack elements, as observed via [pop] and [top], must be the same in [env1] and [env2]. Also, if [equal env1 env2] holds, then the checkpoints [input_needed env1] and [input_needed env2] must be equivalent. The function [equal] has time complexity O(1). *) val equal: 'a env -> 'a env -> bool (* These are the start and end positions of the current lookahead token. If invoked in an initial state, this function returns a pair of twice the initial position. *) val positions: 'a env -> position * position (* When applied to an environment taken from a checkpoint of the form [AboutToReduce (env, prod)], the function [env_has_default_reduction] tells whether the reduction that is about to take place is a default reduction. *) val env_has_default_reduction: 'a env -> bool (* [state_has_default_reduction s] tells whether the state [s] has a default reduction. This includes the case where [s] is an accepting state. *) val state_has_default_reduction: _ lr1state -> bool (* [pop env] returns a new environment, where the parser's top stack cell has been popped off. (If the stack is empty, [None] is returned.) This amounts to pretending that the (terminal or nonterminal) symbol that corresponds to this stack cell has not been read. *) val pop: 'a env -> 'a env option (* [force_reduction prod env] should be called only if in the state [env] the parser is capable of reducing the production [prod]. If this condition is satisfied, then this production is reduced, which means that its semantic action is executed (this can have side effects!) and the automaton makes a goto (nonterminal) transition. If this condition is not satisfied, [Invalid_argument _] is raised. *) val force_reduction: production -> 'a env -> 'a env (* [input_needed env] returns [InputNeeded env]. That is, out of an [env] that might have been obtained via a series of calls to the functions [pop], [force_reduction], [feed], etc., it produces a checkpoint, which can be used to resume normal parsing, by supplying this checkpoint as an argument to [offer]. *) (* This function should be used with some care. It could "mess up the lookahead" in the sense that it allows parsing to resume in an arbitrary state [s] with an arbitrary lookahead symbol [t], even though Menhir's reachability analysis (menhir --list-errors) might well think that it is impossible to reach this particular configuration. If one is using Menhir's new error reporting facility, this could cause the parser to reach an error state for which no error message has been prepared. *) val input_needed: 'a env -> 'a checkpoint end (* This signature is a fragment of the inspection API that is made available to the user when [--inspection] is used. This fragment contains type definitions for symbols. *) module type SYMBOLS = sig (* The type ['a terminal] represents a terminal symbol. The type ['a nonterminal] represents a nonterminal symbol. In both cases, the index ['a] represents the type of the semantic values associated with this symbol. The concrete definitions of these types are generated. *) type 'a terminal type 'a nonterminal (* The type ['a symbol] represents a terminal or nonterminal symbol. It is the disjoint union of the types ['a terminal] and ['a nonterminal]. *) type 'a symbol = | T : 'a terminal -> 'a symbol | N : 'a nonterminal -> 'a symbol (* The type [xsymbol] is an existentially quantified version of the type ['a symbol]. This type is useful in situations where the index ['a] is not statically known. *) type xsymbol = | X : 'a symbol -> xsymbol end (* This signature describes the inspection API that is made available to the user when [--inspection] is used. *) module type INSPECTION = sig (* The types of symbols are described above. *) include SYMBOLS (* The type ['a lr1state] is meant to be the same as in [INCREMENTAL_ENGINE]. *) type 'a lr1state (* The type [production] is meant to be the same as in [INCREMENTAL_ENGINE]. It represents a production of the grammar. A production can be examined via the functions [lhs] and [rhs] below. *) type production (* An LR(0) item is a pair of a production [prod] and a valid index [i] into this production. That is, if the length of [rhs prod] is [n], then [i] is comprised between 0 and [n], inclusive. *) type item = production * int (* Ordering functions. *) val compare_terminals: _ terminal -> _ terminal -> int val compare_nonterminals: _ nonterminal -> _ nonterminal -> int val compare_symbols: xsymbol -> xsymbol -> int val compare_productions: production -> production -> int val compare_items: item -> item -> int (* [incoming_symbol s] is the incoming symbol of the state [s], that is, the symbol that the parser must recognize before (has recognized when) it enters the state [s]. This function gives access to the semantic value [v] stored in a stack element [Element (s, v, _, _)]. Indeed, by case analysis on the symbol [incoming_symbol s], one discovers the type ['a] of the value [v]. *) val incoming_symbol: 'a lr1state -> 'a symbol (* [items s] is the set of the LR(0) items in the LR(0) core of the LR(1) state [s]. This set is not epsilon-closed. This set is presented as a list, in an arbitrary order. *) val items: _ lr1state -> item list (* [lhs prod] is the left-hand side of the production [prod]. This is always a non-terminal symbol. *) val lhs: production -> xsymbol (* [rhs prod] is the right-hand side of the production [prod]. This is a (possibly empty) sequence of (terminal or nonterminal) symbols. *) val rhs: production -> xsymbol list (* [nullable nt] tells whether the non-terminal symbol [nt] is nullable. That is, it is true if and only if this symbol produces the empty word [epsilon]. *) val nullable: _ nonterminal -> bool (* [first nt t] tells whether the FIRST set of the nonterminal symbol [nt] contains the terminal symbol [t]. That is, it is true if and only if [nt] produces a word that begins with [t]. *) val first: _ nonterminal -> _ terminal -> bool (* [xfirst] is analogous to [first], but expects a first argument of type [xsymbol] instead of [_ terminal]. *) val xfirst: xsymbol -> _ terminal -> bool (* [foreach_terminal] enumerates the terminal symbols, including [error]. [foreach_terminal_but_error] enumerates the terminal symbols, excluding [error]. *) val foreach_terminal: (xsymbol -> 'a -> 'a) -> 'a -> 'a val foreach_terminal_but_error: (xsymbol -> 'a -> 'a) -> 'a -> 'a (* The type [env] is meant to be the same as in [INCREMENTAL_ENGINE]. *) type 'a env (* [feed symbol startp semv endp env] causes the parser to consume the (terminal or nonterminal) symbol [symbol], accompanied with the semantic value [semv] and with the start and end positions [startp] and [endp]. Thus, the automaton makes a transition, and reaches a new state. The stack grows by one cell. This operation is permitted only if the current state (as determined by [env]) has an outgoing transition labeled with [symbol]. Otherwise, [Invalid_argument _] is raised. *) val feed: 'a symbol -> position -> 'a -> position -> 'b env -> 'b env end (* This signature combines the incremental API and the inspection API. *) module type EVERYTHING = sig include INCREMENTAL_ENGINE include INSPECTION with type 'a lr1state := 'a lr1state with type production := production with type 'a env := 'a env end end module EngineTypes : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This file defines several types and module types that are used in the specification of module [Engine]. *) (* --------------------------------------------------------------------------- *) (* It would be nice if we could keep the structure of stacks and environments hidden. However, stacks and environments must be accessible to semantic actions, so the following data structure definitions must be public. *) (* --------------------------------------------------------------------------- *) (* A stack is a linked list of cells. A sentinel cell -- which is its own successor -- is used to mark the bottom of the stack. The sentinel cell itself is not significant -- it contains dummy values. *) type ('state, 'semantic_value) stack = { (* The state that we should go back to if we pop this stack cell. *) (* This convention means that the state contained in the top stack cell is not the current state [env.current]. It also means that the state found within the sentinel is a dummy -- it is never consulted. This convention is the same as that adopted by the code-based back-end. *) state: 'state; (* The semantic value associated with the chunk of input that this cell represents. *) semv: 'semantic_value; (* The start and end positions of the chunk of input that this cell represents. *) startp: Lexing.position; endp: Lexing.position; (* The next cell down in the stack. If this is a self-pointer, then this cell is the sentinel, and the stack is conceptually empty. *) next: ('state, 'semantic_value) stack; } (* --------------------------------------------------------------------------- *) (* A parsing environment contains all of the parser's state (except for the current program point). *) type ('state, 'semantic_value, 'token) env = { (* If this flag is true, then the first component of [env.triple] should be ignored, as it has been logically overwritten with the [error] pseudo-token. *) error: bool; (* The last token that was obtained from the lexer, together with its start and end positions. Warning: before the first call to the lexer has taken place, a dummy (and possibly invalid) token is stored here. *) triple: 'token * Lexing.position * Lexing.position; (* The stack. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. *) stack: ('state, 'semantic_value) stack; (* The current state. In [CodeBackend], it is passed around on its own, whereas, here, it is accessed via the environment. *) current: 'state; } (* --------------------------------------------------------------------------- *) (* This signature describes the parameters that must be supplied to the LR engine. *) module type TABLE = sig (* The type of automaton states. *) type state (* States are numbered. *) val number: state -> int (* The type of tokens. These can be thought of as real tokens, that is, tokens returned by the lexer. They carry a semantic value. This type does not include the [error] pseudo-token. *) type token (* The type of terminal symbols. These can be thought of as integer codes. They do not carry a semantic value. This type does include the [error] pseudo-token. *) type terminal (* The type of nonterminal symbols. *) type nonterminal (* The type of semantic values. *) type semantic_value (* A token is conceptually a pair of a (non-[error]) terminal symbol and a semantic value. The following two functions are the pair projections. *) val token2terminal: token -> terminal val token2value: token -> semantic_value (* Even though the [error] pseudo-token is not a real token, it is a terminal symbol. Furthermore, for regularity, it must have a semantic value. *) val error_terminal: terminal val error_value: semantic_value (* [foreach_terminal] allows iterating over all terminal symbols. *) val foreach_terminal: (terminal -> 'a -> 'a) -> 'a -> 'a (* The type of productions. *) type production val production_index: production -> int val find_production: int -> production (* If a state [s] has a default reduction on production [prod], then, upon entering [s], the automaton should reduce [prod] without consulting the lookahead token. The following function allows determining which states have default reductions. *) (* Instead of returning a value of a sum type -- either [DefRed prod], or [NoDefRed] -- it accepts two continuations, and invokes just one of them. This mechanism allows avoiding a memory allocation. *) val default_reduction: state -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer (* An LR automaton can normally take three kinds of actions: shift, reduce, or fail. (Acceptance is a particular case of reduction: it consists in reducing a start production.) *) (* There are two variants of the shift action. [shift/discard s] instructs the automaton to discard the current token, request a new one from the lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to state [s] without requesting a new token. This instruction should be used when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for details. *) (* This is the automaton's action table. It maps a pair of a state and a terminal symbol to an action. *) (* Instead of returning a value of a sum type -- one of shift/discard, shift/nodiscard, reduce, or fail -- this function accepts three continuations, and invokes just one them. This mechanism allows avoiding a memory allocation. *) (* In summary, the parameters to [action] are as follows: - the first two parameters, a state and a terminal symbol, are used to look up the action table; - the next parameter is the semantic value associated with the above terminal symbol; it is not used, only passed along to the shift continuation, as explained below; - the shift continuation expects an environment; a flag that tells whether to discard the current token; the terminal symbol that is being shifted; its semantic value; and the target state of the transition; - the reduce continuation expects an environment and a production; - the fail continuation expects an environment; - the last parameter is the environment; it is not used, only passed along to the selected continuation. *) val action: state -> terminal -> semantic_value -> ('env -> bool -> terminal -> semantic_value -> state -> 'answer) -> ('env -> production -> 'answer) -> ('env -> 'answer) -> 'env -> 'answer (* This is the automaton's goto table. This table maps a pair of a state and a nonterminal symbol to a new state. By extension, it also maps a pair of a state and a production to a new state. *) (* The function [goto_nt] can be applied to [s] and [nt] ONLY if the state [s] has an outgoing transition labeled [nt]. Otherwise, its result is undefined. Similarly, the call [goto_prod prod s] is permitted ONLY if the state [s] has an outgoing transition labeled with the nonterminal symbol [lhs prod]. The function [maybe_goto_nt] involves an additional dynamic check and CAN be called even if there is no outgoing transition. *) val goto_nt : state -> nonterminal -> state val goto_prod: state -> production -> state val maybe_goto_nt: state -> nonterminal -> state option (* [is_start prod] tells whether the production [prod] is a start production. *) val is_start: production -> bool (* By convention, a semantic action is responsible for: 1. fetching whatever semantic values and positions it needs off the stack; 2. popping an appropriate number of cells off the stack, as dictated by the length of the right-hand side of the production; 3. computing a new semantic value, as well as new start and end positions; 4. pushing a new stack cell, which contains the three values computed in step 3; 5. returning the new stack computed in steps 2 and 4. Point 1 is essentially forced upon us: if semantic values were fetched off the stack by this interpreter, then the calling convention for semantic actions would be variadic: not all semantic actions would have the same number of arguments. The rest follows rather naturally. *) (* Semantic actions are allowed to raise [Error]. *) exception Error type semantic_action = (state, semantic_value, token) env -> (state, semantic_value) stack val semantic_action: production -> semantic_action (* [may_reduce state prod] tests whether the state [state] is capable of reducing the production [prod]. This function is currently costly and is not used by the core LR engine. It is used in the implementation of certain functions, such as [force_reduction], which allow the engine to be driven programmatically. *) val may_reduce: state -> production -> bool (* The LR engine requires a number of hooks, which are used for logging. *) (* The comments below indicate the conventional messages that correspond to these hooks in the code-based back-end; see [CodeBackend]. *) (* If the flag [log] is false, then the logging functions are not called. If it is [true], then they are called. *) val log : bool module Log : sig (* State %d: *) val state: state -> unit (* Shifting (<terminal>) to state <state> *) val shift: terminal -> state -> unit (* Reducing a production should be logged either as a reduction event (for regular productions) or as an acceptance event (for start productions). *) (* Reducing production <production> / Accepting *) val reduce_or_accept: production -> unit (* Lookahead token is now <terminal> (<pos>-<pos>) *) val lookahead_token: terminal -> Lexing.position -> Lexing.position -> unit (* Initiating error handling *) val initiating_error_handling: unit -> unit (* Resuming error handling *) val resuming_error_handling: unit -> unit (* Handling error in state <state> *) val handling_error: state -> unit end end (* --------------------------------------------------------------------------- *) (* This signature describes the monolithic (traditional) LR engine. *) (* In this interface, the parser controls the lexer. *) module type MONOLITHIC_ENGINE = sig type state type token type semantic_value (* An entry point to the engine requires a start state, a lexer, and a lexing buffer. It either succeeds and produces a semantic value, or fails and raises [Error]. *) exception Error val entry: state -> (Lexing.lexbuf -> token) -> Lexing.lexbuf -> semantic_value end (* --------------------------------------------------------------------------- *) (* The following signatures describe the incremental LR engine. *) (* First, see [INCREMENTAL_ENGINE] in the file [IncrementalEngine.ml]. *) (* The [start] function is set apart because we do not wish to publish it as part of the generated [parser.mli] file. Instead, the table back-end will publish specialized versions of it, with a suitable type cast. *) module type INCREMENTAL_ENGINE_START = sig (* [start] is an entry point. It requires a start state and a start position and begins the parsing process. If the lexer is based on an OCaml lexing buffer, the start position should be [lexbuf.lex_curr_p]. [start] produces a checkpoint, which usually will be an [InputNeeded] checkpoint. (It could be [Accepted] if this starting state accepts only the empty word. It could be [Rejected] if this starting state accepts no word at all.) It does not raise any exception. *) (* [start s pos] should really produce a checkpoint of type ['a checkpoint], for a fixed ['a] that depends on the state [s]. We cannot express this, so we use [semantic_value checkpoint], which is safe. The table back-end uses [Obj.magic] to produce safe specialized versions of [start]. *) type state type semantic_value type 'a checkpoint val start: state -> Lexing.position -> semantic_value checkpoint end (* --------------------------------------------------------------------------- *) (* This signature describes the LR engine, which combines the monolithic and incremental interfaces. *) module type ENGINE = sig include MONOLITHIC_ENGINE include IncrementalEngine.INCREMENTAL_ENGINE with type token := token and type 'a lr1state = state (* useful for us; hidden from the end user *) include INCREMENTAL_ENGINE_START with type state := state and type semantic_value := semantic_value and type 'a checkpoint := 'a checkpoint end end module Engine : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) open EngineTypes (* The LR parsing engine. *) module Make (T : TABLE) : ENGINE with type state = T.state and type token = T.token and type semantic_value = T.semantic_value and type production = T.production and type 'a env = (T.state, T.semantic_value, T.token) EngineTypes.env (* We would prefer not to expose the definition of the type [env]. However, it must be exposed because some of the code in the inspection API needs access to the engine's internals; see [InspectionTableInterpreter]. Everything would be simpler if --inspection was always ON, but that would lead to bigger parse tables for everybody. *) end module ErrorReports : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* -------------------------------------------------------------------------- *) (* The following functions help keep track of the start and end positions of the last two tokens in a two-place buffer. This is used to nicely display where a syntax error took place. *) type 'a buffer (* [wrap lexer] returns a pair of a new (initially empty) buffer and a lexer which internally relies on [lexer] and updates [buffer] on the fly whenever a token is demanded. *) open Lexing val wrap: (lexbuf -> 'token) -> (position * position) buffer * (lexbuf -> 'token) (* [show f buffer] prints the contents of the buffer, producing a string that is typically of the form "after '%s' and before '%s'". The function [f] is used to print an element. The buffer MUST be nonempty. *) val show: ('a -> string) -> 'a buffer -> string (* [last buffer] returns the last element of the buffer. The buffer MUST be nonempty. *) val last: 'a buffer -> 'a (* -------------------------------------------------------------------------- *) end module Printers : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This module is part of MenhirLib. *) module Make (I : IncrementalEngine.EVERYTHING) (User : sig (* [print s] is supposed to send the string [s] to some output channel. *) val print: string -> unit (* [print_symbol s] is supposed to print a representation of the symbol [s]. *) val print_symbol: I.xsymbol -> unit (* [print_element e] is supposed to print a representation of the element [e]. This function is optional; if it is not provided, [print_element_as_symbol] (defined below) is used instead. *) val print_element: (I.element -> unit) option end) : sig open I (* Printing a list of symbols. *) val print_symbols: xsymbol list -> unit (* Printing an element as a symbol. This prints just the symbol that this element represents; nothing more. *) val print_element_as_symbol: element -> unit (* Printing a stack as a list of elements. This function needs an element printer. It uses [print_element] if provided by the user; otherwise it uses [print_element_as_symbol]. (Ending with a newline.) *) val print_stack: 'a env -> unit (* Printing an item. (Ending with a newline.) *) val print_item: item -> unit (* Printing a production. (Ending with a newline.) *) val print_production: production -> unit (* Printing the current LR(1) state. The current state is first displayed as a number; then the list of its LR(0) items is printed. (Ending with a newline.) *) val print_current_state: 'a env -> unit (* Printing a summary of the stack and current state. This function just calls [print_stack] and [print_current_state] in succession. *) val print_env: 'a env -> unit end end module InfiniteArray : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (** This module implements infinite arrays. **) type 'a t (** [make x] creates an infinite array, where every slot contains [x]. **) val make: 'a -> 'a t (** [get a i] returns the element contained at offset [i] in the array [a]. Slots are numbered 0 and up. **) val get: 'a t -> int -> 'a (** [set a i x] sets the element contained at offset [i] in the array [a] to [x]. Slots are numbered 0 and up. **) val set: 'a t -> int -> 'a -> unit (** [extent a] is the length of an initial segment of the array [a] that is sufficiently large to contain all [set] operations ever performed. In other words, all elements beyond that segment have the default value. *) val extent: 'a t -> int (** [domain a] is a fresh copy of an initial segment of the array [a] whose length is [extent a]. *) val domain: 'a t -> 'a array end module PackedIntArray : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* A packed integer array is represented as a pair of an integer [k] and a string [s]. The integer [k] is the number of bits per integer that we use. The string [s] is just an array of bits, which is read in 8-bit chunks. *) (* The ocaml programming language treats string literals and array literals in slightly different ways: the former are statically allocated, while the latter are dynamically allocated. (This is rather arbitrary.) In the context of Menhir's table-based back-end, where compact, immutable integer arrays are needed, ocaml strings are preferable to ocaml arrays. *) type t = int * string (* [pack a] turns an array of integers into a packed integer array. *) (* Because the sign bit is the most significant bit, the magnitude of any negative number is the word size. In other words, [pack] does not achieve any space savings as soon as [a] contains any negative numbers, even if they are ``small''. *) val pack: int array -> t (* [get t i] returns the integer stored in the packed array [t] at index [i]. *) (* Together, [pack] and [get] satisfy the following property: if the index [i] is within bounds, then [get (pack a) i] equals [a.(i)]. *) val get: t -> int -> int (* [get1 t i] returns the integer stored in the packed array [t] at index [i]. It assumes (and does not check) that the array's bit width is [1]. The parameter [t] is just a string. *) val get1: string -> int -> int (* [unflatten1 (n, data) i j] accesses the two-dimensional bitmap represented by [(n, data)] at indices [i] and [j]. The integer [n] is the width of the bitmap; the string [data] is the second component of the packed array obtained by encoding the table as a one-dimensional array. *) val unflatten1: int * string -> int -> int -> int end module RowDisplacement : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This module compresses a two-dimensional table, where some values are considered insignificant, via row displacement. *) (* A compressed table is represented as a pair of arrays. The displacement array is an array of offsets into the data array. *) type 'a table = int array * (* displacement *) 'a array (* data *) (* [compress equal insignificant dummy m n t] turns the two-dimensional table [t] into a compressed table. The parameter [equal] is equality of data values. The parameter [wildcard] tells which data values are insignificant, and can thus be overwritten with other values. The parameter [dummy] is used to fill holes in the data array. [m] and [n] are the integer dimensions of the table [t]. *) val compress: ('a -> 'a -> bool) -> ('a -> bool) -> 'a -> int -> int -> 'a array array -> 'a table (* [get ct i j] returns the value found at indices [i] and [j] in the compressed table [ct]. This function call is permitted only if the value found at indices [i] and [j] in the original table is significant -- otherwise, it could fail abruptly. *) (* Together, [compress] and [get] have the property that, if the value found at indices [i] and [j] in an uncompressed table [t] is significant, then [get (compress t) i j] is equal to that value. *) val get: 'a table -> int -> int -> 'a (* [getget] is a variant of [get] which only requires read access, via accessors, to the two components of the table. *) val getget: ('displacement -> int -> int) -> ('data -> int -> 'a) -> 'displacement * 'data -> int -> int -> 'a end module LinearizedArray : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* An array of arrays (of possibly different lengths!) can be ``linearized'', i.e., encoded as a data array (by concatenating all of the little arrays) and an entry array (which contains offsets into the data array). *) type 'a t = (* data: *) 'a array * (* entry: *) int array (* [make a] turns the array of arrays [a] into a linearized array. *) val make: 'a array array -> 'a t (* [read la i j] reads the linearized array [la] at indices [i] and [j]. Thus, [read (make a) i j] is equivalent to [a.(i).(j)]. *) val read: 'a t -> int -> int -> 'a (* [write la i j v] writes the value [v] into the linearized array [la] at indices [i] and [j]. *) val write: 'a t -> int -> int -> 'a -> unit (* [length la] is the number of rows of the array [la]. Thus, [length (make a)] is equivalent to [Array.length a]. *) val length: 'a t -> int (* [row_length la i] is the length of the row at index [i] in the linearized array [la]. Thus, [row_length (make a) i] is equivalent to [Array.length a.(i)]. *) val row_length: 'a t -> int -> int (* [read_row la i] reads the row at index [i], producing a list. Thus, [read_row (make a) i] is equivalent to [Array.to_list a.(i)]. *) val read_row: 'a t -> int -> 'a list (* The following variants read the linearized array via accessors [get_data : int -> 'a] and [get_entry : int -> int]. *) val row_length_via: (* get_entry: *) (int -> int) -> (* i: *) int -> int val read_via: (* get_data: *) (int -> 'a) -> (* get_entry: *) (int -> int) -> (* i: *) int -> (* j: *) int -> 'a val read_row_via: (* get_data: *) (int -> 'a) -> (* get_entry: *) (int -> int) -> (* i: *) int -> 'a list end module TableFormat : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This signature defines the format of the parse tables. It is used as an argument to [TableInterpreter.Make]. *) module type TABLES = sig (* This is the parser's type of tokens. *) type token (* This maps a token to its internal (generation-time) integer code. *) val token2terminal: token -> int (* This is the integer code for the error pseudo-token. *) val error_terminal: int (* This maps a token to its semantic value. *) val token2value: token -> Obj.t (* Traditionally, an LR automaton is described by two tables, namely, an action table and a goto table. See, for instance, the Dragon book. The action table is a two-dimensional matrix that maps a state and a lookahead token to an action. An action is one of: shift to a certain state, reduce a certain production, accept, or fail. The goto table is a two-dimensional matrix that maps a state and a non-terminal symbol to either a state or undefined. By construction, this table is sparse: its undefined entries are never looked up. A compression technique is free to overlap them with other entries. In Menhir, things are slightly different. If a state has a default reduction on token [#], then that reduction must be performed without consulting the lookahead token. As a result, we must first determine whether that is the case, before we can obtain a lookahead token and use it as an index in the action table. Thus, Menhir's tables are as follows. A one-dimensional default reduction table maps a state to either ``no default reduction'' (encoded as: 0) or ``by default, reduce prod'' (encoded as: 1 + prod). The action table is looked up only when there is no default reduction. *) val default_reduction: PackedIntArray.t (* Menhir follows Dencker, Dürre and Heuft, who point out that, although the action table is not sparse by nature (i.e., the error entries are significant), it can be made sparse by first factoring out a binary error matrix, then replacing the error entries in the action table with undefined entries. Thus: A two-dimensional error bitmap maps a state and a terminal to either ``fail'' (encoded as: 0) or ``do not fail'' (encoded as: 1). The action table, which is now sparse, is looked up only in the latter case. *) (* The error bitmap is flattened into a one-dimensional table; its width is recorded so as to allow indexing. The table is then compressed via [PackedIntArray]. The bit width of the resulting packed array must be [1], so it is not explicitly recorded. *) (* The error bitmap does not contain a column for the [#] pseudo-terminal. Thus, its width is [Terminal.n - 1]. We exploit the fact that the integer code assigned to [#] is greatest: the fact that the right-most column in the bitmap is missing does not affect the code for accessing it. *) val error: int (* width of the bitmap *) * string (* second component of [PackedIntArray.t] *) (* A two-dimensional action table maps a state and a terminal to one of ``shift to state s and discard the current token'' (encoded as: s | 10), ``shift to state s without discarding the current token'' (encoded as: s | 11), or ``reduce prod'' (encoded as: prod | 01). *) (* The action table is first compressed via [RowDisplacement], then packed via [PackedIntArray]. *) (* Like the error bitmap, the action table does not contain a column for the [#] pseudo-terminal. *) val action: PackedIntArray.t * PackedIntArray.t (* A one-dimensional lhs table maps a production to its left-hand side (a non-terminal symbol). *) val lhs: PackedIntArray.t (* A two-dimensional goto table maps a state and a non-terminal symbol to either undefined (encoded as: 0) or a new state s (encoded as: 1 + s). *) (* The goto table is first compressed via [RowDisplacement], then packed via [PackedIntArray]. *) val goto: PackedIntArray.t * PackedIntArray.t (* The number of start productions. A production [prod] is a start production if and only if [prod < start] holds. This is also the number of start symbols. A nonterminal symbol [nt] is a start symbol if and only if [nt < start] holds. *) val start: int (* A one-dimensional semantic action table maps productions to semantic actions. The calling convention for semantic actions is described in [EngineTypes]. This table contains ONLY NON-START PRODUCTIONS, so the indexing is off by [start]. Be careful. *) val semantic_action: ((int, Obj.t, token) EngineTypes.env -> (int, Obj.t) EngineTypes.stack) array (* The parser defines its own [Error] exception. This exception can be raised by semantic actions and caught by the engine, and raised by the engine towards the final user. *) exception Error (* The parser indicates whether to generate a trace. Generating a trace requires two extra tables, which respectively map a terminal symbol and a production to a string. *) val trace: (string array * string array) option end end module InspectionTableFormat : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This signature defines the format of the tables that are produced (in addition to the tables described in [TableFormat]) when the command line switch [--inspection] is enabled. It is used as an argument to [InspectionTableInterpreter.Make]. *) module type TABLES = sig (* The types of symbols. *) include IncrementalEngine.SYMBOLS (* The type ['a lr1state] describes an LR(1) state. The generated parser defines it internally as [int]. *) type 'a lr1state (* Some of the tables that follow use encodings of (terminal and nonterminal) symbols as integers. So, we need functions that map the integer encoding of a symbol to its algebraic encoding. *) val terminal: int -> xsymbol val nonterminal: int -> xsymbol (* The left-hand side of every production already appears in the signature [TableFormat.TABLES], so we need not repeat it here. *) (* The right-hand side of every production. This a linearized array of arrays of integers, whose [data] and [entry] components have been packed. The encoding of symbols as integers in described in [TableBackend]. *) val rhs: PackedIntArray.t * PackedIntArray.t (* A mapping of every (non-initial) state to its LR(0) core. *) val lr0_core: PackedIntArray.t (* A mapping of every LR(0) state to its set of LR(0) items. Each item is represented in its packed form (see [Item]) as an integer. Thus the mapping is an array of arrays of integers, which is linearized and packed, like [rhs]. *) val lr0_items: PackedIntArray.t * PackedIntArray.t (* A mapping of every LR(0) state to its incoming symbol, if it has one. *) val lr0_incoming: PackedIntArray.t (* A table that tells which non-terminal symbols are nullable. *) val nullable: string (* This is a packed int array of bit width 1. It can be read using [PackedIntArray.get1]. *) (* A two-table dimensional table, indexed by a nonterminal symbol and by a terminal symbol (other than [#]), encodes the FIRST sets. *) val first: int (* width of the bitmap *) * string (* second component of [PackedIntArray.t] *) end end module InspectionTableInterpreter : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This functor is invoked inside the generated parser, in [--table] mode. It produces no code! It simply constructs the types [symbol] and [xsymbol] on top of the generated types [terminal] and [nonterminal]. *) module Symbols (T : sig type 'a terminal type 'a nonterminal end) : IncrementalEngine.SYMBOLS with type 'a terminal := 'a T.terminal and type 'a nonterminal := 'a T.nonterminal (* This functor is invoked inside the generated parser, in [--table] mode. It constructs the inspection API on top of the inspection tables described in [InspectionTableFormat]. *) module Make (TT : TableFormat.TABLES) (IT : InspectionTableFormat.TABLES with type 'a lr1state = int) (ET : EngineTypes.TABLE with type terminal = int and type nonterminal = int and type semantic_value = Obj.t) (E : sig type 'a env = (ET.state, ET.semantic_value, ET.token) EngineTypes.env end) : IncrementalEngine.INSPECTION with type 'a terminal := 'a IT.terminal and type 'a nonterminal := 'a IT.nonterminal and type 'a lr1state := 'a IT.lr1state and type production := int and type 'a env := 'a E.env end module TableInterpreter : sig (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (* This module provides a thin decoding layer for the generated tables, thus providing an API that is suitable for use by [Engine.Make]. It is part of [MenhirLib]. *) (* The exception [Error] is declared within the generated parser. This is preferable to pre-declaring it here, as it ensures that each parser gets its own, distinct [Error] exception. This is consistent with the code-based back-end. *) (* This functor is invoked by the generated parser. *) module MakeEngineTable (T : TableFormat.TABLES) : EngineTypes.TABLE with type state = int and type token = T.token and type semantic_value = Obj.t and type production = int and type terminal = int and type nonterminal = int end module StaticVersion : sig val require_20181113 : unit end
BellInterpreter.ml
module type Config = sig val debug : bool val debug_files : bool val verbose : int val libfind : string -> string val compat : bool val variant : string -> bool end module Make (C: Config) = struct let interpret_bell model = (* phew, a lot of work to set up the interpreter *) let module InterpreterConfig = struct (* Model *) let m = model (* Bell stuff *) let bell = true let bell_fname = None (* Model, restricted *) let showsome = false let debug = C.debug let debug_files = C.debug_files let verbose = C.verbose let skipchecks = StringSet.empty let strictskip = false let cycles = StringSet.empty let compat = C.compat (* Show control, useless.. *) let doshow = StringSet.empty let showraw = StringSet.empty let symetric = StringSet.empty let libfind = C.libfind (* Variant, coming from outer world *) let variant = C.variant end in (* A dummy semantics! *) let module UnitS = struct module E = struct type event = unit let event_compare () () = 0 let pp_eiid () = "eiid" let pp_instance () = "instance" let is_store () = false let is_pt () = false module Ordered = struct type t = unit let compare = event_compare end module EventSet = MySet.Make(Ordered) module EventRel = InnerRel.Make(Ordered) module EventMap = MyMap.Make(Ordered) end type test = unit type concrete = unit type event = E.event type event_set = E.EventSet.t type event_rel = E.EventRel.t type rel_pp = (string * event_rel) list type set_pp = event_set StringMap.t end in let module I = Interpreter.Make (InterpreterConfig) (UnitS) (struct (* Should not be called *) let partition_events _ = assert false let loc2events _ _ = assert false let check_through _ = assert false let pp_failure _ _ msg _ = if C.debug then eprintf "%s\n" msg let pp _ _ _ _ = () let fromto _ _ = assert false let same_value _ _ = assert false let same_oa _ _ = assert false let writable2 _ _ = assert false end) in let empty_test = () in (* construct an empty ks *) let conc = () in let evts = UnitS.E.EventSet.empty and id = lazy UnitS.E.EventRel.empty and unv = lazy UnitS.E.EventRel.empty and po = UnitS.E.EventRel.empty in let ks = {I.id; unv; evts; conc; po;} in let vb_pp = lazy [] in (* Continuation: notice that it should be called once at most *) let function_arg st res = match res with | None -> Some st.I.out_bell_info | Some _ -> assert false in (* call the interpreter and collect bell info *) match I.interpret empty_test Misc.identity ks I.init_env_empty vb_pp function_arg None with | None -> assert false (* Continuation must be called at least once *) | Some i -> if C.debug then begin eprintf "Bell file execute, result:\n" ; eprintf "%s" (BellModel.pp_info i) end ; i end
(****************************************************************************) (* the diy toolsuite *) (* *) (* Jade Alglave, University College London, UK. *) (* Luc Maranget, INRIA Paris-Rocquencourt, France. *) (* *) (* Copyright 2015-present Institut National de Recherche en Informatique et *) (* en Automatique and the authors. All rights reserved. *) (* *) (* This software is governed by the CeCILL-B license under French law and *) (* abiding by the rules of distribution of free software. You can use, *) (* modify and/ or redistribute the software under the terms of the CeCILL-B *) (* license as circulated by CEA, CNRS and INRIA at the following URL *) (* "http://www.cecill.info". We also give a copy in LICENSE.txt. *) (****************************************************************************) open Printf
node_services.ml
module S = struct let config = RPC_service.get_service ~description: "Return the runtime node configuration (this takes into account the \ command-line arguments and the on-disk configuration file)" ~query:RPC_query.empty ~output:Node_config_file.encoding RPC_path.(root / "config") end open RPC_context let config ctxt = make_call S.config ctxt () ()
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
test_conflict_handler.ml
(** Testing ------- Component: Plugin.Mempool Invocation: dune exec src/proto_alpha/lib_plugin/test/test_conflict_handler.exe Subject: Unit tests the Mempool.conflict_handler fonction of the plugin *) let pp_answer fmt = function | `Keep -> Format.fprintf fmt "Keep" | `Replace -> Format.fprintf fmt "Replace" let check_answer ?__LOC__ expected actual = assert (Qcheck2_helpers.qcheck_eq ~pp:pp_answer ?__LOC__ expected actual : bool) let is_manager_op ((_ : Operation_hash.t), op) = (* This is implemented differently from [Plugin.Mempool.is_manager_operation] (which relies on [Alpha_context.Operation.acceptable_pass]), used in [Plugin.Mempool.conflict_handler], to avoid the test being just a copy of the code. *) let {Alpha_context.protocol_data = Operation_data proto_data; _} = op in match proto_data.contents with | Single (Manager_operation _) | Cons (Manager_operation _, _) -> true | _ -> false (** Test that when the operations are not both manager operations, the conflict handler picks the higher operation according to [Operation.compare]. *) let test_random_ops () = let ops = let open Operation_generator in QCheck2.Gen.(generate ~n:100 (pair generate_operation generate_operation)) in List.iter (fun ((_, op1), (_, op2)) -> let answer = Plugin.Mempool.conflict_handler Plugin.Mempool.default_config ~existing_operation:op1 ~new_operation:op2 in if is_manager_op op1 && is_manager_op op2 then (* When both operations are manager operations, the result is complicated and depends on the [config]. Testing it here would mean basically reimplementing [conflict_handler]. Instead, we test this case in [test_manager_ops] below. *) () else if (* When there is at least one non-manager operation, the conflict handler defers to [Operation.compare]: the higher operation is selected. *) Alpha_context.Operation.compare op1 op2 >= 0 then check_answer ~__LOC__ `Keep answer else check_answer ~__LOC__ `Replace answer) ops ; return_unit (** Generator for a manager batch with the specified total fee and gas. *) let generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas = let open Alpha_context in let open QCheck2.Gen in let rec set_fee_and_gas : type kind. _ -> _ -> kind contents_list -> kind contents_list t = fun desired_total_fee desired_total_gas -> function | Single (Manager_operation data) -> let fee = Tez.of_mutez_exn (Int64.of_int desired_total_fee) in let gas_limit = Gas.Arith.integral_of_int_exn desired_total_gas in return (Single (Manager_operation {data with fee; gas_limit})) | Cons (Manager_operation data, tail) -> let* local_fee = (* We generate some corner cases where some individual operations in the batch have zero fees. *) let* r = frequencyl [(7, `Random); (2, `Zero); (1, `All)] in match r with | `Random -> int_range 0 desired_total_fee | `Zero -> return 0 | `All -> return desired_total_fee in let* local_gas = int_range 0 desired_total_gas in let fee = Tez.of_mutez_exn (Int64.of_int local_fee) in let gas_limit = Gas.Arith.integral_of_int_exn local_gas in let* tail = set_fee_and_gas (desired_total_fee - local_fee) (desired_total_gas - local_gas) tail in return (Cons (Manager_operation {data with fee; gas_limit}, tail)) | Single _ -> (* This function is only called on a manager operation. *) assert false in (* Generate a random manager operation. *) let* batch_size = int_range 1 Operation_generator.max_batch_size in let* op = Operation_generator.generate_manager_operation batch_size in (* Modify its fee and gas to match the [fee_in_mutez] and [gas] inputs. *) let {shell = _; protocol_data = Operation_data protocol_data} = op in let* contents = set_fee_and_gas fee_in_mutez gas protocol_data.contents in let protocol_data = {protocol_data with contents} in let op = {op with protocol_data = Operation_data protocol_data} in return (Operation.hash_packed op, op) let check_conflict_handler ~__LOC__ config ~old ~nw expected = let answer = Plugin.Mempool.conflict_handler config ~existing_operation:old ~new_operation:nw in check_answer ~__LOC__ expected answer (** Test the semantics of the conflict handler on manager operations, with either hand-picked or carefully generated fee and gas. *) let test_manager_ops () = let make_op ~fee_in_mutez ~gas = QCheck2.Gen.generate1 (generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas) in (* Test operations with specific fee and gas, using the default configuration. This configuration replaces the old operation when the new one is at least 5% better, in terms of both fees and fee/gas ratios. *) let default = Plugin.Mempool.default_config in let ref_fee = 10_000_000 in let ref_gas = 2100 in (* Reference operation arbitrarily has 10 tez of fees and 2100 gas. The gas is chosen to still give an integer when multiplied by 100/105. *) let old = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in (* Operation with same fee and ratio. *) let op_same = make_op ~fee_in_mutez:ref_fee ~gas:ref_gas in check_conflict_handler ~__LOC__ default ~old ~nw:op_same `Keep ; (* 5% better fee but same ratio (because gas is also 5% more). *) let more5 = Q.make (Z.of_int 105) (Z.of_int 100) in let fee_more5 = Q.(to_int (mul more5 (of_int ref_fee))) in let gas_more5 = Q.(to_int (mul more5 (of_int ref_gas))) in let op_fee5 = make_op ~fee_in_mutez:fee_more5 ~gas:gas_more5 in check_conflict_handler ~__LOC__ default ~old ~nw:op_fee5 `Keep ; (* 5% better ratio but same fee (because gas is multiplied by 100/105). *) let less5 = Q.make (Z.of_int 100) (Z.of_int 105) in let gas_less5 = Q.(to_int (mul less5 (of_int ref_gas))) in let op_ratio5 = make_op ~fee_in_mutez:ref_fee ~gas:gas_less5 in check_conflict_handler ~__LOC__ default ~old ~nw:op_ratio5 `Keep ; (* Both 5% better fee and 5% better ratio. *) let op_both5 = make_op ~fee_in_mutez:fee_more5 ~gas:ref_gas in check_conflict_handler ~__LOC__ default ~old ~nw:op_both5 `Replace ; (* Config that requires 10% better fee and ratio to replace. *) let config10 = { Plugin.Mempool.default_config with replace_by_fee_factor = Q.make (Z.of_int 11) (Z.of_int 10); } in check_conflict_handler ~__LOC__ config10 ~old ~nw:op_same `Keep ; check_conflict_handler ~__LOC__ config10 ~old ~nw:op_fee5 `Keep ; check_conflict_handler ~__LOC__ config10 ~old ~nw:op_ratio5 `Keep ; check_conflict_handler ~__LOC__ config10 ~old ~nw:op_both5 `Keep ; (* Config that replaces when the new op has at least as much fee and ratio. *) let config0 = {Plugin.Mempool.default_config with replace_by_fee_factor = Q.one} in check_conflict_handler ~__LOC__ config0 ~old ~nw:op_same `Replace ; check_conflict_handler ~__LOC__ config0 ~old ~nw:op_fee5 `Replace ; check_conflict_handler ~__LOC__ config0 ~old ~nw:op_ratio5 `Replace ; check_conflict_handler ~__LOC__ config0 ~old ~nw:op_both5 `Replace ; (* This config does not replace when the new operation has worse fees (even when the ratio is higher). *) let op_less_fee = make_op ~fee_in_mutez:(ref_fee - 1) ~gas:(ref_gas - 1) in check_conflict_handler ~__LOC__ default ~old ~nw:op_less_fee `Keep ; (* This config does not replace either when the ratio is smaller. *) let op_worse_ratio = make_op ~fee_in_mutez:ref_fee ~gas:(ref_gas + 1) in check_conflict_handler ~__LOC__ default ~old ~nw:op_worse_ratio `Keep ; (* Generate random operations which do not have 5% better fees than the reference [op]: they should not replace [op] when using the default config. *) let open QCheck2.Gen in let repeat = 30 in let max_gas = 5 * ref_gas in let generator_not_5more_fee = let* fee_in_mutez = int_range 0 (fee_more5 - 1) in let* gas = int_range 0 max_gas in Format.eprintf "op_not_fee5: fee = %d; gas = %d@." fee_in_mutez gas ; generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas in let ops_not_5more_fee = generate ~n:repeat generator_not_5more_fee in List.iter (fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep) ops_not_5more_fee ; (* Generate random operations which do not have 5% better ratio than the reference [op]: they should not replace [op] when using the default config. *) let ratio_5more = Q.(mul more5 (make (Z.of_int ref_fee) (Z.of_int ref_gas))) in let generator_not_5more_ratio = let* gas = int_range 0 max_gas in let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in let fee_upper_bound = Q.to_int fee_for_5more_ratio - 1 in let* fee_in_mutez = int_range 0 (max 0 fee_upper_bound) in Format.eprintf "op_not_ratio5: fee = %d; gas = %d@." fee_in_mutez gas ; generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas in let ops_not_5more_ratio = generate ~n:repeat generator_not_5more_ratio in List.iter (fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Keep) ops_not_5more_ratio ; (* Generate random operations which have both 5% higher fees and 5% better ratio than the reference [op]: they should replace [op] when using the default config. *) let max_fee = (* We use a significantly higher factor to define [max_fee] from [ref_fee] than [max_gas] from [ref_gas]. Therefore, even if we generate a gas equal to [max_gas], we can still generate a fee that makes the ratio at least 5% better than the reference operation's. *) 10 * ref_fee in let generator_both_5more = let* gas = int_range 0 max_gas in let fee_for_5more_ratio = Q.(mul (of_int gas) ratio_5more) in let fee_lower_bound = max fee_more5 (Q.to_int fee_for_5more_ratio + 1) in let* fee_in_mutez = int_range fee_lower_bound max_fee in Format.eprintf "op_both_better: fee = %d; gas = %d@." fee_in_mutez gas ; generate_manager_op_with_fee_and_gas ~fee_in_mutez ~gas in let ops_both_5more = generate ~n:repeat generator_both_5more in List.iter (fun nw -> check_conflict_handler ~__LOC__ default ~old ~nw `Replace) ops_both_5more ; return_unit let () = Alcotest_lwt.run "conflict_handler" [ ( "conflict_handler", [ Tztest.tztest "Random operations (not both manager)" `Quick test_random_ops; Tztest.tztest "Manager operations" `Quick test_manager_ops; ] ); ] |> Lwt_main.run
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
dune
; This file was automatically generated, do not edit. ; Edit file manifest/main.ml instead. (library (name tezos_signer_backends_unix) (public_name tezos-signer-backends.unix) (instrumentation (backend bisect_ppx)) (libraries ocplib-endian.bigstring fmt tezos-base tezos-base.unix tezos-stdlib-unix tezos-stdlib tezos-client-base tezos-rpc-http tezos-rpc-http-client tezos-rpc-http-client-unix tezos-signer-services tezos-signer-backends tezos-shell-services (select ledger.ml from (ledgerwallet-tezos -> ledger.available.ml) (-> ledger.none.ml))) (flags (:standard -open Tezos_base.TzPervasives -open Tezos_stdlib_unix -open Tezos_stdlib -open Tezos_client_base -open Tezos_rpc_http -open Tezos_rpc_http_client -open Tezos_rpc_http_client_unix -open Tezos_signer_services -open Tezos_signer_backends -open Tezos_shell_services)))
app_test.mli
(*_ This file intentionally left blank *)
(*_ This file intentionally left blank *)
oracle.mli
module type S = sig (** Interface for oracles Oracles provide a way to discard candidate invariants. The safety and correctness of Cubicle does not depend on the oracle, so any answer can be returned. However the efficiency of BRAB does. So the more precise the oracle, the better ! *) val init : Ast.t_system -> unit (** Initialize the oracle on a given system *) val first_good_candidate : Node.t list -> Node.t option (** Given a list of candidate invariants, returns the first one that seems to be indeed an invariant. *) end
(**************************************************************************) (* *) (* Cubicle *) (* *) (* Copyright (C) 2011-2014 *) (* *) (* Sylvain Conchon and Alain Mebsout *) (* Universite Paris-Sud 11 *) (* *) (* *) (* This file is distributed under the terms of the Apache Software *) (* License version 2.0 *) (* *) (**************************************************************************)
pretty.mli
open Format (** Pretty printing functions *) val vt_width : int (** Width of the virtual terminal (80 if cannot be detected) *) val print_line : formatter -> unit -> unit (** prints separating line *) val print_double_line : formatter -> unit -> unit (** prints separating double line *) val print_title : formatter -> string -> unit (** prints section title for stats *) val print_list : (formatter -> 'a -> unit) -> ('b, formatter, unit) format -> formatter -> 'a list -> unit (** [print_list f sep fmt l] prints list [l] whose elements are printed with [f], each of them being separated by the separator [sep]. *)
(**************************************************************************) (* *) (* Cubicle *) (* *) (* Copyright (C) 2011-2014 *) (* *) (* Sylvain Conchon and Alain Mebsout *) (* Universite Paris-Sud 11 *) (* *) (* *) (* This file is distributed under the terms of the Apache Software *) (* License version 2.0 *) (* *) (**************************************************************************)
yurt_request_ctx.ml
open Lwt.Infix module Request = Cohttp_lwt_unix.Request module Response = Cohttp.Response module Header = Cohttp.Header module Body = struct include Cohttp_lwt.Body type transfer_encoding = Cohttp.Transfer.encoding let to_string = Cohttp_lwt.Body.to_string let to_stream = Cohttp_lwt.Body.to_stream let to_json body = Cohttp_lwt.Body.to_string body >|= fun s -> Ezjsonm.from_string s let of_string = Cohttp_lwt.Body.of_string let of_stream = Cohttp_lwt.Body.of_stream let of_json j = Ezjsonm.to_string j |> Cohttp_lwt.Body.of_string let map = Cohttp_lwt.Body.map let length = Cohttp_lwt.Body.length let is_empty = Cohttp_lwt.Body.is_empty let drain = Cohttp_lwt.Body.drain_body let transfer_encoding = Cohttp_lwt.Body.transfer_encoding end (** Response status code *) type status_code = Cohttp.Code.status_code (** Response type *) and response = (Response.t * Body.t) Lwt.t (** HTTP handler *) and endpoint = Request.t -> Yurt_route.params -> Body.t -> response module Query = struct type t = (string, string list) Hashtbl.t let query_all (req : Request.t) : (string * string list) list = Uri.query (Request.uri req) let query_dict_of_query (q : (string * string list) list) = let d = Hashtbl.create 16 in List.iter (fun (k, v) -> if Hashtbl.mem d k then let l = Hashtbl.find d k in Hashtbl.replace d k (l @ v) else Hashtbl.replace d k v) q; d (** Get a hashtable of all query string parameters *) let get req : (string, string list) Hashtbl.t = query_dict_of_query (query_all req) (** Convert all query string paramters to a json object *) let to_json req : Ezjsonm.t = let f = query_all req in `O (List.map (fun (k, v) -> if List.length v = 1 then k, Ezjsonm.encode_string (List.nth v 0) else k, `A (List.map Ezjsonm.encode_string v)) f) (** Get a string value for a single query string value by key *) let string req (name : string) : string option = Uri.get_query_param (Request.uri req) name (** Get an int value for a single query string value by key *) let int req (name : string) : int option = let qs = string req name in match qs with | Some s -> begin try Some (int_of_string s) with _ -> None end | None -> None (** Get a float value for a single query string value by key*) let float req (name : string) : float option = let qe = string req name in match qe with | Some s -> begin try Some (float_of_string s) with _ -> None end | None -> None (** Get a json value for a single query string value by key*) let json req (name : string) = let qe = string req name in match qe with | Some s -> (try Some (Ezjsonm.from_string s) with _ -> None) | None -> None end
version.ml
let t = match Build_info.V1.version () with | None -> "n/a" | Some v -> Build_info.V1.Version.to_string v
equal_ui.c
#include "fexpr.h" int fexpr_equal_ui(const fexpr_t expr, ulong c) { if (c <= FEXPR_COEFF_MAX) return expr->data[0] == (c << FEXPR_TYPE_BITS); else return (expr->data[0] == (FEXPR_TYPE_BIG_INT_POS | (2 << FEXPR_TYPE_BITS)) && expr->data[1] == c); }
/* Copyright (C) 2021 Fredrik Johansson This file is part of Calcium. Calcium 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/>. */
info_gen.ml
let libraries = [ "base-bigarray", "base"; "base-threads", "base"; "base-unix", "base"; "cmdliner", "1.0.4"; "conf-m4", "1"; "dune", "2.0.0"; "fmt", "0.8.8"; "ocaml", "4.08.1"; "ocaml-base-compiler", "4.08.1"; "ocaml-config", "1"; "ocamlbuild", "0.14.0"; "ocamlfind", "1.8.1"; "seq", "base"; "stdlib-shims", "0.1.0"; "topkg", "1.0.1"] let info = Functoria_runtime.{ name = "foo"; libraries }
light.ml
module M : Tezos_proxy.Light_proto.PROTO_RPCS = struct let merkle_tree (pgi : Tezos_proxy.Proxy.proxy_getter_input) key leaf_kind = Protocol_client_context.Alpha_block_services.Context.merkle_tree pgi.rpc_context ~chain:pgi.chain ~block:pgi.block ~holey: (match leaf_kind with | Tezos_shell_services.Block_services.Hole -> true | Tezos_shell_services.Block_services.Raw_context -> false) key 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. *) (* *) (*****************************************************************************)
utop.ml
open Stdune open Import module Utop = Dune_rules.Utop let doc = "Load library in utop" let man = [ `S "DESCRIPTION" ; `P {|$(b,dune utop DIR) build and run utop toplevel with libraries defined in DIR|} ; `Blocks Common.help_secs ] let info = Cmd.info "utop" ~doc ~man let term = let+ common = Common.term and+ dir = Arg.(value & pos 0 string "" & Arg.info [] ~docv:"DIR") and+ ctx_name = Common.context_arg ~doc:{|Select context where to build/run utop.|} and+ args = Arg.(value & pos_right 0 string [] (Arg.info [] ~docv:"ARGS")) in let config = Common.init common in let dir = Common.prefix_target common dir in if not (Path.is_directory (Path.of_string dir)) then User_error.raise [ Pp.textf "cannot find directory: %s" (String.maybe_quoted dir) ]; let sctx, utop_path = Scheduler.go ~common ~config (fun () -> let open Fiber.O in let* setup = Import.Main.setup () in Build_system.run_exn (fun () -> let open Memo.O in let* setup = setup in let utop_target = let context = Import.Main.find_context_exn setup ~name:ctx_name in let utop_target = Filename.concat dir Utop.utop_exe in Path.build (Path.Build.relative context.build_dir utop_target) in Build_system.file_exists utop_target >>= function | false -> User_error.raise [ Pp.textf "no library is defined in %s" (String.maybe_quoted dir) ] | true -> let+ () = Build_system.build_file utop_target in let sctx = Import.Main.find_scontext_exn setup ~name:ctx_name in (sctx, Path.to_string utop_target))) in Hooks.End_of_build.run (); restore_cwd_and_execve common utop_path (utop_path :: args) (Super_context.context_env sctx) let command = Cmd.v info term
pa_local.ml
(* $Id$ *) #load "pa_extend.cmo"; #load "q_MLast.cmo"; open Pcaml; value expr_of_patt p = let loc = MLast.loc_of_patt p in match p with [ <:patt< $lid:x$ >> -> <:expr< $lid:x$ >> | _ -> Stdpp.raise_with_loc loc (Stream.Error "identifier expected") ] ; value fst3 (a,b,c) = a ; EXTEND str_item: [ [ "local"; rf = [ "rec" -> True | -> False ]; lb = LIST1 let_binding SEP "and"; "in"; "value"; rf1 = [ "rec" -> True | -> False ]; lb1 = LIST1 let_binding SEP "and" -> let pl = List.map fst3 lb1 in let el = List.map expr_of_patt pl in <:str_item< value ($list:pl$) = let $opt:rf$ $list:lb$ in let $opt:rf1$ $list:lb1$ in ($list:el$) >> ] ] ; END;
(***********************************************************************) (* *) (* Ledit *) (* *) (* Daniel de Rauglaudre, INRIA Rocquencourt *) (* *) (* Copyright 2001-2007 Institut National de Recherche en Informatique *) (* et Automatique. Distributed only by permission. *) (* *) (***********************************************************************)
blake2b_impl.c
/* WARNING: autogenerated file! * * The blake2s_impl.c is autogenerated from blake2b_impl.c. */ #ifndef Py_BUILD_CORE_BUILTIN # define Py_BUILD_CORE_MODULE 1 #endif #include "Python.h" #include "pycore_strhex.h" // _Py_strhex() #include "../hashlib.h" #include "blake2module.h" #ifndef HAVE_LIBB2 /* pure SSE2 implementation is very slow, so only use the more optimized SSSE3+ * https://bugs.python.org/issue31834 */ #if defined(__SSSE3__) || defined(__SSE4_1__) || defined(__AVX__) || defined(__XOP__) #include "impl/blake2b.c" #else #include "impl/blake2b-ref.c" #endif #endif // !HAVE_LIBB2 #define HAVE_BLAKE2B 1 extern PyType_Spec blake2b_type_spec; typedef struct { PyObject_HEAD blake2b_param param; blake2b_state state; PyThread_type_lock lock; } BLAKE2bObject; #include "clinic/blake2b_impl.c.h" /*[clinic input] module _blake2 class _blake2.blake2b "BLAKE2bObject *" "&PyBlake2_BLAKE2bType" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d47b0527b39c673f]*/ static BLAKE2bObject * new_BLAKE2bObject(PyTypeObject *type) { BLAKE2bObject *self; self = (BLAKE2bObject *)type->tp_alloc(type, 0); if (self != NULL) { self->lock = NULL; } return self; } /*[clinic input] @classmethod _blake2.blake2b.__new__ as py_blake2b_new data: object(c_default="NULL") = b'' / * digest_size: int(c_default="BLAKE2B_OUTBYTES") = _blake2.blake2b.MAX_DIGEST_SIZE key: Py_buffer(c_default="NULL", py_default="b''") = None salt: Py_buffer(c_default="NULL", py_default="b''") = None person: Py_buffer(c_default="NULL", py_default="b''") = None fanout: int = 1 depth: int = 1 leaf_size: unsigned_long = 0 node_offset: unsigned_long_long = 0 node_depth: int = 0 inner_size: int = 0 last_node: bool = False usedforsecurity: bool = True Return a new BLAKE2b hash object. [clinic start generated code]*/ static PyObject * py_blake2b_new_impl(PyTypeObject *type, PyObject *data, int digest_size, Py_buffer *key, Py_buffer *salt, Py_buffer *person, int fanout, int depth, unsigned long leaf_size, unsigned long long node_offset, int node_depth, int inner_size, int last_node, int usedforsecurity) /*[clinic end generated code: output=32bfd8f043c6896f input=b947312abff46977]*/ { BLAKE2bObject *self = NULL; Py_buffer buf; self = new_BLAKE2bObject(type); if (self == NULL) { goto error; } /* Zero parameter block. */ memset(&self->param, 0, sizeof(self->param)); /* Set digest size. */ if (digest_size <= 0 || digest_size > BLAKE2B_OUTBYTES) { PyErr_Format(PyExc_ValueError, "digest_size must be between 1 and %d bytes", BLAKE2B_OUTBYTES); goto error; } self->param.digest_length = digest_size; /* Set salt parameter. */ if ((salt->obj != NULL) && salt->len) { if (salt->len > BLAKE2B_SALTBYTES) { PyErr_Format(PyExc_ValueError, "maximum salt length is %d bytes", BLAKE2B_SALTBYTES); goto error; } memcpy(self->param.salt, salt->buf, salt->len); } /* Set personalization parameter. */ if ((person->obj != NULL) && person->len) { if (person->len > BLAKE2B_PERSONALBYTES) { PyErr_Format(PyExc_ValueError, "maximum person length is %d bytes", BLAKE2B_PERSONALBYTES); goto error; } memcpy(self->param.personal, person->buf, person->len); } /* Set tree parameters. */ if (fanout < 0 || fanout > 255) { PyErr_SetString(PyExc_ValueError, "fanout must be between 0 and 255"); goto error; } self->param.fanout = (uint8_t)fanout; if (depth <= 0 || depth > 255) { PyErr_SetString(PyExc_ValueError, "depth must be between 1 and 255"); goto error; } self->param.depth = (uint8_t)depth; if (leaf_size > 0xFFFFFFFFU) { PyErr_SetString(PyExc_OverflowError, "leaf_size is too large"); goto error; } // NB: Simple assignment here would be incorrect on big endian platforms. store32(&(self->param.leaf_length), leaf_size); #ifdef HAVE_BLAKE2S if (node_offset > 0xFFFFFFFFFFFFULL) { /* maximum 2**48 - 1 */ PyErr_SetString(PyExc_OverflowError, "node_offset is too large"); goto error; } store48(&(self->param.node_offset), node_offset); #else // NB: Simple assignment here would be incorrect on big endian platforms. store64(&(self->param.node_offset), node_offset); #endif if (node_depth < 0 || node_depth > 255) { PyErr_SetString(PyExc_ValueError, "node_depth must be between 0 and 255"); goto error; } self->param.node_depth = node_depth; if (inner_size < 0 || inner_size > BLAKE2B_OUTBYTES) { PyErr_Format(PyExc_ValueError, "inner_size must be between 0 and is %d", BLAKE2B_OUTBYTES); goto error; } self->param.inner_length = inner_size; /* Set key length. */ if ((key->obj != NULL) && key->len) { if (key->len > BLAKE2B_KEYBYTES) { PyErr_Format(PyExc_ValueError, "maximum key length is %d bytes", BLAKE2B_KEYBYTES); goto error; } self->param.key_length = (uint8_t)key->len; } /* Initialize hash state. */ if (blake2b_init_param(&self->state, &self->param) < 0) { PyErr_SetString(PyExc_RuntimeError, "error initializing hash state"); goto error; } /* Set last node flag (must come after initialization). */ self->state.last_node = last_node; /* Process key block if any. */ if (self->param.key_length) { uint8_t block[BLAKE2B_BLOCKBYTES]; memset(block, 0, sizeof(block)); memcpy(block, key->buf, key->len); blake2b_update(&self->state, block, sizeof(block)); secure_zero_memory(block, sizeof(block)); } /* Process initial data if any. */ if (data != NULL) { GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error); if (buf.len >= HASHLIB_GIL_MINSIZE) { Py_BEGIN_ALLOW_THREADS blake2b_update(&self->state, buf.buf, buf.len); Py_END_ALLOW_THREADS } else { blake2b_update(&self->state, buf.buf, buf.len); } PyBuffer_Release(&buf); } return (PyObject *)self; error: if (self != NULL) { Py_DECREF(self); } return NULL; } /*[clinic input] _blake2.blake2b.copy Return a copy of the hash object. [clinic start generated code]*/ static PyObject * _blake2_blake2b_copy_impl(BLAKE2bObject *self) /*[clinic end generated code: output=ff6acee5f93656ae input=e383c2d199fd8a2e]*/ { BLAKE2bObject *cpy; if ((cpy = new_BLAKE2bObject(Py_TYPE(self))) == NULL) return NULL; ENTER_HASHLIB(self); cpy->param = self->param; cpy->state = self->state; LEAVE_HASHLIB(self); return (PyObject *)cpy; } /*[clinic input] _blake2.blake2b.update data: object / Update this hash object's state with the provided bytes-like object. [clinic start generated code]*/ static PyObject * _blake2_blake2b_update(BLAKE2bObject *self, PyObject *data) /*[clinic end generated code: output=010dfcbe22654359 input=ffc4aa6a6a225d31]*/ { Py_buffer buf; GET_BUFFER_VIEW_OR_ERROUT(data, &buf); if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE) self->lock = PyThread_allocate_lock(); if (self->lock != NULL) { Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(self->lock, 1); blake2b_update(&self->state, buf.buf, buf.len); PyThread_release_lock(self->lock); Py_END_ALLOW_THREADS } else { blake2b_update(&self->state, buf.buf, buf.len); } PyBuffer_Release(&buf); Py_RETURN_NONE; } /*[clinic input] _blake2.blake2b.digest Return the digest value as a bytes object. [clinic start generated code]*/ static PyObject * _blake2_blake2b_digest_impl(BLAKE2bObject *self) /*[clinic end generated code: output=a5864660f4bfc61a input=7d21659e9c5fff02]*/ { uint8_t digest[BLAKE2B_OUTBYTES]; blake2b_state state_cpy; ENTER_HASHLIB(self); state_cpy = self->state; blake2b_final(&state_cpy, digest, self->param.digest_length); LEAVE_HASHLIB(self); return PyBytes_FromStringAndSize((const char *)digest, self->param.digest_length); } /*[clinic input] _blake2.blake2b.hexdigest Return the digest value as a string of hexadecimal digits. [clinic start generated code]*/ static PyObject * _blake2_blake2b_hexdigest_impl(BLAKE2bObject *self) /*[clinic end generated code: output=b5598a87d8794a60 input=76930f6946351f56]*/ { uint8_t digest[BLAKE2B_OUTBYTES]; blake2b_state state_cpy; ENTER_HASHLIB(self); state_cpy = self->state; blake2b_final(&state_cpy, digest, self->param.digest_length); LEAVE_HASHLIB(self); return _Py_strhex((const char *)digest, self->param.digest_length); } static PyMethodDef py_blake2b_methods[] = { _BLAKE2_BLAKE2B_COPY_METHODDEF _BLAKE2_BLAKE2B_DIGEST_METHODDEF _BLAKE2_BLAKE2B_HEXDIGEST_METHODDEF _BLAKE2_BLAKE2B_UPDATE_METHODDEF {NULL, NULL} }; static PyObject * py_blake2b_get_name(BLAKE2bObject *self, void *closure) { return PyUnicode_FromString("blake2b"); } static PyObject * py_blake2b_get_block_size(BLAKE2bObject *self, void *closure) { return PyLong_FromLong(BLAKE2B_BLOCKBYTES); } static PyObject * py_blake2b_get_digest_size(BLAKE2bObject *self, void *closure) { return PyLong_FromLong(self->param.digest_length); } static PyGetSetDef py_blake2b_getsetters[] = { {"name", (getter)py_blake2b_get_name, NULL, NULL, NULL}, {"block_size", (getter)py_blake2b_get_block_size, NULL, NULL, NULL}, {"digest_size", (getter)py_blake2b_get_digest_size, NULL, NULL, NULL}, {NULL} }; static void py_blake2b_dealloc(PyObject *self) { BLAKE2bObject *obj = (BLAKE2bObject *)self; /* Try not to leave state in memory. */ secure_zero_memory(&obj->param, sizeof(obj->param)); secure_zero_memory(&obj->state, sizeof(obj->state)); if (obj->lock) { PyThread_free_lock(obj->lock); obj->lock = NULL; } PyTypeObject *type = Py_TYPE(self); PyObject_Free(self); Py_DECREF(type); } static PyType_Slot blake2b_type_slots[] = { {Py_tp_dealloc, py_blake2b_dealloc}, {Py_tp_doc, (char *)py_blake2b_new__doc__}, {Py_tp_methods, py_blake2b_methods}, {Py_tp_getset, py_blake2b_getsetters}, {Py_tp_new, py_blake2b_new}, {0,0} }; PyType_Spec blake2b_type_spec = { .name = "_blake2.blake2b", .basicsize = sizeof(BLAKE2bObject), .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE, .slots = blake2b_type_slots };
/* * Written in 2013 by Dmitry Chestnykh <dmitry@codingrobots.com> * Modified for CPython by Christian Heimes <christian@python.org> * * To the extent possible under law, the author have dedicated all * copyright and related and neighboring rights to this software to * the public domain worldwide. This software is distributed without * any warranty. http://creativecommons.org/publicdomain/zero/1.0/ */
aligner_sig.ml
[@@@warning "+A"] module type CONTENTS = (sig type contents val contents_length: contents -> int val pp: Format.formatter -> contents -> unit end) module type ALIGNER = (sig type contents type _tree_contents = | Leaf of contents | Node of tree_contents list and tree_contents = { node: _tree_contents; fill_with: char; align: Alignment.alignment; } val leaf: ?fill_with:char -> ?align:Alignment.alignment -> contents -> tree_contents val node: ?fill_with:char -> ?align:Alignment.alignment -> tree_contents list -> tree_contents val tree_size : tree_contents -> Size_tree.t val tree_size_of_list : tree_contents list -> Size_tree.t option val print_tree_with_size: ?trailing_whitespaces:bool -> Size_tree.t -> Format.formatter -> tree_contents -> unit val print_table: ?trailing_whitespaces:bool -> Format.formatter -> tree_contents list -> unit val kprint_table: ?trailing_whitespaces:bool -> (Format.formatter -> unit) -> Format.formatter -> tree_contents list -> unit val stringify_table: ?trailing_whitespaces:bool -> tree_contents list -> string list val pp_of_table: ?trailing_whitespaces:bool -> tree_contents list -> (Format.formatter -> unit) list end)
pycore_ast_state.h
// File automatically generated by Parser/asdl_c.py. #ifndef Py_INTERNAL_AST_STATE_H #define Py_INTERNAL_AST_STATE_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif struct ast_state { int initialized; int recursion_depth; int recursion_limit; PyObject *AST_type; PyObject *Add_singleton; PyObject *Add_type; PyObject *And_singleton; PyObject *And_type; PyObject *AnnAssign_type; PyObject *Assert_type; PyObject *Assign_type; PyObject *AsyncFor_type; PyObject *AsyncFunctionDef_type; PyObject *AsyncWith_type; PyObject *Attribute_type; PyObject *AugAssign_type; PyObject *Await_type; PyObject *BinOp_type; PyObject *BitAnd_singleton; PyObject *BitAnd_type; PyObject *BitOr_singleton; PyObject *BitOr_type; PyObject *BitXor_singleton; PyObject *BitXor_type; PyObject *BoolOp_type; PyObject *Break_type; PyObject *Call_type; PyObject *ClassDef_type; PyObject *Compare_type; PyObject *Constant_type; PyObject *Continue_type; PyObject *Del_singleton; PyObject *Del_type; PyObject *Delete_type; PyObject *DictComp_type; PyObject *Dict_type; PyObject *Div_singleton; PyObject *Div_type; PyObject *Eq_singleton; PyObject *Eq_type; PyObject *ExceptHandler_type; PyObject *Expr_type; PyObject *Expression_type; PyObject *FloorDiv_singleton; PyObject *FloorDiv_type; PyObject *For_type; PyObject *FormattedValue_type; PyObject *FunctionDef_type; PyObject *FunctionType_type; PyObject *GeneratorExp_type; PyObject *Global_type; PyObject *GtE_singleton; PyObject *GtE_type; PyObject *Gt_singleton; PyObject *Gt_type; PyObject *IfExp_type; PyObject *If_type; PyObject *ImportFrom_type; PyObject *Import_type; PyObject *In_singleton; PyObject *In_type; PyObject *Interactive_type; PyObject *Invert_singleton; PyObject *Invert_type; PyObject *IsNot_singleton; PyObject *IsNot_type; PyObject *Is_singleton; PyObject *Is_type; PyObject *JoinedStr_type; PyObject *LShift_singleton; PyObject *LShift_type; PyObject *Lambda_type; PyObject *ListComp_type; PyObject *List_type; PyObject *Load_singleton; PyObject *Load_type; PyObject *LtE_singleton; PyObject *LtE_type; PyObject *Lt_singleton; PyObject *Lt_type; PyObject *MatMult_singleton; PyObject *MatMult_type; PyObject *MatchAs_type; PyObject *MatchClass_type; PyObject *MatchMapping_type; PyObject *MatchOr_type; PyObject *MatchSequence_type; PyObject *MatchSingleton_type; PyObject *MatchStar_type; PyObject *MatchValue_type; PyObject *Match_type; PyObject *Mod_singleton; PyObject *Mod_type; PyObject *Module_type; PyObject *Mult_singleton; PyObject *Mult_type; PyObject *Name_type; PyObject *NamedExpr_type; PyObject *Nonlocal_type; PyObject *NotEq_singleton; PyObject *NotEq_type; PyObject *NotIn_singleton; PyObject *NotIn_type; PyObject *Not_singleton; PyObject *Not_type; PyObject *Or_singleton; PyObject *Or_type; PyObject *Pass_type; PyObject *Pow_singleton; PyObject *Pow_type; PyObject *RShift_singleton; PyObject *RShift_type; PyObject *Raise_type; PyObject *Return_type; PyObject *SetComp_type; PyObject *Set_type; PyObject *Slice_type; PyObject *Starred_type; PyObject *Store_singleton; PyObject *Store_type; PyObject *Sub_singleton; PyObject *Sub_type; PyObject *Subscript_type; PyObject *TryStar_type; PyObject *Try_type; PyObject *Tuple_type; PyObject *TypeIgnore_type; PyObject *UAdd_singleton; PyObject *UAdd_type; PyObject *USub_singleton; PyObject *USub_type; PyObject *UnaryOp_type; PyObject *While_type; PyObject *With_type; PyObject *YieldFrom_type; PyObject *Yield_type; PyObject *__dict__; PyObject *__doc__; PyObject *__match_args__; PyObject *__module__; PyObject *_attributes; PyObject *_fields; PyObject *alias_type; PyObject *annotation; PyObject *arg; PyObject *arg_type; PyObject *args; PyObject *argtypes; PyObject *arguments_type; PyObject *asname; PyObject *ast; PyObject *attr; PyObject *bases; PyObject *body; PyObject *boolop_type; PyObject *cases; PyObject *cause; PyObject *cls; PyObject *cmpop_type; PyObject *col_offset; PyObject *comparators; PyObject *comprehension_type; PyObject *context_expr; PyObject *conversion; PyObject *ctx; PyObject *decorator_list; PyObject *defaults; PyObject *elt; PyObject *elts; PyObject *end_col_offset; PyObject *end_lineno; PyObject *exc; PyObject *excepthandler_type; PyObject *expr_context_type; PyObject *expr_type; PyObject *finalbody; PyObject *format_spec; PyObject *func; PyObject *generators; PyObject *guard; PyObject *handlers; PyObject *id; PyObject *ifs; PyObject *is_async; PyObject *items; PyObject *iter; PyObject *key; PyObject *keys; PyObject *keyword_type; PyObject *keywords; PyObject *kind; PyObject *kw_defaults; PyObject *kwarg; PyObject *kwd_attrs; PyObject *kwd_patterns; PyObject *kwonlyargs; PyObject *left; PyObject *level; PyObject *lineno; PyObject *lower; PyObject *match_case_type; PyObject *mod_type; PyObject *module; PyObject *msg; PyObject *name; PyObject *names; PyObject *op; PyObject *operand; PyObject *operator_type; PyObject *ops; PyObject *optional_vars; PyObject *orelse; PyObject *pattern; PyObject *pattern_type; PyObject *patterns; PyObject *posonlyargs; PyObject *rest; PyObject *returns; PyObject *right; PyObject *simple; PyObject *slice; PyObject *step; PyObject *stmt_type; PyObject *subject; PyObject *tag; PyObject *target; PyObject *targets; PyObject *test; PyObject *type; PyObject *type_comment; PyObject *type_ignore_type; PyObject *type_ignores; PyObject *unaryop_type; PyObject *upper; PyObject *value; PyObject *values; PyObject *vararg; PyObject *withitem_type; }; #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_AST_STATE_H */
randtest.c
#include "padic.h" #define PADIC_RANDTEST_TRIES 10 void padic_randtest(padic_t rop, flint_rand_t state, const padic_ctx_t ctx) { const slong N = padic_prec(rop); slong min, max; fmpz_t pow; int alloc; if (N > 0) { min = - ((N + 9) / 10); max = N; } else if (N < 0) { min = N - ((-N + 9) / 10); max = N; } else /* ctx->N == 0 */ { min = -10; max = 0; } padic_val(rop) = n_randint(state, max - min) + min; alloc = _padic_ctx_pow_ui(pow, N - padic_val(rop), ctx); fmpz_randm(padic_unit(rop), state, pow); _padic_canonicalise(rop, ctx); if (alloc) fmpz_clear(pow); } void padic_randtest_not_zero(padic_t rop, flint_rand_t state, const padic_ctx_t ctx) { slong i; padic_randtest(rop, state, ctx); for (i = 1; !padic_is_zero(rop) && i < PADIC_RANDTEST_TRIES; i++) padic_randtest(rop, state, ctx); if (padic_is_zero(rop)) { fmpz_one(padic_unit(rop)); padic_val(rop) = padic_prec(rop) - 1; } } void padic_randtest_int(padic_t rop, flint_rand_t state, const padic_ctx_t ctx) { const slong N = padic_prec(rop); if (N <= 0) { padic_zero(rop); } else { fmpz_t pow; int alloc; padic_val(rop) = n_randint(state, N); alloc = _padic_ctx_pow_ui(pow, N - padic_val(rop), ctx); fmpz_randm(padic_unit(rop), state, pow); _padic_canonicalise(rop, ctx); if (alloc) fmpz_clear(pow); } }
/* Copyright (C) 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/>. */
conex_key.ml
open Conex_utils open Conex_resource open Conex_opts open Conex_nc let jump _ id force pub = Nocrypto_entropy_unix.initialize () ; msg_to_cmdliner (match id with | None -> Error "need an id" | Some id -> let fp k = let public = PRIV.pub_of_priv k in Logs.app (fun m -> m "key %s created %s keyid %s" (PRIV.id k) (PRIV.created k) (Digest.to_string (Key.keyid V.raw_digest public))) ; if pub then Logs.app (fun m -> m "public key: %a@.%s" Conex_resource.Key.pp public (Conex_opam_encoding.encode (Key.wire public))) ; Ok () in let gen_or_err () = PRIV.generate to_ts `RSA id () >>= fun t -> Logs.app (fun m -> m "generated fresh key") ; fp t in if force then gen_or_err () else match PRIV.read to_ts id with | Ok key -> fp key | Error `None -> gen_or_err () | Error e -> Error (Fmt.to_to_string PRIV.pp_r_err e)) let setup_log style_renderer level = Fmt_tty.setup_std_outputs ?style_renderer (); Logs.set_level level; Logs.set_reporter (Logs_fmt.reporter ~dst:Format.std_formatter ()) open Cmdliner let docs = Keys.docs let setup_log = Term.(const setup_log $ Fmt_cli.style_renderer ~docs () $ Logs_cli.level ~docs ()) let pub = let doc = "Display full public key." in Arg.(value & flag & info ["pub"] ~docs ~doc) let cmd = let doc = "key management" in Term.(ret (const jump $ setup_log $ Keys.id $ Keys.force $ pub)), Term.info "conex_key" ~version:"0.11.0" ~doc let () = match Term.eval cmd with `Ok () -> exit 0 | _ -> exit 1
solo5_os.mli
module Lifecycle : sig val await_shutdown_request : ?can_poweroff:bool -> ?can_reboot:bool -> unit -> [ `Poweroff | `Reboot ] Lwt.t (** [await_shutdown_request ()] is thread that resolves when the domain is asked to shut down. The optional [poweroff] (default:[true]) and [reboot] (default:[false]) arguments can be used to indicate which features the caller wants to advertise (however, you can still get a request for a mode you didn't claim to support). *) end module Main : sig val wait_for_work_on_handle : int64 -> unit Lwt.t val run : unit Lwt.t -> unit end module Memory : sig (** Memory management operations. *) type stat = { heap_words : int; (** total number of words allocatable on the heap. *) live_words : int; (** number of live (i.e. allocated) words on the heap. *) stack_words : int; (** number of words in use by the program stack. This includes any space reserved by a stack guard. *) free_words : int; (** number of free (i.e. allocatable) words on the heap. *) } (** Memory allocation statistics. Units are the system word size, as used by the OCaml stdlib Gc module. *) val stat : unit -> stat (** [stat ()] returns memory allocation statistics. This uses mallinfo and walks over the entire heap. This call is slower than {!quick_stat}. *) val quick_stat : unit -> stat (** [quick_stat ()] returns memory allocation statistics. This call uses a precomputed value. This call is cheaper than {!stat}, but the returned values may not be completely accurate. *) val trim : unit -> unit (** [trim ()] release free memory from the heap (may update the value returned by {!quick_stat}) *) val metrics : ?quick:bool -> tags:'a Metrics.Tags.t -> unit -> ('a, unit -> Metrics.Data.t) Metrics.src (** [metrics ~quick ~tags] is a metrics source calling {quick_stat} (unless [quick] is set to [false]) or {stat}. By default, this metrics source is registered with [Metrics_lwt.periodically] (with [quick] set to [true]. *) end module Time : sig val sleep_ns : int64 -> unit Lwt.t (** [sleep_ns d] Block the current thread for [n] nanoseconds. *) end module Solo5 : sig type solo5_result = | SOLO5_R_OK | SOLO5_R_AGAIN | SOLO5_R_EINVAL | SOLO5_R_EUNSPEC (** A type mapping the C enum solo5_result_t to OCaml **) end
cocoa_platform.h
//======================================================================== // GLFW 3.4 macOS - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== #include <stdint.h> #include <Carbon/Carbon.h> #include <IOKit/hid/IOHIDLib.h> // NOTE: All of NSGL was deprecated in the 10.14 SDK // This disables the pointless warnings for every symbol we use #ifndef GL_SILENCE_DEPRECATION #define GL_SILENCE_DEPRECATION #endif #if defined(__OBJC__) #import <Cocoa/Cocoa.h> #else typedef void* id; #endif // NOTE: Many Cocoa enum values have been renamed and we need to build across // SDK versions where one is unavailable or deprecated. // We use the newer names in code and replace them with the older names if // the base SDK does not provide the newer names. #if MAC_OS_X_VERSION_MAX_ALLOWED < 101400 #define NSOpenGLContextParameterSwapInterval NSOpenGLCPSwapInterval #define NSOpenGLContextParameterSurfaceOpacity NSOpenGLCPSurfaceOpacity #endif #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 #define NSBitmapFormatAlphaNonpremultiplied NSAlphaNonpremultipliedBitmapFormat #define NSEventMaskAny NSAnyEventMask #define NSEventMaskKeyUp NSKeyUpMask #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask #define NSEventModifierFlagCommand NSCommandKeyMask #define NSEventModifierFlagControl NSControlKeyMask #define NSEventModifierFlagDeviceIndependentFlagsMask NSDeviceIndependentModifierFlagsMask #define NSEventModifierFlagOption NSAlternateKeyMask #define NSEventModifierFlagShift NSShiftKeyMask #define NSEventTypeApplicationDefined NSApplicationDefined #define NSWindowStyleMaskBorderless NSBorderlessWindowMask #define NSWindowStyleMaskClosable NSClosableWindowMask #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask #define NSWindowStyleMaskResizable NSResizableWindowMask #define NSWindowStyleMaskTitled NSTitledWindowMask #endif // NOTE: Many Cocoa dynamically linked constants have been renamed and we need // to build across SDK versions where one is unavailable or deprecated. // We use the newer names in code and replace them with the older names if // the deployment target is older than the newer names. #if MAC_OS_X_VERSION_MIN_REQUIRED < 101300 #define NSPasteboardTypeURL NSURLPboardType #endif typedef VkFlags VkMacOSSurfaceCreateFlagsMVK; typedef VkFlags VkMetalSurfaceCreateFlagsEXT; typedef struct VkMacOSSurfaceCreateInfoMVK { VkStructureType sType; const void* pNext; VkMacOSSurfaceCreateFlagsMVK flags; const void* pView; } VkMacOSSurfaceCreateInfoMVK; typedef struct VkMetalSurfaceCreateInfoEXT { VkStructureType sType; const void* pNext; VkMetalSurfaceCreateFlagsEXT flags; const void* pLayer; } VkMetalSurfaceCreateInfoEXT; typedef VkResult (APIENTRY *PFN_vkCreateMacOSSurfaceMVK)(VkInstance,const VkMacOSSurfaceCreateInfoMVK*,const VkAllocationCallbacks*,VkSurfaceKHR*); typedef VkResult (APIENTRY *PFN_vkCreateMetalSurfaceEXT)(VkInstance,const VkMetalSurfaceCreateInfoEXT*,const VkAllocationCallbacks*,VkSurfaceKHR*); #define GLFW_COCOA_WINDOW_STATE _GLFWwindowNS ns; #define GLFW_COCOA_LIBRARY_WINDOW_STATE _GLFWlibraryNS ns; #define GLFW_COCOA_MONITOR_STATE _GLFWmonitorNS ns; #define GLFW_COCOA_CURSOR_STATE _GLFWcursorNS ns; #define GLFW_NSGL_CONTEXT_STATE _GLFWcontextNSGL nsgl; #define GLFW_NSGL_LIBRARY_CONTEXT_STATE _GLFWlibraryNSGL nsgl; // HIToolbox.framework pointer typedefs #define kTISPropertyUnicodeKeyLayoutData _glfw.ns.tis.kPropertyUnicodeKeyLayoutData typedef TISInputSourceRef (*PFN_TISCopyCurrentKeyboardLayoutInputSource)(void); #define TISCopyCurrentKeyboardLayoutInputSource _glfw.ns.tis.CopyCurrentKeyboardLayoutInputSource typedef void* (*PFN_TISGetInputSourceProperty)(TISInputSourceRef,CFStringRef); #define TISGetInputSourceProperty _glfw.ns.tis.GetInputSourceProperty typedef UInt8 (*PFN_LMGetKbdType)(void); #define LMGetKbdType _glfw.ns.tis.GetKbdType // NSGL-specific per-context data // typedef struct _GLFWcontextNSGL { id pixelFormat; id object; } _GLFWcontextNSGL; // NSGL-specific global data // typedef struct _GLFWlibraryNSGL { // dlopen handle for OpenGL.framework (for glfwGetProcAddress) CFBundleRef framework; } _GLFWlibraryNSGL; // Cocoa-specific per-window data // typedef struct _GLFWwindowNS { id object; id delegate; id view; id layer; GLFWbool maximized; GLFWbool occluded; GLFWbool retina; // Cached window properties to filter out duplicate events int width, height; int fbWidth, fbHeight; float xscale, yscale; // The total sum of the distances the cursor has been warped // since the last cursor motion event was processed // This is kept to counteract Cocoa doing the same internally double cursorWarpDeltaX, cursorWarpDeltaY; } _GLFWwindowNS; // Cocoa-specific global data // typedef struct _GLFWlibraryNS { CGEventSourceRef eventSource; id delegate; GLFWbool cursorHidden; TISInputSourceRef inputSource; IOHIDManagerRef hidManager; id unicodeData; id helper; id keyUpMonitor; id nibObjects; char keynames[GLFW_KEY_LAST + 1][17]; short int keycodes[256]; short int scancodes[GLFW_KEY_LAST + 1]; char* clipboardString; CGPoint cascadePoint; // Where to place the cursor when re-enabled double restoreCursorPosX, restoreCursorPosY; // The window whose disabled cursor mode is active _GLFWwindow* disabledCursorWindow; struct { CFBundleRef bundle; PFN_TISCopyCurrentKeyboardLayoutInputSource CopyCurrentKeyboardLayoutInputSource; PFN_TISGetInputSourceProperty GetInputSourceProperty; PFN_LMGetKbdType GetKbdType; CFStringRef kPropertyUnicodeKeyLayoutData; } tis; } _GLFWlibraryNS; // Cocoa-specific per-monitor data // typedef struct _GLFWmonitorNS { CGDirectDisplayID displayID; CGDisplayModeRef previousMode; uint32_t unitNumber; id screen; double fallbackRefreshRate; } _GLFWmonitorNS; // Cocoa-specific per-cursor data // typedef struct _GLFWcursorNS { id object; } _GLFWcursorNS; GLFWbool _glfwConnectCocoa(int platformID, _GLFWplatform* platform); int _glfwInitCocoa(void); void _glfwTerminateCocoa(void); GLFWbool _glfwCreateWindowCocoa(_GLFWwindow* window, const _GLFWwndconfig* wndconfig, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig); void _glfwDestroyWindowCocoa(_GLFWwindow* window); void _glfwSetWindowTitleCocoa(_GLFWwindow* window, const char* title); void _glfwSetWindowIconCocoa(_GLFWwindow* window, int count, const GLFWimage* images); void _glfwGetWindowPosCocoa(_GLFWwindow* window, int* xpos, int* ypos); void _glfwSetWindowPosCocoa(_GLFWwindow* window, int xpos, int ypos); void _glfwGetWindowSizeCocoa(_GLFWwindow* window, int* width, int* height); void _glfwSetWindowSizeCocoa(_GLFWwindow* window, int width, int height); void _glfwSetWindowSizeLimitsCocoa(_GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight); void _glfwSetWindowAspectRatioCocoa(_GLFWwindow* window, int numer, int denom); void _glfwGetFramebufferSizeCocoa(_GLFWwindow* window, int* width, int* height); void _glfwGetWindowFrameSizeCocoa(_GLFWwindow* window, int* left, int* top, int* right, int* bottom); void _glfwGetWindowContentScaleCocoa(_GLFWwindow* window, float* xscale, float* yscale); void _glfwIconifyWindowCocoa(_GLFWwindow* window); void _glfwRestoreWindowCocoa(_GLFWwindow* window); void _glfwMaximizeWindowCocoa(_GLFWwindow* window); void _glfwShowWindowCocoa(_GLFWwindow* window); void _glfwHideWindowCocoa(_GLFWwindow* window); void _glfwRequestWindowAttentionCocoa(_GLFWwindow* window); void _glfwFocusWindowCocoa(_GLFWwindow* window); void _glfwSetWindowMonitorCocoa(_GLFWwindow* window, _GLFWmonitor* monitor, int xpos, int ypos, int width, int height, int refreshRate); GLFWbool _glfwWindowFocusedCocoa(_GLFWwindow* window); GLFWbool _glfwWindowIconifiedCocoa(_GLFWwindow* window); GLFWbool _glfwWindowVisibleCocoa(_GLFWwindow* window); GLFWbool _glfwWindowMaximizedCocoa(_GLFWwindow* window); GLFWbool _glfwWindowHoveredCocoa(_GLFWwindow* window); GLFWbool _glfwFramebufferTransparentCocoa(_GLFWwindow* window); void _glfwSetWindowResizableCocoa(_GLFWwindow* window, GLFWbool enabled); void _glfwSetWindowDecoratedCocoa(_GLFWwindow* window, GLFWbool enabled); void _glfwSetWindowFloatingCocoa(_GLFWwindow* window, GLFWbool enabled); float _glfwGetWindowOpacityCocoa(_GLFWwindow* window); void _glfwSetWindowOpacityCocoa(_GLFWwindow* window, float opacity); void _glfwSetWindowMousePassthroughCocoa(_GLFWwindow* window, GLFWbool enabled); void _glfwSetRawMouseMotionCocoa(_GLFWwindow *window, GLFWbool enabled); GLFWbool _glfwRawMouseMotionSupportedCocoa(void); void _glfwPollEventsCocoa(void); void _glfwWaitEventsCocoa(void); void _glfwWaitEventsTimeoutCocoa(double timeout); void _glfwPostEmptyEventCocoa(void); void _glfwGetCursorPosCocoa(_GLFWwindow* window, double* xpos, double* ypos); void _glfwSetCursorPosCocoa(_GLFWwindow* window, double xpos, double ypos); void _glfwSetCursorModeCocoa(_GLFWwindow* window, int mode); const char* _glfwGetScancodeNameCocoa(int scancode); int _glfwGetKeyScancodeCocoa(int key); GLFWbool _glfwCreateCursorCocoa(_GLFWcursor* cursor, const GLFWimage* image, int xhot, int yhot); GLFWbool _glfwCreateStandardCursorCocoa(_GLFWcursor* cursor, int shape); void _glfwDestroyCursorCocoa(_GLFWcursor* cursor); void _glfwSetCursorCocoa(_GLFWwindow* window, _GLFWcursor* cursor); void _glfwSetClipboardStringCocoa(const char* string); const char* _glfwGetClipboardStringCocoa(void); EGLenum _glfwGetEGLPlatformCocoa(EGLint** attribs); EGLNativeDisplayType _glfwGetEGLNativeDisplayCocoa(void); EGLNativeWindowType _glfwGetEGLNativeWindowCocoa(_GLFWwindow* window); void _glfwGetRequiredInstanceExtensionsCocoa(char** extensions); GLFWbool _glfwGetPhysicalDevicePresentationSupportCocoa(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily); VkResult _glfwCreateWindowSurfaceCocoa(VkInstance instance, _GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); void _glfwFreeMonitorCocoa(_GLFWmonitor* monitor); void _glfwGetMonitorPosCocoa(_GLFWmonitor* monitor, int* xpos, int* ypos); void _glfwGetMonitorContentScaleCocoa(_GLFWmonitor* monitor, float* xscale, float* yscale); void _glfwGetMonitorWorkareaCocoa(_GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* height); GLFWvidmode* _glfwGetVideoModesCocoa(_GLFWmonitor* monitor, int* count); void _glfwGetVideoModeCocoa(_GLFWmonitor* monitor, GLFWvidmode* mode); GLFWbool _glfwGetGammaRampCocoa(_GLFWmonitor* monitor, GLFWgammaramp* ramp); void _glfwSetGammaRampCocoa(_GLFWmonitor* monitor, const GLFWgammaramp* ramp); void _glfwPollMonitorsCocoa(void); void _glfwSetVideoModeCocoa(_GLFWmonitor* monitor, const GLFWvidmode* desired); void _glfwRestoreVideoModeCocoa(_GLFWmonitor* monitor); float _glfwTransformYCocoa(float y); void* _glfwLoadLocalVulkanLoaderCocoa(void); GLFWbool _glfwInitNSGL(void); void _glfwTerminateNSGL(void); GLFWbool _glfwCreateContextNSGL(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig); void _glfwDestroyContextNSGL(_GLFWwindow* window);
applicative.ml
open! Import include Applicative_intf module List = List0 (** This module serves mostly as a partial check that [S2] and [S] are in sync, but actually calling it is occasionally useful. *) module S_to_S2 (X : S) : S2 with type ('a, 'e) t = 'a X.t = struct include X type ('a, 'e) t = 'a X.t end module S2_to_S (X : S2) : S with type 'a t = ('a, unit) X.t = struct include X type 'a t = ('a, unit) X.t end module S2_to_S3 (X : S2) : S3 with type ('a, 'd, 'e) t = ('a, 'd) X.t = struct include X type ('a, 'd, 'e) t = ('a, 'd) X.t end module S3_to_S2 (X : S3) : S2 with type ('a, 'd) t = ('a, 'd, unit) X.t = struct include X type ('a, 'd) t = ('a, 'd, unit) X.t end module Make3 (X : Basic3) : S3 with type ('a, 'd, 'e) t := ('a, 'd, 'e) X.t = struct include X let ( <*> ) = apply let derived_map t ~f = return f <*> t let map = match X.map with | `Define_using_apply -> derived_map | `Custom x -> x ;; let ( >>| ) t f = map t ~f let map2 ta tb ~f = map ~f ta <*> tb let map3 ta tb tc ~f = map ~f ta <*> tb <*> tc let all ts = List.fold_right ts ~init:(return []) ~f:(map2 ~f:(fun x xs -> x :: xs)) let both ta tb = map2 ta tb ~f:(fun a b -> a, b) let ( *> ) u v = return (fun () y -> y) <*> u <*> v let ( <* ) u v = return (fun x () -> x) <*> u <*> v let all_unit ts = List.fold ts ~init:(return ()) ~f:( *> ) module Applicative_infix = struct let ( <*> ) = ( <*> ) let ( *> ) = ( *> ) let ( <* ) = ( <* ) let ( >>| ) = ( >>| ) end end module Make2 (X : Basic2) : S2 with type ('a, 'e) t := ('a, 'e) X.t = Make3 (struct include X type ('a, 'd, 'e) t = ('a, 'd) X.t end) module Make (X : Basic) : S with type 'a t := 'a X.t = Make2 (struct include X type ('a, 'e) t = 'a X.t end) module Make_let_syntax3 (X : For_let_syntax3) (Intf : sig module type S end) (Impl : Intf.S) = struct module Let_syntax = struct include X module Let_syntax = struct include X module Open_on_rhs = Impl end end end module Make_let_syntax2 (X : For_let_syntax2) (Intf : sig module type S end) (Impl : Intf.S) = Make_let_syntax3 (struct include X type ('a, 'd, _) t = ('a, 'd) X.t end) (Intf) (Impl) module Make_let_syntax (X : For_let_syntax) (Intf : sig module type S end) (Impl : Intf.S) = Make_let_syntax2 (struct include X type ('a, _) t = 'a X.t end) (Intf) (Impl) (** This functor closely resembles [Make3], and indeed it could be implemented much shorter in terms of [Make3]. However, we implement it by hand so that the resulting functions are more efficient, e.g. using [map2] directly instead of defining [apply] in terms of it and then [map2] in terms of that. For most applicatives this does not matter, but for some (such as Bonsai.Value.t), it has a larger impact. *) module Make3_using_map2 (X : Basic3_using_map2) : S3 with type ('a, 'd, 'e) t := ('a, 'd, 'e) X.t = struct include X let apply tf ta = map2 tf ta ~f:(fun f a -> f a) let ( <*> ) = apply let derived_map t ~f = return f <*> t let map = match X.map with | `Define_using_map2 -> derived_map | `Custom x -> x ;; let ( >>| ) t f = map t ~f let both ta tb = map2 ta tb ~f:(fun a b -> a, b) let map3 ta tb tc ~f = map2 (map2 ta tb ~f) tc ~f:(fun fab c -> fab c) let all ts = List.fold_right ts ~init:(return []) ~f:(map2 ~f:(fun x xs -> x :: xs)) let ( *> ) u v = map2 u v ~f:(fun () y -> y) let ( <* ) u v = map2 u v ~f:(fun x () -> x) let all_unit ts = List.fold ts ~init:(return ()) ~f:( *> ) module Applicative_infix = struct let ( <*> ) = ( <*> ) let ( *> ) = ( *> ) let ( <* ) = ( <* ) let ( >>| ) = ( >>| ) end end module Make2_using_map2 (X : Basic2_using_map2) : S2 with type ('a, 'e) t := ('a, 'e) X.t = Make3_using_map2 (struct include X type ('a, 'd, 'e) t = ('a, 'd) X.t end) module Make_using_map2 (X : Basic_using_map2) : S with type 'a t := 'a X.t = Make2_using_map2 (struct include X type ('a, 'e) t = 'a X.t end) module Of_monad2 (M : Monad.S2) : S2 with type ('a, 'e) t := ('a, 'e) M.t = Make2 (struct type ('a, 'e) t = ('a, 'e) M.t let return = M.return let apply mf mx = M.bind mf ~f:(fun f -> M.map mx ~f) let map = `Custom M.map end) module Of_monad (M : Monad.S) : S with type 'a t := 'a M.t = Of_monad2 (struct include M type ('a, _) t = 'a M.t end) module Compose (F : S) (G : S) : S with type 'a t = 'a F.t G.t = struct type 'a t = 'a F.t G.t include Make (struct type nonrec 'a t = 'a t let return a = G.return (F.return a) let apply tf tx = G.apply (G.map ~f:F.apply tf) tx let custom_map t ~f = G.map ~f:(F.map ~f) t let map = `Custom custom_map end) end module Pair (F : S) (G : S) : S with type 'a t = 'a F.t * 'a G.t = struct type 'a t = 'a F.t * 'a G.t include Make (struct type nonrec 'a t = 'a t let return a = F.return a, G.return a let apply tf tx = F.apply (fst tf) (fst tx), G.apply (snd tf) (snd tx) let custom_map t ~f = F.map ~f (fst t), G.map ~f (snd t) let map = `Custom custom_map end) end
pack_value.ml
open! Import include Pack_value_intf module Kind = struct type t = | Commit_v1 | Commit_v2 | Contents | Inode_v1_unstable | Inode_v1_stable | Inode_v2_root | Inode_v2_nonroot | Dangling_parent_commit let to_magic = function | Commit_v1 -> 'C' | Commit_v2 -> 'D' | Contents -> 'B' | Inode_v1_unstable -> 'I' | Inode_v1_stable -> 'N' | Inode_v2_root -> 'R' | Inode_v2_nonroot -> 'O' | Dangling_parent_commit -> 'P' let of_magic_exn = function | 'C' -> Commit_v1 | 'D' -> Commit_v2 | 'B' -> Contents | 'I' -> Inode_v1_unstable | 'N' -> Inode_v1_stable | 'R' -> Inode_v2_root | 'O' -> Inode_v2_nonroot | 'P' -> Dangling_parent_commit | c -> Fmt.failwith "Kind.of_magic: unexpected magic char %C" c let all = [ Commit_v1; Commit_v2; Contents; Inode_v1_unstable; Inode_v1_stable; Inode_v2_root; Inode_v2_nonroot; Dangling_parent_commit; ] let to_enum = function | Commit_v1 -> 0 | Commit_v2 -> 1 | Contents -> 2 | Inode_v1_unstable -> 3 | Inode_v1_stable -> 4 | Inode_v2_root -> 5 | Inode_v2_nonroot -> 6 | Dangling_parent_commit -> 7 let pp = Fmt.of_to_string (function | Commit_v1 -> "Commit_v1" | Commit_v2 -> "Commit_v2" | Contents -> "Contents" | Inode_v1_unstable -> "Inode_v1_unstable" | Inode_v1_stable -> "Inode_v1_stable" | Inode_v2_root -> "Inode_v2_root" | Inode_v2_nonroot -> "Inode_v2_nonroot" | Dangling_parent_commit -> "Dangling_parent_commit") let length_header_exn : t -> length_header = let some_varint = Some `Varint in function | Commit_v1 | Inode_v1_unstable | Inode_v1_stable -> None | Commit_v2 | Inode_v2_root | Inode_v2_nonroot | Dangling_parent_commit -> some_varint | Contents -> Fmt.failwith "Can't determine length header for user-defined codec Contents" let t = Irmin.Type.map ~pp Irmin.Type.char of_magic_exn to_magic end type ('h, 'a) value = { hash : 'h; kind : Kind.t; v : 'a } [@@deriving irmin] module type S = S with type kind := Kind.t let get_dynamic_sizer_exn : type a. a Irmin.Type.t -> string -> int -> int = fun typ -> match Irmin.Type.(Size.of_encoding typ) with | Unknown -> Fmt.failwith "Type must have a recoverable encoded length: %a" Irmin.Type.pp_ty typ | Static n -> fun _ _ -> n | Dynamic f -> f module Of_contents (Conf : Config) (Hash : Irmin.Hash.S) (Key : T) (Data : Irmin.Type.S) = struct module Hash = Irmin.Hash.Typed (Hash) (Data) type t = Data.t [@@deriving irmin ~size_of] type key = Key.t type hash = Hash.t let hash = Hash.hash let kind = Kind.Contents let length_header = Fun.const Conf.contents_length_header let value = [%typ: (Hash.t, Data.t) value] let encode_value = Irmin.Type.(unstage (encode_bin value)) let decode_value = Irmin.Type.(unstage (decode_bin value)) let encode_bin ~dict:_ ~offset_of_key:_ hash v f = encode_value { kind; hash; v } f let decode_bin ~dict:_ ~key_of_offset:_ ~key_of_hash:_ s off = let t = decode_value s off in t.v let decode_bin_length = get_dynamic_sizer_exn value let kind _ = kind let weight = (* Normalise the weight of the blob, assuming that the 'average' size for a blob is 1k bytes. *) let normalise n = max 1 (n / 1_000) in match Irmin.Type.Size.of_value t with | Unknown -> (* this should not happen unless the user has specified a very weird content type. *) Fun.const max_int | Dynamic f -> fun v -> normalise (f v) | Static n -> Fun.const (normalise n) end module Of_commit (Hash : Irmin.Hash.S) (Key : Irmin.Key.S with type hash = Hash.t) (Commit : Irmin.Commit.Generic_key.S with type node_key = Key.t and type commit_key = Key.t) = struct module Hash = Irmin.Hash.Typed (Hash) (Commit) type t = Commit.t [@@deriving irmin] type key = Key.t type hash = Hash.t [@@deriving irmin ~encode_bin ~decode_bin] let hash = Hash.hash let kind _ = Kind.Commit_v2 let weight _ = 1 (* A commit implementation that uses integer offsets for addresses where possible. *) module Commit_direct = struct type address = Offset of int63 | Hash of Hash.t [@@deriving irmin] type t = { node_offset : address; parent_offsets : address list; info : Commit.Info.t; } [@@deriving irmin ~encode_bin ~to_bin_string ~decode_bin] let size_of = match Irmin.Type.Size.of_value t with | Dynamic f -> f | Static _ | Unknown -> assert false end module Entry = struct module V0 = struct type t = (hash, Commit.t) value [@@deriving irmin ~decode_bin] end module V1 = struct type data = { length : int; v : Commit_direct.t } [@@deriving irmin] type t = (hash, data) value [@@deriving irmin ~encode_bin ~decode_bin] end end let length_header = function | Kind.Contents -> assert false | x -> Kind.length_header_exn x let encode_bin ~dict:_ ~offset_of_key hash v f = let address_of_key k : Commit_direct.address = match offset_of_key k with | None -> Hash (Key.to_hash k) | Some k -> Offset k in let v = let info = Commit.info v in let node_offset = address_of_key (Commit.node v) in let parent_offsets = List.map address_of_key (Commit.parents v) in { Commit_direct.node_offset; parent_offsets; info } in let length = Commit_direct.size_of v in Entry.V1.encode_bin { hash; kind = Commit_v2; v = { length; v } } f let decode_bin ~dict:_ ~key_of_offset ~key_of_hash s off = let key_of_address : Commit_direct.address -> Key.t = function | Offset x -> key_of_offset x | Hash x -> key_of_hash x in match Kind.of_magic_exn s.[!off + Hash.hash_size] with | Commit_v1 -> (Entry.V0.decode_bin s off).v | Commit_v2 -> let { v = { Entry.V1.v = commit; _ }; _ } = Entry.V1.decode_bin s off in let info = commit.info in let node = key_of_address commit.node_offset in let parents = List.map key_of_address commit.parent_offsets in Commit.v ~info ~node ~parents | _ -> assert false let decode_bin_length = let of_v0_entry = get_dynamic_sizer_exn Entry.V0.t and of_v1_entry = get_dynamic_sizer_exn Entry.V1.t in fun s off -> match Kind.of_magic_exn s.[off + Hash.hash_size] with | Commit_v1 -> of_v0_entry s off | Commit_v2 -> of_v1_entry s off | _ -> assert false end
(* * Copyright (c) 2018-2022 Tarides <contact@tarides.com> * * 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. *)