filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
issue798.ml
module List = struct include List let foo l = match l with | hd :: tl -> let _ = hd in assert false | [] -> assert false end
block.ml
open Protocol module Proto_Nonce = Nonce (* Renamed otherwise is masked by Alpha_context *) open Alpha_context (* This type collects a block and the context that results from its application *) type t = { hash : Block_hash.t; header : Block_header.t; operations : Operation.packed list; context : Tezos_protocol_environment.Context.t; } type block = t let rpc_context block = { Environment.Updater.block_hash = block.hash; block_header = block.header.shell; context = block.context; } let rpc_ctxt = new Environment.proto_rpc_context_of_directory rpc_context Plugin.RPC.rpc_services (******** Policies ***********) (* Policies are functions that take a block and return a tuple [(account, level, timestamp)] for the [forge_header] function. *) (* This type is used only to provide a simpler interface to the exterior. *) type baker_policy = | By_round of int | By_account of public_key_hash | Excluding of public_key_hash list type baking_mode = Application | Baking let get_next_baker_by_round round block = Plugin.RPC.Baking_rights.get rpc_ctxt ~all:true ~max_round:(round + 1) block >|=? fun bakers -> let {Plugin.RPC.Baking_rights.delegate = pkh; timestamp; _} = WithExceptions.Option.get ~loc:__LOC__ @@ List.find (fun {Plugin.RPC.Baking_rights.round = r; _} -> r = round) bakers in (pkh, round, WithExceptions.Option.to_exn ~none:(Failure "") timestamp) let get_next_baker_by_account pkh block = Plugin.RPC.Baking_rights.get rpc_ctxt ~delegates:[pkh] block >>=? fun bakers -> (match List.hd bakers with | Some b -> return b | None -> failwith "No slots found for %a" Signature.Public_key_hash.pp pkh) >>=? fun {Plugin.RPC.Baking_rights.delegate = pkh; timestamp; round; _} -> return (pkh, round, WithExceptions.Option.to_exn ~none:(Failure __LOC__) timestamp) let get_next_baker_excluding excludes block = Plugin.RPC.Baking_rights.get rpc_ctxt block >|=? fun bakers -> let {Plugin.RPC.Baking_rights.delegate = pkh; timestamp; round; _} = WithExceptions.Option.get ~loc:__LOC__ @@ List.find (fun {Plugin.RPC.Baking_rights.delegate; _} -> not (List.mem ~equal:Signature.Public_key_hash.equal delegate excludes)) bakers in (pkh, round, WithExceptions.Option.to_exn ~none:(Failure "") timestamp) let dispatch_policy = function | By_round r -> get_next_baker_by_round r | By_account a -> get_next_baker_by_account a | Excluding al -> get_next_baker_excluding al let get_next_baker ?(policy = By_round 0) = dispatch_policy policy let get_round (b : t) = let fitness = b.header.shell.fitness in Fitness.(from_raw fitness >|? round) |> Environment.wrap_tzresult module Forge = struct type header = { baker : public_key_hash; (* the signer of the block *) shell : Block_header.shell_header; contents : Block_header.contents; } let default_proof_of_work_nonce = Bytes.create Constants.proof_of_work_nonce_size let make_contents ?(proof_of_work_nonce = default_proof_of_work_nonce) ~payload_hash ~payload_round ?(liquidity_baking_escape_vote = false) ~seed_nonce_hash () = Block_header. { payload_hash; payload_round; proof_of_work_nonce; seed_nonce_hash; liquidity_baking_escape_vote; } let make_shell ~level ~predecessor ~timestamp ~fitness ~operations_hash = Tezos_base.Block_header. { level; predecessor; timestamp; fitness; operations_hash; (* We don't care of the following values, only the shell validates them. *) proto_level = 0; validation_passes = 0; context = Context_hash.zero; } let set_seed_nonce_hash seed_nonce_hash {baker; shell; contents} = {baker; shell; contents = {contents with seed_nonce_hash}} let set_baker baker header = {header with baker} let sign_header {baker; shell; contents} = Account.find baker >|=? fun delegate -> let unsigned_bytes = Data_encoding.Binary.to_bytes_exn Block_header.unsigned_encoding (shell, contents) in let signature = Signature.sign ~watermark:Block_header.(to_watermark (Block_header Chain_id.zero)) delegate.sk unsigned_bytes in Block_header.{shell; protocol_data = {contents; signature}} let classify_operations operations = let validation_passes_len = List.length Main.validation_passes in let t = Array.make validation_passes_len [] in List.iter (fun (op : packed_operation) -> List.iter (fun pass -> t.(pass) <- op :: t.(pass)) (Main.acceptable_passes op)) operations ; let t = Array.map List.rev t in Array.to_list t let forge_header ?(locked_round = None) ?(payload_round = None) ?(policy = By_round 0) ?timestamp ?(operations = []) ?liquidity_baking_escape_vote pred = let pred_fitness = match Fitness.from_raw pred.header.shell.fitness with | Ok pred_fitness -> pred_fitness | _ -> assert false in let predecessor_round = Fitness.round pred_fitness in dispatch_policy policy pred >>=? fun (pkh, round, expected_timestamp) -> let timestamp = Option.value ~default:expected_timestamp timestamp in let level = Int32.succ pred.header.shell.level in Raw_level.of_int32 level |> Environment.wrap_tzresult >>?= fun raw_level -> Round.of_int round |> Environment.wrap_tzresult >>?= fun round -> Fitness.create ~level:raw_level ~predecessor_round ~round ~locked_round >|? Fitness.to_raw |> Environment.wrap_tzresult >>?= fun fitness -> (Plugin.RPC.current_level ~offset:1l rpc_ctxt pred >|=? function | {expected_commitment = true; _} -> Some (fst (Proto_Nonce.generate ())) | {expected_commitment = false; _} -> None) >|=? fun seed_nonce_hash -> let hashes = List.map Operation.hash_packed operations in let operations_hash = Operation_list_list_hash.compute [Operation_list_hash.compute hashes] in let shell = make_shell ~level ~predecessor:pred.hash ~timestamp ~fitness ~operations_hash in let operations = classify_operations operations in let non_consensus_operations = List.concat (match List.tl operations with None -> [] | Some l -> l) in let hashes = List.map Operation.hash_packed non_consensus_operations in let non_consensus_operations_hash = Operation_list_hash.compute hashes in let payload_round = match payload_round with None -> round | Some r -> r in let payload_hash = Block_payload.hash ~predecessor:shell.predecessor payload_round non_consensus_operations_hash in let contents = make_contents ~seed_nonce_hash ?liquidity_baking_escape_vote ~payload_hash ~payload_round () in {baker = pkh; shell; contents} (* compatibility only, needed by incremental *) let contents ?(proof_of_work_nonce = default_proof_of_work_nonce) ?seed_nonce_hash ?(liquidity_baking_escape_vote = false) ~payload_hash ~payload_round () = { Block_header.proof_of_work_nonce; seed_nonce_hash; liquidity_baking_escape_vote; payload_hash; payload_round; } end (********* Genesis creation *************) (* Hard-coded context key *) let protocol_param_key = ["protocol_parameters"] let check_constants_consistency constants = let open Constants in let {blocks_per_cycle; blocks_per_commitment; blocks_per_stake_snapshot; _} = constants in Error_monad.unless (blocks_per_commitment <= blocks_per_cycle) (fun () -> failwith "Inconsistent constants : blocks per commitment must be less than \ blocks per cycle") >>=? fun () -> Error_monad.unless (blocks_per_cycle >= blocks_per_stake_snapshot) (fun () -> failwith "Inconsistent constants : blocks per cycle must be superior than \ blocks per roll snapshot") let prepare_main_init_params ?bootstrap_contracts commitments constants initial_accounts = let open Tezos_protocol_012_Psithaca_parameters in let bootstrap_accounts = List.map (fun (Account.{pk; pkh; _}, amount) -> Default_parameters.make_bootstrap_account (pkh, pk, amount)) initial_accounts in let parameters = Default_parameters.parameters_of_constants ~bootstrap_accounts ?bootstrap_contracts ~commitments constants in let json = Default_parameters.json_of_parameters parameters in let proto_params = Data_encoding.Binary.to_bytes_exn Data_encoding.json json in Tezos_protocol_environment.Context.( let empty = Memory_context.empty in add empty ["version"] (Bytes.of_string "genesis") >>= fun ctxt -> add ctxt protocol_param_key proto_params) let initial_context ?(commitments = []) ?bootstrap_contracts constants header initial_accounts = prepare_main_init_params ?bootstrap_contracts commitments constants initial_accounts >>= fun ctxt -> Main.init ctxt header >|= Environment.wrap_tzresult >|=? fun {context; _} -> context let initial_alpha_context ?(commitments = []) constants (block_header : Block_header.shell_header) initial_accounts = prepare_main_init_params commitments constants initial_accounts >>= fun ctxt -> let level = block_header.level in let timestamp = block_header.timestamp in let typecheck (ctxt : Alpha_context.context) (script : Alpha_context.Script.t) = let allow_forged_in_storage = false (* There should be no forged value in bootstrap contracts. *) in Script_ir_translator.parse_script ctxt ~legacy:true ~allow_forged_in_storage script >>=? fun (Ex_script parsed_script, ctxt) -> Script_ir_translator.extract_lazy_storage_diff ctxt Optimized parsed_script.storage_type parsed_script.storage ~to_duplicate:Script_ir_translator.no_lazy_storage_id ~to_update:Script_ir_translator.no_lazy_storage_id ~temporary:false >>=? fun (storage, lazy_storage_diff, ctxt) -> Script_ir_translator.unparse_data ctxt Optimized parsed_script.storage_type storage >|=? fun (storage, ctxt) -> let storage = Alpha_context.Script.lazy_expr (Micheline.strip_locations storage) in (({script with storage}, lazy_storage_diff), ctxt) in Main.init_cache ctxt >>= fun ctxt -> Alpha_context.prepare_first_block ~typecheck ~level ~timestamp ctxt >|= Environment.wrap_tzresult let genesis_with_parameters parameters = let hash = Block_hash.of_b58check_exn "BLockGenesisGenesisGenesisGenesisGenesisCCCCCeZiLHU" in let fitness = Fitness_repr.create_without_locked_round ~level:(Protocol.Raw_level_repr.of_int32_exn 0l) ~predecessor_round:Round_repr.zero ~round:Round_repr.zero |> Fitness_repr.to_raw in let shell = Forge.make_shell ~level:0l ~predecessor:hash ~timestamp:Time.Protocol.epoch ~fitness ~operations_hash:Operation_list_list_hash.zero in let contents = Forge.make_contents ~payload_hash:Block_payload_hash.zero ~payload_round:Round.zero ~seed_nonce_hash:None () in let open Tezos_protocol_012_Psithaca_parameters in let json = Default_parameters.json_of_parameters parameters in let proto_params = Data_encoding.Binary.to_bytes_exn Data_encoding.json json in Tezos_protocol_environment.Context.( let empty = Memory_context.empty in add empty ["version"] (Bytes.of_string "genesis") >>= fun ctxt -> add ctxt protocol_param_key proto_params) >>= fun ctxt -> Main.init ctxt shell >|= Environment.wrap_tzresult >|=? fun {context; _} -> { hash; header = {shell; protocol_data = {contents; signature = Signature.zero}}; operations = []; context; } let validate_initial_accounts (initial_accounts : (Account.t * Tez.t) list) tokens_per_roll = if initial_accounts = [] then Stdlib.failwith "Must have one account with a roll to bake" ; (* Check there is at least one roll *) Lwt.catch (fun () -> List.fold_left_es (fun acc (_, amount) -> Environment.wrap_tzresult @@ Tez.( +? ) acc amount >>?= fun acc -> if acc >= tokens_per_roll then raise Exit else return acc) Tez.zero initial_accounts >>=? fun _ -> failwith "Insufficient tokens in initial accounts to create one roll") (function Exit -> return_unit | exc -> raise exc) let prepare_initial_context_params ?consensus_threshold ?min_proposal_quorum ?level ?cost_per_byte ?liquidity_baking_subsidy ?endorsing_reward_per_slot ?baking_reward_bonus_per_slot ?baking_reward_fixed_portion ?origination_size ?blocks_per_cycle initial_accounts = let open Tezos_protocol_012_Psithaca_parameters in let constants = Default_parameters.constants_test in let min_proposal_quorum = Option.value ~default:constants.min_proposal_quorum min_proposal_quorum in let cost_per_byte = Option.value ~default:constants.cost_per_byte cost_per_byte in let liquidity_baking_subsidy = Option.value ~default:constants.liquidity_baking_subsidy liquidity_baking_subsidy in let endorsing_reward_per_slot = Option.value ~default:constants.endorsing_reward_per_slot endorsing_reward_per_slot in let baking_reward_bonus_per_slot = Option.value ~default:constants.baking_reward_bonus_per_slot baking_reward_bonus_per_slot in let baking_reward_fixed_portion = Option.value ~default:constants.baking_reward_fixed_portion baking_reward_fixed_portion in let origination_size = Option.value ~default:constants.origination_size origination_size in let blocks_per_cycle = Option.value ~default:constants.blocks_per_cycle blocks_per_cycle in (* ?origination_size *) let consensus_threshold = Option.value ~default:constants.consensus_threshold consensus_threshold in let constants = { constants with endorsing_reward_per_slot; baking_reward_bonus_per_slot; baking_reward_fixed_portion; origination_size; blocks_per_cycle; min_proposal_quorum; cost_per_byte; liquidity_baking_subsidy; consensus_threshold; } in (* Check there is at least one roll *) Lwt.catch (fun () -> List.fold_left_es (fun acc (_, amount) -> Environment.wrap_tzresult @@ Tez.( +? ) acc amount >>?= fun acc -> if acc >= constants.tokens_per_roll then raise Exit else return acc) Tez.zero initial_accounts >>=? fun _ -> failwith "Insufficient tokens in initial accounts to create one roll") (function Exit -> return_unit | exc -> raise exc) >>=? fun () -> check_constants_consistency constants >>=? fun () -> let hash = Block_hash.of_b58check_exn "BLockGenesisGenesisGenesisGenesisGenesisCCCCCeZiLHU" in let level = Option.value ~default:0l level in let fitness = Fitness_repr.create_without_locked_round ~level:(Protocol.Raw_level_repr.of_int32_exn level) ~predecessor_round:Round_repr.zero ~round:Round_repr.zero |> Fitness_repr.to_raw in let shell = Forge.make_shell ~level ~predecessor:hash ~timestamp:Time.Protocol.epoch ~fitness ~operations_hash:Operation_list_list_hash.zero in validate_initial_accounts initial_accounts constants.tokens_per_roll (* Perhaps this could return a new type signifying its name *) >|=? fun _initial_accounts -> (constants, shell, hash) (* if no parameter file is passed we check in the current directory where the test is run *) let genesis ?commitments ?consensus_threshold ?min_proposal_quorum ?bootstrap_contracts ?level ?cost_per_byte ?liquidity_baking_subsidy ?endorsing_reward_per_slot ?baking_reward_bonus_per_slot ?baking_reward_fixed_portion ?origination_size ?blocks_per_cycle (initial_accounts : (Account.t * Tez.t) list) = prepare_initial_context_params ?consensus_threshold ?min_proposal_quorum ?level ?cost_per_byte ?liquidity_baking_subsidy ?endorsing_reward_per_slot ?baking_reward_bonus_per_slot ?baking_reward_fixed_portion ?origination_size ?blocks_per_cycle initial_accounts >>=? fun (constants, shell, hash) -> initial_context ?commitments ?bootstrap_contracts constants shell initial_accounts >|=? fun context -> let contents = Forge.make_contents ~payload_hash:Block_payload_hash.zero ~payload_round:Round.zero ~seed_nonce_hash:None () in { hash; header = {shell; protocol_data = {contents; signature = Signature.zero}}; operations = []; context; } let alpha_context ?commitments ?min_proposal_quorum (initial_accounts : (Account.t * Tez.t) list) = prepare_initial_context_params ?min_proposal_quorum initial_accounts >>=? fun (constants, shell, _hash) -> initial_alpha_context ?commitments constants shell initial_accounts (********* Baking *************) (* Note that by calling this function without [protocol_data], we force the mode to be partial construction (by correspondingly calling [begin_construction] without [protocol_data]). *) let get_application_vstate (pred : t) (operations : Protocol.operation trace) = Forge.forge_header pred ~operations >>=? fun header -> Forge.sign_header header >>=? fun header -> let open Environment.Error_monad in Main.begin_application ~chain_id:Chain_id.zero ~predecessor_context:pred.context ~predecessor_fitness:pred.header.shell.fitness ~predecessor_timestamp:pred.header.shell.timestamp header >|= Environment.wrap_tzresult let get_construction_vstate ?(policy = By_round 0) ?timestamp ?(protocol_data = None) (pred : t) = let open Protocol in dispatch_policy policy pred >>=? fun (_pkh, _round, expected_timestamp) -> let timestamp = Option.value ~default:expected_timestamp timestamp in Main.begin_construction ~chain_id:Chain_id.zero ~predecessor_context:pred.context ~predecessor_timestamp:pred.header.shell.timestamp ~predecessor_level:pred.header.shell.level ~predecessor_fitness:pred.header.shell.fitness ~predecessor:pred.hash ?protocol_data ~timestamp () >|= Environment.wrap_tzresult let apply_with_metadata ?(policy = By_round 0) ~baking_mode header ?(operations = []) pred = let open Environment.Error_monad in ( (match baking_mode with | Application -> Main.begin_application ~chain_id:Chain_id.zero ~predecessor_context:pred.context ~predecessor_fitness:pred.header.shell.fitness ~predecessor_timestamp:pred.header.shell.timestamp header >|= Environment.wrap_tzresult | Baking -> get_construction_vstate ~policy ~protocol_data:(Some header.protocol_data) (pred : t)) >>=? fun vstate -> List.fold_left_es (fun vstate op -> apply_operation vstate op >|= Environment.wrap_tzresult >|=? fun (state, _result) -> state) vstate operations >>=? fun vstate -> Main.finalize_block vstate (Some header.shell) >|= Environment.wrap_tzresult >|=? fun (validation, result) -> (validation.context, result) ) >|=? fun (context, result) -> let hash = Block_header.hash header in ({hash; header; operations; context}, result) let apply header ?(operations = []) pred = apply_with_metadata header ~operations pred ~baking_mode:Application >>=? fun (t, _metadata) -> return t let bake_with_metadata ?locked_round ?policy ?timestamp ?operation ?operations ?payload_round ~baking_mode ?liquidity_baking_escape_vote pred = let operations = match (operation, operations) with | (Some op, Some ops) -> Some (op :: ops) | (Some op, None) -> Some [op] | (None, Some ops) -> Some ops | (None, None) -> None in Forge.forge_header ?payload_round ?locked_round ?timestamp ?policy ?operations ?liquidity_baking_escape_vote pred >>=? fun header -> Forge.sign_header header >>=? fun header -> apply_with_metadata ?policy ~baking_mode header ?operations pred let bake ?(baking_mode = Application) ?payload_round ?locked_round ?policy ?timestamp ?operation ?operations ?liquidity_baking_escape_vote pred = bake_with_metadata ?payload_round ~baking_mode ?locked_round ?policy ?timestamp ?operation ?operations ?liquidity_baking_escape_vote pred >>=? fun (t, (_metadata : block_header_metadata)) -> return t (********** Cycles ****************) (* This function is duplicated from Context to avoid a cyclic dependency *) let get_constants b = Alpha_services.Constants.all rpc_ctxt b let bake_n ?(baking_mode = Application) ?policy ?liquidity_baking_escape_vote n b = List.fold_left_es (fun b _ -> bake ~baking_mode ?policy ?liquidity_baking_escape_vote b) b (1 -- n) let bake_n_with_all_balance_updates ?(baking_mode = Application) ?policy ?liquidity_baking_escape_vote n b = List.fold_left_es (fun (b, balance_updates_rev) _ -> bake_with_metadata ~baking_mode ?policy ?liquidity_baking_escape_vote b >>=? fun (b, metadata) -> let balance_updates_rev = List.rev_append metadata.balance_updates balance_updates_rev in let balance_updates_rev = List.fold_left (fun balance_updates_rev -> let open Apply_results in function | Successful_manager_result (Reveal_result _) | Successful_manager_result (Delegation_result _) -> balance_updates_rev | Successful_manager_result (Set_deposits_limit_result _) -> balance_updates_rev | Successful_manager_result (Transaction_result {balance_updates; _}) | Successful_manager_result (Origination_result {balance_updates; _}) | Successful_manager_result (Register_global_constant_result {balance_updates; _}) -> List.rev_append balance_updates balance_updates_rev) balance_updates_rev metadata.implicit_operations_results in return (b, balance_updates_rev)) (b, []) (1 -- n) >|=? fun (b, balance_updates_rev) -> (b, List.rev balance_updates_rev) let bake_n_with_origination_results ?(baking_mode = Application) ?policy n b = List.fold_left_es (fun (b, origination_results_rev) _ -> bake_with_metadata ~baking_mode ?policy b >>=? fun (b, metadata) -> let origination_results_rev = List.fold_left (fun origination_results_rev -> let open Apply_results in function | Successful_manager_result (Reveal_result _) | Successful_manager_result (Delegation_result _) | Successful_manager_result (Transaction_result _) | Successful_manager_result (Register_global_constant_result _) | Successful_manager_result (Set_deposits_limit_result _) -> origination_results_rev | Successful_manager_result (Origination_result x) -> Origination_result x :: origination_results_rev) origination_results_rev metadata.implicit_operations_results in return (b, origination_results_rev)) (b, []) (1 -- n) >|=? fun (b, origination_results_rev) -> (b, List.rev origination_results_rev) let bake_n_with_liquidity_baking_escape_ema ?(baking_mode = Application) ?policy ?liquidity_baking_escape_vote n b = List.fold_left_es (fun (b, _escape_ema) _ -> bake_with_metadata ~baking_mode ?policy ?liquidity_baking_escape_vote b >|=? fun (b, metadata) -> (b, metadata.liquidity_baking_escape_ema)) (b, 0l) (1 -- n) let bake_until_cycle_end ?policy b = get_constants b >>=? fun Constants.{parametric = {blocks_per_cycle; _}; _} -> let current_level = b.header.shell.level in let current_level = Int32.rem current_level blocks_per_cycle in let delta = Int32.sub blocks_per_cycle current_level in bake_n ?policy (Int32.to_int delta) b let bake_until_n_cycle_end ?policy n b = List.fold_left_es (fun b _ -> bake_until_cycle_end ?policy b) b (1 -- n) let current_cycle b = get_constants b >>=? fun Constants.{parametric = {blocks_per_cycle; _}; _} -> let current_level = b.header.shell.level in let current_cycle = Int32.div current_level blocks_per_cycle in let current_cycle = Cycle.add Cycle.root (Int32.to_int current_cycle) in return current_cycle let bake_until_cycle ?policy cycle (b : t) = let rec loop (b : t) = current_cycle b >>=? fun current_cycle -> if Cycle.equal cycle current_cycle then return b else bake_until_cycle_end ?policy b >>=? fun b -> loop b in loop b
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
petrol.mli
type table_name (** Uniquely identifies a table in the system. *) module Expr : sig (** Defines an extensible embedding of SQL expressions. *) type 'a t (** ['a t] represents an SQL expression that evaluates to a value of OCaml type ['a] *) val pp: Format.formatter -> 'a t -> unit (** [pp fmt expr] pretty prints the expression [expr]. {b Note} You shouldn't have to call this yourself. Petrol usually takes care of this for you, but you may want to use it for debugging. *) type wrapped_assign (** An opaque wrapper that represents an assignment of a value to a particular field in a table. *) (** Represents a heterogeneous sequence of SQL expressions. *) type 'a expr_list = | [] : unit expr_list | (::) : ('a t * 'b expr_list) -> ('a * 'b) expr_list val pp_expr_list : Format.formatter -> 'a expr_list -> unit (** [pp_expr_list fmt exps] pretty prints the expression list [exps] of type {!expr_list}. See also {!t} and {!pp}. *) end module Type : sig type 'a t (** Represents an SQL data type that maps to an OCaml type ['a]. *) val pp: Format.formatter -> 'a t -> unit val show : 'a t -> string val custom : ty:'a Caqti_type.t -> repr:string -> 'a t (** [custom ~ty ~repr] creates a new SQL type that is represented by the Caqti type [ty], and is represented in a SQL query as [repr]. For example, you might define the BOOL datatype as follows: {[ let bool = Type.custom ~ty:Caqti_type.bool ~repr:"BOOLEAN" ]} {b Note} Petrol doesn't implement the boolean type using this function, and uses a slightly more efficient internal encoding, but for more bespoke custom user types this function should be sufficient. *) val pp_value : 'a t -> Format.formatter -> 'a -> unit (** [pp_value ty fmt vl] returns a pretty printer for values of a type [ty]. *) module Numeric : sig (** Poor man's type classes for numeric arguments. *) (** ['a integral] represents an integral type. *) type 'a integral = 'a Type.Numeric.integral = Int : int integral | Int32 : int32 integral | Int64 : int64 integral (** ['a t] represents a numeric type. *) type 'a t = 'a Type.Numeric.t = Int : int t | Int32 : int32 t | Int64 : int64 t | Real : float t end end type ('ret_ty, 'query_kind) query (** [('ret_ty, 'query_tag) query] represents an SQL query that returns values of type ['ret_ty] and is a SQL query of kind ['query_kind] -- see {!Petrol.Query.t}. *) type ('res, 'multiplicity) request (** Represents a compiled SQL database request. *) module Request : sig (** This module defines a request type [t] that can be executed by Caqti (see {!exec}, {!find}, {!find_opt}). The functions defined in this module cache their inputs, so it is safe to call these repeatedly. {b Note} In order to cache a query, Petrol uses the string representation of the query with holes for variables as the cache key -- this means that you are highly recommended to {i not} use the static constant functions for any values that change frequently and instead use the non-static constant functions. *) type ('res, 'multiplicity) t = ('res, 'multiplicity) request (** Represents a compiled SQL database request. *) val make_zero : (unit, 'b) query -> (unit, [ `Zero ]) t (** [make_zero query] constructs a SQL request with multiplicity zero from the query [query]. *) val make_one : ('a, 'b) query -> ('a, [ `One ]) t (** [make_one query] constructs a SQL request with multiplicity one from the query [query]. *) val make_zero_or_one : ('a, 'b) query -> ('a, [ `One | `Zero ]) t (** [make_one query] constructs a SQL request with multiplicity zero or one from the query [query]. *) val make_many : ('a, 'b) query -> ('a, [ `Many | `One | `Zero ]) t (** [make_one query] constructs a SQL request with multiplicity zero or more from the query [query]. *) end module Sqlite3 : sig module Request = Request (** Defines {!Petrol}'s e-DSL for Sqlite3 SQL. {b Note} Typically you should open this module at the start of the file. {[ open Petrol open Petrol.Sqlite3 Expr.[i 1; bl false] (* - : (int * (bool * ())) Expr.expr_list *) ]} *) module Type : sig (** Defines all supported Sqlite types. *) type 'a t = 'a Type.t (** Represents a SQL type. *) val bool : bool t (** [bool] represents the SQL boolean type (internally the type is INTEGER, as Sqlite does not have a dedicated boolean type). *) val int : int t (** [int] represents the SQL INTEGER type. *) val real : float t (** [real] represents the SQL REAL type. *) val text : string t (** [text] represents the SQL TEXT type. *) val blob : string t (** [blob] represents the SQL BLOB type. *) module Numeric = Type.Numeric end module Expr : sig (** Provides an SQL E-DSL for writing well-typed SQL expressions. *) type 'a t = 'a Expr.t (** ['a t] represents an SQL expression that produces a value corresponding to the type ['a]. *) (** Represents a heterogeneous sequence of SQL expressions. {b Note} Provided you have opened the Expr module, you can use List syntax to construct such lists: {[ open Petrol.Sqlite3 Expr.[i 1; bl false] (* - : (int * (bool * ())) Expr.expr_list *) ]} *) type 'a expr_list = 'a Expr.expr_list = | [] : unit expr_list | (::) : ('a t * 'b expr_list) -> ('a * 'b) expr_list type wrapped_assign = Expr.wrapped_assign (** An opaque wrapper that represents an assignment of a value to a particular field in a table. *) (** {1 Constants}*) (** The following functions define constant value expressions. {b Note} For each type, there are two flavours of constant expression: variable and static. The key difference between the two is in terms of how they are represented in the final SQL query - in particular, variable constant expressions are encoded as holes (?) in the query, to which a constant value is supplied, whereas static constant expressions are encoded directly in the query string. As Petrol functions cache the construction of SQL queries by their final string representation, you should prefer the dynamic form if you expect the constant value to change frequently - for example, if it is a constant value that you are receiving from elsewhere. Use the static form if you know that the value doesn't change and will always be the same. *) val i : int -> int t (** [i v] returns an expression that evaluates to the integer value [v]. *) val f : float -> float t (** [f v] returns an expression that evaluates to the real value [v]. *) val s : string -> string t (** [s v] returns an expression that evaluates to the string value [v]. *) val b : string -> string t (** [b v] returns an expression that evaluates to the bytes value [v]. *) val bl : bool -> bool t (** [bl v] returns an expression that evaluates to the bool value [v]. *) val vl: ty:'a Type.t -> 'a -> 'a t (** [vl ~ty value] returns an expression that evaluates to the value [value] with type [ty]. *) val i_stat : int -> int t (** [i_stat v] returns a static expression that evaluates to the integer value [v]. *) val f_stat : float -> float t (** [f_stat v] returns a static expression that evaluates to the real value [v]. *) val s_stat : string -> string t (** [s_stat v] returns a static expression that evaluates to the string value [v]. *) val b_stat : string -> string t (** [b_stat v] returns a static expression that evaluates to the bytes value [v]. *) val true_ : bool t (** [true_] represents the SQL constant [TRUE]. *) val false_ : bool t (** [false_] represents the SQL constant [FALSE]. *) val vl_stat: ty:'a Type.t -> 'a -> 'a t (** [vl_stat ~ty value] returns a static expression that evaluates to the value [value] with type [ty]. *) (** {1 Book-keeping: Types, Naming, Nulls}*) val as_ : 'a t -> name:string -> 'a t * 'a t (** [as_ exp ~name] returns a tuple [(exp',exp'_ref)] where [exp'] is the SQL expression [exp AS name] that names [exp] as [name], and [exp'_ref] is simply [name]. *) val nullable: 'a t -> 'a option t (** [nullable e] encodes the fact that the expression [e] may return [NULL]. *) val is_not_null : 'a t -> bool t (** [is_not_null e] constructs an SQL expression that is [TRUE] iff the expression [e] is not [NULL] and [FALSE] otherwise. *) val is_null : 'a t -> bool t (** [is_null e] constructs an SQL expression that is [TRUE] iff the expression [e] is [NULL] and [FALSE] otherwise. *) val coerce : 'a t -> 'b Type.t -> 'b t (** [coerce expr ty] coerces expression [expr] to the type [ty]. This coercion is not checked, so make sure you know what you're doing or it could fail at runtime. *) val (:=) : 'a t -> 'a t -> wrapped_assign (** [v := expr] returns an SQL expression that can be used with an update or insert clause to change the values in the database. *) val unset : 'a t -> wrapped_assign (** [unset v] returns an SQL expression that can be used with an update query to set a field to NULL in the database. *) (** {1 Operators} *) val ( + ) : int t -> int t -> int t val ( - ) : int t -> int t -> int t val ( * ) : int t -> int t -> int t val ( / ) : int t -> int t -> int t val ( +. ) : float t -> float t -> float t val ( -. ) : float t -> float t -> float t val ( *. ) : float t -> float t -> float t val ( /. ) : float t -> float t -> float t val ( = ) : 'a t -> 'a t -> bool t val ( <> ) : 'a t -> 'a t -> bool t val ( <= ) : 'a t -> 'a t -> bool t val ( < ) : 'a t -> 'a t -> bool t val ( > ) : 'a t -> 'a t -> bool t val ( >= ) : 'a t -> 'a t -> bool t val ( && ) : bool t -> bool t -> bool t val ( || ) : bool t -> bool t -> bool t val not : bool t -> bool t val exists: ('a, [> `SELECT | `SELECT_CORE ]) query -> bool t val in_ : 'a t -> ('a * unit, [> `SELECT | `SELECT_CORE]) query -> bool t val between : lower:'a t -> upper:'a t -> 'a t -> bool t val not_between : lower:'a t -> upper:'a t -> 'a t -> bool t (** {1 Functions} *) val count : ?distinct:bool -> 'a expr_list -> int t val count_star : int t val abs : int t -> int t val max : ?distinct:bool -> int t -> int t val min : ?distinct:bool -> int t -> int t val sum : ?distinct:bool -> int t -> int t val absf : float t -> float t val maxf : ?distinct:bool -> float t -> float t val minf : ?distinct:bool -> float t -> float t val sumf : ?distinct:bool -> float t -> float t val abs_gen : 'a Type.Numeric.t -> 'a t -> 'a t val max_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val min_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val sum_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val total : ?distinct:bool -> int t -> int t val group_concat: ?distinct:bool -> ?sep_by:string t -> string t -> string t val changes : int t val glob : pat:string t -> string t -> bool t val coalesce : 'a t list -> 'a t val like : string t -> pat:string t -> bool t val max_of : int t list -> int t val min_of : int t list -> int t val maxf_of : float t list -> float t val minf_of : float t list -> float t val max_gen_of : 'a Type.Numeric.t -> 'a t list -> 'a t val min_gen_of : 'a Type.Numeric.t -> 'a t list -> 'a t val random : int t val lower : string t -> string t val upper : string t -> string t end end module Postgres : sig module Request = Request (** Defines {!Petrol}'s e-DSL for Postgres SQL. {b Note} Typically you should open this module at the start of the file. {[ open Petrol open Petrol.Postgres Expr.[i 1; bl false] (* - : (int * (bool * ())) Expr.expr_list *) ]} *) module Type : sig (** Defines all supported Postgres types. *) type 'a t = 'a Type.t (** Represents a SQL type. *) val bool : bool t (** [bool] represents the SQL boolean type. *) val int : int t (** [int] represents the SQL INTEGER type. *) val real : float t (** [real] represents the SQL REAL type. *) val text : string t (** [text] represents the SQL TEXT type. *) val big_int : int64 Type.t (** [big_int] represents the SQL BIGINT type. *) val big_serial : int64 Type.t (** [big_serial] represents the SQL BIGSERIAL type. *) val bytea : string Type.t (** [bytea] represents the SQL BYTEA type. *) val character : int -> string Type.t (** [character n] represents the SQL CHARACTER(n) type. *) val character_varying : int -> string Type.t (** [character_varying n] represents the SQL CHARACTER VARYING(n) type. *) val date : Ptime.t Type.t (** [date] represents the SQL DATE type. *) val double_precision : float Type.t (** [double_precision] represents the SQL double_precision type. *) val int4 : int32 Type.t (** [int4] represents the SQL INT4 type. *) val smallint : int Type.t (** [smallint] represents the SQL SMALLINT type. *) val smallserial : int Type.t (** [smallserial] represents the SQL SMALLSERIAL type. *) val time : Ptime.t Type.t (** [time] represents the SQL time type. *) module Numeric = Type.Numeric end module Expr : sig (** Provides an SQL E-DSL for writing well-typed SQL expressions. *) type 'a t = 'a Expr.t (** ['a t] represents an SQL expression that produces a value corresponding to the type ['a]. *) (** Represents a heterogeneous sequence of SQL expressions. {b Note} Provided you have opened the Expr module, you can use List syntax to construct such lists: {[ open Petrol.Sqlite3 Expr.[i 1; bl false] (* - : (int * (bool * ())) Expr.expr_list *) ]} *) type 'a expr_list = 'a Expr.expr_list = | [] : unit expr_list | (::) : ('a t * 'b expr_list) -> ('a * 'b) expr_list type wrapped_assign = Expr.wrapped_assign (** An opaque wrapper that represents an assignment of a value to a particular field in a table. *) (** {1 Constants}*) (** The following functions define constant value expressions. {b Note} For each type, there are two flavours of constant expression: variable and static. The key difference between the two is in terms of how they are represented in the final SQL query - in particular, variable constant expressions are encoded as holes (?) in the query, to which a constant value is supplied, whereas static constant expressions are encoded directly in the query string. As Petrol functions cache the construction of SQL queries by their final string representation, you should prefer the dynamic form if you expect the constant value to change frequently - for example, if it is a constant value that you are receiving from elsewhere. Use the static form if you know that the value doesn't change and will always be the same. *) val i : int -> int t (** [i v] returns an expression that evaluates to the integer value [v]. *) val f : float -> float t (** [f v] returns an expression that evaluates to the real value [v]. *) val s : string -> string t (** [s v] returns an expression that evaluates to the string value [v]. *) val bl : bool -> bool t (** [bl v] returns an expression that evaluates to the bool value [v]. *) val vl: ty:'a Type.t -> 'a -> 'a t (** [vl ~ty value] returns an expression that evaluates to the value [value] with type [ty]. *) val i_stat : int -> int t (** [i_stat v] returns a static expression that evaluates to the integer value [v]. *) val f_stat : float -> float t (** [f_stat v] returns a static expression that evaluates to the real value [v]. *) val s_stat : string -> string t (** [s_stat v] returns a static expression that evaluates to the string value [v]. *) val true_ : bool t (** [true_] represents the SQL constant [TRUE]. *) val false_ : bool t (** [false_] represents the SQL constant [FALSE]. *) val vl_stat: ty:'a Type.t -> 'a -> 'a t (** [vl_stat ~ty value] returns a static expression that evaluates to the value [value] with type [ty]. *) (** {1 Book-keeping: Types, Naming, Nulls}*) val as_ : 'a t -> name:string -> 'a t * 'a t (** [as_ exp ~name] returns a tuple [(exp',exp'_ref)] where [exp'] is the SQL expression [exp AS name] that names [exp] as [name], and [exp'_ref] is simply [name]. *) val nullable: 'a t -> 'a option t (** [nullable e] encodes the fact that the expression [e] may return [NULL]. *) val is_not_null : 'a t -> bool t (** [is_not_null e] constructs an SQL expression that is [TRUE] iff the expression [e] is not [NULL] and [FALSE] otherwise. *) val is_null : 'a t -> bool t (** [is_null e] constructs an SQL expression that is [TRUE] iff the expression [e] is [NULL] and [FALSE] otherwise. *) val coerce : 'a t -> 'b Type.t -> 'b t (** [coerce expr ty] coerces expression [expr] to the type [ty]. This coercion is not checked, so make sure you know what you're doing or it could fail at runtime. *) val (:=) : 'a t -> 'a t -> wrapped_assign (** [v := expr] returns an SQL expression that can be used with an update or insert clause to change the values in the database. *) val unset : 'a t -> wrapped_assign (** [unset v] returns an SQL expression that can be used with an update query to set a field to NULL in the database. *) (** {1 Operators} *) val ( + ) : int t -> int t -> int t val ( - ) : int t -> int t -> int t val ( * ) : int t -> int t -> int t val ( / ) : int t -> int t -> int t val ( +. ) : float t -> float t -> float t val ( -. ) : float t -> float t -> float t val ( *. ) : float t -> float t -> float t val ( /. ) : float t -> float t -> float t val ( = ) : 'a t -> 'a t -> bool t val ( <> ) : 'a t -> 'a t -> bool t val ( <= ) : 'a t -> 'a t -> bool t val ( < ) : 'a t -> 'a t -> bool t val ( > ) : 'a t -> 'a t -> bool t val ( >= ) : 'a t -> 'a t -> bool t val ( && ) : bool t -> bool t -> bool t val ( || ) : bool t -> bool t -> bool t val not : bool t -> bool t val exists: ('a, [> `SELECT | `SELECT_CORE ]) query -> bool t val in_ : 'a t -> ('a * unit, [> `SELECT | `SELECT_CORE]) query -> bool t val between : lower:'a t -> upper:'a t -> 'a t -> bool t val not_between : lower:'a t -> upper:'a t -> 'a t -> bool t val between_symmetric : lower:'a t -> upper:'a t -> 'a t -> bool t val not_between_symmetric : lower:'a t -> upper:'a t -> 'a t -> bool t val is_distinct_from : 'a t -> 'a t -> bool t val is_not_distinct_from : 'a t -> 'a t -> bool t val is_true : bool t -> bool t val is_not_true : bool t -> bool t val is_false : bool t -> bool t val is_not_false : bool t -> bool t val is_unknown : bool t -> bool t val is_not_unknown : bool t -> bool t (** {1 Arithmetic Functions} *) val ceil : float t -> float t val floor : float t -> float t val round : float t -> float t val trunc : float t -> float t val ceili : int t -> int t val floori : int t -> int t val roundi : int t -> int t val trunci : int t -> int t val ceil_gen : ty:'a Type.Numeric.t -> 'a t -> 'a t val floor_gen : ty:'a Type.Numeric.t -> 'a t -> 'a t val round_gen : ty:'a Type.Numeric.t -> 'a t -> 'a t val trunc_gen : ty:'a Type.Numeric.t -> 'a t -> 'a t val pi : float t val sqrt : float t -> float t val degrees : float t -> float t val radians : float t -> float t val exp : float t -> float t val ln : float t -> float t val log10 : float t -> float t val log : base:float t -> float t -> float t val power : float t -> float t -> float t val poweri : int t -> int t -> int t val power_gen : ty:'a Type.Numeric.t -> 'a t -> 'a t -> 'a t val cos : float t -> float t val cosd : float t -> float t val acos : float t -> float t val acosd : float t -> float t val cosh : float t -> float t val acosh : float t -> float t val sin : float t -> float t val sind : float t -> float t val asin : float t -> float t val asind : float t -> float t val sinh : float t -> float t val asinh : float t -> float t val tan : float t -> float t val tand : float t -> float t val atan : float t -> float t val atand : float t -> float t val atan2 : float t -> float t val atan2d : float t -> float t val tanh : float t -> float t val atanh : float t -> float t val cot : float t -> float t val cotd : float t -> float t val factorial : int t -> int t val factorial_gen : ty:'a Type.Numeric.integral -> 'a t -> 'a t val gcd : int t -> int t -> int t val gcd_gen : ty:'a Type.Numeric.integral -> 'a t -> 'a t -> 'a t val lcm : int t -> int t -> int t val lcm_gen : ty:'a Type.Numeric.integral -> 'a t -> 'a t -> 'a t val abs : int t -> int t val absf : float t -> float t val abs_gen : 'a Type.Numeric.t -> 'a t -> 'a t (** {1 String functiosn}*) val concat : string t list -> string t val concat_ws : sep_by:string t -> string t list -> string t val like : string t -> pat:string t -> bool t val lower : string t -> string t val upper : string t -> string t val char_length : string t -> int t val length : string t -> int t val substring : ?from:int t -> ?for_:int t -> string t -> string t val replace : from:string t -> to_:string t -> string t -> string t val reverse : string t -> string t val starts_with : prefix:string t -> string t -> bool t val similar_to : pat:string t -> string t -> bool t (** {1 Aggregate Functions} *) val count : ?distinct:bool -> 'a expr_list -> int t val count_star : int t val coalesce : 'a t list -> 'a t val max : ?distinct:bool -> int t -> int t val maxf : ?distinct:bool -> float t -> float t val max_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val min : ?distinct:bool -> int t -> int t val minf : ?distinct:bool -> float t -> float t val min_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val sum : ?distinct:bool -> int t -> int t val sumf : ?distinct:bool -> float t -> float t val sum_gen : ?distinct:bool -> 'a Type.Numeric.t -> 'a t -> 'a t val greatest : int t list -> int t val greatestf : float t list -> float t val greatest_gen : ty:'a Type.Numeric.t -> 'a t list -> 'a t val least : int t list -> int t val leastf : float t list -> float t val least_gen : ty:'a Type.Numeric.t -> 'a t list -> 'a t (* val max_of : int t list -> int t *) (* val min_of : int t list -> int t *) (* val maxf_of : float t list -> float t *) (* val minf_of : float t list -> float t *) (* val max_gen_of : 'a Type.Numeric.t -> 'a t list -> 'a t *) (* val min_gen_of : 'a Type.Numeric.t -> 'a t list -> 'a t *) val random : float t end end module Schema : sig (** Provides an E-DSL for specifying SQL tables in OCaml. *) type conflict_clause = [ `ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] type foreign_conflict_clause = [ `CASCADE | `NO_ACTION | `RESTRICT | `SET_DEFAULT | `SET_NULL ] type 'a constraint_ (** ['a constraint_] represents a constraint on an SQL column or columns. *) type 'a field (** ['a field] represents an SQL table field definition. *) val field : ?constraints:[`Column] constraint_ list -> string -> ty:'a Type.t -> 'a field (** [field ?constraints name ~ty] constructs a new table column with name [name] and type [ty]. [constraints] are a list of column constraints for the column. {b Note} [name] must be a valid SQL identifier - this is not checked by the function, but will cause an SQL error at runtime. *) type 'a table = [] : unit table | (::) : ('a field * 'b table) -> ('a * 'b) table (** *) (** ['a table] represents a heterogeneous list of fields in a SQL Table schema, where ['a] captures the types of each element. Like {!Expr.expr_list}, if you have opened the Schema module, you can use vanilla list syntax to construct terms of this type. *) val primary_key : ?name:string -> ?ordering:[ `ASC | `DESC ] -> ?on_conflict:conflict_clause -> ?auto_increment:bool -> unit -> [ `Column ] constraint_ (** [primary_key ?name ?ordering ?on_conflict ?auto_increment ()] returns a new SQL column constraint that indicates that the column it is attached to must be the primary key. [name] is an optional name for the constraint for debugging purposes. [ordering] is the ordering of the primary key index. [on_conflict] specifies how to handle conflicts. [auto_increment] specifies whether the primary key should be automatically generated. (Note: not supported for Postgres databases.) *) val table_primary_key : ?name:string -> ?on_conflict:conflict_clause -> string list -> [ `Table ] constraint_ (** [table_primary_key ?name ?on_conflict cols] returns a new SQL table constraint that specifies that the table it is attached to's primary key is over the columns in [cols]. [name] is an optional name for the constraint for debugging purposes. [on_conflict] specifies how to handle conflicts. *) val not_null : ?name:string -> ?on_conflict:conflict_clause -> unit -> [ `Column ] constraint_ (** [not_null ?name ?on_conflict ()] returns a new SQL column constraint that specifies that the column it is attached to's value must not be NULL. [name] is an optional name for the constraint for debugging purposes. [on_conflict] specifies how to handle conflicts. *) val unique : ?name:string -> ?on_conflict:conflict_clause -> unit -> [ `Column ] constraint_ (** [unique ?name ?on_conflict ()] returns a new SQL column constraint that specifies that the column it is attached to's values must be unique. [name] is an optional name for the constraint for debugging purposes. [on_conflict] specifies how to handle conflicts. *) val table_unique : ?name:string -> ?on_conflict:conflict_clause -> string list -> [ `Table ] constraint_ (** [unique ?name ?on_conflict cols] returns a new SQL table constraint that specifies that the table it is attached to's values for the columns [cols] must be unique. [name] is an optional name for the constraint for debugging purposes. [on_conflict] specifies how to handle conflicts. *) val foreign_key : ?name:string -> ?on_update:foreign_conflict_clause -> ?on_delete:foreign_conflict_clause -> table:table_name -> columns:'a Expr.expr_list -> unit -> [ `Column ] constraint_ (** [foreign_key ?name ?on_update ?on_delete ~table ~columns ()] returns a new SQL column constraint that specifies that the column it is attached to's values must be a foreign key into the table [table] with columns [columns]. [name] is an optional name for the constraint for debugging purposes. [on_update] and [on_delete] specifies how to handle conflicts for updates and deletes respectively. *) val table_foreign_key : ?name:string -> ?on_update:foreign_conflict_clause -> ?on_delete:foreign_conflict_clause -> table:table_name -> columns:'a Expr.expr_list -> string list -> [ `Table ] constraint_ (** [table_foreign_key ?name ?on_update ?on_delete ~table ~columns cols] returns a new SQL table constraint that specifies that the table it is attached to's values for the columns [cols] must be a foreign key into the table [table] with columns [columns]. [name] is an optional name for the constraint for debugging purposes. [on_update] and [on_delete] specifies how to handle conflicts for updates and deletes respectively.. *) end module Query : sig (** Provides an E-DSL for specifying SQL queries in OCaml. *) type ('ret_ty, 'query_kind) t = ('ret_ty, 'query_kind) query (** [('ret_ty, 'query_tag) t] represents an SQL query that returns values of type ['ret_ty] and is a SQL query of kind ['query_kind].*) val pp : Format.formatter -> ('ret_ty, 'query_kind) t -> unit (** [pp fmt q] prints the query [q] in a form that can be parsed by an SQL engine. *) type join_op = LEFT (** LEFT join -- keep rows from the left table where the right column is NULL *) | RIGHT (** RIGHT join -- keep rows from the right table where the right column is NULL *) | INNER (** INNER -- only keep rows for which both the left and right of the join are present. *) (** Defines the type of join to be used to combine two tables *) type ('a, 'c) where_fun = bool Expr.t -> ('c, 'a) t -> ('c, 'a) t constraint 'a = [< `DELETE | `SELECT | `SELECT_CORE | `UPDATE ] (** [('a,'c) where_fun] defines the type of an SQL function that corresponds to SQL's WHERE clause. *) type ('a, 'b, 'c) group_by_fun = 'b Expr.expr_list -> ('c, 'a) t -> ('c, 'a) t constraint 'a = [< `SELECT | `SELECT_CORE ] (** [('a,'b,'c) group_by_fun] defines the type of an SQL function that corresponds to SQL's GROUP BY clause. *) type ('a, 'c) having_fun = bool Expr.t -> ('c, 'a) t -> ('c, 'a) t constraint 'a = [< `SELECT | `SELECT_CORE ] (** [('a,'b,'c) having_fun] defines the type of an SQL function that corresponds to SQL's HAVING clause. *) type ('a, 'b, 'd, 'c) join_fun = ?op:join_op -> on:bool Expr.t -> ('b, 'd) t -> ('c, 'a) t -> ('c, 'a) t constraint 'a = [< `SELECT_CORE ] constraint 'd = [< `SELECT_CORE | `SELECT ] (** [('a,'b,'c,'d) join_fun] defines the type of an SQL function that corresponds to SQL's JOIN clause. *) type ('a, 'b, 'c) on_err_fun = 'b -> ('c, 'a) t -> ('c, 'a) t constraint 'a = [> `INSERT | `UPDATE ] constraint 'b = [< `ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] (** [('a,'b,'c) having_fun] defines the type of an SQL function that corresponds to SQL's HAVING clause ON ERR. *) val select : 'a Expr.expr_list -> from:table_name -> ('a, [> `SELECT_CORE ]) t (** [select fields ~from] corresponds to the SQL [SELECT {fields} FROM {from}]. *) val update : table:table_name -> set:Expr.wrapped_assign list -> (unit, [> `UPDATE ]) t (** [update ~table ~set] corresponds to the SQL [UPDATE {set} FROM {table}]. *) val insert : table:table_name -> values:Expr.wrapped_assign list -> (unit, [> `INSERT ]) t (** [insert ~table ~values] corresponds to the SQL [INSERT {values} INTO {table}]. *) val delete : from:table_name -> (unit, [> `DELETE ]) t (** [delete ~from] corresponds to the SQL [DELETE FROM {from}]. *) val where : ([< `DELETE | `SELECT | `SELECT_CORE | `UPDATE ], 'c) where_fun (** [where by expr] corresponds to the SQL [{expr} WHERE {by}]. *) val group_by : ([< `SELECT | `SELECT_CORE ], 'b, 'c) group_by_fun (** [group_by fields expr] corresponds to the SQL [{expr} GROUP BY {fields}]. *) val having : ([< `SELECT | `SELECT_CORE ], 'c) having_fun (** [having fields expr] corresponds to the SQL [{expr} HAVING {fields}]. *) val join : ([ `SELECT_CORE ], 'b, [< `SELECT_CORE | `SELECT ], 'c) join_fun (** [join ?op ~on oexpr expr] corresponds to the SQL [{expr} {op} JOIN {oexpr} ON {expr}]. The ordering of the last two arguments has been chosen to allow easily piping this with another SQL query. *) val on_err : [ `ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] -> (unit, 'a) t -> (unit, 'a) t (** [on_err err expr] corresponds to the SQL [{expr} ON ERR {err}]. *) val limit : int Expr.t -> ('a, [< `SELECT | `SELECT_CORE ]) t -> ('a, [> `SELECT ]) t (** [limit count expr] corresponds to the SQL [{expr} LIMIT {count}]. *) val offset : int Expr.t -> ('a, [< `SELECT | `SELECT_CORE ]) t -> ('a, [> `SELECT ]) t (** [offset count expr] corresponds to the SQL [{expr} OFFSET {fields}]. *) val order_by : ?direction:[ `ASC | `DESC ] -> 'a Expr.t -> ('b, [< `SELECT | `SELECT_CORE ]) t -> ('b, [> `SELECT ]) t (** [order_by ?direction fields expr] corresponds to the SQL [{expr} ORDER BY {direction} {fields}]. *) val order_by_ : ?direction:[ `ASC | `DESC ] -> 'a Expr.expr_list -> ('b, [< `SELECT | `SELECT_CORE ]) t -> ('b, [> `SELECT ]) t (** [order_by_ ?direction fields expr] corresponds to the SQL [{expr} ORDER BY {direction} {fields}]. (In contrast to {!Petrol.Query.order_by}, this function allows passing a list of elements to be ordered by) *) end module StaticSchema : sig (** Provides a helper interface, primarily for prototyping/debugging, that declares a static table without any versioning. *) type t (** A global schema, primarily intended for testing. See also {!VersionedSchema.t}, which is the recommended alternative, especially if you expect the schema to change in the future. {b Note} A schema [t] here represents a collection of table schemas but doesn't have to be an exhaustive enumeration - i.e it is possible to have multiple [t] valid for a given SQL database provided they refer to disjoint collections of tables. *) val init: unit -> t (** [init version ~name] constructs a new schema. *) val declare_table : t -> ?constraints:[`Table] Schema.constraint_ list -> name:string -> 'a Schema.table -> table_name * 'a Expr.expr_list (** [declare_table t ?constraints ~name table_spec] declares a new table on the schema [t] with the name [name]. [constraints] are a list of SQL constraints on the columns of the table. *) val initialise : t -> (module Caqti_lwt.CONNECTION) -> (unit, [> Caqti_error.t ]) Lwt_result.t (** [initialise t conn] initialises the SQL schema on [conn]. *) end module VersionedSchema : sig (** Provides an interface that declares a versioned schema. *) type t (** A versioned schema. {b Note} A schema [t] here represents a collection of table schemas but doesn't have to be an exhaustive enumeration - i.e it is possible to have multiple [t] valid for a given SQL database provided they refer to disjoint collections of tables. *) type version = private int list (** Lexiographically ordered schema version numbers *) type migration = (unit, unit, [`Zero]) Caqti_request.t (** Represents SQL statements required to update the schema over versions. *) val version: int list -> version (** [version ls] constructs a new version number from [ls]. *) val init: ?migrations:(version * migration list) list -> version -> name:string -> t (** [init ?migrations dialect version ~name] constructs a new versioned schema declaring it to have the name [name] and version [version] using SQL dialect [dialect]. [name] is the name of the schema -- used to initially determine the stored version number, and is required to stay constant over the lifetime of the project. [version] is the current version of the schema -- note that {!initialise} will fail if it is run using an SQL database has a newer version than the version declared here. [migrations] is an association list, mapping versions to the SQL statements required to migrate the schema to the new format from its previous version. The order of elements in [migrations] is irrelevant. *) val declare_table : t -> ?since:version -> ?constraints:[`Table] Schema.constraint_ list -> ?migrations:(version * migration list) list -> name:string -> 'a Schema.table -> table_name * 'a Expr.expr_list (** [declare_table t ?since ?constraints ?migrations ~name table_spec] declares a new table on the schema [t] with the name [name]. [since] declares the first version in which this table was introduced -- if omitted, Petrol assumes the table has been present since the very first version. [constraints] are a list of SQL constraints on the columns of the table. [migrations] is an association list, mapping versions to the SQL statements required to migrate this table to the new format from its previous version. The order of elements in [migrations] is irrelevant. *) val migrations_needed : t -> (module Caqti_lwt.CONNECTION) -> (bool, [> Caqti_error.t | `Newer_version_than_supported of version ]) Lwt_result.t (** [migrations_needed t conn] returns a boolean indicating whether the current version on the SQL database will require migrations -- i.e whether running {!initialise} will run migrations. [migrations_needed] will also fail if it is run using an SQL database has a newer version than the version declared here. {b Note} [migrations_needed] reserves the table name [petrol_<schema_name>_version_db] in the database. *) val initialise : t -> (module Caqti_lwt.CONNECTION) -> (unit, [> Caqti_error.t | `Newer_version_than_supported of version ]) Lwt_result.t (** [initialise t conn] initialises the SQL database on [conn], performing any necessary migrations if needed. [initialise] will fail if it is run using an SQL database has a newer version than the version declared here. {b Note} [initialise] reserves the table name [petrol_<schema_name>_version_db] in the database. *) end val exec : (module Caqti_lwt.CONNECTION) -> (unit, [< `Zero ]) request -> (unit, [> Caqti_error.call_or_retrieve ]) result Lwt.t (** [exec db req] executes a unit SQL request [req] on the SQL database [db]. *) val find : (module Caqti_lwt.CONNECTION) -> ('a, [< `One ]) request -> ('a, [> Caqti_error.call_or_retrieve ]) result Lwt.t (** [find db req] executes a singleton SQL request [req] on the SQL database [db] returning the result. *) val find_opt : (module Caqti_lwt.CONNECTION) -> ('a, [< `One | `Zero ]) request -> ('a option, [> Caqti_error.call_or_retrieve ]) result Lwt.t (** [find_opt db req] executes a zero-or-one SQL request [req] on the SQL database [db] returning the result if it exists. *) val collect_list : (module Caqti_lwt.CONNECTION) -> ('a, [< `Many | `One | `Zero ]) request -> ('a list, [> Caqti_error.call_or_retrieve ]) result Lwt.t (** [collect_list db req] executes a SQL request [req] on the SQL database [db] and collects the results into a list. *)
dune
(executable (name main) (preprocess (action (run pp/pp.exe %{input-file}))))
b0_unit.ml
open B00_std open B00_std.Fut.Syntax open B00 (* A bit of annoying recursive definition. *) module rec Build_def : sig type t = { u : build_ctx; b : build_state } and build_ctx = { current : Unit.t option; m : Memo.t; } and build_state = { root_dir : Fpath.t; b0_dir : Fpath.t; build_dir : Fpath.t; shared_build_dir : Fpath.t; store : Store.t; must_build : Unit.Set.t; may_build : Unit.Set.t; mutable requested : Unit.t String.Map.t; mutable waiting : Unit.t Rqueue.t; } end = struct type t = { u : build_ctx; b : build_state } and build_ctx = { current : Unit.t option; m : Memo.t; } and build_state = { root_dir : Fpath.t; b0_dir : Fpath.t; build_dir : Fpath.t; shared_build_dir : Fpath.t; store : Store.t; must_build : Unit.Set.t; may_build : Unit.Set.t; mutable requested : Unit.t String.Map.t; mutable waiting : Unit.t Rqueue.t; } end and Unit_def : sig type proc = Build_def.t -> unit Fut.t type action = Build_def.t -> t -> args:string list -> Os.Exit.t Fut.t and t = { def : B0_def.t; proc : proc; action : action option } include B0_def.VALUE with type t := t end = struct type proc = Build_def.t -> unit Fut.t type action = Build_def.t -> t -> args:string list -> Os.Exit.t Fut.t and t = { def : B0_def.t; proc : proc; action : action option } let def_kind = "unit" let def u = u.def let pp_name_str = Fmt.(code string) end and Unit : sig include B0_def.S with type t = Unit_def.t end = B0_def.Make (Unit_def) (* Build procedures *) type build = Build_def.t type proc = Unit_def.proc let proc_nop b = Fut.return () (* Build units *) type action = Unit_def.action include Unit let v ?doc ?meta ?action n proc = let def = define ?doc ?meta n in let u = { Unit_def.def; proc; action } in add u; u let proc u = u.Unit_def.proc let action u = u.Unit_def.action let pp_synopsis ppf v = let pp_tag ppf u = let tag, style = (if has_meta B0_meta.exe u then "exe", [`Fg `Green] else if has_meta B0_meta.lib u then "lib", [`Fg `Magenta] else if has_meta B0_meta.doc u then "doc", [`Fg `Yellow] else " ", [`Fg `Cyan]) in Fmt.tty_string style ppf "["; Fmt.string ppf tag; Fmt.tty_string style ppf "]"; in Fmt.pf ppf "@[%a %a@]" pp_tag v pp_synopsis v let pp ppf v = let pp_non_empty ppf m = match B0_meta.is_empty m with | true -> () | false -> Fmt.pf ppf "@, @[%a@]" B0_meta.pp m in Fmt.pf ppf "@[<v>%a%a@]" pp_synopsis v pp_non_empty (meta v) (* Predefined actions *) module Action = struct let exec_cwd = let doc = "Current working directory for outcome action." in let pp_value = Fmt.any "<built value>" in B0_meta.Key.v "action-cwd" ~doc ~pp_value let scope_cwd b u = (* FIXME c&p with B0_build.scope_dir *) Fut.return @@ match B0_def.scope_dir (def u) with | None -> b.Build_def.b.root_dir | Some dir -> dir let exec_env = let doc = "Process environment for outcome action." in let pp_value = Fmt.any "<built value>" in B0_meta.Key.v "action-env" ~doc ~pp_value let exec_file build u exe_file cmd = let get_exec_meta = function | None -> Fut.return None | Some f -> Fut.map Option.some (f build u) in let* cwd = get_exec_meta (find_meta exec_cwd u) in let* env = get_exec_meta (find_meta exec_env u) in Fut.return (Os.Exit.exec ?env ?cwd exe_file cmd) let exec build u ~args = match get_meta B0_meta.exe_file u with | Error e -> Log.err (fun m -> m "%s" e); Fut.return B00_cli.Exit.some_error | Ok exe_file -> let* exe_file = exe_file in let exe = Fpath.basename exe_file in let cmd = Cmd.(atom exe %% list args) in exec_file build u exe_file cmd end (* Builds *) module Build = struct type build_unit = Unit.t include Build_def let memo b = b.u.m (* Units *) let must_build b = b.b.must_build let may_build b = b.b.may_build let current b = match b.u.current with | None -> invalid_arg "Build not running" | Some u -> u let require b u = if String.Map.mem (name u) b.b.requested then () else match Unit.Set.mem u b.b.may_build with | true -> b.b.requested <- String.Map.add (name u) u b.b.requested; Rqueue.add b.b.waiting u | false -> Memo.fail b.u.m "@[<v>Unit %a requested %a which is not part of the build.@,\ Try with %a or add the unit %a to the build." pp_name (current b) pp_name u Fmt.(code string) "--unlock" pp_name u let current_meta b = meta (current b) (* Directories *) let scope_dir b u = match B0_def.scope_dir (def u) with | None -> b.b.root_dir | Some dir -> dir let current_scope_dir b = scope_dir b (current b) let build_dir b u = B0_dir.unit_build_dir ~build_dir:b.b.build_dir ~name:(name u) let current_build_dir b = build_dir b (current b) let shared_build_dir b = b.b.shared_build_dir let in_build_dir b p = Fpath.(build_dir b (current b) // p) let in_shared_build_dir b p = Fpath.(b.b.shared_build_dir // p) let in_scope_dir b p = Fpath.(scope_dir b (current b) // p) (* Store *) let self = Store.key @@ fun _ -> failwith "B0_build.self was not set at store creation" let store b = b.b.store let get b k = Store.get b.b.store k (* Create *) let create ~root_dir ~b0_dir ~variant m ~may_build ~must_build = let u = { current = None; m } in let build_dir = B0_dir.build_dir ~b0_dir ~variant in let shared_build_dir = B0_dir.shared_build_dir ~build_dir in let store = Store.create m ~dir:(B0_dir.store_dir ~build_dir) [] in let may_build = Set.union may_build must_build in let add_requested u acc = String.Map.add (name u) u acc in let requested = Unit.Set.fold add_requested must_build String.Map.empty in let waiting = let q = Rqueue.empty () in Unit.Set.iter (Rqueue.add q) must_build; q in let b = { root_dir; b0_dir; build_dir; shared_build_dir; store; must_build; may_build; requested; waiting; } in let b = { u; b } in Store.set store self b; b (* Run *) let run_unit b unit = let m = Memo.with_mark b.u.m (name unit) in let u = { current = Some unit; m } in let b = { b with u } in Memo.run_proc m begin fun () -> let* () = Memo.mkdir b.u.m (build_dir b unit) in (proc unit) b end let rec run_units b = match Rqueue.take b.b.waiting with | Some u -> run_unit b u; run_units b | None -> Memo.stir ~block:true b.u.m; if Rqueue.length b.b.waiting = 0 then () else run_units b let log_file b = Fpath.(b.b.build_dir / "_log") let write_log_file ~log_file m = Log.if_error ~use:() @@ B00_cli.Memo.Log.(write log_file (of_memo m)) let report_memo_errors ppf m = match Memo.status m with | Ok _ as v -> v | Error e -> let read_howto = Fmt.any "b0 log -r " in let write_howto = Fmt.any "b0 log -w " in B000_conv.Op.pp_aggregate_error ~read_howto ~write_howto () ppf e; Error () let run b = let log_file = (* FIXME we likely want to surface that at the API level. Either at create or run *) log_file b in let hook () = write_log_file ~log_file b.u.m in Os.Exit.on_sigint ~hook @@ fun () -> begin Memo.run_proc b.u.m begin fun () -> let* () = Memo.delete b.u.m b.b.build_dir in let* () = Memo.mkdir b.u.m b.b.build_dir in let* () = Memo.mkdir b.u.m (Store.dir b.b.store) in run_units b; Fut.return () end; Memo.stir ~block:true b.u.m; let ret = report_memo_errors Fmt.stderr b.u.m in Log.time (fun _ m -> m "deleting trash") begin fun () -> Log.if_error ~use:() (Memo.delete_trash ~block:false b.u.m) end; write_log_file ~log_file b.u.m; ret end end (*--------------------------------------------------------------------------- Copyright (c) 2020 The b0 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) 2020 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*)
c_to_generic.mli
(* may raise AST_generic.Error *) val program : Ast_c.program -> AST_generic.program val any : Ast_c.any -> AST_generic.any
(* may raise AST_generic.Error *) val program : Ast_c.program -> AST_generic.program
dune
(executables (names test_async test_lwt) (flags (:standard -w -27 -w -33)) (modules test_async test_lwt aws_sqs_test) (libraries aws aws_sqs aws-async aws-lwt oUnit yojson async cohttp-async lwt cohttp-lwt cohttp-lwt-unix)) (rule (alias runtest) (deps test_async.exe) (action (run %{deps}))) (rule (alias runtest) (deps test_lwt.exe) (action (run %{deps})))
dune
(executable (name discover) (modules discover) (libraries dune-configurator))
unix_unlink_job.c
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */ /* Informations: - this is the expected prototype of the C function [unlink]: int unlink(char* path) - these are the expected ocaml externals for this job: external unlink_job : string -> unit Lwt_unix.job = "lwt_unix_unlink_job" external unlink_sync : string -> unit = "lwt_unix_unlink_sync" */ /* Caml headers. */ #include <lwt_unix.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/fail.h> #include <caml/signals.h> #if !defined(LWT_ON_WINDOWS) /* Specific headers. */ #include <errno.h> #include <string.h> #include <unistd.h> /* +-----------------------------------------------------------------+ | Asynchronous job | +-----------------------------------------------------------------+ */ /* Structure holding informations for calling [unlink]. */ struct job_unlink { /* Informations used by lwt. It must be the first field of the structure. */ struct lwt_unix_job job; /* This field store the result of the call. */ int result; /* This field store the value of [errno] after the call. */ int errno_copy; /* in parameter. */ char* path; /* Buffer for string parameters. */ char data[]; }; /* The function calling [unlink]. */ static void worker_unlink(struct job_unlink* job) { /* Perform the blocking call. */ job->result = unlink(job->path); /* Save the value of errno. */ job->errno_copy = errno; } /* The function building the caml result. */ static value result_unlink(struct job_unlink* job) { /* Check for errors. */ if (job->result < 0) { /* Save the value of errno so we can use it once the job has been freed. */ int error = job->errno_copy; /* Copy the contents of job->path into a caml string. */ value string_argument = caml_copy_string(job->path); /* Free the job structure. */ lwt_unix_free_job(&job->job); /* Raise the error. */ unix_error(error, "unlink", string_argument); } /* Free the job structure. */ lwt_unix_free_job(&job->job); /* Return the result. */ return Val_unit; } /* The stub creating the job structure. */ CAMLprim value lwt_unix_unlink_job(value path) { /* Get the length of the path parameter. */ mlsize_t len_path = caml_string_length(path) + 1; /* Allocate a new job. */ struct job_unlink* job = lwt_unix_new_plus(struct job_unlink, len_path); /* Set the offset of the path parameter inside the job structure. */ job->path = job->data; /* Copy the path parameter inside the job structure. */ memcpy(job->path, String_val(path), len_path); /* Initializes function fields. */ job->job.worker = (lwt_unix_job_worker)worker_unlink; job->job.result = (lwt_unix_job_result)result_unlink; /* Wrap the structure into a caml value. */ return lwt_unix_alloc_job(&job->job); } #else /* !defined(LWT_ON_WINDOWS) */ CAMLprim value lwt_unix_unlink_job(value Unit) { lwt_unix_not_available("unlink"); return Val_unit; } #endif /* !defined(LWT_ON_WINDOWS) */
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */
bootstrap_storage.ml
open Misc let init_account ctxt ({ public_key_hash ; public_key ; amount }: Parameters_repr.bootstrap_account) = let contract = Contract_repr.implicit_contract public_key_hash in Contract_storage.credit ctxt contract amount >>=? fun ctxt -> match public_key with | Some public_key -> Contract_storage.reveal_manager_key ctxt contract public_key >>=? fun ctxt -> Delegate_storage.set ctxt contract (Some public_key_hash) >>=? fun ctxt -> return ctxt | None -> return ctxt let init_contract ~typecheck ctxt ({ delegate ; amount ; script }: Parameters_repr.bootstrap_contract) = Contract_storage.fresh_contract_from_current_nonce ctxt >>=? fun (ctxt, contract) -> typecheck ctxt script >>=? fun ctxt -> Contract_storage.originate ctxt contract ~balance:amount ~prepaid_bootstrap_storage:true ~manager:Signature.Public_key_hash.zero ~script:(script, None) ~delegate:(Some delegate) ~spendable:false ~delegatable:false >>=? fun ctxt -> return ctxt let init ctxt ~typecheck ?ramp_up_cycles ?no_reward_cycles accounts contracts = let nonce = Operation_hash.hash_bytes [ MBytes.of_string "Un festival de GADT." ] in let ctxt = Raw_context.init_origination_nonce ctxt nonce in fold_left_s init_account ctxt accounts >>=? fun ctxt -> fold_left_s (init_contract ~typecheck) ctxt contracts >>=? fun ctxt -> begin match no_reward_cycles with | None -> return ctxt | Some cycles -> (* Store pending ramp ups. *) let constants = Raw_context.constants ctxt in (* Start without reward *) Raw_context.patch_constants ctxt (fun c -> { c with block_reward = Tez_repr.zero ; endorsement_reward = Tez_repr.zero }) >>= fun ctxt -> (* Store the final reward. *) Storage.Ramp_up.Rewards.init ctxt (Cycle_repr.of_int32_exn (Int32.of_int cycles)) (constants.block_reward, constants.endorsement_reward) end >>=? fun ctxt -> match ramp_up_cycles with | None -> return ctxt | Some cycles -> (* Store pending ramp ups. *) let constants = Raw_context.constants ctxt in Lwt.return Tez_repr.(constants.block_security_deposit /? Int64.of_int cycles) >>=? fun block_step -> Lwt.return Tez_repr.(constants.endorsement_security_deposit /? Int64.of_int cycles) >>=? fun endorsement_step -> (* Start without security_deposit *) Raw_context.patch_constants ctxt (fun c -> { c with block_security_deposit = Tez_repr.zero ; endorsement_security_deposit = Tez_repr.zero }) >>= fun ctxt -> fold_left_s (fun ctxt cycle -> Lwt.return Tez_repr.(block_step *? Int64.of_int cycle) >>=? fun block_security_deposit -> Lwt.return Tez_repr.(endorsement_step *? Int64.of_int cycle) >>=? fun endorsement_security_deposit -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int cycle) in Storage.Ramp_up.Security_deposits.init ctxt cycle (block_security_deposit, endorsement_security_deposit)) ctxt (1 --> (cycles - 1)) >>=? fun ctxt -> (* Store the final security deposits. *) Storage.Ramp_up.Security_deposits.init ctxt (Cycle_repr.of_int32_exn (Int32.of_int cycles)) (constants.block_security_deposit, constants.endorsement_security_deposit) >>=? fun ctxt -> return ctxt let cycle_end ctxt last_cycle = let next_cycle = Cycle_repr.succ last_cycle in begin Storage.Ramp_up.Rewards.get_option ctxt next_cycle >>=? function | None -> return ctxt | Some (block_reward, endorsement_reward) -> Storage.Ramp_up.Rewards.delete ctxt next_cycle >>=? fun ctxt -> Raw_context.patch_constants ctxt (fun c -> { c with block_reward ; endorsement_reward }) >>= fun ctxt -> return ctxt end >>=? fun ctxt -> Storage.Ramp_up.Security_deposits.get_option ctxt next_cycle >>=? function | None -> return ctxt | Some (block_security_deposit, endorsement_security_deposit) -> Storage.Ramp_up.Security_deposits.delete ctxt next_cycle >>=? fun ctxt -> Raw_context.patch_constants ctxt (fun c -> { c with block_security_deposit ; endorsement_security_deposit }) >>= fun ctxt -> return 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. *) (* *) (*****************************************************************************)
get_file.ml
open Lwt module D = Dropbox_lwt_unix let download t fn = D.get_file t fn >>= function | None -> Lwt_io.printlf "No file named %S." fn | Some(m, stream) -> (* Save stream to the disk *) let fname = Filename.basename fn in Lwt_unix.(openfile fname [O_WRONLY; O_CREAT; O_TRUNC] 0o664) >>= fun fd -> let write s = let s = Bytes.of_string s in Lwt_unix.write fd s 0 (Bytes.length s) >>= fun _ -> return_unit in Lwt_stream.iter_s write stream >>= fun () -> Lwt_unix.close fd >>= fun () -> let modified = match m.D.modified with | Some d -> ", " ^ Dropbox.Date.to_string d | None -> "" in Lwt_io.printlf "Wrote %S (%s, %s)%s" fn m.D.size m.D.mime_type modified let main t args = match args with | [] -> Lwt_io.printlf "No file specified." | _ -> (* You can replace Lwt_list.iter_p by Lwt_list.iter_s for a sequential download and see how much slower it is. *) Lwt_list.iter_p (download t) args let () = Common.run main
exparser.ml
#load "q_MLast.cmo"; type spat_comp = [ SpTrm of MLast.loc and MLast.patt and MLast.v (option MLast.expr) | SpNtr of MLast.loc and MLast.patt and MLast.expr | SpLet of MLast.loc and MLast.patt and MLast.expr | SpLhd of MLast.loc and list (list MLast.patt) | SpStr of MLast.loc and MLast.patt ] ; type sexp_comp = [ SeTrm of MLast.loc and MLast.expr | SeNtr of MLast.loc and MLast.expr ] ; type spat_comp_opt = [ SpoNoth | SpoBang | SpoQues of MLast.expr ] ; type spat_parser_ast = (option MLast.patt * list (list (spat_comp * spat_comp_opt) * option MLast.patt * MLast.expr)) ; value strm_n = "strm__"; value peek_fun loc = <:expr< Stream.peek >>; value junk_fun loc = <:expr< Stream.junk >>; (* Parsers *) value rec pattern_eq_expression p e = match (p, e) with [ (<:patt< $lid:a$ >>, <:expr< $lid:b$ >>) -> a = b | (<:patt< $uid:a$ >>, <:expr< $uid:b$ >>) -> a = b | (<:patt< $p1$ $p2$ >>, <:expr< $e1$ $e2$ >>) -> pattern_eq_expression p1 e1 && pattern_eq_expression p2 e2 | _ -> False ] ; value is_raise e = match e with [ <:expr< raise $_$ >> -> True | _ -> False ] ; value is_raise_failure e = match e with [ <:expr< raise Stream.Failure >> -> True | _ -> False ] ; value rec handle_failure e = match e with [ <:expr< try $te$ with [ Stream.Failure -> $e$] >> -> handle_failure e | <:expr< match $me$ with [ $list:pel$ ] >> -> handle_failure me && List.for_all (fun [ (_, <:vala< None >>, e) -> handle_failure e | _ -> False ]) pel | <:expr< let $list:pel$ in $e$ >> -> List.for_all (fun (p, e, _) -> handle_failure e) pel && handle_failure e | <:expr< do { $list:el$ } >> -> List.for_all handle_failure el | <:expr< $uid:_$ . $_$ >> | <:expr< $lid:_$ >> | <:expr< $int:_$ >> | <:expr< $str:_$ >> | <:expr< $chr:_$ >> | <:expr< fun [ $list:_$ ] >> | <:expr< $uid:_$ >> -> True | <:expr< raise $e$ >> -> match e with [ <:expr< Stream.Failure >> -> False | _ -> True ] | <:expr< $f$ $x$ >> -> no_raising_failure_fun f && handle_failure f && handle_failure x | _ -> False ] and no_raising_failure_fun = fun [ <:expr< $uid:_$ >> -> True | <:expr< $lid:_$ >> -> False | <:expr< Stream.peek >> | <:expr< Stream.junk >> -> True | <:expr< $x$ $y$ >> -> no_raising_failure_fun x && handle_failure y | _ -> False ] ; value rec subst v e = match e with [ <:expr:< $lid:x$ >> -> let x = if x = v then strm_n else x in <:expr< $lid:x$ >> | <:expr< $uid:_$ >> -> e | <:expr< $int:_$ >> -> e | <:expr< $chr:_$ >> -> e | <:expr< $str:_$ >> -> e | <:expr< $_$ . $_$ >> -> e | <:expr:< let $flag:rf$ $list:pel$ in $e$ >> -> <:expr< let $flag:rf$ $list:List.map (subst_pe v) pel$ in $subst v e$ >> | <:expr:< $e1$ $e2$ >> -> <:expr< $subst v e1$ $subst v e2$ >> | <:expr:< ( $list:el$ ) >> -> <:expr< ( $list:List.map (subst v) el$ ) >> | _ -> raise Not_found ] and subst_pe v (p, e, attrs) = match p with [ <:patt< $lid:v'$ >> when v <> v' -> (p, subst v e, attrs) | _ -> raise Not_found ] ; value optim = ref True; Pcaml.add_option "-no-pa-opt" (Arg.Clear optim) "No parsers optimization."; value rec perhaps_bound s = fun [ <:expr< ($list:el$) >> -> List.exists (perhaps_bound s) el | <:expr< $uid:_$ >> | <:expr< $str:_$ >> -> False | _ -> True ] ; value wildcard_if_not_bound p e = match p with [ <:patt:< $lid:s$ >> -> if perhaps_bound s e then p else <:patt< _ >> | _ -> p ] ; value stream_pattern_component skont ckont = fun [ SpTrm loc p wo -> <:expr< match $peek_fun loc$ $lid:strm_n$ with [ Some $p$ $_opt:wo$ -> do { $junk_fun loc$ $lid:strm_n$; $skont$ } | _ -> $ckont$ ] >> | SpNtr loc p e -> let e = match e with [ <:expr< fun [ ($lid:v$ : Stream.t _) -> $e$ ] >> when v = strm_n -> e | _ -> <:expr< $e$ $lid:strm_n$ >> ] in if optim.val then if pattern_eq_expression p skont then if is_raise_failure ckont then e else if handle_failure e then e else <:expr< try $e$ with [ Stream.Failure -> $ckont$ ] >> else if is_raise_failure ckont then let p = wildcard_if_not_bound p skont in <:expr< let $p$ = $e$ in $skont$ >> else if is_raise ckont then let tst = if handle_failure e then e else <:expr< try $e$ with [ Stream.Failure -> $ckont$ ] >> in let p = wildcard_if_not_bound p skont in <:expr< let $p$ = $tst$ in $skont$ >> else if pattern_eq_expression <:patt< Some $p$ >> skont then <:expr< try Some $e$ with [ Stream.Failure -> $ckont$ ] >> else <:expr< match try Some $e$ with [ Stream.Failure -> None ] with [ Some $p$ -> $skont$ | _ -> $ckont$ ] >> else <:expr< match try Some $e$ with [ Stream.Failure -> None ] with [ Some $p$ -> $skont$ | _ -> $ckont$ ] >> | SpLet _ _ _ -> assert False | SpLhd loc [pl :: pll] -> let mklistpat loc pl = List.fold_right (fun p1 p2 -> <:patt< [$p1$ :: $p2$] >>) pl <:patt< [] >> in let len = List.length pl in if List.exists (fun pl -> List.length pl <> len) pll then Ploc.raise loc (Stream.Error "lookahead patterns must be of the same lengths") else let p = let p = mklistpat loc pl in let pl = List.map (mklistpat loc) pll in List.fold_left (fun p1 p2 -> <:patt< $p1$ | $p2$ >>) p pl in <:expr< match Stream.npeek $int:string_of_int len$ strm__ with [ $p$ -> $skont$ | _ -> $ckont$ ] >> | SpLhd loc [] -> ckont | SpStr loc p -> try match p with [ <:patt< $lid:v$ >> -> <:expr< let $lid:v$ = strm__ in $skont$ >> (* subst v skont *) | _ -> raise Not_found ] with [ Not_found -> <:expr< let $p$ = $lid:strm_n$ in $skont$ >> ] ] ; value rec stream_pattern loc epo e ekont = fun [ [] -> match epo with [ Some ep -> <:expr< let $ep$ = Stream.count $lid:strm_n$ in $e$ >> | _ -> e ] | [(SpLet loc p1 e1, _) :: spcl] -> let skont = stream_pattern loc epo e ekont spcl in <:expr< let $p1$ = $e1$ in $skont$ >> | [(spc, err) :: spcl] -> let skont = let ekont = fun [ SpoQues estr -> <:expr< raise (Stream.Error $estr$) >> | SpoBang -> <:expr< raise Stream.Failure >> | SpoNoth -> <:expr< raise (Stream.Error "") >> ] in stream_pattern loc epo e ekont spcl in let ckont = ekont err in stream_pattern_component skont ckont spc ] ; value stream_patterns_term loc ekont tspel = let pel = List.map (fun (p, w, loc, spcl, epo, e) -> let p = <:patt< Some $p$ >> in let e = let ekont = fun [ SpoQues estr -> <:expr< raise (Stream.Error $estr$) >> | SpoBang -> <:expr< raise Stream.Failure >> | SpoNoth -> <:expr< raise (Stream.Error "") >> ] in let skont = stream_pattern loc epo e ekont spcl in <:expr< do { $junk_fun loc$ $lid:strm_n$; $skont$ } >> in (p, w, e)) tspel in let pel = pel @ [(<:patt< _ >>, <:vala< None >>, ekont ())] in <:expr< match $peek_fun loc$ $lid:strm_n$ with [ $list:pel$ ] >> ; value rec group_terms = fun [ [([(SpTrm loc p w, SpoNoth) :: spcl], epo, e) :: spel] -> let (tspel, spel) = group_terms spel in ([(p, w, loc, spcl, epo, e) :: tspel], spel) | spel -> ([], spel) ] ; value rec parser_cases loc = fun [ [] -> <:expr< raise Stream.Failure >> | spel -> if optim.val then match group_terms spel with [ ([], [(spcl, epo, e) :: spel]) -> stream_pattern loc epo e (fun _ -> parser_cases loc spel) spcl | (tspel, spel) -> stream_patterns_term loc (fun _ -> parser_cases loc spel) tspel ] else match spel with [ [(spcl, epo, e) :: spel] -> stream_pattern loc epo e (fun _ -> parser_cases loc spel) spcl | [] -> <:expr< raise Stream.Failure >> ] ] ; (* optim: left factorization of consecutive rules *) type tree_node 'a 'b = [ Node of 'a and list (tree_node 'a 'b) | Leaf of 'b ] ; value rec map_tree_node f_node f_leaf = fun [ Node x tl -> f_node x (List.map (map_tree_node f_node f_leaf) tl) | Leaf b -> f_leaf b ] ; value rec insert_in_tree eq (l, a) tl = match tl with [ [Node n tl1 :: tl2] -> match l with [ [x :: l] -> if eq x n then [Node n (insert_in_tree eq (l, a) tl1) :: tl2] else [List.fold_right (fun x n -> Node x [n]) [x :: l] (Leaf a) :: tl] | [] -> loop tl where rec loop = fun [ [Node n tl1 :: tl] -> [Node n tl1 :: loop tl] | tl -> [Leaf a :: tl] ] ] | _ -> [List.fold_right (fun x n -> Node x [n]) l (Leaf a) :: tl] ] ; value tree_of_list eq ll = List.fold_right (insert_in_tree eq) ll []; value rec list_of_tree mk_node mk_leaf tl = List.map (map_tree_node mk_node mk_leaf) tl ; value eq_spat_comp spc1 spc2 = match (spc1, spc2) with [ (SpTrm _ p1 <:vala< None >>, SpTrm _ p2 <:vala< None >>) -> Reloc.eq_patt p1 p2 | (SpNtr _ p1 e1, SpNtr _ p2 e2) -> Reloc.eq_patt p1 p2 && Reloc.eq_expr e1 e2 | _ -> False ] ; value eq_spo spco1 spco2 = match (spco1, spco2) with [ (SpoQues e1, SpoQues e2) -> Reloc.eq_expr e1 e2 | _ -> spco1 = spco2 ] ; value eq_spat_comp_opt (spc1, spco1) (spc2, spco2) = eq_spat_comp spc1 spc2 && eq_spo spco1 spco2 ; value mk_empty b = ([], b); value mk_rule x = fun [ [] -> failwith "mk_rule" | [(rl, a)] -> ([x :: rl], a) | ll -> let loc = Ploc.dummy in let e = let rl = List.map (fun (rl, (eo, a)) -> (rl, eo, a)) ll in let e = parser_cases loc rl in let p = <:patt< ($lid:strm_n$ : Stream.t _) >> in <:expr< fun $p$ -> $e$ >> in let spo = if List.exists (fun (rl, _) -> match rl with [ [] -> True | [(_, SpoBang) :: _] -> True | _ -> False ]) ll then SpoBang else SpoNoth in ([x; (SpNtr loc <:patt< a >> e, spo)], (None, <:expr< a >>)) ] ; value left_factorize rl = let rl = List.map (fun (rl, eo, a) -> (rl, (eo, a))) rl in let t = tree_of_list eq_spat_comp_opt rl in let rl = list_of_tree mk_rule mk_empty t in List.map (fun (rl, (eo, a)) -> (rl, eo, a)) rl ; (* Converting into AST *) value cparser loc (bpo, pc) = let pc = left_factorize pc in let e = parser_cases loc pc in let e = let loc = Ploc.with_comment loc "" in match bpo with [ Some bp -> <:expr< let $bp$ = Stream.count $lid:strm_n$ in $e$ >> | None -> e ] in let p = let loc = Ploc.with_comment loc "" in <:patt< ($lid:strm_n$ : Stream.t _) >> in <:expr< fun $p$ -> $e$ >> ; value rec is_not_bound s = fun [ <:expr< $uid:_$ >> -> True | <:expr< raise Stream.Failure >> -> True | _ -> False ] ; value cparser_match loc me (bpo, pc) = let pc = left_factorize pc in let iloc = Ploc.with_comment loc "" in let pc = parser_cases iloc pc in let e = let loc = iloc in match bpo with [ Some bp -> <:expr< let $bp$ = Stream.count $lid:strm_n$ in $pc$ >> | None -> pc ] in match me with [ <:expr< $lid:x$ >> when x = strm_n -> e | _ -> let p = let loc = iloc in if is_not_bound strm_n e then <:patt< _ >> else <:patt< $lid:strm_n$ >> in <:expr< let ($p$ : Stream.t _) = $me$ in $e$ >> ] ; (* Streams *) value rec not_computing = fun [ <:expr< $lid:_$ >> | <:expr< $uid:_$ >> | <:expr< $int:_$ >> | <:expr< $flo:_$ >> | <:expr< $chr:_$ >> | <:expr< $str:_$ >> -> True | <:expr< $x$ $y$ >> -> is_cons_apply_not_computing x && not_computing y | _ -> False ] and is_cons_apply_not_computing = fun [ <:expr< $uid:_$ >> -> True | <:expr< $lid:_$ >> -> False | <:expr< $x$ $y$ >> -> is_cons_apply_not_computing x && not_computing y | _ -> False ] ; value slazy loc e = match e with [ <:expr< $f$ () >> -> match f with [ <:expr< $lid:_$ >> -> f | _ -> <:expr< fun _ -> $e$ >> ] | _ -> <:expr< fun _ -> $e$ >> ] ; value rec cstream gloc = fun [ [] -> let loc = gloc in <:expr< Stream.sempty >> | [SeTrm loc e] -> if not_computing e then <:expr< Stream.ising $e$ >> else <:expr< Stream.lsing $slazy loc e$ >> | [SeTrm loc e :: secl] -> if not_computing e then <:expr< Stream.icons $e$ $cstream gloc secl$ >> else <:expr< Stream.lcons $slazy loc e$ $cstream gloc secl$ >> | [SeNtr loc e] -> if not_computing e then e else <:expr< Stream.slazy $slazy loc e$ >> | [SeNtr loc e :: secl] -> if not_computing e then <:expr< Stream.iapp $e$ $cstream gloc secl$ >> else <:expr< Stream.lapp $slazy loc e$ $cstream gloc secl$ >> ] ;
(* camlp5r *) (* exparser.ml,v *) (* Copyright (c) INRIA 2007-2017 *)
conex_repository.mli
open Conex_resource open Conex_utils type t val root : t -> Root.t val keydir : t -> path val datadir : t -> path val targets : t -> (Digest.t * Uint.t * S.t) Tree.t val with_targets : t -> (Digest.t * Uint.t * S.t) Tree.t -> t val maintainer_delegation : t -> (Expression.t * bool * S.t) option val create : Root.t -> t type res = [ | `Only_on_disk of path | `Only_in_targets of path | `No_match of path * (Digest.t * Uint.t) list * (Digest.t * Uint.t * S.t) list ] val pp_res : res fmt val validate_targets : t -> (Digest.t * Uint.t) Tree.t -> res list val collect_and_validate_delegations : (Digest.t * Uint.t) M.t -> path -> Expression.t -> Targets.t list -> (path * Expression.t * bool * S.t) list val collect_and_validate_targets : ?tree:(Digest.t * Uint.t * S.t) Tree.t -> (Digest.t * Uint.t) M.t -> path -> Expression.t -> Targets.t list -> (Digest.t * Uint.t * S.t) Tree.t
patcher.ml
let set_debug_level n sections = let debug_sections = List.fold_left (fun map elt -> OpamStd.String.Map.add elt None map) OpamStd.String.Map.empty sections in OpamCoreConfig.(update ~noop:()) ~debug_level:n ~debug_sections () let test_dir = "patcher-test" let write_file ~dir ~name use_crlf ?(eol_at_eof = true) pattern = let ch = open_out_bin (Filename.concat dir name) in let eol = if use_crlf then "\r\n" else "\n" in List.fold_left (fun a (n, s) -> for i = a to a + n - 1 do Printf.fprintf ch "Line %d%s" i eol done; a + n + s) 1 pattern |> ignore; output_string ch "End of file"; if eol_at_eof then output_string ch eol; close_out ch let write_single_line ~dir ~name line = let ch = open_out_bin (Filename.concat dir name) in output_string ch line; close_out ch let touch ~dir name = close_out (open_out_bin (Filename.concat dir name)) let setup_directory ~dir = OpamSystem.remove dir; OpamSystem.mkdir dir; OpamSystem.chdir dir; List.iter OpamSystem.mkdir ["a"; "b"; "c"] let pattern1 ?(test1 = false) ?(test2 = false) ?(test3 = false) ?(test4 = false) ?(eoleof_cr = false) dir = write_file ~dir ~name:"always-lf" false [(5, 0)]; write_file ~dir ~name:"always-crlf" true [(5, 0)]; write_file ~dir ~name:"no-eol-at-eof" eoleof_cr ~eol_at_eof:false [(5, 0)]; write_single_line ~dir ~name:"no-eol-at-all" "Original line"; write_file ~dir ~name:"test1" test1 [(5, 0)]; write_file ~dir ~name:"test2" test2 [(5, 0)]; write_file ~dir ~name:"test3" test3 [(5, 0)]; touch ~dir "null-file"; write_file ~dir ~name:"will-null-file" test4 [(5, 0)] let pattern2 dir = write_file ~dir ~name:"always-lf" false [(3, 1); (1, 0)]; write_file ~dir ~name:"always-crlf" true [(6, 0)]; write_file ~dir ~name:"no-eol-at-eof" false ~eol_at_eof:false [(3, 1); (1, 0)]; write_single_line ~dir ~name:"no-eol-at-all" "Patched line"; write_file ~dir ~name:"test1" false [(6, 0)]; write_file ~dir ~name:"test2" false [(1, 1); (1, 1); (1, 0)]; write_file ~dir ~name:"null-file" false [(5, 0)]; touch ~dir "will-null-file" let eol_style ch fn = let s = match OpamSystem.get_eol_encoding fn with | None -> "mixed" | Some true -> "CRLF" | Some false -> "LF" in let s = let ch = open_in_bin fn in let l = in_channel_length ch in let r = if l = 0 || (seek_in ch (l - 1); input_char ch <> '\n') then s ^ " (no eol-at-eof)" else s in close_in ch; r in output_string ch s let print_directory dir = List.iter (fun fn -> Printf.eprintf " %s: %a\n%!" (OpamSystem.back_to_forward fn) eol_style fn) (OpamSystem.ls dir) let generate_patch () = flush stderr; flush stdout; if Sys.command "diff -Naur a b > input.patch" <> 1 then (Printf.eprintf "patch generation failed\n%!"; exit 2); set_debug_level (-3) ["PATCH"]; OpamSystem.translate_patch ~dir:"c" "input.patch" "output.patch"; set_debug_level 0 []; OpamSystem.chdir "c"; Printf.eprintf "Before patch state of c:\n"; print_directory "."; flush stdout; if Sys.command "patch -p1 -i ../output.patch" <> 0 then (Printf.eprintf "patch application failed\n%!"; exit 2); Printf.eprintf "After patch state of c:\n"; print_directory "."; OpamSystem.chdir Filename.parent_dir_name let tests () = set_debug_level 0 []; let cwd = Sys.getcwd () in setup_directory ~dir:test_dir; pattern1 "a"; pattern2 "b"; pattern1 "c"; generate_patch (); pattern1 ~test2:true ~test4:true ~eoleof_cr:true "c"; generate_patch (); OpamSystem.chdir cwd; OpamSystem.remove test_dir let () = (* This causes Windows to use LF endings instead of CRLF, which simplifies the comparison with the reference file *) Unix.putenv "LC_ALL" "C"; set_binary_mode_out stdout true; Unix.dup2 Unix.stdout Unix.stderr; tests ()
dune
(test (name main) (package tezos-protocol-012-Psithaca-tests) (libraries alcotest-lwt tezos-base tezos-protocol-012-Psithaca tezos-base-test-helpers tezos-012-Psithaca-test-helpers tezos-protocol-012-Psithaca-parameters tezos-protocol-plugin-012-Psithaca) (flags (:standard -open Tezos_base__TzPervasives -open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals -open Tezos_protocol_012_Psithaca -open Tezos_012_Psithaca_test_helpers -open Tezos_base_test_helpers -open Tezos_protocol_012_Psithaca_parameters -open Tezos_protocol_plugin_012_Psithaca)))
dune
(rule (deps (source_tree parser-upstream/) (source_tree ocamlformat_support/) (:diff-ocaml ../tools/diff-ocaml/diff_ocaml.exe)) (mode promote) (action (with-stdout-to diff-stdlib-format.patch (run %{diff-ocaml} ocaml diff stdlib parser-upstream ocamlformat_support)))) (rule (deps (source_tree parser-upstream/) (source_tree parser-standard/) (:diff-ocaml ../tools/diff-ocaml/diff_ocaml.exe)) (mode promote) (action (with-stdout-to diff-parsers-upstream-std.patch (run %{diff-ocaml} ocaml diff parser parser-upstream parser-standard)))) (rule (deps (source_tree parser-extended/) (source_tree parser-recovery/lib/) (:diff-ocaml ../tools/diff-ocaml/diff_ocaml.exe)) (mode promote) (action (with-stdout-to diff-parsers-ext-parsewyc.patch (run %{diff-ocaml} ocaml diff parser parser-extended parser-recovery/lib))))
reg_spec.ml
(** Definition of clock, reset and clear signals for sequential logic (ie registers). *) include Signal.Reg_spec_
(** Definition of clock, reset and clear signals for sequential logic (ie registers). *)
foolib.ml
module Bar = Bar
copy_exe.ml
if Array.length Sys.argv <> 3 then failwith "bad args" ;; Sys.command ( Printf.sprintf "cp %S %S" Sys.argv.(1) (Sys.argv.(2) ^ (if Sys.os_type <> "Unix" then ".exe" else "")) ) ;;
(* * Author: Kaustuv Chaudhuri <kaustuv.chaudhuri@inria.fr> * Copyright (C) 2013 Inria (Institut National de Recherche * en Informatique et en Automatique) * See COPYING for licensing details. *)
roll_storage.ml
open Misc type error += | 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 (* `Permanent *) let () = let open Data_encoding in (* Consume roll change *) register_error_kind `Permanent ~id:"contract.manager.consume_roll_change" ~title:"Consume roll change" ~description:"Change is not enough to consume a roll." ~pp:(fun ppf () -> Format.fprintf ppf "Not enough change to consume a roll.") empty (function Consume_roll_change -> Some () | _ -> None) (fun () -> Consume_roll_change) ; (* No roll for delegate *) register_error_kind `Permanent ~id:"contract.manager.no_roll_for_delegate" ~title:"No roll for delegate" ~description:"Delegate has no roll." ~pp:(fun ppf () -> Format.fprintf ppf "Delegate has no roll.") empty (function No_roll_for_delegate -> Some () | _ -> None) (fun () -> No_roll_for_delegate) ; (* No roll snapshot for cycle *) register_error_kind `Permanent ~id:"contract.manager.no_roll_snapshot_for_cycle" ~title:"No roll snapshot for cycle" ~description:"A snapshot of the rolls distribution does not exist for this cycle." ~pp:(fun ppf c -> Format.fprintf ppf "A snapshot of the rolls distribution does not exist for cycle %a" Cycle_repr.pp c) (obj1 (req "cycle" Cycle_repr.encoding)) (function No_roll_snapshot_for_cycle c-> Some c | _ -> None) (fun c -> No_roll_snapshot_for_cycle c) ; (* Unregistered delegate *) register_error_kind `Permanent ~id:"contract.manager.unregistered_delegate" ~title:"Unregistered delegate" ~description:"A contract cannot be delegated to an unregistered delegate" ~pp:(fun ppf k-> Format.fprintf ppf "The provided public key (with hash %a) is \ \ not registered as valid delegate key." Signature.Public_key_hash.pp k) (obj1 (req "hash" Signature.Public_key_hash.encoding)) (function Unregistered_delegate k -> Some k | _ -> None) (fun k -> Unregistered_delegate k) let get_contract_delegate c contract = Storage.Contract.Delegate.get_option c contract let delegate_pubkey ctxt delegate = Storage.Contract.Manager.get_option ctxt (Contract_repr.implicit_contract delegate) >>=? function | None | Some (Manager_repr.Hash _) -> fail (Unregistered_delegate delegate) | Some (Manager_repr.Public_key pk) -> return pk let clear_cycle c cycle = Storage.Roll.Snapshot_for_cycle.get c cycle >>=? fun index -> Storage.Roll.Snapshot_for_cycle.delete c cycle >>=? fun c -> Storage.Roll.Last_for_snapshot.delete (c, cycle) index >>=? fun c -> Storage.Roll.Owner.delete_snapshot c (cycle, index) >>= fun c -> return c let fold ctxt ~f init = Storage.Roll.Next.get ctxt >>=? fun last -> let rec loop ctxt roll acc = acc >>=? fun acc -> if Roll_repr.(roll = last) then return acc else Storage.Roll.Owner.get_option ctxt roll >>=? function | None -> loop ctxt (Roll_repr.succ roll) (return acc) | Some delegate -> loop ctxt (Roll_repr.succ roll) (f roll delegate acc) in loop ctxt Roll_repr.first (return init) let snapshot_rolls_for_cycle ctxt cycle = Storage.Roll.Snapshot_for_cycle.get ctxt cycle >>=? fun index -> Storage.Roll.Snapshot_for_cycle.set ctxt cycle (index + 1) >>=? fun ctxt -> Storage.Roll.Owner.snapshot ctxt (cycle, index) >>=? fun ctxt -> Storage.Roll.Next.get ctxt >>=? fun last -> Storage.Roll.Last_for_snapshot.init (ctxt, cycle) index last >>=? fun ctxt -> return ctxt let freeze_rolls_for_cycle ctxt cycle = Storage.Roll.Snapshot_for_cycle.get ctxt cycle >>=? fun max_index -> Storage.Seed.For_cycle.get ctxt cycle >>=? fun seed -> let rd = Seed_repr.initialize_new seed [MBytes.of_string "roll_snapshot"] in let seq = Seed_repr.sequence rd 0l in let selected_index = Seed_repr.take_int32 seq (Int32.of_int max_index) |> fst |> Int32.to_int in Storage.Roll.Snapshot_for_cycle.set ctxt cycle selected_index >>=? fun ctxt -> fold_left_s (fun ctxt index -> if Compare.Int.(index = selected_index) then return ctxt else Storage.Roll.Owner.delete_snapshot ctxt (cycle, index) >>= fun ctxt -> Storage.Roll.Last_for_snapshot.delete (ctxt, cycle) index >>=? fun ctxt -> return ctxt ) ctxt Misc.(0 --> (max_index - 1)) >>=? fun ctxt -> return ctxt (* Roll selection *) module Random = struct let int32_to_bytes i = let b = MBytes.create 4 in MBytes.set_int32 b 0 i; b let level_random seed use level = let position = level.Level_repr.cycle_position in Seed_repr.initialize_new seed [MBytes.of_string ("level "^use^":"); int32_to_bytes position] let owner c kind level offset = let cycle = level.Level_repr.cycle in Seed_storage.for_cycle c cycle >>=? fun random_seed -> let rd = level_random random_seed kind level in let sequence = Seed_repr.sequence rd (Int32.of_int offset) in Storage.Roll.Snapshot_for_cycle.get c cycle >>=? fun index -> Storage.Roll.Last_for_snapshot.get (c, cycle) index >>=? fun bound -> let rec loop sequence = let roll, sequence = Roll_repr.random sequence ~bound in Storage.Roll.Owner.Snapshot.get_option c ((cycle, index), roll) >>=? function | None -> loop sequence | Some delegate -> return delegate in Storage.Roll.Owner.snapshot_exists c (cycle, index) >>= fun snapshot_exists -> fail_unless snapshot_exists (No_roll_snapshot_for_cycle cycle) >>=? fun () -> loop sequence end let baking_rights_owner c level ~priority = Random.owner c "baking" level priority let endorsement_rights_owner c level ~slot = Random.owner c "endorsement" level slot let traverse_rolls ctxt head = let rec loop acc roll = Storage.Roll.Successor.get_option ctxt roll >>=? function | None -> return (List.rev acc) | Some next -> loop (next :: acc) next in loop [head] head let get_rolls ctxt delegate = Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? function | None -> return_nil | Some head_roll -> traverse_rolls ctxt head_roll let get_change c delegate = Storage.Roll.Delegate_change.get_option c delegate >>=? function | None -> return Tez_repr.zero | Some change -> return change module Delegate = struct let fresh_roll c = Storage.Roll.Next.get c >>=? fun roll -> Storage.Roll.Next.set c (Roll_repr.succ roll) >>=? fun c -> return (roll, c) let get_limbo_roll c = Storage.Roll.Limbo.get_option c >>=? function | None -> fresh_roll c >>=? fun (roll, c) -> Storage.Roll.Limbo.init c roll >>=? fun c -> return (roll, c) | Some roll -> return (roll, c) let consume_roll_change c delegate = let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> trace Consume_roll_change (Lwt.return Tez_repr.(change -? tokens_per_roll)) >>=? fun new_change -> Storage.Roll.Delegate_change.set c delegate new_change let recover_roll_change c delegate = let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun new_change -> Storage.Roll.Delegate_change.set c delegate new_change let pop_roll_from_delegate c delegate = recover_roll_change c delegate >>=? fun c -> (* beginning: delegate : roll -> successor_roll -> ... limbo : limbo_head -> ... *) Storage.Roll.Limbo.get_option c >>=? fun limbo_head -> Storage.Roll.Delegate_roll_list.get_option c delegate >>=? function | None -> fail No_roll_for_delegate | Some roll -> Storage.Roll.Owner.delete c roll >>=? fun c -> Storage.Roll.Successor.get_option c roll >>=? fun successor_roll -> Storage.Roll.Delegate_roll_list.set_option c delegate successor_roll >>= fun c -> (* delegate : successor_roll -> ... roll ------^ limbo : limbo_head -> ... *) Storage.Roll.Successor.set_option c roll limbo_head >>= fun c -> (* delegate : successor_roll -> ... roll ------v limbo : limbo_head -> ... *) Storage.Roll.Limbo.init_set c roll >>= fun c -> (* delegate : successor_roll -> ... limbo : roll -> limbo_head -> ... *) return (roll, c) let create_roll_in_delegate c delegate delegate_pk = consume_roll_change c delegate >>=? fun c -> (* beginning: delegate : delegate_head -> ... limbo : roll -> limbo_successor -> ... *) Storage.Roll.Delegate_roll_list.get_option c delegate >>=? fun delegate_head -> get_limbo_roll c >>=? fun (roll, c) -> Storage.Roll.Owner.init c roll delegate_pk >>=? fun c -> Storage.Roll.Successor.get_option c roll >>=? fun limbo_successor -> Storage.Roll.Limbo.set_option c limbo_successor >>= fun c -> (* delegate : delegate_head -> ... roll ------v limbo : limbo_successor -> ... *) Storage.Roll.Successor.set_option c roll delegate_head >>= fun c -> (* delegate : delegate_head -> ... roll ------^ limbo : limbo_successor -> ... *) Storage.Roll.Delegate_roll_list.init_set c delegate roll >>= fun c -> (* delegate : roll -> delegate_head -> ... limbo : limbo_successor -> ... *) return c let ensure_inited c delegate = Storage.Roll.Delegate_change.mem c delegate >>= function | true -> return c | false -> Storage.Roll.Delegate_change.init c delegate Tez_repr.zero let add_amount c delegate amount = ensure_inited c delegate >>=? fun c -> let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> Lwt.return Tez_repr.(amount +? change) >>=? fun change -> Storage.Roll.Delegate_change.set c delegate change >>=? fun c -> delegate_pubkey c delegate >>=? fun delegate_pk -> let rec loop c change = if Tez_repr.(change < tokens_per_roll) then return c else Lwt.return Tez_repr.(change -? tokens_per_roll) >>=? fun change -> create_roll_in_delegate c delegate delegate_pk >>=? fun c -> loop c change in Storage.Contract.Inactive_delegate.mem c (Contract_repr.implicit_contract delegate) >>= fun inactive -> if inactive then return c else loop c change let remove_amount c delegate amount = let tokens_per_roll = Constants_storage.tokens_per_roll c in let rec loop c change = if Tez_repr.(amount <= change) then return (c, change) else pop_roll_from_delegate c delegate >>=? fun (_, c) -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun change -> loop c change in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> Storage.Contract.Inactive_delegate.mem c (Contract_repr.implicit_contract delegate) >>= fun inactive -> begin if inactive then return (c, change) else loop c change end >>=? fun (c, change) -> Lwt.return Tez_repr.(change -? amount) >>=? fun change -> Storage.Roll.Delegate_change.set c delegate change let set_inactive ctxt delegate = ensure_inited ctxt delegate >>=? fun ctxt -> let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in Storage.Roll.Delegate_change.get ctxt delegate >>=? fun change -> Storage.Contract.Inactive_delegate.add ctxt (Contract_repr.implicit_contract delegate) >>= fun ctxt -> let rec loop ctxt change = Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? function | None -> return (ctxt, change) | Some _roll -> pop_roll_from_delegate ctxt delegate >>=? fun (_, ctxt) -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun change -> loop ctxt change in loop ctxt change >>=? fun (ctxt, change) -> Storage.Roll.Delegate_change.set ctxt delegate change >>=? fun ctxt -> return ctxt let set_active ctxt delegate = Storage.Contract.Inactive_delegate.mem ctxt (Contract_repr.implicit_contract delegate) >>= fun inactive -> let current_cycle = (Raw_context.current_level ctxt).cycle in let preserved_cycles = Constants_storage.preserved_cycles ctxt in (* When the delegate is new or inactive, she will become active in `1+preserved_cycles`, and we allow `preserved_cycles` for the delegate to start baking. When the delegate is active, we only give her at least `preserved_cycles` after the current cycle before to be deactivated. *) Storage.Contract.Delegate_desactivation.get_option ctxt (Contract_repr.implicit_contract delegate) >>=? fun current_expiration -> let expiration = match current_expiration with | None -> Cycle_repr.add current_cycle (1+2*preserved_cycles) | Some current_expiration -> let delay = if inactive then (1+2*preserved_cycles) else 1+preserved_cycles in let updated = Cycle_repr.add current_cycle delay in Cycle_repr.max current_expiration updated in Storage.Contract.Delegate_desactivation.init_set ctxt (Contract_repr.implicit_contract delegate) expiration >>= fun ctxt -> if not inactive then return ctxt else begin ensure_inited ctxt delegate >>=? fun ctxt -> let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in Storage.Roll.Delegate_change.get ctxt delegate >>=? fun change -> Storage.Contract.Inactive_delegate.del ctxt (Contract_repr.implicit_contract delegate) >>= fun ctxt -> delegate_pubkey ctxt delegate >>=? fun delegate_pk -> let rec loop ctxt change = if Tez_repr.(change < tokens_per_roll) then return ctxt else Lwt.return Tez_repr.(change -? tokens_per_roll) >>=? fun change -> create_roll_in_delegate ctxt delegate delegate_pk >>=? fun ctxt -> loop ctxt change in loop ctxt change >>=? fun ctxt -> return ctxt end end module Contract = struct let add_amount c contract amount = get_contract_delegate c contract >>=? function | None -> return c | Some delegate -> Delegate.add_amount c delegate amount let remove_amount c contract amount = get_contract_delegate c contract >>=? function | None -> return c | Some delegate -> Delegate.remove_amount c delegate amount end let init ctxt = Storage.Roll.Next.init ctxt Roll_repr.first let init_first_cycles ctxt = let preserved = Constants_storage.preserved_cycles ctxt in (* Precompute rolls for cycle (0 --> preserved_cycles) *) List.fold_left (fun ctxt c -> ctxt >>=? fun ctxt -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int c) in Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> snapshot_rolls_for_cycle ctxt cycle >>=? fun ctxt -> freeze_rolls_for_cycle ctxt cycle) (return ctxt) (0 --> preserved) >>=? fun ctxt -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 1)) in (* Precomputed a snapshot for cycle (preserved_cycles + 1) *) Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> snapshot_rolls_for_cycle ctxt cycle >>=? fun ctxt -> (* Prepare storage for storing snapshots for cycle (preserved_cycles+2) *) let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 2)) in Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> return ctxt let snapshot_rolls ctxt = let current_level = Raw_context.current_level ctxt in let preserved = Constants_storage.preserved_cycles ctxt in let cycle = Cycle_repr.add current_level.cycle (preserved+2) in snapshot_rolls_for_cycle ctxt cycle let cycle_end ctxt last_cycle = let preserved = Constants_storage.preserved_cycles ctxt in begin match Cycle_repr.sub last_cycle preserved with | None -> return ctxt | Some cleared_cycle -> clear_cycle ctxt cleared_cycle end >>=? fun ctxt -> let frozen_roll_cycle = Cycle_repr.add last_cycle (preserved+1) in freeze_rolls_for_cycle ctxt frozen_roll_cycle >>=? fun ctxt -> Storage.Roll.Snapshot_for_cycle.init ctxt (Cycle_repr.succ (Cycle_repr.succ frozen_roll_cycle)) 0 >>=? fun ctxt -> return 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. *) (* *) (*****************************************************************************)
unit_kind_generator.ml
open Ppxlib type t = core_type (* The structure items will be inserted after the type type definitions and before any other items.*) let extra_structure_items_to_insert loc = let open (val Ast_builder.make loc) in [ [%stri let unreachable_code = function | (_ : _ t) -> . ;;] ] ;; let constructor_declarations ~loc:_ ~elements_to_convert:_ ~core_type_params:_ = [] let names_list ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr []] ;; let name_function_body ~loc = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let path_function_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let ord_function_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let get_function_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let set_function_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr fun t _ _ -> unreachable_code t] ;; let create_function_body ~loc ~constructor_declarations:_ = let open (val Ast_builder.make loc) in [%expr ()] ;; let type_ids ~loc:_ ~elements_to_convert:_ ~core_type_params:_ = [] let subproduct_type_id_modules ~loc:_ ~elements_to_convert:_ ~core_type_params:_ = [] let type_id_function_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let sexp_of_t_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr match packed with | (_ : t) -> .] ;; let all_body ~loc ~constructor_declarations:_ = let open (val Ast_builder.make loc) in [%expr []] ;; let pack_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr unreachable_code] ;; let t_of_sexp_body ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [%expr Base.raise_s (Sexplib.Sexp.List [ Sexplib.Sexp.Atom "Unit has no fields, so cannot convert to field."; sexp ])] ;; let deep_functor_structure ~loc:_ ~elements_to_convert:_ ~module_expression = module_expression ;; let full_depth_module ~loc ~elements_to_convert:_ = let open (val Ast_builder.make loc) in [ [%stri include Shallow] ] ;; let singleton_modules_structures ~loc:_ ~elements_to_convert:_ = []
dune
(library (name ppx_deriving_accessors) (kind ppx_deriver) (libraries ppxlib))
accuser.ml
module Parameters = struct type persistent_state = { runner : Runner.t option; base_dir : string; node : Node.t; mutable pending_ready : unit option Lwt.u list; } type session_state = {mutable ready : bool} let base_default_name = "accuser" let default_colors = Log.Color. [|BG.yellow ++ FG.black; BG.yellow ++ FG.gray; BG.yellow ++ FG.blue|] end open Parameters include Daemon.Make (Parameters) let node_rpc_port accuser = Node.rpc_port accuser.persistent_state.node let trigger_ready accuser value = let pending = accuser.persistent_state.pending_ready in accuser.persistent_state.pending_ready <- [] ; List.iter (fun pending -> Lwt.wakeup_later pending value) pending let set_ready accuser = (match accuser.status with | Not_running -> () | Running status -> status.session_state.ready <- true) ; trigger_ready accuser (Some ()) let handle_raw_stdout accuser line = if line =~ rex "^Accuser v.+ for .+ started.$" then set_ready accuser let create ~protocol ?name ?color ?event_pipe ?base_dir ?runner node = let name = match name with None -> fresh_name () | Some name -> name in let base_dir = match base_dir with None -> Temp.dir name | Some dir -> dir in let accuser = create ~path:(Protocol.accuser protocol) ?name:(Some name) ?color ?event_pipe ?runner {runner; base_dir; node; pending_ready = []} in on_stdout accuser (handle_raw_stdout accuser) ; accuser let run accuser = (match accuser.status with | Not_running -> () | Running _ -> Test.fail "accuser %s is already running" accuser.name) ; let runner = accuser.persistent_state.runner in let node_runner = Node.runner accuser.persistent_state.node in let node_rpc_port = node_rpc_port accuser in let address = "http://" ^ Runner.address ?from:runner node_runner ^ ":" in let arguments = [ "-E"; address ^ string_of_int node_rpc_port; "--base-dir"; accuser.persistent_state.base_dir; "run"; ] in let on_terminate _ = (* Cancel all [Ready] event listeners. *) trigger_ready accuser None ; unit in run accuser {ready = false} arguments ~on_terminate ?runner let check_event ?where accuser name promise = let* result = promise in match result with | None -> raise (Terminated_before_event {daemon = accuser.name; event = name; where}) | Some x -> return x let wait_for_ready accuser = match accuser.status with | Running {session_state = {ready = true; _}; _} -> unit | Not_running | Running {session_state = {ready = false; _}; _} -> let promise, resolver = Lwt.task () in accuser.persistent_state.pending_ready <- resolver :: accuser.persistent_state.pending_ready ; check_event accuser "Accuser started." promise let init ~protocol ?name ?color ?event_pipe ?base_dir ?runner node = let* () = Node.wait_for_ready node in let accuser = create ~protocol ?name ?color ?event_pipe ?base_dir ?runner node in let* () = run accuser in let* () = wait_for_ready accuser in return accuser let restart accuser = let* () = terminate accuser in let* () = run accuser in wait_for_ready accuser
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
fontstash.ml
open Graphv_core_lib module ErrorCode = struct type t = Atlas_full | Scratch_full | States_overflow | States_underflow end module Params = struct type t = { width : int; height : int; } end module Make(Impl : FontBackend.S) : Graphv_core_lib.Font_impl.S with type data = Impl.Buffer.t = struct module Quad = Quad module GlyphBitmap = GlyphBitmap module Glyph = struct type t = { codepoint : int; size : float; blur : float; x0 : float; y0 : float; x1 : float; y1 : float; xadv : float; xoff : float; yoff : float; tt_glyph : Impl.glyph; } let empty = { codepoint = 0; size = 0.; blur = 0.; x0 = 0.; y0 = 0.; x1 = 0.; y1 = 0.; xadv = 0.; xoff = 0.; yoff = 0.; tt_glyph = Impl.invalid_glyph; } end module LUT = struct type key = { mutable codepoint : float; mutable size : float; mutable blur : float; } let hash (v : key) = let c = int_of_float v.codepoint in let b = int_of_float v.blur in let s = int_of_float v.size in let h = 17 in let h = h * 31 + c in let h = h * 31 + s in h * 31 + b let equal (a : key) (b : key) : bool = if Int.equal (int_of_float a.codepoint) (int_of_float b.codepoint) then ( if Int.equal (int_of_float a.size) (int_of_float b.size) then ( Int.equal (int_of_float a.blur) (int_of_float b.blur) ) else false ) else false include (Hashtbl.Make[@inlined](struct type t = key let hash = hash let equal = equal end) : Hashtbl.S with type key := key) let [@inline always] replace t c s b v = let lookup_key = { codepoint = float c; size = s*.10.; blur = b; } in replace t lookup_key v ;; let lookup_key = { codepoint = 0.; size = 0.; blur = 0.; } let [@inline always] find_opt t c s b = lookup_key.codepoint <- float c; lookup_key.size <- s*.10.; lookup_key.blur <- b; find_opt t lookup_key end module StringTbl = struct include Hashtbl.Make(struct type t = string let hash v = Hashtbl.hash v let equal a b = String.equal a b end) end module IntTbl = struct include Hashtbl.Make(struct type t = int let hash v = v*13 let equal a b = Int.equal a b end) end module Font = struct type t = { id : int; font : Impl.font; name : string; ascender : float; descender : float; line_height : float; glyphs : Glyph.t DynArray.t; lut : Glyph.t LUT.t; fallback : int DynArray.t; } end module TextIter = struct type t = { mutable x : float; mutable y : float; mutable next_x : float; scale : float; spacing : float; font : Font.t; mutable code_point : int; size : float; blur : float; mutable prev_glyph : Glyph.t; str : string; mutable start : int; mutable next : int; end_ : int; mutable utf8_state : int; bitmap_option : GlyphBitmap.t; } let x t = t.x let y t = t.y let next t = t.next let next_x t = t.next_x let start t = t.start let end_ t = t.end_ let codepoint t = t.code_point end module FontState = struct type t = { mutable font : int; mutable align : Align.t; mutable size : float; mutable blur : float; mutable spacing : float; } let create () = { size = 12.0; font = 0; blur = 0.; spacing = 0.; align = Align.(or_ left baseline); } end (* let hash_int a = let a = a + lnot (a lsl 15) in let a = a lxor (a lsr 10) in let a = a + (a lsl 3) in let a = a lxor (a lsr 6) in let a = a + lnot (a lsl 11) in let a = a lxor (a lsr 16) in a ;; *) let utf8_accept = 0 let utf8d = [| (* The first part of the table maps bytes to character classes that *) (* to reduce the size of the transition table and create bitmasks. *) 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0; 1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1; 9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9; 7;7;7;7;7;7;7;7;7;7;7;7;7;7;7;7; 7;7;7;7;7;7;7;7;7;7;7;7;7;7;7;7; 8;8;2;2;2;2;2;2;2;2;2;2;2;2;2;2; 2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2; 10;3;3;3;3;3;3;3;3;3;3;3;3;4;3;3; 11;6;6;6;5;8;8;8;8;8;8;8;8;8;8;8; (* The second part is a transition table that maps a combination *) (* of a state of the automaton and a character class to a state. *) 0;12;24;36;60;96;84;12;12;12;48;72; 12;12;12;12;12;12;12;12;12;12;12;12; 12; 0;12;12;12;12;12; 0;12; 0;12;12; 12;24;12;12;12;12;12;24;12;24;12;12; 12;12;12;12;12;12;12;24;12;12;12;12; 12;24;12;12;12;12;12;12;12;24;12;12; 12;12;12;12;12;12;12;36;12;36;12;12; 12;36;12;12;12;12;12;36;12;36;12;12; 12;36;12;12;12;12;12;12;12;12;12;12; |] let decutf8 state codep byte = let typ = utf8d.(byte) in let value = if !state <> utf8_accept then ( (byte land 0x3f) lor (!codep lsl 6) ) else ( (0xff lsr typ) land byte ) in codep := value; state := utf8d.(256 + !state + typ); !state ;; type t = { params : Params.t; itw : float; ith : float; tex_data : Impl.Buffer.t; mutable dirty_rect : int * int * int * int; fonts : Font.t IntTbl.t; fonts_by_name : Font.t StringTbl.t; mutable next_font_id : int; atlas : Atlas.t; scratch : char DynArray.t; states : FontState.t DynArray.t; } let get_state t = DynArray.last t.states ;; let reset_fallback t ~name = let base = StringTbl.find t.fonts_by_name name in DynArray.clear base.fallback; DynArray.clear base.glyphs; LUT.clear base.lut; ;; let reset_fallback_id t ~font = let base = IntTbl.find t.fonts font in DynArray.clear base.fallback; DynArray.clear base.glyphs; LUT.clear base.lut; ;; let add_fallback_id t ~font ~fallback = let base = IntTbl.find t.fonts font in DynArray.add base.fallback fallback ;; let add_fallback t ~name ~fallback = let base = StringTbl.find t.fonts_by_name name in let fallback = StringTbl.find t.fonts_by_name fallback in DynArray.add base.fallback fallback.id ;; let set_size t size = (get_state t).size <- size let set_spacing t spacing = (get_state t).spacing <- spacing let set_blur t blur = (get_state t).blur <- blur let set_align t align = (get_state t).align <- align let set_font t font = (get_state t).font <- font let create (params : Params.t) = let base_state = FontState.create() in let t = { params; scratch = DynArray.create 100 Char.(chr 0); atlas = Atlas.create ~width:params.width ~height:params.height ~ncount:256; fonts = IntTbl.create 4; next_font_id = 0; itw = 1. /. float params.width; ith = 1. /. float params.height; tex_data = Impl.Buffer.create (params.width * params.height); dirty_rect = (params.width, params.height, 0, 0); states = DynArray.create 1 FontState.(create()); fonts_by_name = StringTbl.create 4; } in DynArray.add t.states base_state; t ;; let create () = create Params.{width=2048; height=2048;} ;; let add_font_internal t name font = let vmetrics = Impl.vmetrics font in let ascent = Impl.VMetrics.ascent vmetrics in let descent = Impl.VMetrics.descent vmetrics in let line_gap = Impl.VMetrics.line_gap vmetrics in let ascent = ascent + line_gap in let fh = float (ascent - descent) in let ascender = float ascent /. fh in let descender = float descent /. fh in let lut = LUT.create 1024 in let font_id = t.next_font_id in t.next_font_id <- t.next_font_id + 1; let f = Font.{ id = font_id; font; name; lut; ascender; descender; line_height = ascender -. descender; glyphs = DynArray.create 10 Glyph.empty; fallback = DynArray.create 10 ~-1; } in IntTbl.replace t.fonts font_id f; StringTbl.replace t.fonts_by_name name f; font_id ;; let add_font t name path = let font = Impl.load_font path in Option.map (add_font_internal t name) font ;; let build_glyph_bitmap font glyph scale = let metrics = Impl.hmetrics font glyph in let box = Impl.get_glyph_bitmap_box font glyph ~scale in metrics, box ;; let get_glyph_size font size glyph = let scale = Impl.scale_for_mapping_em_to_pixels font size in let m, box = build_glyph_bitmap font glyph scale in scale, float (Impl.HMetrics.advance_width m), box ;; let lookup_glyph t (font : Font.t) codepoint = let glyph = Impl.find font.font codepoint in match glyph with | Some g -> Some (font, g) | None -> let rec loop idx = if idx >= DynArray.length font.fallback then None else ( let font = IntTbl.find t.fonts DynArray.(get font.fallback idx) in let g = Impl.find font.font codepoint in match g with | None -> loop (idx+1) | Some g -> Some (font, g) ) in loop 0 ;; let aprec = 16 let zprec = 7 let blur_cols (t : t) (off : int) (w : int) (h : int) (stride : int) (alpha : int) = let off = ref off in for _=0 to h-1 do let z = ref 0 in for x=1 to w-1 do let v = Impl.Buffer.get t.tex_data (!off+x) in let v = (alpha * ((v lsl zprec) - !z)) asr aprec in z := !z + v; Impl.Buffer.set t.tex_data (!off+x) (!z asr zprec) done; Impl.Buffer.set t.tex_data (!off+w-1) 0; z := 0; for x=w-2 downto 0 do let v = Impl.Buffer.get t.tex_data (!off+x) in let v = (alpha * ((v lsl zprec) - !z)) asr aprec in z := !z + v; Impl.Buffer.set t.tex_data (!off+x) (!z asr zprec) done; Impl.Buffer.set t.tex_data !off 0; off := !off + stride; done ;; let blur_rows (t : t) (off : int) (w : int) (h : int) (stride : int) (alpha : int) = let off = ref off in let max = h*stride in for _=0 to w-1 do let z = ref 0 in let rec loop y = if y < max then ( let v = Impl.Buffer.get t.tex_data (!off+y) in let v = (alpha * ((v lsl zprec) - !z)) asr aprec in z := !z + v; Impl.Buffer.set t.tex_data (!off+y) (!z asr zprec); loop (y+stride) ) else () in loop stride; Impl.Buffer.set t.tex_data (!off + (h-1)*stride) 0; z := 0; let rec loop y = if y >= 0 then ( let v = Impl.Buffer.get t.tex_data (!off+y) in let v = (alpha * ((v lsl zprec) - !z)) asr aprec in z := !z + v; Impl.Buffer.set t.tex_data (!off+y) (!z asr zprec); loop (y-stride) ) else () in loop ((h-2)*stride); Impl.Buffer.set t.tex_data !off 0; incr off; done ;; let do_blur (t : t) (off : int) (w : int) (h : int) (width : int) (blur : int) = if blur > 0 then ( let sigma = float blur *. 0.57735 in let alpha = (float (1 lsl aprec)) *. (1. -. (Float.exp (-2.3 /. (sigma +. 1.)))) |> int_of_float in blur_rows t off w h width alpha; blur_cols t off w h width alpha; blur_rows t off w h width alpha; blur_cols t off w h width alpha; ) ;; let build_glyph (t : t) codepoint (orig_font : Font.t) (font : Font.t) stb_glyph size pad blur bitmap_option = (* We may have found no glyph, or fallback glyph, will cache empty glyph *) let scale, advance, box = get_glyph_size font.font size stb_glyph in let gw = Impl.Box.(x1 box - x0 box + pad*2) in let gh = Impl.Box.(y1 box - y0 box + pad*2) in let build_glyph gx gy = Glyph.{ x0 = float gx; y0 = float gy; x1 = float (gx + gw); y1 = float (gy + gh); codepoint; xadv = Float.floor (scale *. advance *. 10.0); size; blur; xoff = float (Impl.Box.x0 box - pad); yoff = float (Impl.Box.y0 box - pad); tt_glyph = stb_glyph; } in match GlyphBitmap.to_pattern bitmap_option with | Optional -> Some (build_glyph ~-1 ~-1) | Required -> match Atlas.add_rect t.atlas gw gh with | None -> None | Some (gx, gy) -> let new_glyph = build_glyph gx gy in let box = Impl.Box.create (gx + pad) (gy + pad) (gx + gw - pad) (gy + gh - pad) in (try Impl.make_glyph_bitmap font.font t.tex_data ~width:t.params.width ~height:t.params.height ~scale box stb_glyph; with _ -> Printf.printf "x0:%d y0:%d x1:%d y1:%d (w %d) (h %d)\n(gx %d) (gy %d) (gw %d) (gh %d)\nscale %.2f w %d h %d pad %d '%c'\n%!" (Impl.Box.x0 box) (Impl.Box.y0 box) (Impl.Box.x1 box) (Impl.Box.y1 box) Impl.Box.(x1 box - x0 box) Impl.Box.(y1 box - y0 box) gx gy gw gh scale t.params.width t.params.height pad (Char.chr new_glyph.codepoint); failwith "EXN" ); if blur > 0. then ( let off = (int_of_float new_glyph.x0 + int_of_float new_glyph.y0 * t.params.width) in do_blur t off gw gh t.params.width (int_of_float blur); ); let int = int_of_float in let x, y, w, h = t.dirty_rect in let x0 = min x (int new_glyph.x0) in let y0 = min y (int new_glyph.y0) in let x1 = max w (int new_glyph.x1) in let y1 = max h (int new_glyph.y1) in t.dirty_rect <- x0, y0, x1, y1; (* Cache in both the found font and the fallback font *) LUT.replace font.lut codepoint size blur new_glyph; LUT.replace orig_font.lut codepoint size blur new_glyph; Some new_glyph ;; let get_glyph (t : t) (font : Font.t) (codepoint : int) (size : float) (blur : float) (bitmap_option : GlyphBitmap.t) : Glyph.t option = if size < 2. then None else ( let size = size *. 0.1 in let blur = if blur > 20. then 20. else Float.floor blur in (* TUPLE allocation *) let glyph = LUT.find_opt font.lut codepoint size blur in match glyph with | Some g as ret when bitmap_option = GlyphBitmap.optional || (g.x0 >= 0. && g.y0 >= 0.) -> ret | _ -> let pad = (int_of_float blur)+2 in (* Create a new glyph or rasterize bitmap data for a cached glyph *) let glyph_font = lookup_glyph t font codepoint in let orig_font = font in match glyph_font with | None -> build_glyph t codepoint orig_font font Impl.invalid_glyph size pad blur bitmap_option | Some (font, stb_glyph) -> build_glyph t codepoint orig_font font stb_glyph size pad blur bitmap_option ) ;; let get_quad t font (prev_glyph : Glyph.t) (glyph : Glyph.t) ~scale ~spacing ~x ~y (quad : Quad.t) = let x = ref x in if Impl.is_invalid_glyph prev_glyph.tt_glyph = false then ( let adv = float (Impl.kern_advance font prev_glyph.tt_glyph glyph.tt_glyph) *. scale in x := !x +. Float.floor (adv +. spacing +. 0.5); ); let xoff = Float.floor (glyph.xoff +. 1.) in let yoff = Float.floor (glyph.yoff +. 1.) in let x0 = glyph.x0 +. 1. in let y0 = glyph.y0 +. 1. in let x1 = glyph.x1 -. 1. in let y1 = glyph.y1 -. 1. in let rx = Float.floor (!x +. xoff) in x := !x +. Float.floor (glyph.xadv /. 10.0 +. 0.5); let ry = Float.floor (y +. yoff) in quad.x0 <- rx; quad.y0 <- ry; quad.x1 <- rx +. x1 -. x0; quad.y1 <- ry +. y1 -. y0; quad.s0 <- x0 *. t.itw; quad.t0 <- y0 *. t.ith; quad.s1 <- x1 *. t.itw; quad.t1 <- y1 *. t.ith; !x ;; let validate_texture (t : t) = let x0, y0, x1, y1 = t.dirty_rect in if x0 < x1 && y0 < y1 then ( t.dirty_rect <- t.params.width, t.params.height, 0, 0; Some (x0, y0, x1, y1) ) else ( None ) ;; let get_texture_data t = t.tex_data, t.params.width, t.params.height ;; let get_vert_align (font : Font.t) align size = if Align.has align ~flag:Align.top then ( font.ascender *. (Float.floor size *. 0.1) ) else if Align.has align ~flag:Align.middle then ( (font.ascender +. font.descender) *. 0.5 *. (Float.floor size *. 0.1) ) else if Align.has align ~flag:Align.baseline then ( 0. ) else if Align.has align ~flag:Align.bottom then ( font.descender *. (Float.floor size *. 0.1) ) else ( 0. ) ;; let tb_quad = Quad.empty() let text_bounds t x y str start end_ = let state = get_state t in let isize = Float.floor (state.size*.10.) in let blur = Float.floor state.blur in let font = IntTbl.find t.fonts state.font in let scale = Impl.scale_for_mapping_em_to_pixels font.font state.size in let y = y +. get_vert_align font state.align isize in let minx = ref x in let miny = ref y in let maxx = ref x in let maxy = ref y in let startx = ref x in let x = ref x in let end_ = match end_ with | None -> String.length str | Some end_ -> max 0 (min end_ String.(length str)) in Quad.reset tb_quad; let start = ref start in let utf8_state = ref 0 in let codepoint = ref 0 in let prev_glyph_index = ref Glyph.empty in while !start <> end_ do if decutf8 utf8_state codepoint String.(get str !start |> Char.code) = 0 then ( let glyph = get_glyph t font !codepoint isize blur GlyphBitmap.optional in match glyph with | None -> prev_glyph_index := Glyph.empty | Some (glyph : Glyph.t) -> let xn = get_quad t font.font !prev_glyph_index glyph ~scale ~spacing:state.spacing ~x:!x ~y tb_quad in x := xn; if tb_quad.x0 < !minx then (minx := tb_quad.x0); if tb_quad.x1 > !maxx then (maxx := tb_quad.x1); if tb_quad.y0 < !miny then (miny := tb_quad.y0); if tb_quad.y1 > !maxy then (maxy := tb_quad.y1); prev_glyph_index := glyph ); incr start; done; let advance = !x -. !startx in if Align.has state.align ~flag:Align.right then ( minx := !minx -. advance; maxx := !maxx -. advance; ) else if Align.has state.align ~flag:Align.center then ( minx := !minx -. advance*.0.5; maxx := !maxx -. advance*.0.5; ); advance, Bounds.{xmin = !minx; ymin = !miny; xmax = !maxx; ymax = !maxy} ;; let line_bounds t y = let state = get_state t in let font = IntTbl.find t.fonts state.font in let size = state.size in let y = y +. get_vert_align font state.align (Float.floor (size*.10.)) in let miny = y -. font.ascender *. size in let maxy = miny +. font.line_height *. size in miny, maxy ;; let iter_init t x y ?(start=0) ?end_ str bitmap = let state = get_state t in let font = IntTbl.find t.fonts state.font in (* alignment *) let x = if Align.has state.align ~flag:Align.right then ( let w, _ = text_bounds t x y str start end_ in x -. w ) else if Align.has state.align ~flag:Align.center then ( let w, _ = text_bounds t x y str start end_ in x -. w*.0.5 ) else ( x ) in let size = Float.floor (state.size *. 10.) in let y = y +. get_vert_align font state.align size in let len = String.length str in let end_ = match end_ with | None -> len | Some e -> if e < 0 then 0 else if e > len then len else e in let iter : TextIter.t = { font; size = size; blur = Float.floor state.blur; scale = Impl.scale_for_mapping_em_to_pixels font.font (size /. 10.); x; y; next_x = x; spacing = state.spacing; next = start; str; start; end_; code_point = 0; prev_glyph = Glyph.empty; utf8_state = 0; bitmap_option = bitmap; } in iter ;; let iter_next (t : t) (iter : TextIter.t) quad = Quad.reset quad; iter.start <- iter.next; if iter.next = iter.end_ then ( false ) else ( let state = ref iter.utf8_state in let codepoint = ref iter.code_point in let rec loop start = if Int.equal start iter.end_ then ( start ) else ( let ch = String.get iter.str start in if decutf8 state codepoint (ch |> Char.code) = 0 then ( let start = start+1 in iter.code_point <- !codepoint; iter.utf8_state <- !state; iter.x <- iter.next_x; let glyph = get_glyph t iter.font iter.code_point iter.size iter.blur iter.bitmap_option in begin match glyph with | None -> iter.prev_glyph <- Glyph.empty; loop start | Some (glyph : Glyph.t) -> let next_x = get_quad t iter.font.font iter.prev_glyph glyph ~scale:iter.scale ~spacing:iter.spacing ~x:iter.next_x ~y:iter.y quad in iter.next_x <- next_x; iter.prev_glyph <- glyph; start end; ) else ( iter.code_point <- !codepoint; iter.utf8_state <- !state; loop (start+1) ); ) in let start = loop iter.next in iter.next <- start; true ) ;; let find_font (t : t) name = StringTbl.find_opt t.fonts_by_name name ;; type v_metrics = { ascender : float; descender : float; line_height : float; } let vert_metrics (t : t) = let state = get_state t in let font = IntTbl.find t.fonts state.font in let size = Float.floor (state.size*.10.) in {ascender = font.ascender*.size/.10.; descender = font.descender*.size/.10.; line_height = font.line_height*.size/.10.; } ;; type font = int module Iter = TextIter type iter = TextIter.t type data = Impl.Buffer.t let bounds t x y ?(off=0) ?end_ str = text_bounds t x y str off end_ let find_font t f = let res = find_font t f in match res with | None -> None | Some font -> Some font.id end
clb_pstacks.h
#ifndef CLB_PSTACKS #define CLB_PSTACKS #include <clb_memory.h> /*---------------------------------------------------------------------*/ /* Data type declarations */ /*---------------------------------------------------------------------*/ /* Generic stack data type, can take (long) integers or pointers */ typedef long PStackPointer; typedef struct pstackcell { long size; /* ...of allocated memory */ PStackPointer current; /* First unused address, 0 for empty stack */ IntOrP *stack; /* Stack area */ }PStackCell, *PStack_p; #define PSTACK_DEFAULT_SIZE 128 /* Stacks grow exponentially (and never shrink unless explicitly freed) - take care */ #define PStackCellAlloc() (PStackCell*)SizeMalloc(sizeof(PStackCell)) #define PStackCellFree(junk) SizeFree(junk, sizeof(PStackCell)) #ifdef CONSTANT_MEM_ESTIMATE #define PSTACK_AVG_MEM 68 #else #define PSTACK_AVG_MEM (MEMSIZE(PStackCell)+MEMSIZE(IntOrP)*6) #endif #define PStackBaseAddress(stackarg) ((stackarg)->stack) static inline PStack_p PStackAlloc(void); static inline PStack_p PStackVarAlloc(long size); static inline void PStackFree(PStack_p junk); static inline PStack_p PStackCopy(PStack_p stack); #define PStackEmpty(stack) ((stack)->current == 0) static inline void PStackReset(PStack_p stack); static inline void PStackPushInt(PStack_p stack, long val); static inline void PStackPushP(PStack_p stack, void* val); #define PStackGetSP(stack) ((stack)->current) #define PStackGetTopSP(stack) ((stack)->current-1) static inline IntOrP PStackPop(PStack_p stack); #define PStackPopInt(stack) (PStackPop(stack).i_val) #define PStackPopP(stack) (PStackPop(stack).p_val) static inline void PStackDiscardTop(PStack_p stack); static inline IntOrP PStackTop(PStack_p stack); #define PStackTopInt(stack) (PStackTop(stack).i_val) #define PStackTopP(stack) (PStackTop(stack).p_val) IntOrP* PStackTopAddr(PStack_p stack); static inline IntOrP PStackBelowTop(PStack_p stack); #define PStackBelowTopInt(stack) (PStackBelowTop(stack).i_val) #define PStackBelowTopP(stack) (PStackBelowTop(stack).p_val) static inline IntOrP PStackElement(PStack_p stack, PStackPointer pos); #define PStackElementInt(stack,pos) (PStackElement(stack,pos).i_val) #define PStackElementP(stack,pos) (PStackElement(stack,pos).p_val) static inline IntOrP *PStackElementRef(PStack_p stack, PStackPointer pos); #define PStackAssignP(stack, pos, value) \ PStackElementRef((stack), (pos))->p_val = (value) #define PStackAssignInt(stack, pos, value) \ PStackElementRef((stack), (pos))->i_val = (value) void PStackDiscardElement(PStack_p stack, PStackPointer i); void PStackSort(PStack_p stack, ComparisonFunctionType cmpfun); PStackPointer PStackBinSearch(PStack_p stack, void* key, PStackPointer lower, PStackPointer upper, ComparisonFunctionType cmpfun); void PStackMerge(PStack_p st1, PStack_p st2, PStack_p res, ComparisonFunctionType cmpfun); double PStackComputeAverage(PStack_p stack, double *deviation); void PStackPushStack(PStack_p target, PStack_p source); void PStackPrintInt(FILE* out, char* format, PStack_p stack); void PStackGrow(PStack_p stack); /*---------------------------------------------------------------------*/ /* Implementations as inline functions */ /*---------------------------------------------------------------------*/ /*----------------------------------------------------------------------- // // Function: push() // // Implements push operation for pstacks and // checks and ensures there is enought space on the steck. // // Global Variables: - // // Side Effects : Memory operations // /----------------------------------------------------------------------*/ static inline void push(PStack_p stack, IntOrP val) { if(UNLIKELY(stack->current == stack->size)) { PStackGrow(stack); } stack->stack[stack->current] = val; stack->current++; } /*----------------------------------------------------------------------- // // Function: PStackAlloc() // // Allocate an empty stack. // // Global Variables: - // // Side Effects : Memory oprations // /----------------------------------------------------------------------*/ static inline PStack_p PStackAlloc(void) { PStack_p handle; handle = PStackCellAlloc(); handle->size = PSTACK_DEFAULT_SIZE; handle->current = 0; handle->stack = SizeMalloc(PSTACK_DEFAULT_SIZE * sizeof(IntOrP)); //printf("\nPStackAlloc: %p\n", handle); return handle; } /*----------------------------------------------------------------------- // // Function: PStackVarAlloc() // // Allocate an empty stack with selectable initial size. // // Global Variables: - // // Side Effects : Memory oprations // /----------------------------------------------------------------------*/ static inline PStack_p PStackVarAlloc(long size) { PStack_p handle; handle = PStackCellAlloc(); handle->size = size; handle->current = 0; handle->stack = SizeMalloc(handle->size * sizeof(IntOrP)); return handle; } /*----------------------------------------------------------------------- // // Function: PStackFree() // // Free a stack. // // Global Variables: - // // Side Effects : Memory operations // /----------------------------------------------------------------------*/ static inline void PStackFree(PStack_p junk) { assert(junk); assert(junk->stack); SizeFree(junk->stack, junk->size * sizeof(IntOrP)); PStackCellFree(junk); } /*----------------------------------------------------------------------- // // Function: PStackCopy() // // Copy a PStack with contents. Use with care, as some data // structures may not be copyable very well (e.g. pointers to the // same array, registered references, ...) // // Global Variables: - // // Side Effects : Memory operations // /----------------------------------------------------------------------*/ static inline PStack_p PStackCopy(PStack_p stack) { PStack_p handle = PStackAlloc(); PStackPointer i; for(i=0; i<PStackGetSP(stack); i++) { push(handle, PStackElement(stack,i)); } return handle; } /*----------------------------------------------------------------------- // // Function: PStackReset() // // Reset a PStack to empty state. // // Global Variables: - // // Side Effects : Changes stackpointer. // /----------------------------------------------------------------------*/ static inline void PStackReset(PStack_p stack) { stack->current = 0; } /*----------------------------------------------------------------------- // // Function: PStackPushInt() // // Push a (long) int onto the stack // // Global Variables: - // // Side Effects : By push() // /----------------------------------------------------------------------*/ static inline void PStackPushInt(PStack_p stack, long val) { IntOrP help; help.i_val = val; push(stack, help); } /*----------------------------------------------------------------------- // // Function: PStackPushP() // // Push a pointer onto the stack // // Global Variables: - // // Side Effects : by push() // /----------------------------------------------------------------------*/ static inline void PStackPushP(PStack_p stack, void* val) { IntOrP help; help.p_val = val; push(stack, help); } /*----------------------------------------------------------------------- // // Function: PStackPop() // // Implement pop operation for non-empty pstacks. // // Global Variables: // // Side Effects : // /----------------------------------------------------------------------*/ static inline IntOrP PStackPop(PStack_p stack) { assert(stack->current); stack->current--; return stack->stack[stack->current]; } /*----------------------------------------------------------------------- // // Function: PStackDiscardTop() // // Do a PStackPop without returning result, to avoid warnings. // // Global Variables: // // Side Effects : // /----------------------------------------------------------------------*/ static inline void PStackDiscardTop(PStack_p stack) { assert(stack->current); stack->current--; } /*----------------------------------------------------------------------- // // Function: PStackTop() // // Implement Top operation for non-empty pstacks. // // Global Variables: - // // Side Effects : - // /----------------------------------------------------------------------*/ static inline IntOrP PStackTop(PStack_p stack) { assert(stack->current); return stack->stack[stack->current-1]; } /*----------------------------------------------------------------------- // // Function: PStackBelowTop() // // Return second item on the stack (asserts that stack has >=2 // elements). // // Global Variables: - // // Side Effects : - // /----------------------------------------------------------------------*/ static inline IntOrP PStackBelowTop(PStack_p stack) { assert(stack->current>=2); return stack->stack[stack->current-2]; } /*----------------------------------------------------------------------- // // Function: PStackElement() // // Return element at position pos. // // Global Variables: - // // Side Effects : - // /----------------------------------------------------------------------*/ static inline IntOrP PStackElement(PStack_p stack, PStackPointer pos) { assert(pos<stack->current); assert(pos>=0); return stack->stack[pos]; } /*----------------------------------------------------------------------- // // Function: PStackElementRef() // // Return reference to element at position pos. // // Global Variables: - // // Side Effects : - // /----------------------------------------------------------------------*/ static inline IntOrP *PStackElementRef(PStack_p stack, PStackPointer pos) { assert(pos<stack->current); assert(pos>=0); return &(stack->stack[pos]); } #endif /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : clb_pstacks.h Author: Stephan Schulz Contents Soemwhat efficient unlimited growth stacks for pointers/long ints. Copyright 1998, 1999 by the author. This code is released under the GNU General Public Licence and the GNU Lesser General Public License. See the file COPYING in the main E directory for details.. Run "eprover -h" for contact information. Changes <1> Wed Dec 3 16:22:48 MET 1997 New -----------------------------------------------------------------------*/
tmLanguage.ml
include Common include Reader include Tokenizer
record_kind_generator.ml
open Ppxlib type t = label_declaration (* The structure items will be inserted after the type type definitions and before any other items.*) let extra_structure_items_to_insert _ = [] let constructor_declarations ~loc ~elements_to_convert ~core_type_params = Product_kind_generator.constructor_declarations (module Record_generator) ~loc ~elements_to_convert ~core_type_params ;; let names_list ~loc ~elements_to_convert = Product_kind_generator.names_list (module Record_generator) ~loc ~elements_to_convert ;; let name_function_body ~loc = Product_kind_generator.name_function_body ~loc let path_function_body ~loc ~elements_to_convert = Product_kind_generator.path_function_body (module Record_generator) ~loc ~elements_to_convert ;; let ord_function_body ~loc ~elements_to_convert = Product_kind_generator.ord_function_body (module Record_generator) ~loc ~elements_to_convert ;; let get_function_body ~loc ~elements_to_convert = Product_kind_generator.get_function_body (module Record_generator) ~loc ~elements_to_convert ;; let set_function_body ~loc ~elements_to_convert = Product_kind_generator.set_function_body (module Record_generator) ~loc ~elements_to_convert ;; let create_function_body ~loc ~constructor_declarations = Product_kind_generator.create_function_body (module Record_generator) ~loc ~constructor_declarations ;; let subproduct_type_id_modules ~loc ~elements_to_convert = Product_kind_generator.subproduct_type_id_modules (module Record_generator) ~loc ~elements_to_convert ;; let type_ids ~loc ~elements_to_convert ~core_type_params = Product_kind_generator.type_ids (module Record_generator) ~loc ~elements_to_convert ~core_type_params ;; let type_id_function_body ~loc ~elements_to_convert = Product_kind_generator.type_id_function_body (module Record_generator) ~loc ~elements_to_convert ;; let all_body ~loc ~constructor_declarations = Product_kind_generator.all_body (module Record_generator) ~loc ~constructor_declarations ;; let pack_body ~loc ~elements_to_convert = Product_kind_generator.pack_body (module Record_generator) ~loc ~elements_to_convert ;; let sexp_of_t_body ~loc ~elements_to_convert = Product_kind_generator.sexp_of_t_body (module Record_generator) ~loc ~elements_to_convert ;; let t_of_sexp_body ~loc ~elements_to_convert = Product_kind_generator.t_of_sexp_body (module Record_generator) ~loc ~elements_to_convert ;; let deep_functor_structure ~loc ~elements_to_convert ~module_expression = Product_kind_generator.deep_functor_structure (module Record_generator) ~loc ~elements_to_convert ~module_expression ;; let full_depth_module ~loc ~elements_to_convert = Product_kind_generator.full_depth_module (module Record_generator) ~loc ~elements_to_convert ;; let singleton_modules_structures ~loc ~elements_to_convert = Product_kind_generator.singleton_modules_structures (module Record_generator) ~loc ~elements_to_convert ;;
token.c
/* Auto-generated by Tools/scripts/generate_token.py */ #include "Python.h" #include "token.h" /* Token names */ const char * const _PyParser_TokenNames[] = { "ENDMARKER", "NAME", "NUMBER", "STRING", "NEWLINE", "INDENT", "DEDENT", "LPAR", "RPAR", "LSQB", "RSQB", "COLON", "COMMA", "SEMI", "PLUS", "MINUS", "STAR", "SLASH", "VBAR", "AMPER", "LESS", "GREATER", "EQUAL", "DOT", "PERCENT", "LBRACE", "RBRACE", "EQEQUAL", "NOTEQUAL", "LESSEQUAL", "GREATEREQUAL", "TILDE", "CIRCUMFLEX", "LEFTSHIFT", "RIGHTSHIFT", "DOUBLESTAR", "PLUSEQUAL", "MINEQUAL", "STAREQUAL", "SLASHEQUAL", "PERCENTEQUAL", "AMPEREQUAL", "VBAREQUAL", "CIRCUMFLEXEQUAL", "LEFTSHIFTEQUAL", "RIGHTSHIFTEQUAL", "DOUBLESTAREQUAL", "DOUBLESLASH", "DOUBLESLASHEQUAL", "AT", "ATEQUAL", "RARROW", "ELLIPSIS", "COLONEQUAL", "OP", "AWAIT", "ASYNC", "TYPE_IGNORE", "TYPE_COMMENT", "SOFT_KEYWORD", "<ERRORTOKEN>", "<COMMENT>", "<NL>", "<ENCODING>", "<N_TOKENS>", }; /* Return the token corresponding to a single character */ int PyToken_OneChar(int c1) { switch (c1) { case '%': return PERCENT; case '&': return AMPER; case '(': return LPAR; case ')': return RPAR; case '*': return STAR; case '+': return PLUS; case ',': return COMMA; case '-': return MINUS; case '.': return DOT; case '/': return SLASH; case ':': return COLON; case ';': return SEMI; case '<': return LESS; case '=': return EQUAL; case '>': return GREATER; case '@': return AT; case '[': return LSQB; case ']': return RSQB; case '^': return CIRCUMFLEX; case '{': return LBRACE; case '|': return VBAR; case '}': return RBRACE; case '~': return TILDE; } return OP; } int PyToken_TwoChars(int c1, int c2) { switch (c1) { case '!': switch (c2) { case '=': return NOTEQUAL; } break; case '%': switch (c2) { case '=': return PERCENTEQUAL; } break; case '&': switch (c2) { case '=': return AMPEREQUAL; } break; case '*': switch (c2) { case '*': return DOUBLESTAR; case '=': return STAREQUAL; } break; case '+': switch (c2) { case '=': return PLUSEQUAL; } break; case '-': switch (c2) { case '=': return MINEQUAL; case '>': return RARROW; } break; case '/': switch (c2) { case '/': return DOUBLESLASH; case '=': return SLASHEQUAL; } break; case ':': switch (c2) { case '=': return COLONEQUAL; } break; case '<': switch (c2) { case '<': return LEFTSHIFT; case '=': return LESSEQUAL; case '>': return NOTEQUAL; } break; case '=': switch (c2) { case '=': return EQEQUAL; } break; case '>': switch (c2) { case '=': return GREATEREQUAL; case '>': return RIGHTSHIFT; } break; case '@': switch (c2) { case '=': return ATEQUAL; } break; case '^': switch (c2) { case '=': return CIRCUMFLEXEQUAL; } break; case '|': switch (c2) { case '=': return VBAREQUAL; } break; } return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { switch (c1) { case '*': switch (c2) { case '*': switch (c3) { case '=': return DOUBLESTAREQUAL; } break; } break; case '.': switch (c2) { case '.': switch (c3) { case '.': return ELLIPSIS; } break; } break; case '/': switch (c2) { case '/': switch (c3) { case '=': return DOUBLESLASHEQUAL; } break; } break; case '<': switch (c2) { case '<': switch (c3) { case '=': return LEFTSHIFTEQUAL; } break; } break; case '>': switch (c2) { case '>': switch (c3) { case '=': return RIGHTSHIFTEQUAL; } break; } break; } return OP; }
/* Auto-generated by Tools/scripts/generate_token.py */
b00_std.ml
module Stdlib_set = Set (* Type identifiers *) module Tid = struct (* See http://alan.petitepomme.net/cwn/2015.03.24.html#1 *) type _ id = .. module type ID = sig type t type _ id += V : t id end type 'a t = (module ID with type t = 'a) let v () (type s) = let module T = struct type t = s type _ id += V : t id end in (module T : ID with type t = s) type ('a, 'b) eq = Eq : ('a, 'a) eq let equal (type t0) (type t1) (t0 : t0 t) (t1 : t1 t) : (t0, t1) eq option = let module T0 = (val t0 : ID with type t = t0) in let module T1 = (val t1 : ID with type t = t1) in match T0.V with T1.V -> Some Eq | _ -> None end (* ANSI terminal interaction *) module Tty = struct (* Terminals *) type t = [ `Dumb | `Term of string] option let of_fd fd = let rec isatty fd = try Unix.isatty fd with | Unix.Unix_error (Unix.EINTR, _, _) -> isatty fd | Unix.Unix_error (e, _, _) -> false in if not (isatty fd) then None else match Unix.getenv "TERM" with | "" -> None | "dumb" -> (Some `Dumb) | v -> Some (`Term v) | exception Not_found -> None (* Capabilities *) type cap = [ `None | `Ansi ] let cap tty = match tty with None | (Some `Dumb) -> `None | _ -> `Ansi (* ANSI escapes and styling *) type color = [ `Default | `Black | `Red | `Green | `Yellow | `Blue | `Magenta | `Cyan | `White ] let rec sgr_base_int_of_color = function | `Black -> 0 | `Red -> 1 | `Green -> 2 | `Yellow -> 3 | `Blue -> 4 | `Magenta -> 5 | `Cyan -> 6 | `White -> 7 | `Default -> 9 | `Hi (#color as c) -> 60 + sgr_base_int_of_color c let sgr_of_fg_color c = Printf.sprintf "%d" (30 + sgr_base_int_of_color c) let sgr_of_bg_color c = Printf.sprintf "%d" (40 + sgr_base_int_of_color c) type style = [ `Bold | `Faint | `Italic | `Underline | `Blink of [ `Rapid | `Slow ] | `Reverse | `Fg of [ color | `Hi of color ] | `Bg of [ color | `Hi of color ] ] let sgr_of_style = function | `Bold -> "01" | `Faint -> "02" | `Italic -> "03" | `Underline -> "04" | `Blink `Slow -> "05" | `Blink `Rapid -> "06" | `Reverse -> "07" | `Fg c -> sgr_of_fg_color c | `Bg c -> sgr_of_bg_color c let sgrs_of_styles styles = String.concat ";" (List.map sgr_of_style styles) let styled_str cap styles s = match cap with | `None -> s | `Ansi -> Printf.sprintf "\027[%sm%s\027[m" (sgrs_of_styles styles) s let strip_escapes s = let len = String.length s in let b = Buffer.create len in let max = len - 1 in let flush start stop = match start < 0 || start > max with | true -> () | false -> Buffer.add_substring b s start (stop - start + 1) in let rec skip_esc i = match i > max with | true -> loop i i | false -> let k = i + 1 in if s.[i] = 'm' then loop k k else skip_esc k and loop start i = match i > max with | true -> if Buffer.length b = len then s else (flush start max; Buffer.contents b) | false -> match s.[i] with | '\027' -> flush start (i - 1); skip_esc (i + 1) | _ -> loop start (i + 1) in loop 0 0 end (* Formatters *) module Fmt = struct (* Standard outputs and formatters *) let stdout = Format.std_formatter let stderr = Format.err_formatter (* Formatting *) let pf = Format.fprintf let pr = Format.printf let epr = Format.eprintf let str = Format.asprintf let kpf = Format.kfprintf let kstr = Format.kasprintf let failwith fmt = kstr failwith fmt let failwith_notrace fmt = kstr (fun s -> raise_notrace (Failure s)) fmt let invalid_arg fmt = kstr invalid_arg fmt let error fmt = kstr (fun s -> Error s) fmt (* Formatters *) type 'a t = Format.formatter -> 'a -> unit let flush ppf _ = Format.pp_print_flush ppf () let flush_nl ppf _ = Format.pp_print_newline ppf () let nop ppf _ = () let any fmt ppf _ = pf ppf fmt let using f pp_v ppf v = pp_v ppf (f v) (* Separators *) let cut ppf _ = Format.pp_print_cut ppf () let sp ppf _ = Format.pp_print_space ppf () let sps n ppf _ = Format.pp_print_break ppf n 0 let comma ppf _ = Format.pp_print_string ppf ","; sp ppf () let semi ppf _ = Format.pp_print_string ppf ";"; sp ppf () (* Sequencing *) let iter ?sep:(pp_sep = cut) iter pp_elt ppf v = let is_first = ref true in let pp_elt v = if !is_first then (is_first := false) else pp_sep ppf (); pp_elt ppf v in iter pp_elt v let iter_bindings ?sep:(pp_sep = cut) iter pp_binding ppf v = let is_first = ref true in let pp_binding k v = if !is_first then (is_first := false) else pp_sep ppf (); pp_binding ppf (k, v) in iter pp_binding v let append pp_v0 pp_v1 ppf v = pp_v0 ppf v; pp_v1 ppf v let ( ++ ) = append let concat ?sep pps ppf v = iter ?sep List.iter (fun ppf pp -> pp ppf v) ppf pps (* Boxes *) let box ?(indent = 0) pp_v ppf v = Format.(pp_open_box ppf indent; pp_v ppf v; pp_close_box ppf ()) let hbox pp_v ppf v = Format.(pp_open_hbox ppf (); pp_v ppf v; pp_close_box ppf ()) let vbox ?(indent = 0) pp_v ppf v = Format.(pp_open_vbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hvbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hvbox ppf indent; pp_v ppf v; pp_close_box ppf ()) let hovbox ?(indent = 0) pp_v ppf v = Format.(pp_open_hovbox ppf indent; pp_v ppf v; pp_close_box ppf ()) (* Brackets *) let surround s1 s2 pp_v ppf v = Format.(pp_print_string ppf s1; pp_v ppf v; pp_print_string ppf s2) let parens pp_v = box ~indent:1 (surround "(" ")" pp_v) let brackets pp_v = box ~indent:1 (surround "[" "]" pp_v) let oxford_brackets pp_v = box ~indent:2 (surround "[|" "|]" pp_v) let braces pp_v = box ~indent:1 (surround "{" "}" pp_v) let quote ?(mark = "\"") pp_v = let pp_mark ppf _ = Format.pp_print_as ppf 1 mark in box ~indent:1 (pp_mark ++ pp_v ++ pp_mark) (* Stdlib formatters *) let bool = Format.pp_print_bool let int = Format.pp_print_int let int32 ppf i = pf ppf "%ld" i let int64 ppf i = pf ppf "%Ld" i let float ppf f = pf ppf "%g" f let char = Format.pp_print_char let string = Format.pp_print_string let sys_signal ppf snum = let sigs = [ Sys.sigabrt, "SIGABRT"; Sys.sigalrm, "SIGALRM"; Sys.sigfpe, "SIGFPE"; Sys.sighup, "SIGHUP"; Sys.sigill, "SIGILL"; Sys.sigint, "SIGINT"; Sys.sigkill, "SIGKILL"; Sys.sigpipe, "SIGPIPE"; Sys.sigquit, "SIGQUIT"; Sys.sigsegv, "SIGSEGV"; Sys.sigterm, "SIGTERM"; Sys.sigusr1, "SIGUSR1"; Sys.sigusr2, "SIGUSR2"; Sys.sigchld, "SIGCHLD"; Sys.sigcont, "SIGCONT"; Sys.sigstop, "SIGSTOP"; Sys.sigtstp, "SIGTSTP"; Sys.sigttin, "SIGTTIN"; Sys.sigttou, "SIGTTOU"; Sys.sigvtalrm, "SIGVTALRM"; Sys.sigprof, "SIGPROF"; Sys.sigbus, "SIGBUS"; Sys.sigpoll, "SIGPOLL"; Sys.sigsys, "SIGSYS"; Sys.sigtrap, "SIGTRAP"; Sys.sigurg, "SIGURG"; Sys.sigxcpu, "SIGXCPU"; Sys.sigxfsz, "SIGXFSZ"; ] in try string ppf (List.assoc snum sigs) with | Not_found -> pf ppf "SIG(%d)" snum let pp_backtrace_str ppf s = let stop = String.length s - 1 (* there's a newline at the end *) in let rec loop left right = if right = stop then string ppf (String.sub s left (right - left)) else if s.[right] <> '\n' then loop left (right + 1) else begin string ppf (String.sub s left (right - left)); cut ppf (); loop (right + 1) (right + 1) end in if s = "" then (string ppf "No backtrace available.") else loop 0 0 let backtrace = vbox @@ (using Printexc.raw_backtrace_to_string) pp_backtrace_str let exn ppf e = string ppf (Printexc.to_string e) let exn_backtrace ppf (e, bt) = pf ppf "@[<v>Exception: %a@,%a@]" exn e pp_backtrace_str (Printexc.raw_backtrace_to_string bt) let pair ?sep:(pp_sep = cut) pp_fst pp_snd ppf (fst, snd) = pp_fst ppf fst; pp_sep ppf (); pp_snd ppf snd let option ?none:(pp_none = nop) pp_v ppf = function | None -> pp_none ppf () | Some v -> pp_v ppf v let none ppf () = string ppf "<none>" let list ?(empty = nop) ?sep:pp_sep pp_elt ppf = function | [] -> empty ppf () | l -> Format.pp_print_list ?pp_sep pp_elt ppf l let array ?(empty = nop) ?sep pp_elt ppf a = match Array.length a with | 0 -> empty ppf () | n -> iter ?sep Array.iter pp_elt ppf a (* Magnitudes *) let ilog10 x = let rec loop p x = if x = 0 then p else loop (p + 1) (x / 10) in loop (-1) x let ipow10 n = let rec loop acc n = if n = 0 then acc else loop (acc * 10) (n - 1) in loop 1 n let si_symb_max = 16 let si_symb = [| "y"; "z"; "a"; "f"; "p"; "n"; "u"; "m"; ""; "k"; "M"; "G"; "T"; "P"; "E"; "Z"; "Y"|] let rec pp_at_factor ~scale u symb factor ppf s = let m = s / factor in let n = s mod factor in match m with | m when m >= 100 -> (* No fractional digit *) let m_up = if n > 0 then m + 1 else m in if m_up >= 1000 then si_size ~scale u ppf (m_up * factor) else pf ppf "%d%s%s" m_up symb u | m when m >= 10 -> (* One fractional digit w.o. trailing 0 *) let f_factor = factor / 10 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in begin match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 10 -> si_size ~scale u ppf (m * factor + f * f_factor) | f -> pf ppf "%d.%d%s%s" m f symb u end | m -> (* Two or zero fractional digits w.o. trailing 0 *) let f_factor = factor / 100 in let f_m = n / f_factor in let f_n = n mod f_factor in let f_m_up = if f_n > 0 then f_m + 1 else f_m in match f_m_up with | 0 -> pf ppf "%d%s%s" m symb u | f when f >= 100 -> si_size ~scale u ppf (m * factor + f * f_factor) | f when f mod 10 = 0 -> pf ppf "%d.%d%s%s" m (f / 10) symb u | f -> pf ppf "%d.%02d%s%s" m f symb u and si_size ~scale u ppf s = match scale < -8 || scale > 8 with | true -> invalid_arg "~scale is %d, must be in [-8;8]" scale | false -> let pow_div_3 = if s = 0 then 0 else (ilog10 s / 3) in let symb = (scale + 8) + pow_div_3 in let symb, factor = match symb > si_symb_max with | true -> si_symb_max, ipow10 ((8 - scale) * 3) | false -> symb, ipow10 (pow_div_3 * 3) in if factor = 1 then pf ppf "%d%s%s" s si_symb.(symb) u else pp_at_factor ~scale u si_symb.(symb) factor ppf s let byte_size ppf s = si_size ~scale:0 "B" ppf s (* XXX From 4.08 on use Int64.unsigned_* See Hacker's Delight for the implementation of these unsigned_* funs *) let unsigned_compare x0 x1 = Int64.(compare (sub x0 min_int) (sub x1 min_int)) let unsigned_div n d = match d < Int64.zero with | true -> if unsigned_compare n d < 0 then Int64.zero else Int64.one | false -> let q = Int64.(shift_left (div (shift_right_logical n 1) d) 1) in let r = Int64.(sub n (mul q d)) in if unsigned_compare r d >= 0 then Int64.succ q else q let unsigned_rem n d = Int64.(sub n (mul (unsigned_div n d) d)) let us_span = 1_000L let ms_span = 1_000_000L let sec_span = 1_000_000_000L let min_span = 60_000_000_000L let hour_span = 3600_000_000_000L let day_span = 86_400_000_000_000L let year_span = 31_557_600_000_000_000L let rec pp_si_span unit_str si_unit si_higher_unit ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span si_unit in let n = unsigned_rem span si_unit in match m with | m when geq m 100L -> (* No fractional digit *) let m_up = if Int64.equal n 0L then m else Int64.succ m in let span' = Int64.mul m_up si_unit in if geq span' si_higher_unit then uint64_ns_span ppf span' else pf ppf "%Ld%s" m_up unit_str | m when geq m 10L -> (* One fractional digit w.o. trailing zero *) let f_factor = unsigned_div si_unit 10L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in begin match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 10L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f -> pf ppf "%Ld.%Ld%s" m f unit_str end | m -> (* Two or zero fractional digits w.o. trailing zero *) let f_factor = unsigned_div si_unit 100L in let f_m = unsigned_div n f_factor in let f_n = unsigned_rem n f_factor in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | 0L -> pf ppf "%Ld%s" m unit_str | f when geq f 100L -> uint64_ns_span ppf Int64.(add (mul m si_unit) (mul f f_factor)) | f when Int64.equal (Int64.rem f 10L) 0L -> pf ppf "%Ld.%Ld%s" m (Int64.div f 10L) unit_str | f -> pf ppf "%Ld.%02Ld%s" m f unit_str and pp_non_si unit_str unit unit_lo_str unit_lo unit_lo_size ppf span = let geq x y = unsigned_compare x y >= 0 in let m = unsigned_div span unit in let n = unsigned_rem span unit in if Int64.equal n 0L then pf ppf "%Ld%s" m unit_str else let f_m = unsigned_div n unit_lo in let f_n = unsigned_rem n unit_lo in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f unit_lo_size -> uint64_ns_span ppf Int64.(add (mul m unit) (mul f unit_lo)) | f -> pf ppf "%Ld%s%Ld%s" m unit_str f unit_lo_str and uint64_ns_span ppf span = let geq x y = unsigned_compare x y >= 0 in let lt x y = unsigned_compare x y = -1 in match span with | s when lt s us_span -> pf ppf "%Ldns" s | s when lt s ms_span -> pp_si_span "us" us_span ms_span ppf s | s when lt s sec_span -> pp_si_span "ms" ms_span sec_span ppf s | s when lt s min_span -> pp_si_span "s" sec_span min_span ppf s | s when lt s hour_span -> pp_non_si "min" min_span "s" sec_span 60L ppf s | s when lt s day_span -> pp_non_si "h" hour_span "min" min_span 60L ppf s | s when lt s year_span -> pp_non_si "d" day_span "h" hour_span 24L ppf s | s -> let m = unsigned_div s year_span in let n = unsigned_rem s year_span in if Int64.equal n 0L then pf ppf "%Lda" m else let f_m = unsigned_div n day_span in let f_n = unsigned_rem n day_span in let f_m_up = if Int64.equal f_n 0L then f_m else Int64.succ f_m in match f_m_up with | f when geq f 366L -> pf ppf "%Lda" (Int64.succ m) | f -> pf ppf "%Lda%Ldd" m f (* Text *) let text = Format.pp_print_text let lines ppf s = let rec stop_at sat ~start ~max s = if start > max then start else if sat s.[start] then start else stop_at sat ~start:(start + 1) ~max s in let sub s start stop ~max = if start = stop then "" else if start = 0 && stop > max then s else String.sub s start (stop - start) in let is_nl c = c = '\n' in let max = String.length s - 1 in let rec loop start s = match stop_at is_nl ~start ~max s with | stop when stop > max -> Format.pp_print_string ppf (sub s start stop ~max) | stop -> Format.pp_print_string ppf (sub s start stop ~max); Format.pp_force_newline ppf (); loop (stop + 1) s in loop 0 s let truncated ~max ppf s = match String.length s <= max with | true -> Format.pp_print_string ppf s | false -> for i = 0 to max - 4 do Format.pp_print_char ppf s.[i] done; Format.pp_print_string ppf "..." (* HCI fragments *) let op_enum op ?(empty = nop) pp_v ppf = function | [] -> empty ppf () | [v] -> pp_v ppf v | vs -> let rec loop ppf = function | [v0; v1] -> pf ppf "%a@ %s@ %a" pp_v v0 op pp_v v1 | v :: vs -> pf ppf "%a,@ " pp_v v; loop ppf vs | [] -> assert false in loop ppf vs let and_enum ?empty pp_v ppf vs = op_enum "and" ?empty pp_v ppf vs let or_enum ?empty pp_v ppf vs = op_enum "or" ?empty pp_v ppf vs let did_you_mean pp_v ppf = function | [] -> () | vs -> pf ppf "Did@ you@ mean %a ?" (or_enum pp_v) vs let must_be pp_v ppf = function | [] -> () | vs -> pf ppf "Must be %a." (or_enum pp_v) vs let unknown ~kind pp_v ppf v = pf ppf "Unknown %a %a." kind () pp_v v let unknown' ~kind pp_v ~hint ppf (v, hints) = match hints with | [] -> unknown ~kind pp_v ppf v | hints -> unknown ~kind pp_v ppf v; sp ppf (); (hint pp_v) ppf hints (* ANSI TTY styling XXX What we are doing here is less subtle than what we did in Fmt where capability was associated to formatters and hence could distinguish between stdout/stderr, maybe we should do that again. *) let _tty_cap = ref `None let set_tty_cap ?cap () = let cap = match cap with | None -> Tty.(cap (of_fd Unix.stdout)) | Some cap -> cap in _tty_cap := cap let tty_cap () = !_tty_cap let tty_string styles ppf s = match !_tty_cap with | `None -> Format.pp_print_string ppf s | `Ansi -> Format.fprintf ppf "@<0>%s%s@<0>%s" (Printf.sprintf "\027[%sm" @@ Tty.sgrs_of_styles styles) s "\027[m" let tty styles pp_v ppf v = match !_tty_cap with | `None -> pp_v ppf v | `Ansi -> (* XXX This doesn't compose well, we should get the current state and restore it afterwards rather than resetting. *) let reset ppf = Format.fprintf ppf "@<0>%s" "\027[m" in Format.kfprintf reset ppf "@<0>%s%a" (Printf.sprintf "\027[%sm" @@ Tty.sgrs_of_styles styles) pp_v v let code pp_v ppf v = tty [`Bold] pp_v ppf v (* Records *) external id : 'a -> 'a = "%identity" let field ?(label = tty_string [`Fg `Yellow]) ?(sep = any ":@ ") l prj pp_v ppf v = pf ppf "@[<1>%a%a%a@]" label l sep () pp_v (prj v) let record ?(sep = cut) pps = vbox (concat ~sep pps) end (* Result values *) module Result = struct include Stdlib.Result let product r0 r1 = match r0, r1 with | (Error _ as r), _ | _, (Error _ as r) -> r | Ok v0, Ok v1 -> Ok (v0, v1) let retract = function Ok v | Error v -> v (* Interacting with Stdlib exceptions *) let to_failure = function Ok v -> v | Error e -> failwith e let to_invalid_arg = function Ok v -> v | Error e -> invalid_arg e (* Syntax *) module Syntax = struct let ( let* ) x f = bind x f let ( and* ) a b = product a b let ( let+ ) x f = map f x let ( and+ ) a b = product a b end end (* Characters *) module Char = struct include Char module Ascii = struct let max = '\x7F' (* Decimal and hexadecimal digits *) let is_digit = function '0' .. '9' -> true | _ -> false let is_hex_digit = function | '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' -> true | _ -> false let hex_digit_value = function | '0' .. '9' as c -> Char.code c - 0x30 | 'A' .. 'F' as c -> 10 + (Char.code c - 0x41) | 'a' .. 'f' as c -> 10 + (Char.code c - 0x61) | c -> Fmt.invalid_arg "%C: not a hex digit" c let lower_hex_digit n = let n = n land 0xF in Char.unsafe_chr (if n < 10 then 0x30 + n else 0x57 + n) let upper_hex_digit n = let n = n land 0xF in Char.unsafe_chr (if n < 10 then 0x30 + n else 0x37 + n) (* Predicates *) let is_valid : t -> bool = fun c -> c <= max let is_upper = function 'A' .. 'Z' -> true | _ -> false let is_lower = function 'a' .. 'z' -> true | _ -> false let is_letter = function 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false let is_alphanum = function | '0' .. '9' | 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false let is_white = function ' ' | '\t' .. '\r' -> true | _ -> false let is_blank = function ' ' | '\t' -> true | _ -> false let is_graphic = function '!' .. '~' -> true | _ -> false let is_print = function ' ' .. '~' -> true | _ -> false let is_control = function '\x00' .. '\x1F' | '\x7F' -> true | _ -> false (* Casing transforms *) let uppercase = function 'a' .. 'z' as c -> chr (code c - 0x20) | c -> c let lowercase = function 'A' .. 'Z' as c -> chr (code c + 0x20) | c -> c end end (* Strings *) module String = struct include String let empty = "" let head s = if s = "" then None else Some s.[0] let of_char c = String.make 1 c (* Predicates *) let is_empty s = equal empty s let starts_with ~prefix s = let len_a = String.length prefix in let len_s = String.length s in if len_a > len_s then false else let max_idx_a = len_a - 1 in let rec loop i = if i > max_idx_a then true else if unsafe_get prefix i <> unsafe_get s i then false else loop (i + 1) in loop 0 let ends_with ~suffix s = let len_a = String.length suffix in let len_s = String.length s in if len_a > len_s then false else let max_idx_a = len_a - 1 in let max_idx_s = len_s - len_a in let rec loop i k = if i > max_idx_s then false else if k > max_idx_a then true else if k > 0 then if unsafe_get suffix k = unsafe_get s (i + k) then loop i (k + 1) else loop (i + 1) 0 else if unsafe_get suffix 0 = unsafe_get s i then loop i 1 else loop (i + 1) 0 in loop 0 0 let includes ~affix s = let len_a = String.length affix in let len_s = String.length s in if len_a > len_s then false else let max_idx_a = len_a - 1 in let max_idx_s = len_s - len_a in let rec loop i k = if i > max_idx_s then false else if k > max_idx_a then true else if k > 0 then if unsafe_get affix k = unsafe_get s (i + k) then loop i (k + 1) else loop (i + 1) 0 else if unsafe_get affix 0 = unsafe_get s i then loop i 1 else loop (i + 1) 0 in loop 0 0 let for_all sat s = let max_idx = String.length s - 1 in let rec loop i = if i > max_idx then true else if sat (unsafe_get s i) then loop (i + 1) else false in loop 0 let exists sat s = let max_idx = String.length s - 1 in let rec loop i = if i > max_idx then false else if sat (unsafe_get s i) then true else loop (i + 1) in loop 0 (* Finding substrings. *) let find_sub ?(start = 0) ~sub s = (* naive algorithm, worst case O(length sub * length s) *) let len_sub = length sub in let len_s = length s in let max_idx_sub = len_sub - 1 in let max_idx_s = if len_sub <> 0 then len_s - len_sub else len_s - 1 in let rec loop i k = if i > max_idx_s then None else if k > max_idx_sub then Some i else if k > 0 then if unsafe_get sub k = unsafe_get s (i + k) then loop i (k + 1) else loop (i + 1) 0 else if unsafe_get sub 0 = unsafe_get s i then loop i 1 else loop (i + 1) 0 in loop start 0 (* Extracting substrings *) let subrange ?(first = 0) ?last s = let max = String.length s - 1 in let last = match last with | None -> max | Some l when l > max -> max | Some l -> l in let first = if first < 0 then 0 else first in if first > last then "" else String.sub s first (last - first + 1) (* Breaking with magnitudes *) let take_left n s = subrange ~last:(n - 1) s let drop_left n s = subrange ~first:n s let break_left n s = (take_left n s, drop_left n s) let take_right n s = subrange ~first:(String.length s - n) s let drop_right n s = subrange ~last:(String.length s - n - 1) s let break_right n s = (drop_right n s, take_right n s) (* Breaking with predicates *) let keep_left sat s = let max = String.length s - 1 in let rec loop max s i = match i > max with | true -> s | false when sat s.[i] -> loop max s (i + 1) | false -> subrange ~last:(i - 1) s in loop max s 0 let lose_left sat s = let max = String.length s - 1 in let rec loop max s i = match i > max with | true -> "" | false when sat s.[i] -> loop max s (i + 1) | false -> subrange ~first:i s in loop max s 0 let span_left sat s = let max = String.length s - 1 in let rec loop max s i = match i > max with | true -> s, "" | false when sat s.[i] -> loop max s (i + 1) | false -> subrange ~last:(i - 1) s, subrange ~first:i s in loop max s 0 let keep_right sat s = let max = String.length s - 1 in let rec loop s i = match i < 0 with | true -> s | false when sat s.[i] -> loop s (i - 1) | false -> subrange ~first:(i + 1) s in loop s max let lose_right sat s = let max = String.length s - 1 in let rec loop s i = match i < 0 with | true -> "" | false when sat s.[i] -> loop s (i - 1) | false -> subrange ~last:i s in loop s max let span_right sat s = let max = String.length s - 1 in let rec loop s i = match i < 0 with | true -> "", s | false when sat s.[i] -> loop s (i - 1) | false -> subrange ~last:i s, subrange ~first:(i + 1) s in loop s max (* Breaking with separators *) let err_empty_sep = "~sep is an empty string" let cut_left ~sep s = let sep_len = length sep in if sep_len = 0 then invalid_arg err_empty_sep else let s_len = length s in let max_sep_idx = sep_len - 1 in let max_s_idx = s_len - sep_len in let rec check_sep i k = match k > max_sep_idx with | true -> let r_start = i + sep_len in Some (String.sub s 0 i, String.sub s r_start (s_len - r_start)) | false -> if unsafe_get s (i + k) = unsafe_get sep k then check_sep i (k + 1) else scan (i + 1) and scan i = if i > max_s_idx then None else if String.get s i = String.get sep 0 then check_sep i 1 else scan (i + 1) in scan 0 let cut_right ~sep s = let sep_len = length sep in if sep_len = 0 then invalid_arg err_empty_sep else let s_len = length s in let max_sep_idx = sep_len - 1 in let max_s_idx = s_len - 1 in let rec check_sep i k = match k > max_sep_idx with | true -> let r_start = i + sep_len in Some (String.sub s 0 i, String.sub s r_start (s_len - r_start)) | false -> if unsafe_get s (i + k) = unsafe_get sep k then check_sep i (k + 1) else rscan (i - 1) and rscan i = if i < 0 then None else if String.get s i = String.get sep 0 then check_sep i 1 else rscan (i - 1) in rscan (max_s_idx - max_sep_idx) let cuts_left ?(drop_empty = false) ~sep s = let rec loop acc s = match cut_left ~sep s with | Some (v, vs) -> loop (if drop_empty && v = "" then acc else (v :: acc)) vs | None -> List.rev (if drop_empty && s = "" then acc else (s :: acc)) in loop [] s let cuts_right ?(drop_empty = false) ~sep s = let rec loop acc s = match cut_right ~sep s with | Some (vs, v) -> loop (if drop_empty && v = "" then acc else (v :: acc)) vs | None -> if drop_empty && s = "" then acc else (s :: acc) in loop [] s (* Formatting *) let pp = Fmt.string let pp_dump ppf s = Fmt.pf ppf "%S" s (* Suggesting *) let edit_distance s0 s1 = (* As found here http://rosettacode.org/wiki/Levenshtein_distance#OCaml *) let minimum a b c = min a (min b c) in let m = String.length s0 in let n = String.length s1 in (* for all i and j, d.(i).(j) will hold the Levenshtein distance between the first i characters of s and the first j characters of t *) let d = Array.make_matrix (m+1) (n+1) 0 in for i = 0 to m do d.(i).(0) <- i done; for j = 0 to n do d.(0).(j) <- j done; for j = 1 to n do for i = 1 to m do if s0.[i-1] = s1.[j-1] then d.(i).(j) <- d.(i-1).(j-1) (* no operation required *) else d.(i).(j) <- minimum (d.(i-1).(j) + 1) (* a deletion *) (d.(i).(j-1) + 1) (* an insertion *) (d.(i-1).(j-1) + 1) (* a substitution *) done; done; d.(m).(n) let suggest ?(dist = 2) candidates s = let add (min, acc) name = let d = edit_distance s name in if d = min then min, (name :: acc) else if d < min then d, [name] else min, acc in let d, suggs = List.fold_left add (max_int, []) candidates in if d <= dist (* suggest only if not too far *) then List.rev suggs else [] (* Escaping and unescaping bytes XXX: limitation cannot escape multiple bytes. Multibyte could be achieved by tweaking the sigs to return integer pairs but that would allocate quite a bit. *) let byte_replaced_length char_len s = let rec loop s max i l = match i > max with | true -> l | false -> loop s max (i + 1) (l + char_len s.[i]) in loop s (String.length s - 1) 0 0 let byte_replace set_char s ~len ~replaced_len = let b = Bytes.create replaced_len in let rec loop s max i k = match i > max with | true -> Bytes.unsafe_to_string b | false -> loop s max (i + 1) (set_char b k s.[i]) in loop s (len - 1) 0 0 let byte_escaper char_len set_char s = let len = String.length s in let replaced_len = byte_replaced_length char_len s in match replaced_len = len with | true -> s | false -> byte_replace set_char s ~len ~replaced_len let byte_replacer char_len set_char s = let len = String.length s in let replaced_len = byte_replaced_length char_len s in byte_replace set_char s ~len ~replaced_len exception Illegal_escape of int (* index *) let byte_unreplace_length char_len_at s = let rec loop max i len = match i > max with | true -> len | false -> let esc_len = char_len_at s i in loop max (i + esc_len) (len - esc_len + 1) in loop (String.length s - 1) 0 (String.length s) let byte_unreplace set_char s ~len ~unreplace_len = let b = Bytes.create unreplace_len in let rec loop s max i k = match i > max with | true -> Ok (Bytes.unsafe_to_string b) | false -> loop s max (set_char b k s i) (k + 1) in loop s (String.length s - 1) 0 0 let byte_unescaper char_len_at set_char s = try let len = String.length s in let unreplace_len = byte_unreplace_length char_len_at s in match len = unreplace_len with | true -> Ok s | false -> byte_unreplace set_char s ~len ~unreplace_len with | Illegal_escape i -> Error i let byte_unreplacer char_len_at set_char s = try let len = String.length s in let unreplace_len = byte_unreplace_length char_len_at s in byte_unreplace set_char s ~len ~unreplace_len with | Illegal_escape i -> Error i (* US-ASCII string support *) module Ascii = struct (* Predicates *) let is_valid s = let rec loop max i = match i > max with | true -> true | false when unsafe_get s i > Char.Ascii.max -> false | false -> loop max (i + 1) in loop (String.length s - 1) 0 (* Casing transforms *) let caseify is_not_case to_case s = let max_idx = length s - 1 in let caseify b i = for k = i to max_idx do Bytes.unsafe_set b k (to_case (unsafe_get s k)) done; Bytes.unsafe_to_string b in let rec try_no_alloc i = if i > max_idx then s else if is_not_case (unsafe_get s i) then caseify (Bytes.of_string s) i else try_no_alloc (i + 1) in try_no_alloc 0 let uppercase s = caseify Char.Ascii.is_lower Char.Ascii.uppercase s let lowercase s = caseify Char.Ascii.is_upper Char.Ascii.lowercase s let caseify_first is_not_case to_case s = if length s = 0 then s else let c = unsafe_get s 0 in if not (is_not_case c) then s else let b = Bytes.of_string s in Bytes.unsafe_set b 0 (to_case c); Bytes.unsafe_to_string b let capitalize s = caseify_first Char.Ascii.is_lower Char.Ascii.uppercase s let uncapitalize s = caseify_first Char.Ascii.is_upper Char.Ascii.lowercase s (* Converting to US-ASCII hexadecimal characters *) let to_hex s = let rec loop max s i h k = match i > max with | true -> Bytes.unsafe_to_string h | false -> let byte = Char.code s.[i] in Bytes.set h k (Char.Ascii.lower_hex_digit (byte lsr 4)); Bytes.set h (k + 1) (Char.Ascii.lower_hex_digit byte); loop max s (i + 1) h (k + 2) in let len = String.length s in let h = Bytes.create (2 * len) in loop (len - 1) s 0 h 0 let of_hex h = let hex_value s i = match s.[i] with | '0' .. '9' as c -> Char.code c - 0x30 | 'A' .. 'F' as c -> 10 + (Char.code c - 0x41) | 'a' .. 'f' as c -> 10 + (Char.code c - 0x61) | _ -> raise_notrace (Illegal_escape i) in match String.length h with | len when len mod 2 <> 0 -> Error len | len -> let rec loop max s i h k = match i > max with | true -> Ok (Bytes.unsafe_to_string s) | false -> let hi = hex_value h k and lo = hex_value h (k + 1) in Bytes.set s i (Char.chr @@ (hi lsl 4) lor lo); loop max s (i + 1) h (k + 2) in let s_len = len / 2 in let s = Bytes.create s_len in try loop (s_len - 1) s 0 h 0 with Illegal_escape i -> Error i let of_hex' h = match of_hex h with | Ok _ as v -> v | Error i -> match i = String.length h with | true -> Error "Missing final hex digit" | false -> Fmt.error "Byte %d: not an ASCII hexadecimal digit" i (* Converting to printable US-ASCII characters *) let set_ascii_unicode_escape b k c = (* for c <= 0x7F *) let byte = Char.code c in let hi = byte lsr 4 and lo = byte land 0xF in Bytes.blit_string "\\u{00" 0 b k 5; Bytes.set b (k + 5) (Char.Ascii.upper_hex_digit hi); Bytes.set b (k + 6) (Char.Ascii.upper_hex_digit lo); Bytes.set b (k + 7) '}'; k + 8 let set_hex_escape b k c = let byte = Char.code c in let hi = byte lsr 4 and lo = byte land 0xF in Bytes.blit_string "\\x" 0 b k 2; Bytes.set b (k + 2) (Char.Ascii.upper_hex_digit hi); Bytes.set b (k + 3) (Char.Ascii.upper_hex_digit lo); k + 4 let set_symbol_escape b k symbol = Bytes.set b k '\\'; Bytes.set b (k + 1) symbol; k + 2 let escape = let char_len = function | '\x20' .. '\x5B' | '\x5D' .. '\x7E' -> 1 | _ (* hex escape *) -> 4 in let set_char b k = function | '\x20' .. '\x5B' | '\x5D' .. '\x7E' as c -> Bytes.set b k c; k + 1 | c -> set_hex_escape b k c in byte_escaper char_len set_char let unescape = let char_len_at s i = match s.[i] <> '\\' with | true -> 1 | false -> let max = String.length s - 1 in let j = i + 1 in if j > max then raise_notrace (Illegal_escape i) else if s.[j] <> 'x' then raise_notrace (Illegal_escape i) else let j = i + 3 in if j > max then raise_notrace (Illegal_escape i) else if Char.Ascii.is_hex_digit s.[i + 2] && Char.Ascii.is_hex_digit s.[i + 3] then 4 else raise (Illegal_escape i) (* invalid esc *) in let set_char b k s i = match s.[i] <> '\\' with | true -> Bytes.set b k s.[i]; i + 1 | false -> (* assert (s.[i+1] = 'x') *) let hi = Char.Ascii.hex_digit_value s.[i + 2] in let lo = Char.Ascii.hex_digit_value s.[i + 3] in Bytes.set b k (Char.chr @@ (hi lsl 4) lor lo); i + 4 in byte_unescaper char_len_at set_char let ocaml_string_escape = let char_len = function | '\b' | '\t' | '\n' | '\r' | '"' | '\\' -> 2 | '\x20' .. '\x7E' -> 1 | _ (* hex escape *) -> 4 in let set_char b k = function | '\b' -> set_symbol_escape b k 'b' | '\t' -> set_symbol_escape b k 't' | '\n' -> set_symbol_escape b k 'n' | '\r' -> set_symbol_escape b k 'r' | '"' -> set_symbol_escape b k '"' | '\\' -> set_symbol_escape b k '\\' | '\x20' .. '\x7E' as c -> Bytes.set b k c; k + 1 | c -> set_hex_escape b k c in byte_escaper char_len set_char let ocaml_unescape = let char_len_at s i = match s.[i] <> '\\' with | true -> 1 | false -> let max = String.length s - 1 in let j = i + 1 in if j > max then raise_notrace (Illegal_escape i) else match s.[j] with | 'x' -> let j = i + 3 in if j > max then raise_notrace (Illegal_escape i) else if Char.Ascii.is_hex_digit s.[i + 2] && Char.Ascii.is_hex_digit s.[i + 3] then 4 else raise_notrace (Illegal_escape i) | 'b' | 't' | 'n' | 'r' | ' ' | '"' | '\\' -> 2 | 'o' -> let j = i + 4 in if j > max then raise_notrace (Illegal_escape i) else let is_octal = function '0' .. '7' -> true | _ -> false in if is_octal s.[i + 2] && is_octal s.[i + 3] && is_octal s.[i + 4] then 5 else raise_notrace (Illegal_escape i) | c when Char.Ascii.is_digit c -> let j = i + 3 in if j > max then raise_notrace (Illegal_escape i) else if Char.Ascii.is_digit s.[i + 2] && Char.Ascii.is_digit s.[i + 3] then 4 else raise_notrace (Illegal_escape i) | _ -> raise_notrace (Illegal_escape i) in let set_char b k s i = if s.[i] <> '\\' then (Bytes.set b k s.[i]; i + 1) else match s.[i + 1] with | 'x' -> let hi = Char.Ascii.hex_digit_value s.[i + 2] in let lo = Char.Ascii.hex_digit_value s.[i + 3] in Bytes.set b k (Char.chr @@ (hi lsl 4) lor lo); i + 4 | '\\' -> Bytes.set b k '\\'; i + 2 | 'b' -> Bytes.set b k '\b'; i + 2 | 't' -> Bytes.set b k '\t'; i + 2 | 'n' -> Bytes.set b k '\n'; i + 2 | 'r' -> Bytes.set b k '\r'; i + 2 | ' ' -> Bytes.set b k ' '; i + 2 | '"' -> Bytes.set b k '"'; i + 2 | 'o' -> let o3 = Char.Ascii.hex_digit_value s.[i + 2] in let o2 = Char.Ascii.hex_digit_value s.[i + 3] in let o1 = Char.Ascii.hex_digit_value s.[i + 4] in let byte = o3 * 64 + o2 * 8 + o1 in if byte > 255 then raise_notrace (Illegal_escape i) else Bytes.set b k (Char.chr byte); i + 5 | c when Char.Ascii.is_digit c -> let d3 = Char.Ascii.hex_digit_value s.[i + 1] in let d2 = Char.Ascii.hex_digit_value s.[i + 2] in let d1 = Char.Ascii.hex_digit_value s.[i + 3] in let byte = d3 * 100 + d2 * 10 + d1 in if byte > 255 then raise_notrace (Illegal_escape i) else Bytes.set b k (Char.chr byte); i + 4 | _ -> assert false in byte_unescaper char_len_at set_char end (* Version strings *) let drop_initial_v s = if s = "" then s else match s.[0] with | 'v' | 'V' -> subrange ~first:1 s | _ -> s let to_version s = if s = "" then None else let cut_left_plus_or_tilde s = let cut = match String.index_opt s '+', String.index_opt s '~' with | None, None -> None | (Some _ as i), None | None, (Some _ as i) -> i | Some i, Some i' -> Some (if i < i' then i else i') in match cut with | None -> None | Some i -> Some (subrange ~last:(i - 1) s, subrange ~first:i s) in try match cut_left ~sep:"." s with | None -> None | Some (maj, rest) -> let maj = int_of_string (drop_initial_v maj) in match cut_left ~sep:"." rest with | None -> begin match cut_left_plus_or_tilde rest with | None -> Some (maj, int_of_string rest, 0, None) | Some (min, i) -> Some (maj, int_of_string min, 0, Some i) end | Some (min, rest) -> let min = int_of_string min in begin match cut_left_plus_or_tilde rest with | None -> Some (maj, min, int_of_string rest, None) | Some (p, i) -> Some (maj, min, int_of_string p, Some i) end with | Failure _ -> None (* String map and sets *) module Set = struct include Set.Make (String) let pp ?sep pp_elt = Fmt.iter ?sep iter pp_elt let pp_dump ppf ss = Fmt.pf ppf "@[<1>{%a}@]" (pp ~sep:Fmt.sp pp_dump) ss end module Map = struct include Map.Make (String) let dom m = fold (fun k _ acc -> Set.add k acc) m Set.empty let of_list bs = List.fold_left (fun m (k,v) -> add k v m) empty bs let add_to_list k v m = match find k m with | exception Not_found -> add k [v] m | l -> add k (v :: l) m let add_to_set (type set) (type elt) (module S : Stdlib_set.S with type elt = elt and type t = set) k v m = match find k m with | exception Not_found -> add k (S.singleton v) m | set -> add k (S.add v set) m let pp ?sep pp_binding = Fmt.iter_bindings ?sep iter pp_binding let pp_dump_str = pp_dump let pp_dump pp_v ppf m = let pp_binding ppf (k, v) = Fmt.pf ppf "@[<1>(@[%a@],@ @[%a@])@]" pp_dump_str k pp_v v in Fmt.pf ppf "@[<1>{%a}@]" (pp ~sep:Fmt.sp pp_binding) m let pp_dump_string_map ppf m = pp_dump pp_dump_str ppf m end (* Uniqueness *) let uniquify ss = let rec loop seen acc = function | [] -> List.rev acc | s :: ss when Set.mem s seen -> loop seen acc ss | s :: ss -> loop (Set.add s seen) (s :: acc) ss in loop Set.empty [] ss let unique ?(limit = 1_000_000_000) ~exists n = let rec loop i n = match i > limit with | true -> Fmt.invalid_arg "Could not uniquify %s after %d retries." n limit | false -> let r = Fmt.str "%s~%d" n i in if exists r then loop (i + 1) n else r in if exists n then loop 1 n else n (* Substituting *) let subst_pct_vars ?buf vars s = let max = String.length s - 1 in let buf = match buf with | None -> Buffer.create (max + 1) | Some buf -> Buffer.clear buf; buf in let add buf s ~start ~last = Buffer.add_substring buf s start (last - start + 1) in let rec find_var_end s i max = match i > max with | true -> None | false -> if i + 1 > max then None else if s.[i] = '%' && s.[i + 1] = '%' then Some (i + 1) else find_var_end s (i + 1) max in let rec loop buf s start i max = match i > max with | true -> if start = 0 then None else if start > max then Some (Buffer.contents buf) else (add buf s ~start ~last:max; Some (Buffer.contents buf)) | false -> if i + 4 > max then loop buf s start (max + 1) max else if s.[i] <> '%' then loop buf s start (i + 1) max else if s.[i + 1] <> '%' then loop buf s start (i + 2) max else match find_var_end s (i + 3) max with | None -> loop buf s start (max + 1) max | Some k -> let var = subrange ~first:(i + 2) ~last:(k - 2) s in match Map.find var vars with | exception Not_found -> loop buf s start (k + 1) max | v -> add buf s ~start ~last:(i - 1); Buffer.add_string buf v; loop buf s (k + 1) (k + 1) max in loop buf s 0 0 max end module List = struct include List let rec find_map f = function | [] -> None | v :: vs -> match f v with Some _ as r -> r | None -> find_map f vs let concat_map f l = let rec loop f acc = function | [] -> rev acc | v :: vs -> loop f (List.rev_append (f v) acc) vs in loop f [] l let classify (type a) (type b) ?(cmp_elts : a -> a -> int = Stdlib.compare) ?(cmp_classes : b -> b -> int = Stdlib.compare) ~classes:(classes : (a -> b list)) els = let module S = Set.Make (struct type t = a let compare = cmp_elts end) in let module M = Map.Make (struct type t = b let compare = cmp_classes end) in let add_classes acc p = let add_class acc c = try M.add c (S.add p (M.find c acc)) acc with | Not_found -> M.add c (S.singleton p) acc in List.fold_left add_class acc (classes p) in let classes = List.fold_left add_classes M.empty els in List.rev (M.fold (fun c els acc -> (c, S.elements els) :: acc) classes []) end (* File paths *) module Fpath = struct (* Errors *) let err_invalid_seg s = Fmt.str "%a: Invalid path segment" String.pp_dump s let err_start s = Fmt.error "%a: Not a path" String.pp_dump s let err_null s = Fmt.error "%a: Not a path: has null bytes" String.pp_dump s let err_empty s = Fmt.error "%a: Not a path: is empty" String.pp_dump s (* Pct encoding *) let pct_esc_len ~escape_space = function | '%' | '#' | '?' -> 3 | ' ' when escape_space -> 3 | c when Char.Ascii.is_control c -> 3 | _ -> 1 let set_pct_encoded b i c = let c = Char.code c in let hi = Char.Ascii.upper_hex_digit ((c lsr 4) land 0xF) in let lo = Char.Ascii.upper_hex_digit (c land 0xF) in Bytes.set b i '%'; Bytes.set b (i + 1) hi; Bytes.set b (i + 2) lo; i + 3 let pct_esc_set_char ~escape_space b i = function | '%' | '#' | '?' as c -> set_pct_encoded b i c | ' ' as c when escape_space -> set_pct_encoded b i c | c when Char.Ascii.is_control c -> set_pct_encoded b i c | c -> Bytes.set b i c; i + 1 (* Platform specifics. *) let undouble_sep sep dbl_sep s = let rec loop last_is_sep b k s i max = match i > max with | true -> Bytes.unsafe_to_string b | false -> let c = String.get s i in let c_is_sep = Char.equal c sep && i <> 0 (* handle // *) in let is_dbl = last_is_sep && c_is_sep in match is_dbl with | true -> loop c_is_sep b k s (i + 1) max | false -> Bytes.set b k c; loop c_is_sep b (k + 1) s (i + 1) max in let len = String.length s in loop false (Bytes.create (len - dbl_sep)) 0 s 0 (len - 1) module Windows = struct (* XXX the {of_string,path_start} needs reviewing/testing *) let dir_sep_char = '\\' let char_is_dir_sep c = c = '\\' || c = '/' let dir_sep = "\\" let has_dir_sep s = String.exists (function '/' | '\\' -> true | _ -> false) s let is_seg s = let valid c = c <> dir_sep_char && c <> '/' && c <> '\x00' in String.for_all valid s let is_unc_path p = String.starts_with ~prefix:"\\\\" p let has_drive p = String.exists (Char.equal ':') p let non_unc_path_start p = match String.rindex p ':' with | exception Not_found -> 0 | i -> i + 1 (* exists by construction once injected *) let path_start p = (* once [p] is injected this does not raise *) match is_unc_path p with | false -> non_unc_path_start p | true -> let plen = String.length p in if plen = 2 then raise Not_found else let sep_from p from = String.index_from p from dir_sep_char in let i = sep_from p 2 in let j = sep_from p (i + 1) in match p.[i - 1] with | '.' when i = 3 -> j | '?' when i = 3 -> if p.[j - 1] = ':' then j else if i + 3 < plen && p.[i + 1] = 'U' && p.[i + 2] = 'N' && p.[i + 3] = 'C' then sep_from p (sep_from p (j + 1) + 1) else sep_from p (j + 1) | _ -> sep_from p j let last_non_empty_seg_start p = match String.rindex p dir_sep_char with | exception Not_found -> path_start p | k -> match k = String.length p - 1 with | false -> k + 1 | true -> match String.rindex_from p (k - 1) dir_sep_char with | exception Not_found -> path_start p | k -> k + 1 let chop_volume p = String.subrange ~first:(path_start p) p let backslashify s = let b = Bytes.copy (Bytes.unsafe_of_string s) in for i = 0 to Bytes.length b - 1 do if Bytes.get b i = '/' then Bytes.set b i '\\' done; Bytes.unsafe_to_string b let of_string s = if s = "" then err_empty s else try let p = let rec loop has_slash last_is_sep dbl_sep i max = match i > max with | true -> let s = if has_slash then backslashify s else s in if dbl_sep > 0 then undouble_sep dir_sep_char dbl_sep s else s | false -> let c = String.unsafe_get s i in if Char.equal c '\x00' then raise Exit else let is_slash = Char.equal c '/' in let has_slash = has_slash || is_slash in let c_is_sep = (is_slash || Char.equal c dir_sep_char) && i <> 0 in let is_dbl = last_is_sep && c_is_sep in let dbl_sep = if is_dbl then dbl_sep + 1 else dbl_sep in loop has_slash c_is_sep dbl_sep (i + 1) max in loop false false 0 0 (String.length s - 1) in match path_start p with | exception Not_found -> err_start p | n -> let p = match n = String.length p with | true -> (* add root if there's only a UNC volume *) p ^ dir_sep | false -> p in Ok p with Exit -> err_null s let append p0 p1 = match is_unc_path p1 || has_drive p1 || p1.[0] = dir_sep_char with | true (* with volume or absolute *) -> p1 | false -> let p0_last_is_sep = p0.[String.length p0 - 1] = dir_sep_char in let sep = if p0_last_is_sep then "" else dir_sep in String.concat sep [p0; p1] let is_rel p = match is_unc_path p with | true -> false | false -> p.[non_unc_path_start p] <> dir_sep_char let is_root p = p.[path_start p] = dir_sep_char let to_uri_path ?(escape_space = true) p = let set_char b i = function | '\\' -> Bytes.set b i '/'; i + 1 | c -> pct_esc_set_char ~escape_space b i c in String.byte_escaper (pct_esc_len ~escape_space) set_char p end module Posix = struct let dir_sep_char = '/' let char_is_dir_sep c = Char.equal c '/' let dir_sep = "/" let has_dir_sep s = String.exists (function '/' -> true | _ -> false) s let is_seg s = String.for_all (fun c -> c <> dir_sep_char && c <> '\x00') s let of_string = function | "" as s -> err_empty s | s -> try let rec loop last_is_sep dbl_sep i max = match i > max with | true -> if dbl_sep > 0 then Ok (undouble_sep dir_sep_char dbl_sep s) else Ok s | false -> let c = String.unsafe_get s i in if Char.equal c '\x00' then raise Exit else let c_is_sep = Char.equal c dir_sep_char && i <> 0 in let is_dbl = last_is_sep && c_is_sep in let dbl_sep = if is_dbl then dbl_sep + 1 else dbl_sep in loop c_is_sep dbl_sep (i + 1) max in loop false 0 0 (String.length s - 1) with | Exit -> err_null s let last_non_empty_seg_start p = match String.rindex p dir_sep_char with | exception Not_found -> 0 | k -> match k = String.length p - 1 with | false -> k + 1 | true -> match String.rindex_from p (k - 1) dir_sep_char with | exception Not_found -> 0 | k -> k + 1 let dir_sep_char = '/' let last_non_empty_seg_start p = match String.rindex p dir_sep_char with | exception Not_found -> 0 | k -> match k = String.length p - 1 with | false -> k + 1 | true -> match String.rindex_from p (k - 1) dir_sep_char with | exception Not_found -> 0 | k -> k + 1 let path_start p = 0 let chop_volume p = p let append p0 p1 = if p1.[0] = dir_sep_char (* absolute *) then p1 else let p0_last_is_sep = p0.[String.length p0 - 1] = dir_sep_char in let sep = if p0_last_is_sep then "" else dir_sep in String.concat sep [p0; p1] let is_rel p = p.[0] <> dir_sep_char let is_root p = String.equal p dir_sep || String.equal p "//" let to_uri_path ?(escape_space = true) p = String.byte_escaper (pct_esc_len ~escape_space) (pct_esc_set_char ~escape_space) p end let path_start = if Sys.win32 then Windows.path_start else Posix.path_start let chop_volume = if Sys.win32 then Windows.chop_volume else Posix.chop_volume (* Separators and segments *) let dir_sep_char = if Sys.win32 then Windows.dir_sep_char else Posix.dir_sep_char let dir_sep = if Sys.win32 then Windows.dir_sep else Posix.dir_sep let char_is_dir_sep = if Sys.win32 then Windows.char_is_dir_sep else Posix.char_is_dir_sep let last_is_dir_sep p = Char.equal (p.[String.length p - 1]) dir_sep_char let has_dir_sep = if Sys.win32 then Windows.has_dir_sep else Posix.has_dir_sep let is_seg = if Sys.win32 then Windows.is_seg else Posix.is_seg let is_rel_seg = function "." | ".." -> true | _ -> false let last_seg_len p = match String.rindex p dir_sep_char with | exception Not_found -> String.length p | k -> String.length p - (k + 1) let last_non_empty_seg_start = match Sys.win32 with | true -> Windows.last_non_empty_seg_start | false -> Posix.last_non_empty_seg_start (* Paths *) type t = string (* N.B. a path is never "" *) let of_string = if Sys.win32 then Windows.of_string else Posix.of_string let to_string p = p let v s = match of_string s with Ok p -> p | Error m -> invalid_arg m let add_seg p seg = if not (is_seg seg) then invalid_arg (err_invalid_seg seg) else let sep = if last_is_dir_sep p then "" else dir_sep in String.concat sep [p; seg] let append = if Sys.win32 then Windows.append else Posix.append (* Famous file paths *) let null = v (if Sys.win32 then "NUL" else "/dev/null") let dash = v "-" (* Directory paths *) let is_dir_path p = (* check is . .. or ends with / /. or /.. *) let k = String.length p - 1 in if k < 0 then (* should not happen *) false else match p.[k] with | c when Char.equal c dir_sep_char -> true | '.' -> let k = k - 1 in if k < 0 then true else begin match p.[k] with | c when Char.equal c dir_sep_char -> true | '.' -> let k = k - 1 in k < 0 || Char.equal p.[k] dir_sep_char | _ -> false end | _ -> false let add_dir_sep p = add_seg p "" let strip_dir_sep p = match String.length p with | 1 -> p | 2 -> if p.[0] <> dir_sep_char && p.[1] = dir_sep_char then String.of_char p.[0] else p | len -> let max = len - 1 in if p.[max] <> dir_sep_char then p else String.subrange p ~last:(max - 1) (* Strict prefixes *) let is_prefix pre p = match String.starts_with ~prefix:pre p with | false -> false | true -> let suff_start = String.length pre in let p_len = String.length p in (* Check [prefix] and [p] are not equal modulo directoryness. *) if suff_start = p_len then false else if suff_start = p_len - 1 && p.[suff_start] = dir_sep_char then false else (* Check the prefix is segment based *) (pre.[suff_start - 1] = dir_sep_char || p.[suff_start] = dir_sep_char) let strip_prefix pre p = match is_prefix pre p with | false -> None | true -> let len = String.length pre in let first = if p.[len] = dir_sep_char then len + 1 else len in Some (String.subrange p ~first) let drop_prefixed dirs = let is_prefixed d by = is_prefix by d in let not_prefixed ~by:dirs d = not (List.exists (is_prefixed d) dirs) in List.filter (not_prefixed ~by:dirs) dirs let reroot ~root ~dst src = let rel_file = Option.get (strip_prefix root src) in append dst rel_file (* Predicates and comparisons *) let is_rel = if Sys.win32 then Windows.is_rel else Posix.is_rel let is_abs p = not (is_rel p) let is_root = if Sys.win32 then Windows.is_root else Posix.is_root (* FIXME this is wrong on windows. *) let current_dir_dir = "." ^ dir_sep let is_current_dir p = String.equal p "." || String.equal p current_dir_dir let parent_dir_dir = ".." ^ dir_sep let is_parent_dir p = String.equal p ".." || String.equal p parent_dir_dir let equal = String.equal let compare = String.compare (* File extensions *) type ext = string let ext_sep_char = '.' let rec ext_single_range spos epos k p = let i = String.rindex_from p k ext_sep_char (* raises if not fnd *) in match i <= spos with | true -> raise Not_found | false -> match not (Char.equal p.[i - 1] ext_sep_char) with | true -> i, epos | false -> ext_single_range spos epos (i - 1) p let rec ext_multi_range epos k p = let i = String.index_from p k ext_sep_char (* raises if not fnd *) in match i > epos with | true -> raise Not_found | false -> match not (Char.equal p.[i - 1] ext_sep_char) with | true -> i, epos | false -> ext_multi_range epos (i + 1) p let ext_range ?(multi = false) p = let plen = String.length p in let seg_start = last_non_empty_seg_start p in let seg_stop = match last_is_dir_sep p with | true -> plen - 2 | false -> plen - 1 in if seg_start >= seg_stop then raise Not_found else match multi with | true -> ext_multi_range seg_stop (seg_start + 1) p | false -> ext_single_range seg_start seg_stop seg_stop p let get_ext ?multi p = match ext_range ?multi p with | exception Not_found -> "" | first, last -> String.subrange ~first ~last p let has_ext e p = match ext_range ~multi:true p with | exception Not_found -> String.equal e "" | first, last -> let plen = last - first + 1 in let elen = String.length e in match plen < elen with | true -> false | false -> let rec loop pi ei = match ei < 0 with | true -> true | false -> Char.equal p.[pi] e.[ei] && loop (pi - 1) (ei - 1) in loop last (elen - 1) let mem_ext exts p = List.exists (fun ext -> has_ext ext p) exts let add_ext e p = let plen = String.length p in match last_is_dir_sep p with | false -> p ^ e | true -> let elen = String.length e in let nlen = plen + elen in let n = Bytes.create nlen in Bytes.blit_string p 0 n 0 (plen - 1); Bytes.blit_string e 0 n (plen - 1) elen; Bytes.set n (nlen - 1) dir_sep_char; Bytes.unsafe_to_string n let _rem_ext efirst elast p = let plen = String.length p in match elast = plen - 1 with | true -> String.subrange ~last:(efirst - 1) p | false -> let elen = elast - efirst + 1 in let nlen = plen - elen in let n = Bytes.create nlen in Bytes.blit_string p 0 n 0 nlen; Bytes.set n (nlen - 1) dir_sep_char; Bytes.unsafe_to_string n let strip_ext ?multi p = match ext_range ?multi p with | exception Not_found -> p | efirst, elast -> _rem_ext efirst elast p let set_ext ?multi e p = add_ext e (strip_ext ?multi p) let cut_ext ?multi p = match ext_range ?multi p with | exception Not_found -> p, "" | efirst, elast -> let ext = String.subrange ~first:efirst ~last:elast p in let p = _rem_ext efirst elast p in p, ext (* Basename and parent directory *) let basename ?(no_ext = false) p = let max = String.length p - 1 in let first, last = match String.rindex p dir_sep_char with | exception Not_found -> (* B *) path_start p, max | k when k <> max || k = 0 -> (* /B or .../B *) k + 1, max | k -> (* .../ *) let j = k - 1 in match String.rindex_from p j dir_sep_char with | exception Not_found -> (* B/ *) path_start p, j | i -> (* .../B/ *) i + 1, j in match last - first + 1 with | 1 when p.[first] = '.' -> "" | 2 when p.[first] = '.' && p.[first + 1] = '.' -> "" | _ when not no_ext -> String.subrange ~first ~last p | _ -> (* Drop multi ext *) let rec loop first last i = match i > last with | true -> String.subrange ~first ~last p | false -> match p.[i] = ext_sep_char with | false -> loop first last (i + 1) | true -> if p.[i - 1] = ext_sep_char then loop first last (i + 1) else String.subrange ~first ~last:(i - 1) p in loop first last (first + 1) let rec parent p = let plen = String.length p in let seg_start = last_non_empty_seg_start p in let seg_stop = match last_is_dir_sep p with | true -> plen - 2 | false -> plen - 1 in let seg_len = seg_stop - seg_start + 1 in let via_dotdot p = add_seg (add_seg p "..") "" in match seg_len with | 0 -> p | 1 when p.[seg_start] = '.' -> if seg_start = 0 then "../" else parent (String.subrange ~last:(seg_start - 1) p) | 2 when p.[seg_start] = '.' && p.[seg_stop] = '.' -> via_dotdot p | _ when seg_start = 0 -> "./" | _ -> add_seg (String.subrange ~last:(seg_start - 1) p) "" let equal_basename p0 p1 = (* XXX could avoid alloc *) String.equal (basename p0) (basename p1) let relative ~to_dir p = (* FIXME this function needs to be rewritten *) (* XXX dirty, need a normalization function and/or a better parent to handle that. Also the results should be normalized again. *) if String.includes ~affix:".." to_dir (* cmon that's obvi..ously wrong *) then Fmt.invalid_arg "%s: no dotdot allowed" p; let to_dir = add_dir_sep to_dir in match strip_prefix to_dir p with | Some q -> q | None -> let rec loop loc dir = if is_current_dir dir || is_root dir then p else match strip_prefix dir p with | Some q -> append loc q | None -> loop (add_seg loc "..") (parent dir) in loop ".." (parent to_dir) (* Converting *) let to_uri_path = if Sys.win32 then Windows.to_uri_path else Posix.to_uri_path let pp_quoted ppf p = String.pp ppf (Filename.quote p) let pp_unquoted = String.pp let pp = pp_quoted let pp_dump = String.pp_dump (* Uniqueness *) let uniquify = String.uniquify (* Path and sets *) type path = t module Set = struct let pp_set ppf ss = Fmt.pf ppf "@[<1>{%a}@]" (String.Set.pp ~sep:Fmt.sp pp) ss include String.Set end module Map = String.Map (* Sorts *) let sort_by_parent ps = let add_path p acc = Map.add_to_set (module Set) (parent p) p acc in Set.fold add_path ps Map.empty let sort_by_ext ?multi ps = let add_path p acc = String.Map.add_to_set (module Set) (get_ext ?multi p) p acc in Set.fold add_path ps String.Map.empty (* Search paths *) let search_path_sep = if Sys.win32 then ";" else ":" let list_of_search_path ?(sep = search_path_sep) path = let rec loop acc = function | "" -> Ok (List.rev acc) | p -> let dir, p = match String.cut_left ~sep p with | None -> p, "" | Some (dir, p) -> dir, p in if dir = "" then loop acc p else match of_string dir with | Error e -> Fmt.error "search path %s: %S: %s" path dir e | Ok d -> loop (d :: acc) p in loop [] path (* Operators *) let ( / ) = add_seg let ( // ) = append let ( + ) p e = add_ext e p let ( -+ ) p e = set_ext e p end (* Hash values and functions *) module Hash = struct (* Hash values *) type t = string let nil = "" let length = String.length (* Predicates and comparisons *) let equal = String.equal let compare = String.compare let is_nil h = equal nil h (* Converting *) let to_bytes h = h let of_bytes h = h let to_hex = String.Ascii.to_hex let of_hex = String.Ascii.of_hex let pp ppf h = Fmt.string ppf (if is_nil h then "nil" else to_hex h) (* Hash functions *) module type T = sig val id : string val length : int val string : string -> t val fd : Unix.file_descr -> t val file : Fpath.t -> (t, string) result end let rec file_with_hash_fd hash_fd f = let err f e = Fmt.error "%a: %s" Fpath.pp f e in match Unix.openfile (Fpath.to_string f) Unix.[O_RDONLY] 0 with | exception Unix.Unix_error (Unix.EINTR, _, _) -> file_with_hash_fd hash_fd f | exception Unix.Unix_error (e, _, _) -> err f (Unix.error_message e) | fd -> match hash_fd fd with | exception Sys_error e -> (try Unix.close fd with Unix.Unix_error (_, _, _) -> ()); err f e | hash -> match Unix.close fd with | () -> Ok hash | exception Unix.Unix_error (e, _, _) -> err f (Unix.error_message e) module Murmur3_128 = struct type t = string type seed = int let no_seed = 0 external hash_fd : Unix.file_descr -> seed -> t = "ocaml_b00_murmurhash_fd" external hash_unsafe : string -> int -> int -> seed -> t = "ocaml_b00_murmurhash" let id = "murmur3-128" let length = 16 let string s = hash_unsafe s 0 (String.length s) no_seed let fd fd = hash_fd fd no_seed let file f = file_with_hash_fd fd f end module Xxh_64 = struct type t = int64 type seed = int64 external hash_fd : Unix.file_descr -> seed -> t = "ocaml_b00_xxhash_fd" external hash_unsafe : string -> int -> int -> seed -> t = "ocaml_b00_xxhash" external set_64u : Bytes.t -> int -> int64 -> unit = "%caml_string_set64u" external swap_64 : int64 -> int64 = "%bswap_int64" external noswap : int64 -> int64 = "%identity" let layout = if Sys.big_endian then noswap else swap_64 let to_bytes t = let b = Bytes.create 8 in set_64u b 0 (layout t); Bytes.unsafe_to_string b let id = "xxh64" let seed = 0L let length = 8 let string s = hash_unsafe s 0 (String.length s) seed |> to_bytes let fd fd = hash_fd fd seed |> to_bytes let file f = file_with_hash_fd fd f end let funs = ref [(module Murmur3_128 : T); (module Xxh_64 : T);] let add_fun m = funs := m :: !funs let funs () = !funs let get_fun id = let has_id id (module H : T) = String.equal H.id id in let funs = funs () in match List.find (has_id id) funs with | m -> Ok m | exception Not_found -> let kind = Fmt.any "hash" in let pp_id = Fmt.(code string) in let ids = List.map (fun (module H : T) -> H.id) funs in let hint, ids = match String.suggest ids id with | [] -> Fmt.must_be, ids | ids -> Fmt.did_you_mean, ids in Fmt.error "@[%a@]" (Fmt.unknown' ~kind pp_id ~hint) (id, ids) end (* Monotonic time stamps and spans *) module Mtime = struct type uint64 = int64 module Span = struct (* Time spans Represented by a nanosecond magnitude stored in an unsigned 64-bit integer. Allows to represent spans for ~584.5 Julian years. *) type t = uint64 let zero = 0L let one = 1L let max_span = -1L let add = Int64.add let abs_diff s0 s1 = match Int64.unsigned_compare s0 s1 < 0 with | true -> Int64.sub s1 s0 | false -> Int64.sub s0 s1 (* Predicates and comparisons *) let equal = Int64.equal let compare = Int64.unsigned_compare (* Durations *) let ( * ) n s = Int64.mul (Int64.of_int n) s let ns = 1L let us = 1_000L let ms = 1_000_000L let s = 1_000_000_000L let min = 60_000_000_000L let hour = 3600_000_000_000L let day = 86400_000_000_000L let year = 31_557_600_000_000_000L (* Conversions *) let to_uint64_ns s = s let of_uint64_ns ns = ns let pp = Fmt.uint64_ns_span let pp_ns ppf s = Fmt.pf ppf "%Luns" s end type span = Span.t (* Monotonic timestamps *) type t = uint64 let to_uint64_ns s = s let of_uint64_ns ns = ns let min_stamp = 0L let max_stamp = -1L let pp ppf s = Fmt.pf ppf "%Lu" s (* Predicates *) let equal = Int64.equal let compare = Int64.unsigned_compare let is_earlier t ~than = compare t than < 0 let is_later t ~than = compare t than > 0 (* Arithmetic *) let span t0 t1 = match compare t0 t1 < 0 with | true -> Int64.sub t1 t0 | false -> Int64.sub t0 t1 let add_span t s = let sum = Int64.add t s in if compare t sum <= 0 then Some sum else None let sub_span t s = if compare t s < 0 then None else Some (Int64.sub t s) end (* Command lines *) module Cmd = struct (* Command lines *) type t = | A of string | Unstamp of t | Rseq of t list (* Sequence is reversed; only empty at toplevel *) let empty = Rseq [] let rec is_empty = function Rseq [] -> true | _ -> false let atom a = A a let append l0 l1 = match l0, l1 with | Rseq [], l1 -> l1 | l0, Rseq [] -> l0 | Rseq ls, l -> Rseq (l :: ls) | l1, l2 -> Rseq ([l2; l1]) let unstamp = function | Rseq [] -> empty | l -> Unstamp l let ( % ) l a = append l (atom a) let ( %% ) = append (* Derived combinators *) let if' cond l = if cond then l else empty let path p = A (Fpath.to_string p) let int i = A (string_of_int i) let float f = A (string_of_float f) let list ?slip l = match slip with | None -> Rseq (List.rev_map atom l) | Some slip -> Rseq (List.fold_left (fun acc v -> A v :: A slip :: acc) [] l) let rev_list ?slip l = match slip with | None -> Rseq (List.map atom l) | Some slip -> Rseq (List.fold_right (fun v acc -> A v :: A slip :: acc) l []) let of_list ?slip conv l = match slip with | None -> Rseq (List.rev_map (fun a -> A (conv a)) l) | Some slip -> let add acc v = A (conv v) :: A slip :: acc in Rseq (List.fold_left add [] l) let of_rev_list ?slip conv l = match slip with | None -> Rseq (List.rev_map (fun a -> A (conv a)) l) | Some slip -> let add a acc = A (conv a) :: A slip :: acc in Rseq (List.fold_right add l []) let paths ?slip ps = of_list ?slip Fpath.to_string ps let rev_paths ?slip ps = of_rev_list ?slip Fpath.to_string ps (* Converting *) let to_list l = let rec loop acc = function | A a -> a :: acc | Rseq ls -> List.fold_left loop acc ls | Unstamp l -> loop acc l in loop [] l let to_list_and_stamp l = let rec loop unstamped acc sg = function | A a -> (a :: acc), (if unstamped then sg else a :: sg) | Rseq ls -> let rec sub unstamped acc sg = function | [] -> acc, sg | l :: ls -> let acc, sg = loop unstamped acc sg l in sub unstamped acc sg ls in sub unstamped acc sg ls | Unstamp l -> loop true acc sg l in loop false [] [] l let to_stamp l = let rec loop acc = function | A a -> (a :: acc) | Rseq ls -> List.fold_left loop acc ls | Unstamp l -> acc in loop [] l let of_string s = (* Parsing is loosely based on http://pubs.opengroup.org/onlinepubs/009695399/utilities/\ xcu_chap02.html#tag_02_03 XXX Rewrite, this was quickly ported from bos code based on Astring.String.sub *) try let err_unclosed kind _ = Fmt.failwith "unclosed %s quote delimited string" kind in let skip_white s = String.lose_left Char.Ascii.is_white s in let tok_sep c = c = '\'' || c = '\"' || Char.Ascii.is_white c in let tok_char c = not (tok_sep c) in let not_squote c = c <> '\'' in let tail s = (* Yikes *) String.subrange ~first:1 s in let parse_squoted s = let tok, rem = String.span_left not_squote (tail s) in if not (String.equal rem "") then tok, tail rem else err_unclosed "single" s in let parse_dquoted acc s = let is_data = function '\\' | '"' -> false | _ -> true in let rec loop acc s = let data, rem = String.span_left is_data s in match String.head rem with | Some '"' -> (data :: acc), (tail rem) | Some '\\' -> let rem = tail rem in begin match String.head rem with | Some ('"' | '\\' | '$' | '`' as c) -> let acc = String.(of_char c) :: data :: acc in loop acc (tail rem) | Some ('\n') -> loop (data :: acc) (tail rem) | Some c -> let acc = (data ^ (Fmt.str "\\%c" c)) :: acc in loop acc (tail rem) | None -> err_unclosed "double" s end | None -> err_unclosed "double" s | Some _ -> assert false in loop acc (tail s) in let parse_token s = let ret acc s = String.concat "" (List.rev acc), s in let rec loop acc s = match String.head s with | None -> ret acc s | Some c when Char.Ascii.is_white c -> ret acc s | Some '\'' -> let tok, rem = parse_squoted s in loop (tok :: acc) rem | Some '\"' -> let acc, rem = parse_dquoted acc s in loop acc rem | Some c -> let sat = tok_char in let tok, rem = String.span_left sat s in loop (tok :: acc) rem in loop [] s in let rec loop acc s = match String.equal s "" with | false -> let token, s = parse_token s in loop (A token :: acc) (skip_white s) | true -> match acc with | [a] -> a | acc -> Rseq acc in Ok (loop [] (skip_white s)) with Failure err -> Fmt.error "command line %a: %s" String.pp_dump s err let to_string l = String.concat " " (List.map Filename.quote @@ to_list l) let pp ppf l = Fmt.pf ppf "@[%a@]" Fmt.(list ~sep:sp string) (to_list l) let pp_dump ppf l = let pp_atom ppf a = Fmt.string ppf (Filename.quote a) in Fmt.pf ppf "@[<h>%a@]" Fmt.(list ~sep:sp pp_atom) (to_list l) let rec fold ~arg ~unstamp ~append ~empty = function | A a -> arg a | Unstamp c -> unstamp (fold ~arg ~unstamp ~append ~empty c) | Rseq l -> let append acc v = append (fold ~arg ~unstamp ~append ~empty v) acc in List.fold_left append empty l let rec iter_enc ~arg ~unstamp ~append ~empty e = function | A a -> arg e a | Unstamp c -> unstamp e; iter_enc ~arg ~unstamp ~append ~empty e c | Rseq l -> let append e v = append e; iter_enc ~arg ~unstamp ~append ~empty e v; e in ignore (List.fold_left append e l); empty e (* Tools *) type tool = Fpath.t let rec tool = function | A a -> Result.to_option (Fpath.of_string a) | Unstamp l -> tool l | Rseq ls -> let rec loop = function | [l] -> tool l | l :: ls -> loop ls | [] -> None in loop ls let rec set_tool tool = function | Rseq [] -> None | l -> let rec loop = function | A a -> A (Fpath.to_string tool) | Unstamp l -> Unstamp (loop l) | Rseq ls -> match List.rev ls with | arg :: args -> Rseq (List.rev @@ (loop arg) :: args) | [] -> assert false in Some (loop l) let get_tool l = match tool l with | Some t -> t | None when is_empty l -> invalid_arg "empty command line" | None -> Fmt.invalid_arg "cmd %s: tool parse error" (to_string l) let pp_tool ppf t = Fmt.tty_string [`Fg `Blue] ppf (Filename.quote (Fpath.to_string t)) (* Predicates *) let rec is_singleton = function | A a -> true | Unstamp l -> is_singleton l | Rseq _ -> false end (* Futures *) module Fut = struct type 'a state = Det of 'a | Undet of { mutable awaits : ('a -> unit) list } type 'a t = 'a state ref let rec kontinue ks v = let todo = ref ks in while match !todo with [] -> false | _ -> true do match !todo with k :: ks -> todo := ks; k v | [] -> () done let set f v = match !f with | Det _ -> invalid_arg "The future is already set" | Undet u -> f := Det v; kontinue u.awaits v let _create () = ref (Undet { awaits = [] }) let create () = let f = _create () in f, set f let value f = match !f with Det v -> Some v | _ -> None let await f k = match !f with | Det v -> k v | Undet u -> u.awaits <- k :: u.awaits let rec sync f = match !f with | Det v -> v | Undet _ -> let relax () = try ignore (Unix.select [] [] [] 0.0001) with | Unix.Unix_error _ -> () in relax (); sync f let return v = ref (Det v) let map fn f = let r = _create () in await f (fun v -> set r (fn v)); r let bind f fn = let r = _create () in await f (fun v -> await (fn v) (set r)); r let pair f0 f1 = let r = _create () in await f0 (fun v0 -> await f1 (fun v1 -> set r (v0, v1))); r let of_list fs = match fs with | [] -> return [] | fs -> let r = _create () in let rec loop acc = function | [] -> set r (List.rev acc) | f :: fs -> await f (fun v -> loop (v :: acc) fs) in loop [] fs; r module Syntax = struct let ( >>= ) = bind let ( let* ) = bind let ( and* ) = pair end end (* Operating system interactions *) module Os = struct (* A bit of randomness for functions that need unique filenames *) let rand_gen = lazy (Random.State.make_self_init ()) (* Error handling *) let uerr = Unix.error_message let err_doing doing e = Fmt.str "%s: %s" doing e let ferr file e = Fmt.error "%a: %s" Fpath.pp file e let ffail file e = Fmt.failwith "%a: %s" Fpath.pp file e let ffail_notrace file e = Fmt.failwith_notrace "%a: %s" Fpath.pp file e module Cpu = struct external logical_count : unit -> int = "ocaml_b00_cpu_logical_count" (* Measuring CPU time *) module Time = struct (* CPU time spans *) let sec_to_span sec = Int64.of_float (sec *. 1e9) type span = { utime : Mtime.span; stime : Mtime.span; children_utime : Mtime.span; children_stime : Mtime.span; } let span ~utime ~stime ~children_utime ~children_stime = { utime; stime; children_utime; children_stime } let zero = span ~utime:0L ~stime:0L ~children_utime:0L ~children_stime:0L let utime c = c.utime let stime c = c.stime let children_utime c = c.children_utime let children_stime c = c.children_stime (* CPU counters *) type counter = span let counter () = let now = Unix.times () in { utime = sec_to_span now.Unix.tms_utime; stime = sec_to_span now.Unix.tms_stime; children_utime = sec_to_span now.Unix.tms_cutime; children_stime = sec_to_span now.Unix.tms_cstime; } let count c = let now = Unix.times () in { utime = Int64.sub (sec_to_span now.Unix.tms_utime) c.utime; stime = Int64.sub (sec_to_span now.Unix.tms_stime) c.stime; children_utime = Int64.sub (sec_to_span now.Unix.tms_cutime) c.children_utime; children_stime = Int64.sub (sec_to_span now.Unix.tms_cstime) c.children_stime; } end end module Mtime = struct external mtime_now_ns : unit -> Mtime.t = "ocaml_b00_monotonic_now_ns" (* Monotonic clock *) let origin = mtime_now_ns () let elapsed () = Int64.sub (mtime_now_ns ()) origin let now = mtime_now_ns (* Monotonic time counter *) type counter = Mtime.t let counter = mtime_now_ns let count c = Int64.sub (mtime_now_ns ()) c end module Env = struct (* Variables *) let find ~empty_is_none name = match Unix.getenv name with | "" when empty_is_none -> None | v -> Some v | exception Not_found -> None let find' ~empty_is_none parse name = match find ~empty_is_none name with | None -> Ok None | Some v -> match parse v with | Error e -> Fmt.error "%s env: %s" name e | Ok v -> Ok (Some v) (* Process environment *) type t = string String.Map.t let empty = String.Map.empty let add = String.Map.add let override env ~by = if String.Map.is_empty by then env else let lean_right _ l r = match r with | Some _ as v -> v | None -> match l with Some _ as v -> v | None -> assert false in String.Map.merge lean_right env by (* Assignements *) let env_err e = Fmt.error "process environment: %s" e type assignments = string list let current_assignments () = try Ok (Array.to_list @@ Unix.environment ()) with | Sys_error e -> env_err e | Unix.Unix_error (e, _, _) -> env_err (uerr e) let parse_assignments ?(init = String.Map.empty) fold v = try let add acc assign = match String.cut_left ~sep:"=" assign with | Some (var, value) -> String.Map.add var value acc | None -> Fmt.failwith_notrace "%S: cannot parse VAR=VAL assignement" assign in Ok (fold add init v) with | Failure e -> Result.error e let of_assignments ?init l = parse_assignments ?init List.fold_left l let to_assignments env = let add var v acc = String.concat "=" [var; v] :: acc in String.Map.fold add env [] let current () = match parse_assignments Array.fold_left (Unix.environment ()) with | Ok _ as v -> v | Error e -> env_err e | exception Sys_error e -> env_err e | exception Unix.Unix_error (e, _, _) -> env_err (uerr e) end module Fd = struct let unix_buffer_size = 65536 (* UNIX_BUFFER_SIZE 4.0.0 *) let rec openfile fn mode perm = try Unix.openfile fn mode perm with | Unix.Unix_error (Unix.EINTR, _, _) -> openfile fn mode perm let rec close fd = try Unix.close fd with | Unix.Unix_error (Unix.EINTR, _, _) -> close fd let close_no_unix_exn fd = try close fd with Unix.Unix_error _ -> () let apply ~close fd f = let close fd = try close fd with Unix.Unix_error _ -> () in match f fd with v -> close fd; v | exception e -> close fd; raise e let copy ?buf ~src dst = let rec unix_read fd b = try Unix.read fd b 0 (Bytes.length b) with | Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd b in let rec unix_write fd s i l = let rec write fd s i l = try Unix.single_write fd s i l with | Unix.Unix_error (Unix.EINTR, _, _) -> write fd s i l in let bc = write fd s i l in if bc < l then unix_write fd s (i + bc) (l - bc) else () in let rec loop buf src dst = match unix_read src buf with | 0 -> () | l -> unix_write dst buf 0 l; loop buf src dst in let buf = match buf with | Some b -> b | None -> Bytes.create unix_buffer_size in loop buf src dst let to_string fd = let b = Bytes.create unix_buffer_size in let acc = Buffer.create unix_buffer_size in let rec loop () = match Unix.read fd b 0 (Bytes.length b) with | 0 -> Buffer.contents acc | l -> Buffer.add_subbytes acc b 0 l; loop () | exception Unix.Unix_error (Unix.EINTR, _, _) -> loop () in loop () let rec really_read fd b start len = match len <= 0 with | true -> () | false -> match Unix.read fd b start len with | 0 -> failwith (err_doing "Reading" "Unexpected end of file") | r -> really_read fd b (start + r) (len - r) | exception Unix.Unix_error (Unix.EINTR, _, _) -> really_read fd b start len let read_file file fd = try match Unix.lseek fd 0 Unix.SEEK_END with | exception Unix.Unix_error (Unix.ESPIPE, _, _) -> to_string fd | len when len > Sys.max_string_length -> Fmt.failwith_notrace "File to read too large: %d bytes, max supported: %d" len Sys.max_string_length | len -> let b = Bytes.create len in ignore (Unix.lseek fd 0 Unix.SEEK_SET); really_read fd b 0 len; Bytes.unsafe_to_string b with | Failure e -> Fmt.failwith_notrace "%a: %s" Fpath.pp file e | Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "%s: %s" file (err_doing "Reading" (uerr e)) module Set = struct (* Maintains a set of fds to close. *) module Fd = struct type t = Unix.file_descr let compare : t -> t -> int = compare end module S = Set.Make (Fd) type t = S.t ref let empty () = ref S.empty let rem fd s = s := S.remove fd !s let add fd s = s := S.add fd !s let close_all s = S.iter close_no_unix_exn !s; s := S.empty let close fd s = if S.mem fd !s then (close_no_unix_exn fd; s := S.remove fd !s) end end module Fs_base = struct let rec is_dir p = try (Unix.stat p).Unix.st_kind = Unix.S_DIR with | Unix.Unix_error (Unix.EINTR, _, _) -> is_dir p let rec is_symlink p = try (Unix.lstat p).Unix.st_kind = Unix.S_LNK with | Unix.Unix_error (Unix.EINTR, _, _) -> is_symlink p let rec unlink p = try Unix.unlink p with | Unix.Unix_error (Unix.EINTR,_, _) -> unlink p let rec file_delete p = try Ok (Unix.unlink (Fpath.to_string p); true) with | Unix.Unix_error (Unix.ENOENT, _, _) -> Ok false | Unix.Unix_error (Unix.EINTR, _, _) -> file_delete p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Deleting" (uerr e)) (* Directory operations. *) let dir_create ?(mode = 0o755) ~make_path dir = let create_op = "Creating" in let mkdir dir mode = Unix.mkdir (Fpath.to_string dir) mode in try let pmode = 0o755 in try Ok (mkdir dir mode; true) with | Unix.Unix_error (Unix.EEXIST, _, _) -> if is_dir dir then Ok false else ferr dir (err_doing create_op "Path exists but not a directory") | Unix.Unix_error (Unix.ENOENT, _, _) when make_path -> let rec down = function | [] -> assert false | [dir] -> (try Ok (mkdir dir mode; true) with | Unix.Unix_error (Unix.EEXIST, _, _) -> Ok false) | dir :: dirs -> match mkdir dir pmode with | () -> down dirs | exception Unix.Unix_error (Unix.EEXIST, _, _) -> down dirs in let rec up todo p = match Unix.mkdir p pmode with | () -> down todo | exception Unix.Unix_error (Unix.ENOENT, _, _) -> up (p :: todo) (Fpath.parent p) in up [dir] (Fpath.parent dir) with | Unix.Unix_error (e, _, p) -> match String.equal (Fpath.to_string dir) p with | true -> ferr dir (err_doing create_op (uerr e)) | false -> let perr = Fmt.str "%s: %s" p (uerr e) in ferr dir (err_doing create_op perr) let dir_delete ~recurse dir = let delete_op = "Deleting" in let err e = Fmt.failwith_notrace "%a: %s" Fpath.pp dir e in let rec delete_symlink p = if is_symlink p then (unlink p; true) else false in let try_unlink file = match Unix.unlink (Fpath.to_string file) with | () -> true | exception Unix.Unix_error (e, _, _) -> match e with | Unix.ENOENT -> true | Unix.EISDIR (* Linux *) | Unix.EPERM (* POSIX *) -> false | Unix.EACCES when Sys.win32 -> (* This is what Unix.unlink returns on directories on Windows. *) false | e -> let ferr = Fmt.str "%a: %s" Fpath.pp file (uerr e) in err (err_doing delete_op ferr) in let rec delete_contents d dh todo = match Unix.readdir dh with | exception End_of_file -> d :: todo | ".." | "." -> delete_contents d dh todo | file -> let file = Fpath.(d / file) in if try_unlink file then delete_contents d dh todo else file :: d :: todo (* file is a dir we'll come back later for [d] *) in let rec try_delete d todo = match Unix.opendir (Fpath.to_string d) with | dh -> let dirs = match delete_contents d dh todo with | dirs -> Unix.closedir dh; dirs | exception e -> Unix.closedir dh; raise e in doit dirs | exception Unix.Unix_error (e, _, _) -> match e with | Unix.ENOENT | Unix.ENOTDIR -> doit todo | e -> let derr = Fmt.str "%a: %s" Fpath.pp d (uerr e) in err (err_doing delete_op derr) and doit = function | [] -> () | d :: ds -> match Unix.rmdir (Fpath.to_string d) with | () -> doit ds | exception Unix.Unix_error (e, _, _) -> match e with | Unix.ENOTEMPTY -> try_delete d ds | Unix.ENOENT | Unix.ENOTDIR -> doit ds | e -> let derr = Fmt.str "%a: %s" Fpath.pp d (uerr e) in err (err_doing delete_op derr) in try match Unix.rmdir (Fpath.to_string dir) with | () -> Ok true | exception Unix.Unix_error (e, _, _) -> match e with | Unix.ENOTEMPTY when recurse -> Ok (try_delete dir []; true) | Unix.ENOENT -> Ok false | Unix.ENOTDIR -> begin try if delete_symlink (Fpath.to_string dir) then Ok true else err (err_doing delete_op (uerr Unix.ENOTDIR)) with | Unix.Unix_error (e, _, _) -> err (err_doing delete_op (uerr e)) end | e -> err (err_doing delete_op (uerr e)) with | Failure e -> Result.error e (* Handling forced file operations *) let err_force p = ferr p "Path exists" let rec handle_force ~force file = if force then Ok () else try ignore (Unix.lstat (Fpath.to_string file)); err_force file with | Unix.Unix_error (Unix.ENOENT, _, _) -> Ok () | Unix.Unix_error (Unix.EINTR, _, _) -> handle_force ~force file | Unix.Unix_error (e, _, _) -> ferr file (err_doing "Testing existence" (uerr e)) let rec handle_force_open_fdout ?(flags = Unix.[O_WRONLY; O_CREAT; O_SHARE_DELETE; O_CLOEXEC; O_TRUNC]) ~force ~make_path ~mode file = let fls = if force then flags else Unix.O_EXCL :: flags in match Unix.openfile file fls mode with | fd -> Ok fd | exception Unix.Unix_error (Unix.EEXIST, _, _) -> err_force file | exception Unix.Unix_error (Unix.EINTR, _, _) -> handle_force_open_fdout ~flags ~force ~make_path ~mode file | exception Unix.Unix_error (Unix.ENOENT as e, _, _) when make_path -> begin match dir_create ~make_path (Fpath.parent file) with | Error e -> ferr file e | Ok false (* existed *) -> ferr file (uerr e) | Ok true (* created *) -> handle_force_open_fdout ~flags ~force ~make_path ~mode file end | exception Unix.Unix_error (e, _, _) -> ferr file (uerr e) (* Path operations *) let rec path_exists p = try (ignore (Unix.stat (Fpath.to_string p)); Ok true) with | Unix.Unix_error (Unix.ENOENT, _, _) -> Ok false | Unix.Unix_error (Unix.EINTR, _, _) -> path_exists p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Testing existence" (uerr e)) let rec path_get_mode p = try Ok ((Unix.stat @@ Fpath.to_string p).Unix.st_perm) with | Unix.Unix_error (Unix.EINTR, _, _) -> path_get_mode p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Getting file mode" (uerr e)) let rec path_set_mode p m = try Ok (Unix.chmod (Fpath.to_string p) m) with | Unix.Unix_error (Unix.EINTR, _, _) -> path_set_mode p m | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Setting file mode" (uerr e)) let rec path_delete ~recurse p = try Ok (Unix.unlink (Fpath.to_string p); true) with | Unix.Unix_error (Unix.ENOENT, _, _) -> Ok false | Unix.Unix_error (Unix.EINTR, _, _) -> path_delete ~recurse p | Unix.Unix_error ((Unix.EPERM | Unix.EISDIR), _, _) -> dir_delete ~recurse p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Deleting" (uerr e)) let rec path_rename ~force ~make_path ~src p = let err e = Fmt.error "rename %a to %a: %s" Fpath.pp src Fpath.pp p e in match handle_force ~force p with | Error e -> err e | Ok () -> try Ok (Unix.rename (Fpath.to_string src) (Fpath.to_string p)) with | Unix.Unix_error (Unix.ENOENT as e, _, _) when make_path -> begin match dir_create ~make_path (Fpath.parent p) with | Error e -> err e | Ok false (* existed *) -> err (uerr e) | Ok true (* created *) -> path_rename ~force ~make_path ~src p end | Unix.Unix_error (Unix.EINTR, _, _) -> path_rename ~force ~make_path ~src p | Unix.Unix_error (e, _, _) -> err (uerr e) let rec path_stat p = try Ok (Unix.stat (Fpath.to_string p)) with | Unix.Unix_error (Unix.EINTR, _, _) -> path_stat p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "stat" (uerr e)) (* Links *) let rec symlink ~force ~make_path ~src p = let err e = Fmt.error "symlink %a to %a: %s" Fpath.pp src Fpath.pp p e in try Ok (Unix.symlink (Fpath.to_string src) (Fpath.to_string p)) with | Unix.Unix_error (Unix.EEXIST, _, _) when force -> begin match file_delete p with | Error e -> err e | Ok _ -> symlink ~force ~make_path ~src p end | Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR as e), _, _) when make_path -> begin match dir_create ~make_path (Fpath.parent p) with | Error e -> ferr p (err_doing "Creating path" e) | Ok false (* existed *) -> err (uerr e) | Ok true (* created *) -> symlink ~force ~make_path ~src p end | Unix.Unix_error (Unix.EINTR, _, _) -> symlink ~force ~make_path ~src p | Unix.Unix_error (e, _, _) -> err (uerr e) let rec symlink_link p = try let l = Unix.readlink (Fpath.to_string p) in match Fpath.of_string l with | Ok _ as v -> v | Error e -> ferr p (err_doing "Reading symlink" e) with | Unix.Unix_error (Unix.EINVAL, _, _) -> ferr p "Not a symbolic link" | Unix.Unix_error (Unix.EINTR, _, _) -> symlink_link p | Unix.Unix_error (e, _, _) -> ferr p (uerr e) let rec symlink_stat p = try Ok (Unix.lstat (Fpath.to_string p)) with | Unix.Unix_error (Unix.EINTR, _, _) -> symlink_stat p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "lstat" (uerr e)) let copy_symlink ~force ~make_path ~src dst = Result.bind (symlink_link src) @@ fun src -> symlink ~force ~make_path ~src dst end module Tmp = struct let delete_file file = ignore (Fs_base.file_delete file) let files = ref Fpath.Set.empty let add_file file = files := Fpath.Set.add file !files let rem_file file = delete_file file; files := Fpath.Set.remove file !files let delete_dir dir = ignore (Fs_base.dir_delete ~recurse:true dir) let dirs = ref Fpath.Set.empty let add_dir dir = dirs := Fpath.Set.add dir !dirs let rem_dir dir = delete_dir dir; dirs := Fpath.Set.remove dir !dirs let cleanup () = Fpath.Set.iter delete_file !files; Fpath.Set.iter delete_dir !dirs let () = at_exit cleanup let default_dir = let tmp_from_env var ~default = Option.value ~default (Env.find ~empty_is_none:true var) in let dir = match Sys.win32 with | true -> tmp_from_env "TEMP" ~default:Fpath.(v "./") | false -> tmp_from_env "TMPDIR" ~default:(Fpath.v "/tmp/") in ref (Fpath.add_dir_sep dir) type name = (string -> string, unit, string) format let default_name = format_of_string "tmp-%s" let rand_num () = Random.State.bits (Lazy.force rand_gen) land 0xFFFFFF let rand_str () = Printf.sprintf "%06x" (rand_num ()) let tmp_path dir name rand = match dir.[String.length dir - 1] = Fpath.dir_sep_char with | true -> Printf.sprintf ("%s" ^^ name) dir rand | false -> Printf.sprintf ("%s%c" ^^ name) dir Fpath.dir_sep_char rand let err dir name rand e = Fmt.error "tmp file %s: %s" (tmp_path dir name rand) e let err_too_many dir name = err dir name "XXXXXX" "Too many attempts to create" let attempts = 10000 let open' ?(flags = Unix.[O_WRONLY; O_CREAT; O_EXCL; O_SHARE_DELETE; O_CLOEXEC]) ?(mode = 0o600) ?(make_path = true) ?dir ?(name = default_name) () = let dir = match dir with None -> !default_dir | Some d -> d in let dir_str = Fpath.to_string (Fpath.add_dir_sep dir) in let rec loop n = match n with | 0 -> err_too_many dir name | n -> let rand = rand_str () in try let file = tmp_path dir_str name rand in let fd = Unix.openfile file flags mode in let file = Fpath.v file in (add_file file; Ok (file, fd)) with | Unix.Unix_error (Unix.EEXIST, _, _) -> loop (n - 1) | Unix.Unix_error (Unix.EINTR, _, _) -> loop n | Unix.Unix_error (Unix.ENOENT as e, _, _) when make_path -> begin match Fs_base.dir_create ~make_path dir with | Error e -> err dir name rand e | Ok true (* created *) -> loop n | Ok false (* existed *) -> err dir name rand (uerr e) end | Unix.Unix_error (e, _, _) -> err dir name rand (uerr e) in loop attempts let mkdir ?(mode = 0o700) ?(make_path = true) ?dir ?(name = default_name) () = let dir = match dir with None -> !default_dir | Some d -> d in let dir_str = Fpath.to_string dir in let rec loop n = match n with | 0 -> err_too_many dir name | n -> let rand = rand_str () in try let tdir = tmp_path dir_str name rand in let () = Unix.mkdir tdir mode in let tdir = Fpath.v tdir in (add_dir tdir; Ok tdir) with | Unix.Unix_error (Unix.EEXIST, _, _) -> loop (n - 1) | Unix.Unix_error (Unix.EINTR, _, _) -> loop n | Unix.Unix_error (Unix.ENOENT as e, _, _) when make_path -> begin match Fs_base.dir_create ~make_path dir with | Error e -> err dir name rand e | Ok true (* created *) -> loop n | Ok false (* existed *) -> err dir name rand (uerr e) end | Unix.Unix_error (e, _, _) -> err dir name rand (uerr e) in loop attempts let path ?(make_path = true) ?dir ?(name = format_of_string "tmp-%s") () = let dir = match dir with None -> !default_dir | Some d -> d in let dir_str = Fpath.to_string dir in let rec loop n = match n with | 0 -> err_too_many dir name | n -> let rand = rand_str () in let file = tmp_path dir_str name rand in match Unix.access file [Unix.F_OK] with | exception Unix.Unix_error (Unix.ENOENT, _, _) -> Ok file | exception Unix.Unix_error (e, _, _) -> err dir name rand (uerr e) | _ -> loop (n - 1) in if not make_path then loop attempts else match Fs_base.dir_create ~make_path dir with | Error _ as e -> e | Ok _ -> loop attempts end module File = struct let channel_apply ~close c f = let close c = try close c with Sys_error _ -> () in match f c with v -> close c; v | exception e -> close c; raise e (* Famous file paths *) let is_dash = Fpath.equal Fpath.dash (* Existence *) let rec exists file = match (Unix.stat (Fpath.to_string file)).Unix.st_kind with | Unix.S_REG -> Ok true | _ -> Ok false | exception Unix.Unix_error (Unix.ENOENT, _, _) -> Ok false | exception Unix.Unix_error (Unix.EINTR, _, _) -> exists file | exception Unix.Unix_error (e, _, _) -> ferr file (err_doing "Testing existence" (uerr e)) let rec must_exist file = match (Unix.stat (Fpath.to_string file)).Unix.st_kind with | Unix.S_REG -> Ok () | _ -> ferr file "File must exist but not a regular file" | exception Unix.Unix_error (Unix.ENOENT, _, _) -> ferr file "File must exist but no such file" | exception Unix.Unix_error (Unix.EINTR, _, _) -> must_exist file | exception Unix.Unix_error (e, _, _) -> ferr file (err_doing "Testing existence" (uerr e)) let is_executable file = match Unix.access file [Unix.X_OK] with | () -> true | exception Unix.Unix_error _ -> false (* Deleting and truncating *) let delete = Fs_base.file_delete let rec truncate file size = try Ok (Unix.truncate (Fpath.to_string file) size) with | Unix.Unix_error (Unix.EINTR, _, _) -> truncate file size | Unix.Unix_error (e, _, _) -> ferr file (err_doing "Truncating" (uerr e)) (* Hard links *) let rec link ~force ~make_path ~src file = let err e = Fmt.error "link %a to %a: %s" Fpath.pp src Fpath.pp file e in try Ok (Unix.link (Fpath.to_string src) (Fpath.to_string file)) with | Unix.Unix_error (Unix.EEXIST, _, _) when force -> begin match delete file with | Error e -> err e | Ok _ -> link ~force ~make_path ~src file end | Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR as e), _, _) when make_path -> begin match Fs_base.dir_create ~make_path (Fpath.parent file) with | Error e -> ferr file (err_doing "Creating path" e) | Ok false (* existed *) -> err (uerr e) | Ok true (* created *) -> link ~force ~make_path ~src file end | Unix.Unix_error (Unix.EINTR, _, _) -> link ~force ~make_path ~src file | Unix.Unix_error (e, _, _) -> err (uerr e) (* Reads *) let read_with_ic file f = try let ic, close = match is_dash file with | true -> stdin, fun _ -> () | false -> open_in_bin (Fpath.to_string file), close_in in Ok (channel_apply ~close ic f) with | Sys_error e -> Result.error e let read_with_fd file f = try let fdin, close = match is_dash file with | true -> Unix.stdin, (fun _ -> ()) | false -> Fd.openfile (Fpath.to_string file) Unix.[O_RDONLY] 0, Unix.close in Ok (Fd.apply ~close fdin f) with | Unix.Unix_error (e, _, _) -> ferr file (uerr e) let read_stdin () = let b = Bytes.create Fd.unix_buffer_size in let acc = Buffer.create Fd.unix_buffer_size in let rec loop () = match input stdin b 0 (Bytes.length b) with | 0 -> Buffer.contents acc | n -> Buffer.add_subbytes acc b 0 n; loop () in loop () let read_file file ic = match in_channel_length ic with | len when len > Sys.max_string_length -> Fmt.failwith_notrace "File to read too large: %d bytes, max supported: %d" len Sys.max_string_length | len -> let s = Bytes.create len in really_input ic s 0 len; Bytes.unsafe_to_string s let read file = let input c = if c == stdin then read_stdin () else read_file file c in try read_with_ic file input with | Failure e | Sys_error e -> ferr file e (* Writes *) let with_tmp_fd ?flags ?mode ?make_path ?dir ?name f = Result.bind (Tmp.open' ?flags ?mode ?make_path ?dir ?name ()) @@ fun (file, fd) -> let delete_close fd = Tmp.rem_file file; Unix.close fd in Ok (Fd.apply ~close:delete_close fd (f file)) let open_tmp_fd = Tmp.open' let with_tmp_oc ?flags ?mode ?make_path ?dir ?name f = Result.bind (Tmp.open' ?flags ?mode ?make_path ?dir ?name ()) @@ fun (file, fd) -> let oc = Unix.out_channel_of_descr fd in let delete_close oc = Tmp.rem_file file; close_out oc in Ok (channel_apply ~close:delete_close oc (f file)) let rec rename_tmp src dst = try Ok (Unix.rename (Fpath.to_string src) (Fpath.to_string dst)) with | Unix.Unix_error (Unix.EINTR, _, _) -> rename_tmp src dst | Unix.Unix_error (e, _, _) -> let r = Fmt.str "renaming %a to %a" Fpath.pp src Fpath.pp dst in Result.error (err_doing r (uerr e)) let write_op = "Writing" let write_with_fd_atomic ~mode ~force ~make_path ~file f = Result.bind (Fs_base.handle_force ~force file) @@ fun () -> let do_write tmp tmp_oc = match f tmp_oc with | Error _ as v -> Ok v | Ok _ as v -> Result.map (fun () -> v) (rename_tmp tmp file) in match with_tmp_fd ~mode ~make_path ~dir:(Fpath.parent file) do_write with | Ok v -> v | Error e -> ferr file (err_doing write_op e) let write_with_fd ?(atomic = true) ?(mode = 0o644) ~force ~make_path file f = match is_dash file with | true -> Ok (Fd.apply ~close:(fun _ -> ()) Unix.stdout f) | false when atomic -> write_with_fd_atomic ~mode ~force ~make_path ~file f | false -> Result.bind (Fs_base.handle_force_open_fdout ~force ~make_path ~mode file) @@ fun fd -> Ok (Fd.apply ~close:Unix.close fd f) let write_with_oc_atomic ~mode ~force ~make_path ~file f = Result.bind (Fs_base.handle_force ~force file) @@ fun () -> let do_write tmp tmp_oc = match f tmp_oc with | Error _ as v -> Ok v | Ok _ as v -> Result.map (fun () -> v) (rename_tmp tmp file) in match with_tmp_oc ~mode ~make_path ~dir:(Fpath.parent file) do_write with | Ok v -> v | Error e -> ferr file (err_doing write_op e) let write_with_oc ?(atomic = true) ?(mode = 0o644) ~force ~make_path file f = match is_dash file with | true -> Ok (channel_apply ~close:(fun _ -> ()) stdout f) | false when atomic -> write_with_oc_atomic ~mode ~force ~make_path ~file f | false -> Result.bind (Fs_base.handle_force_open_fdout ~force ~make_path ~mode file) @@ fun fd -> let oc = Unix.out_channel_of_descr fd in Ok (channel_apply ~close:close_out oc f) let write ?atomic ?mode ~force ~make_path file data = let out data oc = Ok (output_string oc data) in try Result.join @@ write_with_oc ?atomic ?mode ~force ~make_path file (out data) with | Sys_error e -> ferr file e let copy ?atomic ?mode ~force ~make_path ~src file = let err e = Fmt.str "copy %a to %a: %s" Fpath.pp src Fpath.pp file e in Result.map_error err @@ Result.join @@ read_with_fd src @@ fun fdi -> try match is_dash file with | true -> Ok (Fd.copy ~src:fdi Unix.stdout) | false -> let mode = match mode with | None -> Fs_base.path_get_mode src | Some m -> Ok m in Result.join @@ Result.bind mode @@ fun mode -> write_with_fd ?atomic ~mode ~force ~make_path file @@ fun fdo -> Ok (Fd.copy ~src:fdi fdo) with | Unix.Unix_error (e, _, arg) -> Fmt.error "%s: %s" arg (uerr e) end module Dir = struct (* Existence *) let rec exists dir = match (Unix.stat @@ Fpath.to_string dir).Unix.st_kind with | Unix.S_DIR -> Ok true | _ -> Ok false | exception Unix.Unix_error (Unix.ENOENT, _, _) -> Ok false | exception Unix.Unix_error (Unix.EINTR, _, _) -> exists dir | exception Unix.Unix_error (e, _, _) -> ferr dir (err_doing "Testing existence" (uerr e)) let rec must_exist dir = match (Unix.stat @@ Fpath.to_string dir).Unix.st_kind with | Unix.S_DIR -> Ok () | _ -> ferr dir "Directory must exist but not a directory" | exception Unix.Unix_error (Unix.ENOENT, _, _) -> ferr dir "Directory must exist but no such directory" | exception Unix.Unix_error (Unix.EINTR, _, _) -> must_exist dir | exception Unix.Unix_error (e, _, _) -> ferr dir (err_doing "Testing existence" (uerr e)) (* Creating, deleting and renaming. *) let create = Fs_base.dir_create (* Contents *) let rec readdir ~dotfiles dir = let is_dot_file s = String.length s <> 0 && s.[0] = '.' in let rec loop ~dotfiles dir dh acc = match Unix.readdir dh with | exception End_of_file -> acc | ".." | "." -> loop ~dotfiles dir dh acc | n when is_dot_file n && not dotfiles -> loop ~dotfiles dir dh acc | n when Fpath.is_seg n -> loop ~dotfiles dir dh (n :: acc) | n -> ffail dir (Fmt.str "%S: Invalid file name" n) in let dh = Unix.opendir (Fpath.to_string dir) in match loop ~dotfiles dir dh [] with | fs -> Unix.closedir dh; fs | exception e -> (try Unix.closedir dh with Unix.Unix_error (_, _, _) -> ()); raise e let rec stat p = try (Unix.stat @@ Fpath.to_string p) with | Unix.Unix_error (Unix.EINTR, _, _) -> stat p let rec lstat p = try (Unix.lstat @@ Fpath.to_string p) with | Unix.Unix_error (Unix.EINTR, _, _) -> lstat p let fold_no_rec ~filter ~rel ~dotfiles ~follow_symlinks dir f acc = let rec loop stat f acc adir = function | [] -> Ok acc | n :: ns -> let full = Fpath.(adir / n) in match stat full with | st -> begin match st.Unix.st_kind with | Unix.S_DIR -> if filter = `Non_dir then loop stat f acc adir ns else let p = if rel then Fpath.v n else full in loop stat f (f st n p acc) adir ns | _ when filter <> `Dir -> let p = if rel then Fpath.v n else full in loop stat f (f st n p acc) adir ns | _ -> loop stat f acc adir ns end | exception Unix.Unix_error (Unix.ENOENT, _, _) -> loop stat f acc adir ns | exception Unix.Unix_error (Unix.ENOTDIR, _, _) -> loop stat f acc adir ns in let stat = if follow_symlinks then stat else lstat in loop stat f acc dir (readdir ~dotfiles dir) let fold_rec ~filter ~rel ~dotfiles ~follow_symlinks ~prune dir f acc = let rec loop stat todo adir rdir f acc = function | [] -> begin match todo with | (dir, rdir, ns) :: todo -> loop stat todo dir rdir f acc ns | [] -> Ok acc end | n :: ns -> let full = Fpath.(adir / n) in begin match stat full with | st -> begin match st.Unix.st_kind with | Unix.S_DIR -> let rp = match rdir with | None -> Fpath.v n | Some rdir -> Fpath.(rdir / n) in let p = if not rel then full else rp in if prune st n p acc then loop stat todo adir rdir f acc ns else let acc = if filter = `Non_dir then acc else f st n p acc in let todo = (adir, rdir, ns) :: todo in loop stat todo full (Some rp) f acc (readdir ~dotfiles full) | _ when filter <> `Dir -> let p = if not rel then full else match rdir with | None -> Fpath.v n | Some rdir -> Fpath.(rdir / n) in loop stat todo adir rdir f (f st n p acc) ns | _ -> loop stat todo adir rdir f acc ns end | exception Unix.Unix_error (Unix.ENOENT, _, _) -> loop stat todo adir rdir f acc ns | exception Unix.Unix_error (Unix.ENOTDIR, _, _) -> loop stat todo adir rdir f acc ns end in let stat = if follow_symlinks then stat else lstat in loop stat [] dir None f acc (readdir ~dotfiles dir) let _fold ~(filter : [`Any | `Non_dir | `Dir]) ?(rel = false) ?(dotfiles = false) ?(follow_symlinks = true) ?(prune = fun _ _ _ _ -> false) ~recurse f dir acc = let listing_op = "Listing" in try if recurse then fold_rec ~filter ~rel ~dotfiles ~follow_symlinks ~prune dir f acc else fold_no_rec ~filter ~rel ~dotfiles ~follow_symlinks dir f acc with | Failure e -> ferr dir (err_doing listing_op e) | Unix.Unix_error (e, _, ep) -> if String.equal (Fpath.to_string dir) ep then ferr dir (err_doing listing_op @@ uerr e) else ferr dir (err_doing listing_op @@ Fmt.str "%s: %s" ep (uerr e)) let fold ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc = _fold ~filter:`Any ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc let fold_files ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc = _fold ~filter:`Non_dir ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc let fold_dirs ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc = _fold ~filter:`Dir ?rel ?dotfiles ?follow_symlinks ?prune ~recurse f dir acc let path_list stat _ f acc = match stat.Unix.st_kind with | Unix.S_DIR -> Fpath.add_dir_sep f :: acc | _ -> f :: acc (* copy *) let copy ?(rel = true) ?(atomic = true) ?(follow_symlinks = true) ?(prune = fun _ _ _ -> false) ~make_path ~recurse ~src dst = let err e = Fmt.str "copy %a to %a: %s" Fpath.pp src Fpath.pp dst e in let prune = match rel with (* we invoke [_fold] with [rel:true] *) | true -> fun st name p _ -> prune st name p | false -> fun st name p _ -> prune st name (Fpath.(src // p)) in let copy dst st name p (chmods as acc) = match st.Unix.st_kind with | Unix.S_DIR (* prune was already called on it *) -> let dst = Fpath.(dst // p) in let mode = st.Unix.st_perm in let writeable = (mode land 0o200 <> 0) in let mode, acc = match writeable with | true -> mode, acc | false -> (* We need to be able to write to the directory, we remember the mode and the dir and set it at the end *) 0o700, ((dst, mode) :: chmods) in ignore (Fs_base.dir_create ~mode ~make_path:false dst |> Result.to_failure); acc | Unix.S_REG -> let cp ~mode src dst = Result.join @@ File.read_with_fd src @@ fun fdi -> Result.join @@ File.write_with_fd ~atomic:true ~mode ~force:false ~make_path:false dst @@ fun fdo -> Ok (Fd.copy ~src:fdi fdo) in if prune st name p () then acc else let mode = st.Unix.st_perm in let src = Fpath.(src // p) in let dst = Fpath.(dst // p) in (cp ~mode src dst |> Result.to_failure); acc | Unix.S_LNK -> if prune st name p () then acc else let dst = Fpath.(dst // p) in let src = Fpath.(src // p) in let force = false and make_path = false in Fs_base.copy_symlink ~force ~make_path ~src dst |> Result.to_failure; acc | _ when prune st name p () (* why not *) -> acc | _ -> Fmt.failwith "%a: Not a regular file, directory or symlink" Fpath.pp Fpath.(src // p) in let rec chmod_dirs = function | [] -> () | (d, m) :: ds -> (Fs_base.path_set_mode d m) |> Result.to_failure; chmod_dirs ds in Result.map_error err @@ Result.bind (Fs_base.path_exists dst) @@ function | true -> Error "Destination path already exists" | false -> let tdst = match atomic with | true -> Tmp.mkdir ~make_path ~dir:(Fpath.parent dst) () | false -> Result.bind (Fs_base.dir_create ~make_path dst) @@ fun _ -> Ok dst in Result.bind tdst @@ fun tdst -> try let src_mode = Fs_base.path_get_mode src |> Result.to_failure in let chmods = _fold ~filter:`Any ~rel:true ~dotfiles:true ~follow_symlinks ~prune ~recurse (copy tdst) src ([tdst, src_mode]) |> Result.to_failure in chmod_dirs chmods; match atomic with | false -> Ok () | true -> Fs_base.path_rename ~force:false ~make_path:true ~src:tdst dst with Failure e -> if atomic then ignore (Fs_base.path_delete ~recurse:true tdst); Error e (* Default temporary directory *) let set_default_tmp p = Tmp.default_dir := Fpath.add_dir_sep p let default_tmp () = !Tmp.default_dir (* Temporary directories *) let with_tmp ?mode ?make_path ?dir ?name f = Result.bind (Tmp.mkdir ?mode ?make_path ?dir ?name ()) @@ fun dir -> try let v = f dir in Tmp.rem_dir dir; Ok v with | e -> Tmp.rem_dir dir; raise e let tmp = Tmp.mkdir (* Current working directory *) let rec cwd () = let err e = Fmt.error "get cwd: %s" e in match Fpath.of_string (Unix.getcwd ()) with | Ok dir when Fpath.is_abs dir -> Ok dir | Ok dir -> err (Fmt.str "%a is relative" Fpath.pp dir) | Error e -> err e | exception Unix.Unix_error (Unix.EINTR, _, _) -> cwd () | exception Unix.Unix_error (e, _, _) -> err (uerr e) let rec set_cwd dir = let err e = Fmt.error "set cwd to %a: %s" Fpath.pp dir e in try Ok (Unix.chdir (Fpath.to_string dir)) with | Unix.Unix_error (Unix.EINTR, _, _) -> set_cwd dir | Unix.Unix_error (e, _, _) -> err (uerr e) let with_cwd dir f = Result.bind (cwd ()) @@ fun old -> Result.bind (set_cwd dir) @@ fun () -> match f () with | v -> Result.map (fun () -> v) (set_cwd old) | exception e -> ignore (set_cwd old); raise e (* Base directories *) let err_dir dir fmt = Fmt.error ("%s directory: " ^^ fmt) dir let fpath_of_env_var dir var = match Env.find ~empty_is_none:true var with | None -> None | Some p -> match Fpath.of_string p with | Error e -> Some (err_dir dir "%s environment variable: %s" var e) | Ok _ as v -> Some v let base_dir dir var var_alt fallback = match fpath_of_env_var dir var with | Some r -> r | None -> match Option.bind var_alt (fpath_of_env_var dir) with | Some r -> r | None -> fallback () let home_dir = "user" let home_var = "HOME" let user () = let home_env home_var = match fpath_of_env_var home_dir home_var with | Some r -> r | None -> err_dir home_dir "%s environment variable is undefined" home_var in (* if Sys.win32 then home_env home_win32_var else *) match Fpath.of_string (Unix.getpwuid (Unix.getuid ())).Unix.pw_dir with | Ok _ as v -> v | Error _ -> home_env home_var | exception Not_found -> home_env home_var | exception Unix.Unix_error (e, _, _) -> home_env home_var let home_fallback dir sub = match user () with | Error e -> err_dir dir "%s" e | Ok home -> Ok Fpath.(home // sub) let config_dir = "configuration" let config_var = "XDG_CONFIG_HOME" let config_var_alt = if Sys.win32 then Some "%APPDATA%" else None let config_fallback () = home_fallback config_dir (Fpath.v ".config") let config () = base_dir config_dir config_var config_var_alt config_fallback let data_dir = "data" let data_var = "XDG_DATA_HOME" let data_var_alt = if Sys.win32 then Some "%APPDATA%" else None let data_fallback () = home_fallback data_dir (Fpath.v ".local/share") let data () = base_dir data_dir data_var data_var_alt data_fallback let cache_dir = "cache" let cache_var = "XDG_CACHE_HOME" let cache_var_alt = if Sys.win32 then Some "%TEMP%" else None let cache_fallback () = home_fallback cache_dir (Fpath.v ".cache") let cache () = base_dir cache_dir cache_var cache_var_alt cache_fallback let runtime_dir = "runtime" let runtime_var = "XDG_RUNTIME_HOME" let runtime_var_alt = None let runtime_fallback () = Ok (default_tmp ()) let runtime () = base_dir runtime_dir runtime_var runtime_var_alt runtime_fallback end module Path = struct (* Existence *) let exists = Fs_base.path_exists let rec must_exist p = try (Ok (ignore (Unix.stat (Fpath.to_string p)))) with | Unix.Unix_error (Unix.ENOENT, _, _) -> ferr p "Path must exist but no such path" | Unix.Unix_error (Unix.EINTR, _, _) -> must_exist p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "Testing existence" (uerr e)) (* Deleting and renaming *) let delete = Fs_base.path_delete let rename = Fs_base.path_rename (* Resolving *) external _realpath : string -> string = "ocaml_b00_realpath" let rec realpath p = try Fpath.of_string (_realpath (Fpath.to_string p)) with | Unix.Unix_error (Unix.EINTR, _, _) -> realpath p | Unix.Unix_error (e, _, _) -> ferr p (err_doing "realpath" (uerr e)) (* Copying *) let copy ?(rel = true) ?(atomic = true) ?(follow_symlinks = true) ?(prune = fun _ _ _ -> false) ~make_path ~recurse ~src dst = let err e = Fmt.str "copy %a to %a: %s" Fpath.pp src Fpath.pp dst e in let stat = match follow_symlinks with | true -> Fs_base.path_stat | false -> Fs_base.symlink_stat in match stat src with | Error e -> Error (err e) | Ok stat -> match stat.Unix.st_kind with | Unix.S_DIR -> Dir.copy ~rel ~atomic ~follow_symlinks ~prune ~make_path ~recurse ~src dst | Unix.S_LNK -> Result.map_error err @@ Fs_base.copy_symlink ~force:false ~make_path ~src dst | _ -> File.copy ~atomic ~force:false ~make_path ~src dst (* File modes and stat *) let get_mode = Fs_base.path_get_mode let set_mode = Fs_base.path_set_mode let stat = Fs_base.path_stat (* Symlinks *) let symlink = Fs_base.symlink let symlink_link = Fs_base.symlink_link let symlink_stat = Fs_base.symlink_stat (* Temporary paths *) type tmp_name = Tmp.name let tmp = Tmp.path end module Cmd = struct (* Tool search *) let tool_file ~dir tool = match dir.[String.length dir - 1] with | c when Fpath.char_is_dir_sep c -> dir ^ tool | _ -> String.concat Fpath.dir_sep [dir; tool] let search_in_path tool = let rec loop tool = function | "" -> None | p -> let dir, p = match String.cut_left ~sep:Fpath.search_path_sep p with | None -> p, "" | Some (dir, p) -> dir, p in if dir = "" then loop tool p else let tool_file = tool_file ~dir tool in match File.is_executable tool_file with | false -> loop tool p | true -> Some (Fpath.v tool_file) in match Unix.getenv "PATH" with | p -> loop tool p | exception Not_found -> None let search_in_dirs ~dirs tool = let rec loop tool = function | [] -> None | d :: dirs -> let tool_file = tool_file ~dir:(Fpath.to_string d) tool in match File.is_executable tool_file with | false -> loop tool dirs | true -> Some (Fpath.v tool_file) in loop tool dirs let tool_is_path t = String.contains t Fpath.dir_sep_char let find_tool ?(win_exe = Sys.win32) ?search tool = let tool = let suffix = ".exe" in if not win_exe || String.ends_with ~suffix tool then tool else (tool ^ suffix) in match tool_is_path tool with | true -> if File.is_executable tool then Ok (Some tool) else Ok None | false -> match search with | None -> Ok (search_in_path tool) | Some dirs -> Ok (search_in_dirs ~dirs tool) let pp_search ppf = function | None -> Fmt.string ppf "PATH" | Some dirs ->Fmt.(list ~sep:comma Fpath.pp) ppf dirs let get_tool ?win_exe ?search tool = match find_tool ?win_exe ?search tool with | Ok (Some t) -> Ok t | Error _ as e -> e | Ok None when tool_is_path tool -> Fmt.error "%s: No such executable file" tool | Ok None -> Fmt.error "%s: No such tool found in %a" tool pp_search search let rec get_first_tool ?win_exe ?search tools = let rec loop = function | [] -> Fmt.error "%a:@[<v> No such tool find in %a@,@[as %a@]@]" Fpath.pp_unquoted (List.hd tools) pp_search search (Fmt.or_enum Fpath.pp_unquoted) tools | tool :: tools -> match find_tool ?win_exe ?search tool with | Ok (Some t) -> Ok t | Ok None -> loop tools | Error _ as e -> e in loop tools let find ?win_exe ?search cmd = match Cmd.tool cmd with | None -> Ok None | Some tool -> match find_tool ?win_exe ?search tool with | Ok None as v -> v | Ok (Some t) -> Ok (Cmd.set_tool (Fpath.to_string t) cmd) | Error e -> e let get ?win_exe ?search cmd = match Cmd.tool cmd with | None -> Fmt.error "No tool to lookup: empty command" | Some tool -> match get_tool ?win_exe ?search tool with | Ok t -> Ok (Option.get @@ Cmd.set_tool (Fpath.to_string t) cmd) | Error _ as e -> e (* Process completion statuses *) type status = [ `Exited of int | `Signaled of int ] let status_of_unix_status = function | Unix.WEXITED e -> `Exited e | Unix.WSIGNALED s -> `Signaled s | Unix.WSTOPPED _ -> assert false let pp_status ppf = function | `Exited n -> Fmt.pf ppf "@[exited [%d]@]" n | `Signaled s -> Fmt.pf ppf "@[signaled [%a]@]" Fmt.sys_signal s let pp_cmd_status ppf (cmd, st) = Fmt.pf ppf "cmd [%s]: %a" (Cmd.to_string cmd) pp_status st (* Process standard inputs *) type stdi = | In_string of string | In_file of Fpath.t | In_fd of { fd : Unix.file_descr; close : bool } let in_string s = In_string s let in_file f = In_file f let in_fd ~close fd = In_fd { fd; close } let in_stdin = In_fd { fd = Unix.stdin; close = false } let in_null = In_file Fpath.null let stdi_to_fd fds = function | In_fd { fd; close } -> if close then Fd.Set.add fd fds; fd | In_string s -> begin try (* We write the input string to a temporary file. *) let flags = Unix.[O_RDWR; O_CREAT; O_EXCL; O_SHARE_DELETE] in let f, fd = Result.to_failure (Tmp.open' ~flags ()) in Fd.Set.add fd fds; Tmp.rem_file f; (* We don't need the actual file. *) ignore (Unix.write_substring fd s 0 (String.length s)); ignore (Unix.lseek fd 0 Unix.SEEK_SET); fd with | Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "tmp file for stdin: %s" (uerr e) end | In_file f -> try let f = Fpath.to_string f in let fd = Fd.openfile f Unix.[O_RDONLY] 0o644 in Fd.Set.add fd fds; fd with Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "open file %a for stdin: %s" Fpath.pp f (uerr e) (* Process standard outputs *) type stdo = | Out_fd of { fd : Unix.file_descr; close : bool } | Out_file of { mode : int; force : bool; make_path : bool; file : Fpath.t } let out_file ?(mode = 0o644) ~force ~make_path file = Out_file { mode; force; make_path; file } let out_fd ~close fd = Out_fd { fd; close } let out_stdout = Out_fd { fd = Unix.stdout; close = false } let out_stderr = Out_fd { fd = Unix.stderr; close = false } let out_null = out_file ~force:true ~make_path:false Fpath.null let stdo_to_fd fds = function | Out_fd { fd; close } -> if close then Fd.Set.add fd fds; fd | Out_file { mode; force; make_path; file } -> let flags = Unix.[O_WRONLY; O_CREAT; O_TRUNC] in match Fs_base.handle_force_open_fdout ~flags ~force ~make_path ~mode file with | Error e -> Fmt.failwith_notrace "open for output: %s" e | Ok fd -> Fd.Set.add fd fds; fd (* Low-level command spawn *) type spawn_tracer = int option -> Env.assignments option -> cwd:Fpath.t option -> Cmd.t -> unit let spawn_tracer_nop _ _ ~cwd:_ _ = () let _spawn_tracer = ref spawn_tracer_nop let spawn_tracer () = !_spawn_tracer let set_spawn_tracer t = _spawn_tracer := t let rec getcwd () = try Unix.getcwd () with | Unix.Unix_error (Unix.EINTR, _, _) -> getcwd () | Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "getcwd: %s" (uerr e) let rec chdir cwd = try Unix.chdir cwd with | Unix.Unix_error (Unix.EINTR, _, _) -> chdir cwd | Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "chdir %s: %s" cwd (uerr e) let spawn_err cmd e = match Cmd.is_empty cmd with | true -> Result.error e | false -> Fmt.error "cmd %s: %s" (Cmd.to_string cmd) e let spawn_cwd = function None -> getcwd () | Some d -> Fpath.to_string d let spawn_env = function | None -> Unix.environment () | Some e -> Array.of_list e let _spawn fds ?env ?cwd ~stdin ~stdout ~stderr cmd = match Cmd.to_list cmd with | [] -> failwith "no command, empty command line" | line -> try let env' = spawn_env env in let cwd' = spawn_cwd cwd in let line = Array.of_list line in let exe = line.(0) in let stdin = stdi_to_fd fds stdin in let stdout = stdo_to_fd fds stdout in let stderr = stdo_to_fd fds stderr in let old_cwd = getcwd () in let change_cwd = not @@ String.equal old_cwd cwd' in if change_cwd then chdir cwd'; let pid = Unix.create_process_env exe line env' stdin stdout stderr in if change_cwd then chdir old_cwd; (* XXX pid zombie on fail. *) Fd.Set.close_all fds; !_spawn_tracer (Some pid) env ~cwd cmd; pid with | e -> (* In case one of the std{i,o}_to_fd raises *) let add_out_fd fds = function | Out_fd { fd ; close = true } -> Fd.Set.add fd fds | _ -> () in add_out_fd fds stdout; add_out_fd fds stderr; raise e (* Blocking command execution *) let rec run_collect pid = match Unix.waitpid [] pid with | _, status -> status_of_unix_status status | exception Unix.Unix_error (Unix.EINTR, _, _) -> run_collect pid | exception Unix.Unix_error (e, _, _) -> Fmt.failwith_notrace "waitpid [%d]: %s" pid (uerr e) let run_status ?env ?cwd ?(stdin = in_stdin) ?(stdout = out_stdout) ?(stderr = out_stderr) cmd = let fds = Fd.Set.empty () in try let pid = _spawn fds ?env ?cwd ~stdin ~stdout ~stderr cmd in Ok (run_collect pid) with | Failure e -> Fd.Set.close_all fds; spawn_err cmd e | Unix.Unix_error (e, _, _) -> Fd.Set.close_all fds; spawn_err cmd (uerr e) let run_status_out ?env ?cwd ?(stdin = in_stdin) ?(stderr = `Stdo out_stderr) ~trim cmd = let fds = Fd.Set.empty () in try let flags = Unix.[O_RDWR; O_CREAT; O_EXCL; O_SHARE_DELETE; O_CLOEXEC] in let tmpf, fd = Result.to_failure (Tmp.open' ~flags ()) in let stdout = out_fd ~close:false fd in let stderr = match stderr with `Out -> stdout | `Stdo o -> o in let pid = _spawn fds ?env ?cwd ~stdin ~stdout ~stderr cmd in let status = run_collect pid in let out = Fd.read_file tmpf fd in Tmp.rem_file tmpf; Ok (status, if trim then String.trim out else out) with | Failure e -> Fd.Set.close_all fds; spawn_err cmd e | Unix.Unix_error (e, _, _) -> Fd.Set.close_all fds; spawn_err cmd (uerr e) let run ?env ?cwd ?stdin ?stdout ?stderr cmd = match run_status ?env ?cwd ?stdin ?stdout ?stderr cmd with | Ok (`Exited 0) -> Ok () | Ok st -> Fmt.error "%a" pp_cmd_status (cmd, st) | Error _ as e -> e let run_out ?env ?cwd ?stdin ?stderr ~trim cmd = match run_status_out ?env ?cwd ?stdin ?stderr ~trim cmd with | Ok (`Exited 0, v) -> Ok v | Ok (st, _) -> Fmt.error "%a" pp_cmd_status (cmd, st) | Error _ as e -> e (* Non-blocking command *) type pid = int let pid_to_int pid = pid let spawn ?env ?cwd ?(stdin = in_stdin) ?(stdout = out_stdout) ?(stderr = out_stderr) cmd = let fds = Fd.Set.empty () in try Ok (_spawn fds ?env ?cwd ~stdin ~stdout ~stderr cmd) with | Failure e -> Fd.Set.close_all fds; spawn_err cmd e | Unix.Unix_error (e, _, _) -> Fd.Set.close_all fds; spawn_err cmd (uerr e) let rec spawn_poll_status pid = match Unix.waitpid Unix.[WNOHANG] pid with | 0, _ -> Ok None | _, status -> Ok (Some (status_of_unix_status status)) | exception Unix.Unix_error (Unix.EINTR, _, _) -> spawn_poll_status pid | exception Unix.Unix_error (e, _, _) -> Fmt.error "poll_status: waitpid %d: %s" pid (uerr e) let rec spawn_wait_status pid = match Unix.waitpid [] pid with | _, status -> Ok (status_of_unix_status status) | exception Unix.Unix_error (Unix.EINTR, _, _) -> spawn_wait_status pid | exception Unix.Unix_error (e, _, _) -> Fmt.error "wait_status: waitpid %d: %s" pid (uerr e) (* execv On Windows when Unix.execv[e] is invoked, control is returned to the controlling terminal when the child process starts (vs. child process terminates on POSIX). This entails all sort of weird behaviour. To workaround this, our execv[e] on Windows simply runs the program as a sub-process on which we waitpid(2) and then exit with the resulting status. *) let _execv_win32 ~env file cmd = let exit pid = match Unix.waitpid [] pid with | _, (Unix.WEXITED c) -> exit c | _, (Unix.WSIGNALED sg) -> Unix.(kill (getpid ()) sg); (* In case we don't get killed, exit with bash convention. *) exit (128 + sg) | _ -> assert false in let env = spawn_env env in exit Unix.(create_process_env file cmd env stdin stderr stderr) let _execv_posix ~env file cmd = Ok (Unix.execve file cmd (spawn_env env)) let _execv = if Sys.win32 then _execv_win32 else _execv_posix let execv ?env ?cwd file cmd = let err_execv f e = Fmt.error "execv %a: %s" Fpath.pp f e in try let file = Path._realpath (Fpath.to_string file) in let reset_cwd = match cwd with | None -> Fun.id | Some cwd -> let old_cwd = getcwd () in chdir cwd; fun () -> try chdir old_cwd with Failure _ -> () in Fun.protect ~finally:reset_cwd @@ fun () -> !_spawn_tracer None env ~cwd cmd; _execv ~env file (Array.of_list @@ Cmd.to_list cmd) with | Failure e -> err_execv file e | Unix.Unix_error (e, _, _) -> err_execv file (uerr e) type t = Cmd.t end module Exit = struct type t = Code : int -> t | Exec : (unit -> ('a, string) result) -> t let code c = Code c let exec ?env ?cwd file cmd = Exec (fun () -> Cmd.execv ?env ?cwd file cmd) let get_code = function Code c -> c | _ -> invalid_arg "not an Exit.Code" let exit = function | Code c -> Stdlib.exit c | Exec execv -> Result.bind (execv ()) @@ fun _ -> assert false let on_sigint ~hook f = let hook _ = hook (); Stdlib.exit 130 (* as if SIGINT signaled *) in let previous = Sys.signal Sys.sigint (Sys.Signal_handle hook) in let restore () = Sys.set_signal Sys.sigint previous in Fun.protect ~finally:restore f end end module Log = struct (* Reporting levels *) type level = Quiet | App | Error | Warning | Info | Debug let _level = ref Warning let level () = !_level let set_level l = _level := l let level_to_string = function | Quiet -> "quiet" | App -> "app" | Error -> "error" | Warning -> "warning" | Info -> "info" | Debug -> "debug" let level_of_string s = match String.trim s with | "quiet" -> Ok Quiet | "app" -> Ok App | "error" -> Ok Error | "warning" -> Ok Warning | "info" -> Ok Info | "debug" -> Ok Debug | e -> let pp_level = Fmt.(code string) in let kind = Fmt.any "log level" in let dom = ["quiet"; "app"; "error"; "warning"; "info"; "debug"] in Fmt.error "%a" Fmt.(unknown' ~kind pp_level ~hint:must_be) (e, dom) (* Reporting *) let app_style = [`Fg `Cyan] let err_style = [`Fg `Red] let warn_style = [`Fg `Yellow] let info_style = [`Fg `Blue] let debug_style = [`Faint; `Fg `Magenta] let pp_level_str level ppf v = match level with | App -> Fmt.tty_string app_style ppf v | Error -> Fmt.tty_string err_style ppf v | Warning -> Fmt.tty_string warn_style ppf v | Info -> Fmt.tty_string info_style ppf v | Debug -> Fmt.tty_string debug_style ppf v | Quiet -> assert false let pp_level ppf level = match level with | App -> () | Error -> Fmt.tty_string err_style ppf "ERROR" | Warning -> Fmt.tty_string warn_style ppf "WARNING" | Info -> Fmt.tty_string info_style ppf "INFO" | Debug -> Fmt.tty_string debug_style ppf "DEBUG" | Quiet -> assert false let pp_header = let x = match Array.length Sys.argv with | 0 -> Filename.basename Sys.executable_name | n -> Filename.basename Sys.argv.(0) in let pp_header ppf (l, h) = match h with | None -> if l = App then () else Fmt.pf ppf "%s: [%a] " x pp_level l | Some "" -> () | Some h -> Fmt.pf ppf "%s: [%a] " x (pp_level_str l) h in pp_header (* Log functions *) let _err_count = ref 0 let err_count () = !_err_count let incr_err_count () = incr _err_count let _warn_count = ref 0 let warn_count () = !_warn_count let incr_warn_count () = incr _warn_count type ('a, 'b) msgf = (?header:string -> ('a, Format.formatter, unit, 'b) format4 -> 'a) -> 'b type 'a log = ('a, unit) msgf -> unit type 'a func = { log : 'a. 'a log } let log func = func.log type kmsg = { kmsg : 'a 'b. (unit -> 'b) -> level -> ('a, 'b) msgf -> 'b } let report level k msgf = msgf @@ fun ?header fmt -> let k _ = k () in let ppf = if level = App then Format.std_formatter else Format.err_formatter in Format.kfprintf k ppf ("@[%a" ^^ fmt ^^ "@]@.") pp_header (level, header) let kmsg_nop = let kmsg k level msgf = k () in { kmsg } let kmsg_default = let kmsg k level msgf = match !_level with | Quiet -> k () | level' when level > level' || level = Quiet -> (if level = Error then incr _err_count else if level = Warning then incr _warn_count else ()); (k ()) | _ -> (if level = Error then incr _err_count else if level = Warning then incr _warn_count else ()); report level k msgf in { kmsg } let _kmsg = ref kmsg_default let set_kmsg kmsg = _kmsg := kmsg let kunit _ = () let msg level msgf = !_kmsg.kmsg kunit level msgf let quiet msgf = !_kmsg.kmsg kunit Quiet msgf let app msgf = !_kmsg.kmsg kunit App msgf let err msgf = !_kmsg.kmsg kunit Error msgf let warn msgf = !_kmsg.kmsg kunit Warning msgf let info msgf = !_kmsg.kmsg kunit Info msgf let debug msgf = !_kmsg.kmsg kunit Debug msgf let kmsg k level msgf = !_kmsg.kmsg k level msgf (* Logging result errors *) let if_error ?(level = Error) ?header ~use = function | Ok v -> v | Error msg -> !_kmsg.kmsg (fun _ -> use) level @@ fun m -> m ?header "@[%a@]" Fmt.lines msg let if_error' ?(level = Error) ?header ~use = function | Ok _ as v -> v | Error msg -> !_kmsg.kmsg (fun _ -> Ok use) level @@ fun m -> m ?header "@[%a@]" Fmt.lines msg let if_error_pp ?(level = Error) ?header pp ~use = function | Ok v -> v | Error e -> !_kmsg.kmsg (fun _ -> use) level @@ fun m -> m ?header "@[%a@]" pp e let if_error_pp' ?(level = Error) ?header pp ~use = function | Ok _ as v -> v | Error e -> !_kmsg.kmsg (fun _ -> Ok use) level @@ fun m -> m ?header "@[%a@]" pp e (* Timing logging *) let time ?(level = Info) m f = let time = Os.Mtime.counter () in let r = f () in let span = Os.Mtime.count time in !_kmsg.kmsg (fun () -> r) level (fun w -> let header = Format.asprintf "%a" Mtime.Span.pp span in m r (w ~header)) (* Spawn logging *) let spawn_tracer level = if level = Quiet then Os.Cmd.spawn_tracer_nop else let header = function | None -> "EXECV" | Some pid -> "EXEC:" ^ string_of_int (Os.Cmd.pid_to_int pid) in let pp_env ppf = function | None -> () | Some env -> Fmt.pf ppf "%a@," (Fmt.list String.pp_dump) env in fun pid env ~cwd cmd -> msg level (fun m -> m ~header:(header pid) "@[<v>%a%a@]" pp_env env Cmd.pp_dump cmd) end module Rqueue = struct type 'a t = { rand : Random.State.t; mutable length : int; mutable slots : 'a option array } let grow q = let slots' = Array.make (2 * q.length) None in Array.blit q.slots 0 slots' 0 q.length; q.slots <- slots' let empty ?(rand = Random.State.make_self_init ()) () = { rand; length = 0; slots = Array.make 256 None } let add q v = if q.length = Array.length q.slots then grow q; q.slots.(q.length) <- Some v; q.length <- q.length + 1; () let take q = match q.length with | 0 -> None | _ -> let i = Random.State.int q.rand q.length in let v = match q.slots.(i) with None -> assert false | Some v -> v in q.length <- q.length - 1; q.slots.(i) <- q.slots.(q.length); q.slots.(q.length) <- None; Some v let length q = q.length end (* Binary encoding *) module Bincode = struct (* Encoders *) type 'a enc = Buffer.t -> 'a -> unit (* Decoders *) type 'a dec = string -> int -> int * 'a let err i fmt = Fmt.failwith_notrace ("%d: " ^^ fmt) i let err_byte ~kind i b = err i "corrupted input, unexpected byte 0x%x for %s" b kind let check_next ~kind s i next = if next <= String.length s then () else err i "unexpected end of input, expected %d bytes for %s" (next - i) kind let get_byte s i = Char.code (String.get s i) [@@ocaml.inline] let dec_eoi s i = if i = String.length s then () else err i "expected end of input (len: %d)" (String.length s) (* Codecs *) type 'a t = { enc : 'a enc; dec : 'a dec } let v enc dec = { enc; dec } let enc c = c.enc let dec c = c.dec let to_string ?(buf = Buffer.create 1024) c v = c.enc buf v; Buffer.contents buf let of_string ?(file = Fpath.dash) c s = try let i, v = c.dec s 0 in dec_eoi s i; Ok v with | Failure e -> Fmt.error "%a:%s" Fpath.pp_unquoted file e (* Magic numbers *) let enc_magic magic b () = Buffer.add_string b magic let dec_magic magic s i = let next = i + String.length magic in check_next ~kind:magic s i next; let magic' = String.subrange ~first:i ~last:(next - 1) s in if String.equal magic magic' then next, () else err i "magic mismatch: %S but expected %S" magic' magic let magic magic = v (enc_magic magic) (dec_magic magic) (* Bytes *) let enc_byte b n = Buffer.add_char b (Char.chr (n land 0xFF)) [@@ocaml.inline] let dec_byte ~kind s i = let next = i + 1 in check_next ~kind s i next; let b = get_byte s i in next, b [@@ocaml.inline] let byte ~kind = v enc_byte (dec_byte ~kind) (* unit *) let enc_unit b () = enc_byte b 0 let dec_unit s i = let kind = "unit" in let next, b = dec_byte ~kind s i in match b with | 0 -> next, () | b -> err_byte ~kind i b let unit = v enc_unit dec_unit (* bool *) let enc_bool b bool = enc_byte b (if bool then 1 else 0) let dec_bool s i = let kind = "bool" in let next, b = dec_byte ~kind s i in match b with | 0 -> next, false | 1 -> next, true | b -> err_byte ~kind i b let bool = v enc_bool dec_bool (* int *) let enc_int b n = let w = enc_byte in w b n; w b (n lsr 8); w b (n lsr 16); w b (n lsr 24); if Sys.word_size = 32 then (w b 0x00; w b 0x00; w b 0x00; w b 0x00) else (w b (n lsr 32); w b (n lsr 40); w b (n lsr 48); w b (n lsr 56)) let dec_int s i = let r = get_byte in let next = i + 8 in check_next ~kind:"int" s i next; let b0 = r s (i ) and b1 = r s (i + 1) and b2 = r s (i + 2) and b3 = r s (i + 3) in let n = (b3 lsl 24) lor (b2 lsl 16) lor (b1 lsl 8) lor b0 in if Sys.word_size = 32 then next, n else let b4 = r s (i + 4) and b5 = r s (i + 5) and b6 = r s (i + 6) and b7 = r s (i + 7) in next, (b7 lsl 56) lor (b6 lsl 48) lor (b5 lsl 40) lor (b4 lsl 32) lor n let int = v enc_int dec_int (* int64 *) let enc_int64 b i = (* XXX From 4.08 on use Buffer.add_int64_le *) let w = enc_byte in let i0 = Int64.to_int i in let i1 = Int64.to_int (Int64.shift_right_logical i 16) in let i2 = Int64.to_int (Int64.shift_right_logical i 32) in let i3 = Int64.to_int (Int64.shift_right_logical i 48) in let b0 = i0 and b1 = i0 lsr 8 and b2 = i1 and b3 = i1 lsr 8 and b4 = i2 and b5 = i2 lsr 8 and b6 = i3 and b7 = i3 lsr 8 in w b b0; w b b1; w b b2; w b b3; w b b4; w b b5; w b b6; w b b7 external swap64 : int64 -> int64 = "%bswap_int64" external unsafe_get_int64_ne : string -> int -> int64 = "%caml_string_get64u" let unsafe_get_int64_le b i = match Sys.big_endian with | true -> swap64 (unsafe_get_int64_ne b i) | false -> unsafe_get_int64_ne b i let dec_int64 s i = let next = i + 8 in check_next ~kind:"int64" s i next; next, unsafe_get_int64_le s i let int64 = v enc_int64 dec_int64 (* string *) let enc_string b s = enc_int b (String.length s); Buffer.add_string b s let dec_string s i = let i, len = dec_int s i in let next = i + len in check_next ~kind:"string" s i next; next, String.sub s i len let string = v enc_string dec_string (* fpath *) let enc_fpath b p = enc_string b (Fpath.to_string p) let dec_fpath s i = let next, s = dec_string s i in match Fpath.of_string s with | Error e -> err i "corrupted file path value: %s" e | Ok p -> next, p let fpath = v enc_fpath dec_fpath (* list *) let enc_list el b l = let rec loop len acc = function | [] -> len, acc | v :: vs -> loop (len + 1) (v :: acc) vs in let len, rl = loop 0 [] l in enc_int b len; let rec loop el b = function [] -> () | v :: vs -> el b v; loop el b vs in loop el b rl let dec_list el s i = let i, count = dec_int s i in let rec loop el s i count acc = match count = 0 with | true -> i, acc (* enc_list writes the reverse list. *) | false -> let i, v = el s i in loop el s i (count - 1) (v :: acc) in loop el s i count [] let list c = v (enc_list c.enc) (dec_list c.dec) (* option *) let enc_option some b = function | None -> enc_byte b 0 | Some v -> enc_byte b 1; some b v let dec_option some s i = let kind = "option" in let next, b = dec_byte ~kind s i in match b with | 0 -> next, None | 1 -> let i, v = some s next in i, Some v | b -> err_byte ~kind i b let option c = v (enc_option c.enc) (dec_option c.dec) (* result *) let enc_result ~ok ~error b = function | Ok v -> enc_byte b 0; ok b v | Error e -> enc_byte b 1; error b e let dec_result ~ok ~error s i = let kind = "result" in let next, b = dec_byte ~kind s i in match b with | 0 -> let i, v = ok s next in i, Ok v | 1 -> let i, e = error s next in i, Error e | b -> err_byte ~kind i b let result ~ok ~error = v (enc_result ~ok:ok.enc ~error:error.enc) (dec_result ~ok:ok.dec ~error:error.dec) (* set *) let enc_set (type a) (type t) (module S : Set.S with type elt = a and type t = t) enc_elt b v = let count = S.cardinal v in enc_int b count; S.iter (enc_elt b) v let dec_set (type a) (type t) (module S : Set.S with type elt = a and type t = t) dec_elt s i = let rec loop acc count s i = if count <= 0 then i, acc else let i, elt = dec_elt s i in loop (S.add elt acc) (count - 1) s i in let i, count = dec_int s i in loop S.empty count s i let set s c = v (enc_set s c.enc) (dec_set s c.dec) (* Hash.t *) let enc_hash b h = enc_string b (Hash.to_bytes h) let dec_hash s i = let i, h = dec_string s i in i, (Hash.of_bytes h) let hash = v enc_hash dec_hash (* Time.span *) let enc_time_span b s = enc_int64 b (Mtime.Span.to_uint64_ns s) let dec_time_span s i = let i, s = dec_int64 s i in i, Mtime.Span.of_uint64_ns s let time_span = v enc_time_span dec_time_span (* Time.cpu_span *) let enc_cpu_time_span b c = enc_time_span b (Os.Cpu.Time.utime c); enc_time_span b (Os.Cpu.Time.stime c); enc_time_span b (Os.Cpu.Time.children_utime c); enc_time_span b (Os.Cpu.Time.children_stime c) let dec_cpu_time_span s i = let i, utime = dec_time_span s i in let i, stime = dec_time_span s i in let i, children_utime = dec_time_span s i in let i, children_stime = dec_time_span s i in i, Os.Cpu.Time.span ~utime ~stime ~children_utime ~children_stime let cpu_time_span = v enc_cpu_time_span dec_cpu_time_span end (*--------------------------------------------------------------------------- Copyright (c) 2018 The b0 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) 2018 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*)
w58.ml
(* TEST flags = "-w A" files = "module_without_cmx.mli" * setup-ocamlc.byte-build-env ** ocamlc.byte module = "module_without_cmx.mli" *** ocamlc.byte module = "w58.ml" **** check-ocamlc.byte-output * setup-ocamlopt.byte-build-env ** ocamlopt.byte module = "module_without_cmx.mli" *** ocamlopt.byte module = "w58.ml" **** check-ocamlopt.byte-output *) let () = print_endline (Module_without_cmx.id "Hello World")
(* TEST flags = "-w A" files = "module_without_cmx.mli" * setup-ocamlc.byte-build-env ** ocamlc.byte module = "module_without_cmx.mli" *** ocamlc.byte module = "w58.ml" **** check-ocamlc.byte-output * setup-ocamlopt.byte-build-env ** ocamlopt.byte module = "module_without_cmx.mli" *** ocamlopt.byte module = "w58.ml" **** check-ocamlopt.byte-output *)
conv_oracle.mli
open Names type oracle val empty : oracle (** Order on section paths for unfolding. If [oracle_order kn1 kn2] is true, then unfold kn1 first. Note: the oracle does not introduce incompleteness, it only tries to postpone unfolding of "opaque" constants. *) val oracle_order : ('a -> Constant.t) -> oracle -> bool -> 'a tableKey -> 'a tableKey -> bool (** Priority for the expansion of constant in the conversion test. * Higher levels means that the expansion is less prioritary. * (And Expand stands for -oo, and Opaque +oo.) * The default value (transparent constants) is [Level 0]. *) type level = Expand | Level of int | Opaque val pr_level : level -> Pp.t val transparent : level (** Check whether a level is transparent *) val is_transparent : level -> bool val get_strategy : oracle -> Constant.t tableKey -> level (** Sets the level of a constant. * Level of RelKey constant cannot be set. *) val set_strategy : oracle -> Constant.t tableKey -> level -> oracle (** Fold over the non-transparent levels of the oracle. Order unspecified. *) val fold_strategy : (Constant.t tableKey -> level -> 'a -> 'a) -> oracle -> 'a -> 'a val get_transp_state : oracle -> TransparentState.t
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) (* v * Copyright INRIA, CNRS and contributors *) (* <O___,, * (see version control and CREDITS file for authors & dates) *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (* * (see LICENSE file for the text of the license) *) (************************************************************************)
dune
(library (name amd64) (public_name processor.amd64) (enabled_if (= %{architecture} "amd64")) (foreign_stubs (language c) (names amd64_stubs)) (c_library_flags (-lpthread)))
RPC_arg.mli
type 'a t type 'a arg = 'a t val make : ?descr:string -> name:string -> destruct:(string -> ('a, string) result) -> construct:('a -> string) -> unit -> 'a arg type descr = {name : string; descr : string option} val descr : 'a arg -> descr val bool : bool arg val int : int arg val int32 : int32 arg val int64 : int64 arg val string : string arg val like : 'a arg -> ?descr:string -> string -> 'a arg type ('a, 'b) eq = Eq : ('a, 'a) eq val eq : 'a arg -> 'b arg -> ('a, 'b) eq 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. *) (* *) (*****************************************************************************)
bar.c
#include <stdio.h> #include "foo.cxx" void foo () { int n = cppfoo(); printf("n = %d\n", n); }
cmdlinergen.ml
open Idl module Gen () = struct type implementation = unit -> ((Rpc.call -> Rpc.response) -> (unit -> unit) Cmdliner.Term.t * Cmdliner.Cmd.info) list type ('a, 'b) comp = ('a, 'b) Result.t type 'a rpcfn = Rpc.call -> Rpc.response type 'a res = unit let description = ref None let terms = ref [] let implement : Idl.Interface.description -> implementation = fun x -> description := Some x; fun () -> !terms type _ fn = | Function : 'a Param.t * 'b fn -> ('a -> 'b) fn | NoArgsFunction : 'b fn -> (unit -> 'b) fn | Returning : ('a Param.t * 'b Idl.Error.t) -> ('a, 'b) comp fn let returning a b = Returning (a, b) let ( @-> ) t f = Function (t, f) let noargs f = NoArgsFunction f let pos = ref 0 let term_of_param : type a. a Param.t -> Rpc.t Cmdliner.Term.t = fun p -> let open Rpc.Types in let open Cmdliner in let pinfo = Cmdliner.Arg.info [] ~doc:(String.concat " " p.Param.description) ~docv: (match p.Param.name with | Some s -> s | None -> p.Param.typedef.Rpc.Types.name) in let incr () = let p = !pos in incr pos; p in match p.Param.typedef.Rpc.Types.ty with | Basic Int -> Term.app (Term.const Rpc.rpc_of_int64) Cmdliner.Arg.(required & pos (incr ()) (some int64) None & pinfo) | Basic Int32 -> Term.app (Term.const Rpc.rpc_of_int64) Cmdliner.Arg.(required & pos (incr ()) (some int64) None & pinfo) | Basic Int64 -> Term.app (Term.const Rpc.rpc_of_int64) Cmdliner.Arg.(required & pos (incr ()) (some int64) None & pinfo) | Basic String -> Term.app (Term.const Rpc.rpc_of_string) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Basic Bool -> Term.app (Term.const Rpc.rpc_of_bool) Cmdliner.Arg.(required & pos (incr ()) (some bool) None & pinfo) | Basic Float -> Term.app (Term.const Rpc.rpc_of_float) Cmdliner.Arg.(required & pos (incr ()) (some float) None & pinfo) | Basic Char -> Term.app (Term.const (fun s -> Rpc.rpc_of_char s.[0])) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Unit -> Term.(const Rpc.Null) | DateTime -> Term.app (Term.const Rpc.rpc_of_dateTime) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Base64 -> Term.app (Term.const Rpc.rpc_of_base64) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Array _ -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match x with | Rpc.Enum _ -> x | _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | List _ -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match x with | Rpc.Enum _ -> x | _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Dict _ -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match x with | Rpc.Dict _ -> x | _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Option _ -> Term.(const Rpc.Null) | Tuple _ -> Term.const Rpc.Null | Tuple3 _ -> Term.const Rpc.Null | Tuple4 _ -> Term.const Rpc.Null | Struct _ -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match x with | Rpc.Dict _ -> x | _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Variant _ -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match x with | Rpc.Enum _ | Rpc.String _ -> x | _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) | Abstract { of_rpc; _ } -> Term.app (Term.const (fun x -> let x = Jsonrpc.of_string x in match of_rpc x with | Ok _ -> x | Error _ -> failwith "Type error")) Cmdliner.Arg.(required & pos (incr ()) (some string) None & pinfo) let declare_ is_notification name desc_list ty = let generate rpc = let wire_name = Idl.get_wire_name !description name in let rec inner : type b. ((string * Rpc.t) list * Rpc.t list) Cmdliner.Term.t -> b fn -> (unit -> unit) Cmdliner.Term.t = fun cur f -> match f with | Function (t, f) -> let term = term_of_param t in (match t.Param.name with | Some param_name -> let term = let open Cmdliner.Term in const (fun x (named, unnamed) -> (param_name, x) :: named, unnamed) $ term $ cur in inner term f | None -> let term = let open Cmdliner.Term in const (fun x (named, unnamed) -> named, x :: unnamed) $ term $ cur in inner term f) | NoArgsFunction f -> let term = let open Cmdliner.Term in const (fun (named, unnamed) -> named, unnamed) $ cur in inner term f | Returning (_, _) -> let run (named, unnamed) = let args = match named with | [] -> List.rev unnamed | _ -> Rpc.Dict named :: List.rev unnamed in let call' = Rpc.call wire_name args in let call = { call' with is_notification } in let response = rpc call in match response.Rpc.contents with | x -> Printf.printf "%s\n" (Rpc.to_string x); () in Cmdliner.Term.(const (fun args () -> run args) $ cur) in let doc = String.concat " " desc_list in pos := 0; inner (Cmdliner.Term.const ([], [])) ty, Cmdliner.Cmd.info wire_name ~doc in terms := generate :: !terms let declare name desc_list ty = declare_ false name desc_list ty let declare_notification name desc_list ty = declare_ true name desc_list ty end
muen-sinfo.c
#include "bindings.h" #include "sinfo.h" #include "muschedinfo.h" #define SINFO_ADDR 0xe00000000UL #define SCHED_INFO_ADDR 0xe00008000UL static char subject_name[MAX_NAME_LENGTH + 1]; static bool subject_name_unset = true; static const struct subject_info_type *sinfo = (struct subject_info_type *)(SINFO_ADDR); static volatile struct scheduling_info_type *sched_info = (struct scheduling_info_type *)(SCHED_INFO_ADDR); bool muen_names_equal(const struct muen_name_type *const n1, const char *const n2) { return n1->length == strlen(n2) && strncmp(n1->data, n2, n1->length) == 0; } struct iterator { const struct muen_resource_type *res; unsigned int idx; }; /* * Iterate over all resources beginning at given start resource. If the res * member of the iterator is NULL, the function (re)starts the iteration at the * first available resource. */ static bool iterate_resources(struct iterator *const iter) { if (!muen_check_magic()) return false; if (!iter->res) { iter->res = &sinfo->resources[0]; iter->idx = 0; } else { iter->res++; iter->idx++; } return iter->idx < sinfo->resource_count && iter->res->kind != MUEN_RES_NONE; } inline bool muen_check_magic(void) { return sinfo->magic == MUEN_SUBJECT_INFO_MAGIC; } const char * muen_get_subject_name(void) { if (!muen_check_magic()) return NULL; if (subject_name_unset) { memset(subject_name, 0, MAX_NAME_LENGTH + 1); memcpy(subject_name, &sinfo->name.data, sinfo->name.length); subject_name_unset = false; } return subject_name; } const struct muen_resource_type * muen_get_resource(const char *const name, enum muen_resource_kind kind) { struct iterator i = { NULL, 0 }; while (iterate_resources(&i)) if (i.res->kind == kind && muen_names_equal(&i.res->name, name)) return i.res; return NULL; } const struct muen_device_type * muen_get_device(const uint16_t sid) { struct iterator i = { NULL, 0 }; while (iterate_resources(&i)) if (i.res->kind == MUEN_RES_DEVICE && i.res->data.dev.sid == sid) return &i.res->data.dev; return NULL; } bool muen_for_each_resource(resource_cb func, void *data) { struct iterator i = { NULL, 0 }; while (iterate_resources(&i)) if (!func(i.res, data)) return false; return true; } uint64_t muen_get_tsc_khz(void) { if (!muen_check_magic()) return 0; return sinfo->tsc_khz; } uint64_t muen_get_sched_start(void) { if (!muen_check_magic()) return 0; return sched_info->tsc_schedule_start; } uint64_t muen_get_sched_end(void) { if (!muen_check_magic()) return 0; return sched_info->tsc_schedule_end; }
/* * Copyright (c) 2017 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a sandboxed execution environment. * * 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. */
print.c
#include <stdlib.h> #include "flint.h" #include "fmpz_poly.h" #include "fmpz_poly_mat.h" void fmpz_poly_mat_print(const fmpz_poly_mat_t A, const char * x) { slong i, j; flint_printf("<%wd x %wd matrix over Z[%s]>\n", A->r, A->c, x); for (i = 0; i < A->r; i++) { flint_printf("["); for (j = 0; j < A->c; j++) { fmpz_poly_print_pretty(fmpz_poly_mat_entry(A, i, j), x); if (j + 1 < A->c) flint_printf(", "); } flint_printf("]\n"); } flint_printf("\n"); }
/* Copyright (C) 2011 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
internal.ml
open Import let latest_lang_version = Cmd.v (Cmd.info "latest-lang-version") (let+ () = Term.const () in print_endline (Dune_lang.Syntax.greatest_supported_version Stanza.syntax |> Dune_lang.Syntax.Version.to_string)) let group = Cmd.group (Cmd.info "internal") [ Internal_dump.command; latest_lang_version ]
abstract_quantifiers.mli
(********************************************************************) (* *) (* The Why3 Verification Platform / The Why3 Development Team *) (* Copyright 2010-2023 -- Inria - CNRS - Paris-Saclay University *) (* *) (* This software is distributed under the terms of the GNU Lesser *) (* General Public License version 2.1, with the special exception *) (* on linking described in file LICENSE. *) (* *) (********************************************************************)
t-mul_array_threaded.c
#include <stdio.h> #include <stdlib.h> #include "fmpz_mpoly.h" #include "ulong_extras.h" int main(void) { int i, j, result, max_threads = 5; int tmul = 20; FLINT_TEST_INIT(state); #ifdef _WIN32 tmul = 1; #endif flint_printf("mul_array_threaded...."); fflush(stdout); /* Check mul_array_threaded matches mul_johnson */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { fmpz_mpoly_ctx_t ctx; fmpz_mpoly_t f, g, h, k; slong len, len1, len2, exp_bound, exp_bound1, exp_bound2; slong coeff_bits, max_bound; slong n; fmpz_mpoly_ctx_init_rand(ctx, state, 5); fmpz_mpoly_init(f, ctx); fmpz_mpoly_init(g, ctx); fmpz_mpoly_init(h, ctx); fmpz_mpoly_init(k, ctx); len = n_randint(state, 100); len1 = n_randint(state, 100); len2 = n_randint(state, 100); max_bound = ctx->minfo->ord == ORD_LEX ? 200 : 100; n = FLINT_MAX(WORD(1), ctx->minfo->nvars); max_bound = max_bound/n/n; exp_bound = n_randint(state, max_bound) + 1; exp_bound1 = n_randint(state, max_bound) + 1; exp_bound2 = n_randint(state, max_bound) + 1; coeff_bits = n_randint(state, 100); for (j = 0; j < 4; j++) { fmpz_mpoly_randtest_bound(f, state, len1, coeff_bits, exp_bound1, ctx); fmpz_mpoly_randtest_bound(g, state, len2, coeff_bits, exp_bound2, ctx); fmpz_mpoly_randtest_bound(h, state, len, coeff_bits, exp_bound, ctx); fmpz_mpoly_randtest_bound(k, state, len, coeff_bits, exp_bound, ctx); flint_set_num_threads(n_randint(state, max_threads) + 1); fmpz_mpoly_mul_johnson(h, f, g, ctx); fmpz_mpoly_assert_canonical(h, ctx); result = fmpz_mpoly_mul_array_threaded(k, f, g, ctx); if (!result) { continue; } fmpz_mpoly_assert_canonical(k, ctx); result = fmpz_mpoly_equal(h, k, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check mul_array_threaded matches mul_johnson\ni = %wd, j = %wd\n", i, j); fflush(stdout); flint_abort(); } } fmpz_mpoly_clear(f, ctx); fmpz_mpoly_clear(g, ctx); fmpz_mpoly_clear(h, ctx); fmpz_mpoly_clear(k, ctx); fmpz_mpoly_ctx_clear(ctx); } /* Check aliasing first argument */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { fmpz_mpoly_ctx_t ctx; fmpz_mpoly_t f, g, h; slong len, len1, len2, exp_bound, exp_bound1, exp_bound2; slong coeff_bits, max_bound; slong n; fmpz_mpoly_ctx_init_rand(ctx, state, 10); fmpz_mpoly_init(f, ctx); fmpz_mpoly_init(g, ctx); fmpz_mpoly_init(h, ctx); len = n_randint(state, 50); len1 = n_randint(state, 50); len2 = n_randint(state, 50); n = FLINT_MAX(WORD(1), ctx->minfo->nvars); max_bound = 200/n/n; exp_bound = n_randint(state, max_bound) + 1; exp_bound1 = n_randint(state, max_bound) + 1; exp_bound2 = n_randint(state, max_bound) + 1; coeff_bits = n_randint(state, 200); for (j = 0; j < 4; j++) { fmpz_mpoly_randtest_bound(f, state, len1, coeff_bits, exp_bound1, ctx); fmpz_mpoly_randtest_bound(g, state, len2, coeff_bits, exp_bound2, ctx); fmpz_mpoly_randtest_bound(h, state, len, coeff_bits, exp_bound, ctx); flint_set_num_threads(n_randint(state, max_threads) + 1); fmpz_mpoly_mul_johnson(h, f, g, ctx); fmpz_mpoly_assert_canonical(h, ctx); result = fmpz_mpoly_mul_array_threaded(f, f, g, ctx); if (!result) continue; fmpz_mpoly_assert_canonical(f, ctx); result = fmpz_mpoly_equal(h, f, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check aliasing first argument\ni = %wd, j = %wd\n", i, j); fflush(stdout); flint_abort(); } } fmpz_mpoly_clear(f, ctx); fmpz_mpoly_clear(g, ctx); fmpz_mpoly_clear(h, ctx); fmpz_mpoly_ctx_clear(ctx); } /* Check aliasing second argument */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { fmpz_mpoly_ctx_t ctx; fmpz_mpoly_t f, g, h; slong len, len1, len2, exp_bound, exp_bound1, exp_bound2; slong coeff_bits, max_bound; slong n; fmpz_mpoly_ctx_init_rand(ctx, state, 10); fmpz_mpoly_init(f, ctx); fmpz_mpoly_init(g, ctx); fmpz_mpoly_init(h, ctx); len = n_randint(state, 50); len1 = n_randint(state, 50); len2 = n_randint(state, 50); n = FLINT_MAX(WORD(1), ctx->minfo->nvars); max_bound = 200/n/n; exp_bound = n_randint(state, max_bound) + 1; exp_bound1 = n_randint(state, max_bound) + 1; exp_bound2 = n_randint(state, max_bound) + 1; coeff_bits = n_randint(state, 200); for (j = 0; j < 4; j++) { fmpz_mpoly_randtest_bound(f, state, len1, coeff_bits, exp_bound1, ctx); fmpz_mpoly_randtest_bound(g, state, len2, coeff_bits, exp_bound2, ctx); fmpz_mpoly_randtest_bound(h, state, len, coeff_bits, exp_bound, ctx); flint_set_num_threads(n_randint(state, max_threads) + 1); fmpz_mpoly_mul_johnson(h, f, g, ctx); fmpz_mpoly_assert_canonical(h, ctx); result = fmpz_mpoly_mul_array_threaded(g, f, g, ctx); if (!result) continue; fmpz_mpoly_assert_canonical(g, ctx); result = fmpz_mpoly_equal(h, g, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check aliasing second argument\ni = %wd, j = %wd\n", i, j); fflush(stdout); flint_abort(); } } fmpz_mpoly_clear(f, ctx); fmpz_mpoly_clear(g, ctx); fmpz_mpoly_clear(h, ctx); fmpz_mpoly_ctx_clear(ctx); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2018 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
dune
(library (name odoc_manpage) (public_name odoc.manpage) (instrumentation (backend bisect_ppx)) (libraries odoc_model odoc_document))
Jacobi.c
#include "Jacobi.h" void coorJacobi_init (coorJacobi P, mpmod_t n ) { mpres_init (P->U ,n); mpres_init (P->V ,n); mpres_init (P->W ,n); mpres_init (P->Y ,n); } void coorJacobi_clear (coorJacobi P, mpmod_t n ) { mpres_clear (P->U ,n); mpres_clear (P->V ,n); mpres_clear (P->W ,n); mpres_clear (P->Y ,n); } void coorJacobi_set (coorJacobi P,coorJacobi Q, mpmod_t n ) { mpres_set (P->U ,Q->U ,n); mpres_set (P->V ,Q->V ,n); mpres_set (P->W ,Q->W ,n); mpres_set (P->Y ,Q->Y ,n); } /* Multiply a point by k on a Jacobi elliptic curve over ZZ (use mpz_t) The curve is y^2 = 1 + (-3/s^2+1/s^4)*x^2 + x^4/s^2 The initial point is X=1, Y=1-ep (Z=1) The result is put in (x,y,z) NOTE: for k=0 or k=1 we take k=2! */ void mulJacobiEntiers (mpz_t a,mpz_t b, int k, mpz_t x,mpz_t y,mpz_t z) { if (k<0) { k = -k; } if (k==0) { mpz_set_ui (x,0); mpz_set_ui (y,1); mpz_set_ui (z,1); } else if (k==1) { mpz_mul (x ,a ,a); mpz_mul (z ,b ,b); mpz_sub (y ,x ,z); mpz_set (x,a); mpz_set (z,a); } else if (k ==2) { mpz_mul (y ,b ,b); mpz_mul_ui (y ,y ,2); mpz_mul (z ,a ,a); mpz_add (y ,y ,z); // y = a^2 + 2*b^2 mpz_mul_ui (x ,a ,2); // x = 2*a mpz_set (z ,a); // z = a } else { // general case mpz_t sa,sb,Yi; mpz_t X,Y,Z; mpz_t t1,t2,t3,t4,t5,t7,t8,t9; int i; mpz_init (sa); mpz_init (sb); mpz_init (Yi); mpz_init (X); mpz_init (Z); mpz_init (Y); mpz_init (t1); mpz_init (t2); mpz_init (t3); mpz_init (t4); mpz_init (t5); mpz_init (t7); mpz_init (t8); mpz_init (t9); mpz_mul (sa ,a ,a); mpz_mul (sb ,b ,b); mpz_sub (Yi ,sa ,sb); mpz_set (X ,a); mpz_set (Z ,a); mpz_set (Y ,Yi); for (i=2;i<=k;i++) { mpz_mul (t1 ,X ,Z); mpz_mul (t2 ,X ,X); mpz_mul (t3 ,Z ,Z); mpz_mul (t4 ,t3 ,sa); mpz_mul (t5 ,t2 ,sb); mpz_add (t9 ,t2 ,t3); mpz_mul (t9 ,t9 ,sa); mpz_mul (t9 ,t9 ,sb); mpz_mul (t9 ,t9 ,t1); mpz_mul_ui (t9 ,t9 ,2); mpz_mul (t9 ,t9 ,sa); mpz_mul (t8 ,Yi ,Y); mpz_mul (t8 ,t8 ,sa); mpz_mul_ui (t7 ,sa ,3); mpz_sub (t7 ,sb ,t7); mpz_mul (t7 ,t7 ,sb); mpz_mul (t7 ,t7 ,t1); mpz_add (t8 ,t8 ,t7); mpz_add (t7 ,t4 ,t5); mpz_mul (t8 ,t8 ,t7); mpz_add (t9 ,t9 ,t8); mpz_sub (t8 ,t4 ,t5); mpz_mul (t8 ,t8 ,a); mpz_mul (t7 ,t1 ,Yi); mpz_mul (t2 ,sa ,Y); mpz_add (t7 ,t7 ,t2); mpz_mul (t7 ,t7 ,a); mpz_set (X ,t7); mpz_set (Y ,t9); mpz_set (Z ,t8); } mpz_set (x ,X); mpz_set (y ,Y); mpz_set (z ,Z); mpz_clear (sa); mpz_clear (sb); mpz_clear (Yi); mpz_clear (X); mpz_clear (Z); mpz_clear (Y); mpz_clear (t1); mpz_clear (t2); mpz_clear (t3); mpz_clear (t4); mpz_clear (t5); mpz_clear (t7); mpz_clear (t8); mpz_clear (t9); } } /* Multiply a point by k on a Jacobi elliptic curve The curve is y^2 = 1 + (-3/s^2+1/s^4)*x^2 + x^4/s^2 The initial point is X=1, Y=1-ep (Z=1) The result is put in x,y NOTE: for k=0 or k=1 we take k=2! */ int mulJacobi2 (mpz_t f,mpmod_t n, int k, mpres_t x,mpres_t y, mpres_t Y,mpres_t ep,mpres_t dep) { if (k <= 2) { doubleJacobi2DebFin(f,n,x,y,Y,ep,dep); return MULT_JACOBI; } else if (k == 3) { coorJacobi P,Q; mpres_t t; mpres_init (t,n); coorJacobi_init (P,n); coorJacobi_init (Q,n); mpres_set_ui (P->U,1,n); mpres_set_ui (P->V,1,n); mpres_set_ui (P->W,1,n); mpres_set (P->Y,Y,n); doubleJacobi2Deb(n,Q,Y,ep,dep); addJacobi2fin(n,Q,P,x,y,t,ep,dep); if (!mpres_invert (t,t,n)) // t=1/Z3 { mpres_gcd (f, t, n); mpres_clear (t,n); coorJacobi_clear (P,n); coorJacobi_clear (Q,n); return MULT_JACOBI_FAIL; } mpres_mul (x ,x ,t ,n); mpres_mul (t ,t ,t ,n); mpres_mul (y ,y ,t ,n); mpres_clear (t,n); coorJacobi_clear (P,n); coorJacobi_clear (Q,n); return MULT_JACOBI; } else { coorJacobi P,Q; mpres_t t; int mask; mpres_init (t,n); coorJacobi_init (P,n); coorJacobi_init (Q,n); mpres_set_ui (P->U,1,n); mpres_set_ui (P->V,1,n); mpres_set_ui (P->W,1,n); mpres_set (P->Y,Y,n); mask = (1<<POW_MAX);// mask = 10000 with at least one more bit than k while ( (mask & k) == 0 ) { mask = (mask >> 1); } // mask = 100... with the same number of bits than k mask = (mask >> 1);// mask = 010... with the same number of bits than k doubleJacobi2Deb(n,Q,Y,ep,dep); // Q = 2*P if ( (mask & k) != 0 ) { // case Q+2*Q addJacobi2(n,P,Q,Q,ep,dep); } mask = (mask >> 1);// mask = 0010... with the same number of bits than k while (mask > 1) { addJacobi2(n,Q,Q,Q,ep,dep); if ( (mask & k) != 0 ) { // case Q+2*Q addJacobi2(n,P,Q,Q,ep,dep); } mask = (mask >> 1); } if ( (mask & k) == 0 ) { // case 2*Q coorJacobi_set (P ,Q ,n); addJacobi2fin(n,Q,P,x,y,t,ep,dep); } else { // case 2*Q+Q addJacobi2(n,Q,Q,Q,ep,dep); addJacobi2fin(n,Q,P,x,y,t,ep,dep); } if (!mpres_invert (t,t,n)) // t=1/Z3 { mpres_gcd (f, t, n); mpres_clear (t,n); coorJacobi_clear (P,n); coorJacobi_clear (Q,n); return MULT_JACOBI_FAIL; } mpres_mul (x ,x ,t ,n); mpres_mul (t ,t ,t ,n); mpres_mul (y ,y ,t ,n); mpres_clear (t,n); coorJacobi_clear (P,n); coorJacobi_clear (Q,n); return MULT_JACOBI; } } /* Double a point on the Jacobi curve y^2=1-dep*X^2+ep*X^4 begin with X=1, Y=1-ep (Z=1) We want x,y */ void doubleJacobi2DebFin(mpz_t f,mpmod_t n, mpres_t x,mpres_t y, mpres_t Y,mpres_t ep,mpres_t dep) { mpres_set_ui (x ,2 ,n); // x=2 mpres_mul_ui (y ,ep ,2 ,n); mpres_add_ui (y ,y ,1 ,n); // y = 2*ep+1 = 2/s^2+1 } /* Double a point on the Jacobi curve y^2=1-dep*X^2+ep*X^4 begin with X=1, Y=1-ep (Z=1) We want P2=(U3,V3,W3,Y3) */ void doubleJacobi2Deb(mpmod_t n, coorJacobi P2, mpres_t Y,mpres_t ep,mpres_t dep) { mpres_add_ui (P2->V ,ep, 1 ,n); // V3 = ep+1 mpres_mul (P2->W ,Y ,Y ,n); // W3 = Y^2 mpres_sub (P2->Y ,P2->W ,dep ,n); // Y3=Y^2-dep mpres_mul (P2->Y ,P2->Y ,P2->V ,n); // Y3=(1+ep)*(Y^2-dep) mpres_mul_ui (P2->V ,ep ,4 ,n); mpres_add (P2->Y ,P2->Y ,P2->V ,n); // Y3=(1+ep)*(Y^2-dep) + 4ep mpres_mul_ui (P2->V ,P2->W ,2 ,n); // V3 = 2*Y^2 mpres_mul_ui (P2->U ,P2->V ,2 ,n); // U3 = 4*Y^2 } /* add two points on the jacobi curve y^2=1-dep*X^2+ep*X^4 Initial points P1=(U1,V1,W1,Y1) and P2=(U2,V2,W2,Y2) P1+P2=P3=(U3,V3,W3,Y3) */ void addJacobi2(mpmod_t n, coorJacobi P1,coorJacobi P2, coorJacobi P3, mpres_t ep,mpres_t dep) { mpres_t t1,t3,t5,t7,t9; mpres_init (t1,n); mpres_init (t3,n); mpres_init (t5,n); mpres_init (t7,n); mpres_init (t9,n); mpres_set (t1 ,P1->U ,n); mpres_set (P3->U ,P2->U ,n); mpres_set (t3 ,P1->V ,n); mpres_set (P3->V ,P2->V ,n); mpres_set (t5 ,P1->W ,n); mpres_set (P3->W ,P2->W ,n); mpres_set (t7 ,P1->Y ,n); mpres_set (P3->Y ,P2->Y ,n); mpres_mul (t9 ,t7 ,P3->Y ,n); mpres_add (t7 ,t7 ,t3 ,n); mpres_add (P3->Y ,P3->Y ,P3->V ,n); mpres_mul (t3 ,t3 ,P3->V ,n); mpres_mul (t7 ,t7 ,P3->Y ,n); mpres_sub (t7 ,t7 ,t9 ,n); mpres_sub (t7 ,t7 ,t3 ,n); // X3 mpres_mul (P3->V ,t1 ,P3->U ,n); mpres_mul (P3->Y ,t5 ,P3->W ,n); mpres_add (t1 ,t1 ,t5 ,n); mpres_add (P3->U ,P3->U ,P3->W ,n); mpres_mul (t5 ,t1 ,P3->U ,n); mpres_sub (t5 ,t5 ,P3->V ,n); mpres_sub (t5 ,t5 ,P3->Y ,n); mpres_mul (P3->V ,P3->V ,ep ,n); mpres_sub (t1 ,P3->Y ,P3->V ,n); // Z3 mpres_add (P3->U ,P3->Y ,P3->V ,n); mpres_mul (P3->W ,t3 ,dep ,n); mpres_sub (P3->W ,t9 ,P3->W ,n); mpres_mul (P3->W ,P3->W ,P3->U ,n); mpres_mul_ui (t3 ,t3 ,2 ,n); mpres_mul (t3 ,t3 ,ep ,n); mpres_mul (t3 ,t3 ,t5 ,n); mpres_add (P3->Y ,P3->W ,t3 ,n); // Y3 mpres_mul (P3->U ,t7 ,t7 ,n); // U3 mpres_mul (P3->V ,t1 ,t7 ,n); // V3 mpres_mul (P3->W ,t1 ,t1 ,n); // W3 mpres_clear (t1,n); mpres_clear (t3,n); mpres_clear (t5,n); mpres_clear (t7,n); mpres_clear (t9,n); } /* add two points on the jacobi curve y^2=1-dep*X^2+ep*X^4 Initial points P1=(U1,V1,W1,Y1) and P2=(U2,V2,W2,Y2) P1+P2=P3=(U3,V3,W3,Y3) WARNING: value of P1 and P2 are modified P1 and P2 must be different */ void addJacobi2fin(mpmod_t n, coorJacobi P1,coorJacobi P2, mpres_t X3,mpres_t Y3,mpres_t Z3, mpres_t ep,mpres_t dep) { mpres_mul (Y3 ,P1->Y ,P2->Y ,n); mpres_add (P1->Y ,P1->Y ,P1->V ,n); mpres_add (P2->Y ,P2->Y ,P2->V ,n); mpres_mul (P1->V ,P1->V ,P2->V ,n); mpres_mul (P1->Y ,P1->Y ,P2->Y ,n); mpres_sub (P1->Y ,P1->Y ,Y3 ,n); mpres_sub (X3 ,P1->Y ,P1->V ,n); // X3 mpres_mul (P2->V ,P1->U ,P2->U ,n); mpres_mul (P2->Y ,P1->W ,P2->W ,n); mpres_add (P1->U ,P1->U ,P1->W ,n); mpres_add (P2->U ,P2->U ,P2->W ,n); mpres_mul (P1->W ,P1->U ,P2->U ,n); mpres_sub (P1->W ,P1->W ,P2->V ,n); mpres_sub (P1->W ,P1->W ,P2->Y ,n); mpres_mul (P2->V ,P2->V ,ep ,n); mpres_sub (Z3 ,P2->Y ,P2->V ,n); // Z3 mpres_add (P2->U ,P2->Y ,P2->V ,n); mpres_mul (P2->W ,P1->V ,dep ,n); mpres_sub (P2->W ,Y3 ,P2->W ,n); mpres_mul (P2->W ,P2->W ,P2->U ,n); mpres_mul_ui (P1->V ,P1->V ,2 ,n); mpres_mul (P1->V ,P1->V ,ep ,n); mpres_mul (P1->V ,P1->V ,P1->W ,n); mpres_add (Y3 ,P2->W ,P1->V ,n); // Y3 }
dune
(executable (name main) (package git-unix) (public_name ogit-dot) (libraries digestif.c checkseum.c git-unix))
test_exn.ml
open Printf let () = try let cr = Cairo.create(Cairo.PNG.create "curve_to.png") in Cairo.Surface.finish(Cairo.get_target cr); exit 1; (* should no reach this *) with e -> printf "As expected, raise the exception: %s\n" (Printexc.to_string e)
misc.ml
module Public_key_map = Map.Make (Signature.Public_key) type 'a lazyt = unit -> 'a type 'a lazy_list_t = LCons of 'a * 'a lazy_list_t tzresult Lwt.t lazyt type 'a lazy_list = 'a lazy_list_t tzresult Lwt.t let[@coq_struct "i"] rec ( --> ) i j = (* [i; i+1; ...; j] *) if Compare.Int.(i > j) then [] else i :: (succ i --> j) let[@coq_struct "j"] rec ( <-- ) i j = (* [j; j-1; ...; i] *) if Compare.Int.(i > j) then [] else j :: (i <-- pred j) let[@coq_struct "i"] rec ( ---> ) i j = (* [i; i+1; ...; j] *) if Compare.Int32.(i > j) then [] else i :: (Int32.succ i ---> j) let split delim ?(limit = max_int) path = let l = String.length path in let rec do_slashes acc limit i = if Compare.Int.(i >= l) then List.rev acc else if Compare.Char.(path.[i] = delim) then do_slashes acc limit (i + 1) else do_split acc limit i and do_split acc limit i = if Compare.Int.(limit <= 0) then if Compare.Int.(i = l) then List.rev acc else List.rev (String.sub path i (l - i) :: acc) else do_component acc (pred limit) i i and do_component acc limit i j = if Compare.Int.(j >= l) then if Compare.Int.(i = j) then List.rev acc else List.rev (String.sub path i (j - i) :: acc) else if Compare.Char.(path.[j] = delim) then do_slashes (String.sub path i (j - i) :: acc) limit j else do_component acc limit i (j + 1) in if Compare.Int.(limit > 0) then do_slashes [] limit 0 else [path] [@@coq_axiom_with_reason "non-top-level mutual recursion"] let pp_print_paragraph ppf description = Format.fprintf ppf "@[%a@]" Format.(pp_print_list ~pp_sep:pp_print_space pp_print_string) (split ' ' description) let take n l = let rec loop acc n xs = if Compare.Int.(n <= 0) then Some (List.rev acc, xs) else match xs with [] -> None | x :: xs -> loop (x :: acc) (n - 1) xs in loop [] n l let remove_prefix ~prefix s = let x = String.length prefix in let n = String.length s in if Compare.Int.(n >= x) && Compare.String.(String.sub s 0 x = prefix) then Some (String.sub s x (n - x)) else None let rec remove_elem_from_list nb = function | [] -> [] | _ :: _ as l when Compare.Int.(nb <= 0) -> l | _ :: tl -> remove_elem_from_list (nb - 1) tl
(*****************************************************************************) (* *) (* 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_scenario.ml
open Internal_pervasives module Inconsistency_error = struct type t = [ `Empty_protocol_list | `Too_many_protocols of Tezos_protocol.t list | `Too_many_timestamp_delays of Tezos_protocol.t list ] let should_be_one_protocol = function | [one] -> return one | [] -> fail `Empty_protocol_list | more -> fail (`Too_many_protocols more) let should_be_one_timestamp_delay = function | [_] -> return () | [] -> fail `Empty_protocol_list | more -> fail (`Too_many_timestamp_delays more) let pp fmt err = match err with | `Empty_protocol_list -> Caml.Format.fprintf fmt "Wrong number of protocols in network: 0" | `Too_many_protocols p -> Caml.Format.fprintf fmt "Wrong number of protocols in network: %d" (List.length p) | `Too_many_timestamp_delays p -> Caml.Format.fprintf fmt "Wrong number of protocol timestamp delays in network: %d" (List.length p) end module Topology = struct type node = Tezos_node.t type _ t = | Mesh : {size: int} -> node list t | Bottleneck : {name: string; left: 'a network; right: 'b network} -> ('a * node * 'b) t | Net_in_the_middle : {middle: 'm network; left: 'a network; right: 'b network} -> ('a * 'm * 'b) t and 'a network = {topology: 'a t; name: string} let make name topology = {name; topology} let mesh name size = Mesh {size} |> make name let sub = make let bottleneck name left right = Bottleneck {name; left; right} |> make name let net_in_the_middle name middle left right = Net_in_the_middle {middle; left; right} |> make name let rec node_count : type a. a t -> int = function | Mesh {size} -> size | Bottleneck {left; right; _} -> 1 + node_count left.topology + node_count right.topology | Net_in_the_middle {left; right; middle} -> node_count middle.topology + node_count left.topology + node_count right.topology let rec node_ids : type a. a t -> a -> string list = fun topo res -> match (topo, res) with | Mesh _, l -> List.map l ~f:(fun nod -> nod.Tezos_node.id) | Bottleneck {left; right; _}, (l, i, r) -> (i.Tezos_node.id :: node_ids left.topology l) @ node_ids right.topology r | Net_in_the_middle {left; right; middle}, (l, i, r) -> node_ids middle.topology i @ node_ids left.topology l @ node_ids right.topology r let rec node_names : type a. ?prefix:string -> a network -> string list = fun ?(prefix = "") {name; topology} -> let make_ith i = sprintf "%s%03d" prefix i in let continue a = node_names ~prefix:(prefix ^ name) a in match topology with | Mesh {size} -> List.init size ~f:make_ith | Bottleneck {name; left; right} -> (sprintf "%s%s" prefix name :: continue left) @ continue right | Net_in_the_middle {left; right; middle} -> continue middle @ continue left @ continue right let build ?(external_peer_ports = []) ?(base_port = 15_001) ~make_node network = let all_ports = ref [] in let next_port = ref (base_port + Int.rem base_port 2) in let rpc name = match List.find !all_ports ~f:(fun (n, _) -> String.equal n name) with | Some (_, p) -> p | None -> let p = !next_port in all_ports := (name, p) :: !all_ports ; next_port := !next_port + 2 ; p in let p2p n = rpc n + 1 in let node peers id = let rpc_port = rpc id in let p2p_port = p2p id in let expected_connections = List.length peers + List.length external_peer_ports in let peers = List.filter_map peers ~f:(fun p -> if not (String.equal p id) then Some (p2p p) else None) in make_node id ~expected_connections ~rpc_port ~p2p_port (external_peer_ports @ peers) in let dbgp prefx names = Dbg.f (fun pf -> pf "%s:\n %s\n%!" prefx (String.concat ~sep:"\n " (List.map names ~f:(fun n -> sprintf "%s:%d" n (p2p n))))) in let rec make : type a. ?extra_peers:string list -> prefix:string -> a network -> a = fun ?(extra_peers = []) ~prefix network -> let prefix = prefix ^ network.name in let make ?extra_peers n = make ?extra_peers ~prefix n in match network.topology with | Bottleneck {name; left; right} -> let intermediate = name in let extra_peers = [intermediate] in let left_nodes = make ~extra_peers left in let right_nodes = make ~extra_peers right in let intermediate_node = let peers = node_ids left.topology left_nodes @ node_ids right.topology right_nodes in node peers intermediate in (left_nodes, intermediate_node, right_nodes) | Net_in_the_middle {middle; left; right} -> let middle_names = node_names ~prefix:(prefix ^ middle.name) middle in dbgp "Mid-name" middle_names ; let left_nodes = make ~extra_peers:(extra_peers @ middle_names) left in let right_nodes = make ~extra_peers:(extra_peers @ middle_names) right in let intermediate_nodes = let peers = node_ids left.topology left_nodes @ node_ids right.topology right_nodes in dbgp "peers" peers ; dbgp "extr-peers" extra_peers ; dbgp "left-names" (node_names ~prefix:(prefix ^ left.name) left) ; dbgp "right-names" (node_names ~prefix:(prefix ^ right.name) right) ; make ~extra_peers:(peers @ extra_peers) middle in (left_nodes, intermediate_nodes, right_nodes) | Mesh _ -> let all = node_names ~prefix network in dbgp "mesh-names" all ; let nodes = List.map all ~f:(fun n -> node (all @ extra_peers) n) in nodes in make ~prefix:"" network end module Queries = struct let all_levels ?(chain = "main") state ~nodes = List.fold nodes ~init:(return []) ~f:(fun prevm {Tezos_node.id; rpc_port; _} -> prevm >>= fun prev -> Running_processes.run_cmdf state (* the header RPC is the most consistent across protocols: *) "curl http://localhost:%d/chains/%s/blocks/head/header" rpc_port chain >>= fun metadata -> Console.display_errors_of_command state metadata ~should_output:true >>= (function | true -> ( try `Level ( Jqo.of_lines metadata#out |> Jqo.field ~k:"level" |> Jqo.get_int ) |> return with _ -> return `Failed ) | false -> return `Failed) >>= fun res -> return ((id, res) :: prev)) >>= fun results -> let sorted = List.sort results ~compare:(fun (a, _) (b, _) -> String.compare a b) in return sorted let wait_for_all_levels_to_be ?attempts_factor ?chain state ~attempts ~seconds nodes level = let check_level = match level with | `Equal_to l -> ( = ) l | `At_least l -> fun x -> x >= l in let level_string = match level with | `Equal_to l -> sprintf "= %d" l | `At_least l -> sprintf "≥ %d" l in let msg ids = let show_node (id, res) = sprintf "%s (%s)" id ( match res with | `Failed -> "failed" | `Level l -> sprintf "%d" l | `Null -> "null" | `Unknown s -> sprintf "¿¿ %S ??" s ) in sprintf "Waiting for %s to reach level %s" (String.concat (List.map ~f:show_node ids) ~sep:", ") level_string in Console.say state EF.( wf "Checking for all levels to be %s (nodes: %s%s)" level_string (String.concat ~sep:", " (List.map nodes ~f:(fun n -> n.Tezos_node.id))) (Option.value_map chain ~default:"" ~f:(sprintf ", chain: %s"))) >>= fun () -> Helpers.wait_for state ?attempts_factor ~attempts ~seconds (fun _nth -> all_levels state ~nodes ?chain >>= fun results -> let not_readys = List.filter_map results ~f:(function | _, `Level n when check_level n -> None | id, res -> Some (id, res)) in match not_readys with | [] -> return (`Done ()) | ids -> return (`Not_done (msg ids))) end module Network = struct type t = {nodes: Tezos_node.t list} let make nodes = {nodes} let start_up ?(do_activation = true) ?(check_ports = true) state ~client_exec {nodes} = ( if check_ports then Helpers.Netstat.used_listening_ports state >>= fun all_used -> let taken port = List.find all_used ~f:(fun (p, _) -> Int.equal p port) in List_sequential.iter nodes ~f:(fun {Tezos_node.id; rpc_port; p2p_port; _} -> let fail s (p, `Tcp (_, row)) = System_error.fail_fatalf "Node: %S's %s port %d already in use {%s}" id s p (String.concat ~sep:"|" row) in let time_wait (_, `Tcp (_, row)) = Poly.equal (List.last row) (Some "TIME_WAIT") in match (taken rpc_port, taken p2p_port) with | None, None -> return () | Some p, _ -> if time_wait p then return () else fail "RPC" p | _, Some p -> if time_wait p then return () else fail "P2P" p) else return () ) >>= fun () -> let protocols = List.map ~f:Tezos_node.protocol nodes |> List.dedup_and_sort ~compare:Tezos_protocol.compare in Inconsistency_error.should_be_one_protocol protocols >>= fun protocol -> Inconsistency_error.should_be_one_timestamp_delay protocols >>= fun () -> Tezos_protocol.ensure state protocol >>= fun () -> List.fold nodes ~init:(return ()) ~f:(fun prev_m node -> prev_m >>= fun () -> Running_processes.start state (Tezos_node.process state node) >>= fun _ -> return ()) >>= fun () -> let node_0 = List.hd_exn nodes in let client = Tezos_client.of_node node_0 ~exec:client_exec in Dbg.e EF.(af "Trying to bootstrap client") ; Tezos_client.wait_for_node_bootstrap state client >>= fun () -> Tezos_client.rpc state ~client `Get ~path:"/chains/main/blocks/head/header" >>= fun json -> let do_activation = (* If the level is 0 we still do the activation. *) do_activation || try Int.equal Jqo.(field ~k:"level" json |> get_int) 0 with _ -> false in ( if do_activation then Tezos_client.activate_protocol state client protocol else return () ) >>= fun () -> Dbg.e EF.(af "Waiting for all nodes to be bootstrapped") ; List_sequential.iter nodes ~f:(fun node -> let client = Tezos_client.of_node node ~exec:client_exec in Tezos_client.wait_for_node_bootstrap state client) >>= fun () -> (* We make sure all nodes got activation before trying to continue: *) Queries.wait_for_all_levels_to_be state ~attempts:20 ~seconds:0.5 ~attempts_factor:0.8 nodes (`At_least 1) end let network_with_protocol ?do_activation ?node_custom_network ?external_peer_ports ?base_port ?(size = 5) ?protocol ?(nodes_history_mode_edits = return) state ~node_exec ~client_exec = let pre_edit_nodes = Topology.build ?base_port ?external_peer_ports ~make_node:(fun id ~expected_connections ~rpc_port ~p2p_port peers -> Tezos_node.make ?protocol ~exec:node_exec id ~expected_connections ?custom_network:node_custom_network ~rpc_port ~p2p_port peers) (Topology.mesh "N" size) in nodes_history_mode_edits pre_edit_nodes >>= fun nodes -> let protocols = List.map ~f:Tezos_node.protocol nodes |> List.dedup_and_sort ~compare:Tezos_protocol.compare in Inconsistency_error.should_be_one_protocol protocols >>= fun protocol -> Inconsistency_error.should_be_one_timestamp_delay protocols >>= fun () -> Network.start_up ?do_activation state ~client_exec (Network.make nodes) >>= fun () -> return (nodes, protocol)
mirage_impl_tracing.mli
type tracing = Functoria.job val tracing : tracing Functoria.typ val mprof_trace : size:int -> unit -> tracing Functoria.impl
ctypes_stubs.mli
open Import (* This module would be part of Ctypes_rules, except it creates a circular dependency if Dune_file tries to access it. *) val libraries_needed_for_ctypes : loc:Loc.t -> Lib_dep.t list
script_repr.mli
(** Defines a Michelson expression representation as a Micheline node with canonical ([int]) location and [Michelson_v1_primitives.prim] as content. Types [expr] and [node] both define representation of Michelson expressions and are indeed the same type internally, although this is not visible outside Micheline due to interface abstraction. *) (** Locations are used by Micheline mostly for error-reporting and pretty- printing expressions. [canonical_location] is simply an [int]. *) type location = Micheline.canonical_location (** Annotations attached to Michelson expressions. *) type annot = Micheline.annot (** Represents a Michelson expression as canonical Micheline. *) type expr = Michelson_v1_primitives.prim Micheline.canonical type error += Lazy_script_decode (* `Permanent *) (** A record containing either an underlying serialized representation of an expression or a deserialized one, or both. If either is absent, it will be computed on-demand. *) type lazy_expr = expr Data_encoding.lazy_t type 'location michelson_node = ('location, Michelson_v1_primitives.prim) Micheline.node type unlocated_michelson_node = unit michelson_node (** Same as [expr], but used in different contexts, as required by Micheline's abstract interface. *) type node = location michelson_node val location_encoding : location Data_encoding.t val expr_encoding : expr Data_encoding.t val lazy_expr_encoding : lazy_expr Data_encoding.t val lazy_expr : expr -> lazy_expr (** Type [t] joins the contract's code and storage in a single record. *) type t = {code : lazy_expr; storage : lazy_expr} val encoding : t Data_encoding.encoding (* Basic gas costs of operations related to processing Michelson: *) val deserialization_cost_estimated_from_bytes : int -> Gas_limit_repr.cost val deserialized_cost : expr -> Gas_limit_repr.cost val serialized_cost : bytes -> Gas_limit_repr.cost val bytes_node_cost : bytes -> Gas_limit_repr.cost (** Returns (a lower bound on) the cost to deserialize a {!lazy_expr}. If the expression has already been deserialized (i.e. the lazy expression contains the deserialized value or both the bytes representation and the deserialized value) then the cost is {b free}. *) val force_decode_cost : lazy_expr -> Gas_limit_repr.cost (** Like {!force_decode_cost}, excepted that the returned cost does not depend on the internal state of the lazy_expr. This means that the cost is never free (excepted for zero bytes expressions). *) val stable_force_decode_cost : lazy_expr -> Gas_limit_repr.cost val force_decode : lazy_expr -> expr tzresult (** Returns the cost to serialize a {!lazy_expr}. If the expression has already been deserialized (i.e. le lazy expression contains the bytes representation or both the bytes representation and the deserialized value) then the cost is {b free}. *) val force_bytes_cost : lazy_expr -> Gas_limit_repr.cost val force_bytes : lazy_expr -> bytes tzresult val unit_parameter : lazy_expr val is_unit_parameter : lazy_expr -> bool val strip_annotations : node -> node val strip_locations_cost : _ michelson_node -> Gas_limit_repr.cost val strip_annotations_cost : node -> Gas_limit_repr.cost module Micheline_size : sig type t = { nodes : Saturation_repr.may_saturate Saturation_repr.t; string_bytes : Saturation_repr.may_saturate Saturation_repr.t; z_bytes : Saturation_repr.may_saturate Saturation_repr.t; } val of_node : node -> t end (** [micheline_nodes root] returns the number of internal nodes in the micheline expression held from [root]. *) val micheline_nodes : node -> int (** [fold node i f] traverses [node] applying [f] on an accumulator initialized by [i]. *) val fold : node -> 'c -> ('c -> node -> 'c) -> 'c
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
alias.mli
open Import module Name : sig type t val decode : t Dune_lang.Decoder.t val of_string : string -> t val equal : t -> t -> bool val parse_string_exn : Loc.t * string -> t val to_string : t -> string val to_dyn : t -> Dyn.t val default : t val runtest : t val install : t val fmt : t val all : t val parse_local_path : Loc.t * Path.Local.t -> Path.Local.t * t include Comparable_intf.S with type key := t end type t val equal : t -> t -> bool val hash : t -> int val compare : t -> t -> Ordering.t val make : Name.t -> dir:Path.Build.t -> t val register_as_standard : Name.t -> unit (** The following always holds: [make (name t) ~dir:(dir t) = t] *) val name : t -> Name.t val dir : t -> Path.Build.t val to_dyn : t -> Dyn.t val encode : t Dune_lang.Encoder.t val of_user_written_path : loc:Loc.t -> Path.t -> t val fully_qualified_name : t -> Path.Build.t val default : dir:Path.Build.t -> t val runtest : dir:Path.Build.t -> t val install : dir:Path.Build.t -> t val doc : dir:Path.Build.t -> t val private_doc : dir:Path.Build.t -> t val lint : dir:Path.Build.t -> t val all : dir:Path.Build.t -> t val check : dir:Path.Build.t -> t val fmt : dir:Path.Build.t -> t val is_standard : Name.t -> bool val describe : ?loc:Loc.t -> t -> _ Pp.t
dune
(executable (name main) (public_name dune) (package dune) (enabled_if (<> %{profile} dune-bootstrap)) (libraries memo ocaml dune_lang fiber stdune dune_console unix dune_metrics dune_digest dune_cache dune_cache_storage dune_graph dune_rules dune_engine dune_util dune_upgrader cmdliner threads.posix build_info dune_config chrome_trace dune_stats csexp csexp_rpc dune_rpc_impl dune_rpc_private) (bootstrap_info bootstrap-info)) ; Installing the dune binary depends on the kind of build: ; - for bootstrap builds, dune.exe is copied from ../dune.exe ; and installed using a manual install stanza ; - for non-bootstrap builds (building dune with another dune), ; the executable stanza does everything (and attached it to the ; right package, which is important for build-info to succeed) ; but we still need to setup a dummy dune.exe so that profiles ; agree on the targets. (rule (enabled_if (<> %{profile} dune-bootstrap)) (action (with-stdout-to dune.exe (progn)))) (rule (action (copy ../_boot/dune.exe dune.exe)) (enabled_if (= %{profile} dune-bootstrap))) (install (section bin) (enabled_if (= %{profile} dune-bootstrap)) (package dune) (files (dune.exe as dune))) (deprecated_library_name (old_public_name dune.configurator) (new_public_name dune-configurator))
syscall.c
/* SPDX-License-Identifier: MIT */ #include "syscall.h" #include <liburing.h> int io_uring_enter(unsigned int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { return __sys_io_uring_enter(fd, to_submit, min_complete, flags, sig); } int io_uring_enter2(unsigned int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig, size_t sz) { return __sys_io_uring_enter2(fd, to_submit, min_complete, flags, sig, sz); } int io_uring_setup(unsigned int entries, struct io_uring_params *p) { return __sys_io_uring_setup(entries, p); } int io_uring_register(unsigned int fd, unsigned int opcode, const void *arg, unsigned int nr_args) { return __sys_io_uring_register(fd, opcode, arg, nr_args); }
/* SPDX-License-Identifier: MIT */
bootstrap_storage.ml
open Misc let init_account ctxt ({public_key_hash; public_key; amount} : Parameters_repr.bootstrap_account) = let contract = Contract_repr.implicit_contract public_key_hash in Contract_storage.credit ctxt contract amount >>=? fun ctxt -> match public_key with | Some public_key -> Contract_storage.reveal_manager_key ctxt public_key_hash public_key >>=? fun ctxt -> Delegate_storage.set ctxt contract (Some public_key_hash) | None -> return ctxt let init_contract ~typecheck ctxt ({delegate; amount; script} : Parameters_repr.bootstrap_contract) = Contract_storage.fresh_contract_from_current_nonce ctxt >>?= fun (ctxt, contract) -> typecheck ctxt script >>=? fun (script, ctxt) -> Contract_storage.raw_originate ctxt contract ~balance:amount ~prepaid_bootstrap_storage:true ~script ~delegate:(Some delegate) let init ctxt ~typecheck ?ramp_up_cycles ?no_reward_cycles accounts contracts = let nonce = Operation_hash.hash_bytes [Bytes.of_string "Un festival de GADT."] in let ctxt = Raw_context.init_origination_nonce ctxt nonce in fold_left_s init_account ctxt accounts >>=? fun ctxt -> fold_left_s (init_contract ~typecheck) ctxt contracts >>=? fun ctxt -> ( match no_reward_cycles with | None -> return ctxt | Some cycles -> (* Store pending ramp ups. *) let constants = Raw_context.constants ctxt in (* Start without rewards *) Raw_context.patch_constants ctxt (fun c -> { c with baking_reward_per_endorsement = [Tez_repr.zero]; endorsement_reward = [Tez_repr.zero]; }) >>= fun ctxt -> (* Store the final reward. *) Storage.Ramp_up.Rewards.init ctxt (Cycle_repr.of_int32_exn (Int32.of_int cycles)) (constants.baking_reward_per_endorsement, constants.endorsement_reward) ) >>=? fun ctxt -> match ramp_up_cycles with | None -> return ctxt | Some cycles -> (* Store pending ramp ups. *) let constants = Raw_context.constants ctxt in Tez_repr.(constants.block_security_deposit /? Int64.of_int cycles) >>?= fun block_step -> Tez_repr.(constants.endorsement_security_deposit /? Int64.of_int cycles) >>?= fun endorsement_step -> (* Start without security_deposit *) Raw_context.patch_constants ctxt (fun c -> { c with block_security_deposit = Tez_repr.zero; endorsement_security_deposit = Tez_repr.zero; }) >>= fun ctxt -> fold_left_s (fun ctxt cycle -> Tez_repr.(block_step *? Int64.of_int cycle) >>?= fun block_security_deposit -> Tez_repr.(endorsement_step *? Int64.of_int cycle) >>?= fun endorsement_security_deposit -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int cycle) in Storage.Ramp_up.Security_deposits.init ctxt cycle (block_security_deposit, endorsement_security_deposit)) ctxt (1 --> (cycles - 1)) >>=? fun ctxt -> (* Store the final security deposits. *) Storage.Ramp_up.Security_deposits.init ctxt (Cycle_repr.of_int32_exn (Int32.of_int cycles)) ( constants.block_security_deposit, constants.endorsement_security_deposit ) let cycle_end ctxt last_cycle = let next_cycle = Cycle_repr.succ last_cycle in Storage.Ramp_up.Rewards.find ctxt next_cycle >>=? (function | None -> return ctxt | Some (baking_reward_per_endorsement, endorsement_reward) -> Storage.Ramp_up.Rewards.remove_existing ctxt next_cycle >>=? fun ctxt -> Raw_context.patch_constants ctxt (fun c -> {c with baking_reward_per_endorsement; endorsement_reward}) >|= ok) >>=? fun ctxt -> Storage.Ramp_up.Security_deposits.find ctxt next_cycle >>=? function | None -> return ctxt | Some (block_security_deposit, endorsement_security_deposit) -> Storage.Ramp_up.Security_deposits.remove_existing ctxt next_cycle >>=? fun ctxt -> Raw_context.patch_constants ctxt (fun c -> {c with block_security_deposit; endorsement_security_deposit}) >|= ok
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
pyhash.h
#ifndef Py_HASH_H #define Py_HASH_H #ifdef __cplusplus extern "C" { #endif /* Helpers for hash functions */ #ifndef Py_LIMITED_API PyAPI_FUNC(Py_hash_t) _Py_HashDouble(PyObject *, double); PyAPI_FUNC(Py_hash_t) _Py_HashPointer(const void*); // Similar to _Py_HashPointer(), but don't replace -1 with -2 PyAPI_FUNC(Py_hash_t) _Py_HashPointerRaw(const void*); PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t); #endif /* Prime multiplier used in string and various other hashes. */ #define _PyHASH_MULTIPLIER 1000003UL /* 0xf4243 */ /* Parameters used for the numeric hash implementation. See notes for _Py_HashDouble in Python/pyhash.c. Numeric hashes are based on reduction modulo the prime 2**_PyHASH_BITS - 1. */ #if SIZEOF_VOID_P >= 8 # define _PyHASH_BITS 61 #else # define _PyHASH_BITS 31 #endif #define _PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1) #define _PyHASH_INF 314159 #define _PyHASH_IMAG _PyHASH_MULTIPLIER /* hash secret * * memory layout on 64 bit systems * cccccccc cccccccc cccccccc uc -- unsigned char[24] * pppppppp ssssssss ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t * ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeeeeeee pyexpat XML hash salt * * memory layout on 32 bit systems * cccccccc cccccccc cccccccc uc * ppppssss ........ ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*) * ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeee.... pyexpat XML hash salt * * (*) The siphash member may not be available on 32 bit platforms without * an unsigned int64 data type. */ #ifndef Py_LIMITED_API typedef union { /* ensure 24 bytes */ unsigned char uc[24]; /* two Py_hash_t for FNV */ struct { Py_hash_t prefix; Py_hash_t suffix; } fnv; /* two uint64 for SipHash24 */ struct { uint64_t k0; uint64_t k1; } siphash; /* a different (!) Py_hash_t for small string optimization */ struct { unsigned char padding[16]; Py_hash_t suffix; } djbx33a; struct { unsigned char padding[16]; Py_hash_t hashsalt; } expat; } _Py_HashSecret_t; PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret; #ifdef Py_DEBUG PyAPI_DATA(int) _Py_HashSecret_Initialized; #endif /* hash function definition */ typedef struct { Py_hash_t (*const hash)(const void *, Py_ssize_t); const char *name; const int hash_bits; const int seed_bits; } PyHash_FuncDef; PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void); #endif /* cutoff for small string DJBX33A optimization in range [1, cutoff). * * About 50% of the strings in a typical Python application are smaller than * 6 to 7 chars. However DJBX33A is vulnerable to hash collision attacks. * NEVER use DJBX33A for long strings! * * A Py_HASH_CUTOFF of 0 disables small string optimization. 32 bit platforms * should use a smaller cutoff because it is easier to create colliding * strings. A cutoff of 7 on 64bit platforms and 5 on 32bit platforms should * provide a decent safety margin. */ #ifndef Py_HASH_CUTOFF # define Py_HASH_CUTOFF 0 #elif (Py_HASH_CUTOFF > 7 || Py_HASH_CUTOFF < 0) # error Py_HASH_CUTOFF must in range 0...7. #endif /* Py_HASH_CUTOFF */ /* hash algorithm selection * * The values for Py_HASH_* are hard-coded in the * configure script. * * - FNV and SIPHASH* are available on all platforms and architectures. * - With EXTERNAL embedders can provide an alternative implementation with:: * * PyHash_FuncDef PyHash_Func = {...}; * * XXX: Figure out __declspec() for extern PyHash_FuncDef. */ #define Py_HASH_EXTERNAL 0 #define Py_HASH_SIPHASH24 1 #define Py_HASH_FNV 2 #define Py_HASH_SIPHASH13 3 #ifndef Py_HASH_ALGORITHM # ifndef HAVE_ALIGNED_REQUIRED # define Py_HASH_ALGORITHM Py_HASH_SIPHASH13 # else # define Py_HASH_ALGORITHM Py_HASH_FNV # endif /* uint64_t && uint32_t && aligned */ #endif /* Py_HASH_ALGORITHM */ #ifdef __cplusplus } #endif #endif /* !Py_HASH_H */
kicadLib_sigs.ml
open KicadSch_sigs type relcoord = RelCoord of int * int type circle = {center: relcoord; radius: int} type pin_orientation = P_L | P_R | P_U | P_D type pin_tag = string * size type pin = { name: pin_tag ; number: pin_tag ; length: size ; contact: relcoord ; orient: pin_orientation } type primitive = | Field | Polygon of int * relcoord list | Circle of int * circle | Pin of pin | Text of {c: relcoord; text: string; s: size} | Arc of { s: size ; radius: int ; sp: relcoord ; ep: relcoord ; center: relcoord } type elt = {parts: int; prim: primitive} type component = { names: string list ; draw_pnum: bool ; draw_pname: bool ; multi: bool ; graph: elt list }
dune
(library (name ucb1) (public_name prbnmcn-ucb1) (ocamlopt_flags (-warn-error -39)))
client_event_logging_commands.mli
val commands : unit -> Client_commands.command list
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
t-scalar_divexact_ui.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_mpoly.h" #include "ulong_extras.h" int main(void) { int i, j, result; FLINT_TEST_INIT(state); flint_printf("scalar_divexact_ui...."); fflush(stdout); /* Check (f*a)/a = f */ for (i = 0; i < 10 * flint_test_multiplier(); i++) { fmpz_mpoly_ctx_t ctx; fmpz_mpoly_t f, g, h; ulong c; slong len, coeff_bits, exp_bits; fmpz_mpoly_ctx_init_rand(ctx, state, 20); fmpz_mpoly_init(f, ctx); fmpz_mpoly_init(g, ctx); fmpz_mpoly_init(h, ctx); len = n_randint(state, 100); exp_bits = n_randint(state, 200) + 1; coeff_bits = n_randint(state, 200); for (j = 0; j < 10; j++) { fmpz_mpoly_randtest_bits(f, state, len, coeff_bits, exp_bits, ctx); fmpz_mpoly_randtest_bits(g, state, len, coeff_bits, exp_bits, ctx); fmpz_mpoly_randtest_bits(h, state, len, coeff_bits, exp_bits, ctx); c = n_randtest_not_zero(state); fmpz_mpoly_scalar_mul_ui(g, f, c, ctx); fmpz_mpoly_scalar_divexact_ui(h, g, c, ctx); result = fmpz_mpoly_equal(h, f, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check (f*a)/a = f\ni = %wd, j = %wd\n", i,j); fflush(stdout); flint_abort(); } } fmpz_mpoly_clear(f, ctx); fmpz_mpoly_clear(g, ctx); fmpz_mpoly_clear(h, ctx); } /* Check aliasing */ for (i = 0; i < 10 * flint_test_multiplier(); i++) { fmpz_mpoly_ctx_t ctx; fmpz_mpoly_t f, g, h; ulong c; slong len, coeff_bits, exp_bits; fmpz_mpoly_ctx_init_rand(ctx, state, 20); fmpz_mpoly_init(f, ctx); fmpz_mpoly_init(g, ctx); fmpz_mpoly_init(h, ctx); len = n_randint(state, 100); exp_bits = n_randint(state, 200) + 1; coeff_bits = n_randint(state, 200); for (j = 0; j < 10; j++) { fmpz_mpoly_randtest_bits(f, state, len, coeff_bits, exp_bits, ctx); fmpz_mpoly_randtest_bits(h, state, len, coeff_bits, exp_bits, ctx); c = n_randtest_not_zero(state); fmpz_mpoly_scalar_mul_ui(f, f, c, ctx); fmpz_mpoly_set(g, f, ctx); fmpz_mpoly_scalar_divexact_ui(h, f, c, ctx); fmpz_mpoly_scalar_divexact_ui(g, g, c, ctx); result = fmpz_mpoly_equal(g, h, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check aliasing\ni = %wd, j = %wd\n", i,j); fflush(stdout); flint_abort(); } } fmpz_mpoly_clear(f, ctx); fmpz_mpoly_clear(g, ctx); fmpz_mpoly_clear(h, ctx); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2017 William Hart This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
prm.ml
let () = let args = List.tl (Array.to_list Sys.argv) in let args = List.filter (fun arg -> String.length arg > 2 && arg.[0] = '-' && match arg.[1] with | 'l' | 'L' -> true | _ -> false ) args in print_string (String.concat " " args)
scene.mli
type command = | Move_to of float * float | Curve_to of float * float * float * float * float * float type color = float * float * float type ('color, 'font, 'text) element = | Path of command array * 'color option * 'color option | Polygon of (float * float) array * 'color option * 'color option | Ellipse of float * float * float * float * 'color option * 'color option | Text of float * float * 'text * 'font * 'color option * 'color option (****) val rectangle : float * float * float * float -> 'color option -> 'color option -> ('color, 'font, 'text) element (****) type ('color, 'font, 'text) t type cairo_t = (float * float * float, string * float, string) t val make : unit -> ('color, 'font, 'text) t val add : ('color, 'font, 'text) t -> ('color, 'font, 'text) element -> unit val get : ('color, 'font, 'text) t -> ('color, 'font, 'text) element array
(* Graph viewer * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 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_file_watcher_tests_linux.mli
test_fixed_nb_ticks.ml
(** Testing ------- Component: Wasm_pvm Invocation: dune exec src/lib_scoru_wasm/test/test_scoru_wasm.exe \ -- test "^Max nb of ticks$" Subject: WASM PVM evaluation tests for fixed nb of ticks per top level call *) open Tztest open Wasm_utils let loop_module = {| (module (memory 1) (export "mem"(memory 0)) (func (export "kernel_run") (loop $my_loop br $my_loop) ) ) |} let noop_module = {| (module (memory 1) (export "mem"(memory 0)) (func (export "kernel_run") nop ) ) |} let snapshot_tick = Z.one let input_tick = Z.one let test_looping_kernel () = let open Lwt_result_syntax in let max_nb_ticks = 5000L in (* This module loops indefinitely. *) let*! loop_module_tree = initial_tree ~max_tick:max_nb_ticks loop_module in let*! loop_module_tree = eval_until_input_requested loop_module_tree in let*! tree_with_dummy_input = set_empty_inbox_step 0l loop_module_tree in let* stuck, _ = eval_until_stuck tree_with_dummy_input in match stuck with | Too_many_ticks -> return_unit | _ -> failwith "second: Unexpected stuck state!" let test_noop_kernel () = let open Lwt_result_syntax in let max_nb_ticks = 5000L in (* This module does a noop. *) let*! noop_module_tree = initial_tree ~max_tick:max_nb_ticks noop_module in (* Eval until snapshot, which shouldn't take any tick since the default state is Snapshot. *) let*! tree_snapshotted = eval_until_input_requested noop_module_tree in (* Adds one input tick, part of the maximum number of ticks per toplevel call. *) let*! tree_with_dummy_input = set_empty_inbox_step 0l tree_snapshotted in let*! tree = eval_to_snapshot tree_with_dummy_input in let*! info = Wasm.get_info tree in (* Twice as much as max ticks, one to load the inbox, the other to execute. *) return (assert (Z.(info.current_tick = of_int64 Int64.(mul 2L max_nb_ticks)))) let test_stuck_in_decode_kernel () = let open Lwt_result_syntax in (* The PVM needs at least [4] ticks to load the smallest inbox possible: - 1 for Snapshot --> Collect - 1 for SOL - 1 for EOL - 1 for Collect -> Padding *) let max_nb_ticks = 4L in (* This module does a noop. *) let*! noop_module_tree = initial_tree ~max_tick:max_nb_ticks noop_module in let*! noop_module_tree = eval_until_input_requested noop_module_tree in (* Collect an inbox. *) let*! tree_with_dummy_input = set_empty_inbox_step 0l noop_module_tree in (* Eval one tick *) let* stuck, tree = eval_until_stuck tree_with_dummy_input in assert (stuck = Too_many_ticks) ; let*! info = Wasm.get_info tree in (* Twice as much as max ticks, one to load the inbox, the other to execute. *) return (assert (Z.(info.current_tick = of_int64 Int64.(mul 2L max_nb_ticks)))) let test_stuck_in_init_kernel () = let open Lwt_result_syntax in let max_nb_ticks = 1000L in (* This module does a noop. *) let*! noop_module_tree = initial_tree ~max_tick:max_nb_ticks noop_module in let*! noop_module_tree = eval_until_input_requested noop_module_tree in (* Adds one input tick, part of the maximum number of ticks per toplevel call. *) let*! tree_with_dummy_input = set_empty_inbox_step 0l noop_module_tree in (* go to first Init step *) let*! tree = eval_until_init tree_with_dummy_input in let*! stuck = Wasm.Internal_for_tests.is_stuck tree in assert (stuck = None) ; (* set maximum to next tick and eval one more time *) let*! info = Wasm.get_info tree in let previous_max_nb_ticks = Z.of_int64 max_nb_ticks in let new_max_nb_ticks = (* Remove the input step ticks *) Z.(succ (sub info.current_tick previous_max_nb_ticks)) in let*! tree = Wasm.Internal_for_tests.set_max_nb_ticks new_max_nb_ticks tree in let*! tree = Wasm.compute_step tree in (* Check is_stuck and current tick *) let*! info = Wasm.get_info tree in let*! stuck = Wasm.Internal_for_tests.is_stuck tree in assert (stuck = Some Too_many_ticks) ; return (assert (info.current_tick = Z.add previous_max_nb_ticks new_max_nb_ticks)) let tests = [ tztest "nb of ticks limited" `Quick test_looping_kernel; tztest "evaluation takes fixed nb of ticks" `Quick test_noop_kernel; tztest "stuck in decode" `Quick test_stuck_in_decode_kernel; tztest "stuck in init" `Quick test_stuck_in_init_kernel; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Marigold <contact@marigold.dev> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(cram (deps (glob_files bin/*.exe)))
test_uint.ml
open Conex_utils let ui = let module M = struct type t = Uint.t let pp ppf v = Format.pp_print_string ppf (Uint.to_string v) let equal a b = Uint.compare a b = 0 end in (module M: Alcotest.TESTABLE with type t = M.t) let the x = match Uint.of_string x with Some x -> x | None -> Alcotest.fail "cannot parse" let max = the "FFFFFFFFFFFFFFFF" let max_int64 = the "7FFFFFFFFFFFFFFF" let min_int64 = the "8000000000000000" let compare_initial () = Alcotest.(check int "compare 0 0 is 0" 0 Uint.(compare zero zero)) ; Alcotest.(check int "compare 0 max is -1" (-1) Uint.(compare zero max)) ; Alcotest.(check int "compare max 0 is 1" 1 Uint.(compare max zero)) ; Alcotest.(check int "compare 0 max_int64 is -1" (-1) Uint.(compare zero max_int64)) ; Alcotest.(check int "compare max_int64 0 is 1" 1 Uint.(compare max_int64 zero)) ; Alcotest.(check int "compare 0 min_int64 is -1" (-1) Uint.(compare zero min_int64)) ; Alcotest.(check int "compare min_int64 0 is 1" 1 Uint.(compare min_int64 zero)) let succ_initial () = Alcotest.(check bool "succ max overflows" true (fst (Uint.succ max))) ; let one = snd Uint.(succ zero) in Alcotest.(check (pair bool ui) "succ 0 no overflow and one" (false, one) Uint.(succ zero)) ; Alcotest.(check (pair bool ui) "succ max_int64 no overflow and min_int64" (false, min_int64) Uint.(succ max_int64)) ; Alcotest.(check bool "succ min_int64 no overflow" false (fst Uint.(succ min_int64))) let r () = let buf = Bytes.create 16 in let one i = let r = Random.int 16 in let ascii = r + (if r < 10 then 0x30 else 0x37) in Bytes.set buf i (char_of_int ascii) in for i = 0 to 15 do one i done ; Bytes.to_string buf let rec trim0 s = if String.get s 0 = '0' then trim0 (String.slice ~start:1 s) else s let to_of_str_id n () = for _i = 0 to n do let r = r () in Alcotest.(check string "to_of_string is identity" (trim0 r) Uint.(to_string (the r))) done let compare_random n () = for _i = 0 to n do let r = the (r ()) in let r = if r = Uint.zero then snd (Uint.succ r) else r in Alcotest.(check int ("compare " ^ Uint.to_string r ^ " 0 is 1") 1 Uint.(compare r zero)) ; Alcotest.(check int ("compare 0 " ^ Uint.to_string r ^ " is -1") (-1) Uint.(compare zero r)) ; Alcotest.(check int ("compare " ^ Uint.to_string r ^ " with itself is 0") 0 Uint.(compare r r)) ; if r = max then begin Alcotest.(check int ("compare " ^ Uint.to_string r ^ " max is 0") 0 Uint.(compare r max)) ; Alcotest.(check int ("compare max " ^ Uint.to_string r ^ " is 0") 0 Uint.(compare max r)) end else begin Alcotest.(check int ("compare " ^ Uint.to_string r ^ " max is -1") (-1) Uint.(compare r max)) ; Alcotest.(check int ("compare max " ^ Uint.to_string r ^ " is 1") 1 Uint.(compare max r)) ; end done let tests = [ "basic compare is good", `Quick, compare_initial ; "succ is good", `Quick, succ_initial ; "to/of_string is identity", `Quick, to_of_str_id 10000 ; "compare r zero is good", `Quick, compare_random 1000 ; ]
lissajous.ml
(**************************************************************************) (* Lablgtk - Examples *) (* *) (* This code is in the public domain. *) (* You may freely copy parts of it in your application. *) (* *) (**************************************************************************) (* $Id$ *) (* Lissajous $B?^7A(B *) let main () = let window = GWindow.window ~border_width: 10 () in window#event#connect#delete ~callback:(fun _ -> prerr_endline "Delete event occured"; true); window#connect#destroy ~callback:GMain.quit; let vbx = GPack.vbox ~packing:window#add () in let quit = GButton.button ~label:"Quit" ~packing:vbx#add () in quit#connect#clicked ~callback:window#destroy; let area = GMisc.drawing_area ~width:200 ~height:200 ~packing:vbx#add () in let drawing = area#misc#realize (); new GDraw.drawable (area#misc#window) in let m_pi = acos (-1.) in let c = ref 0. in let expose_event _ = drawing#set_foreground `WHITE; drawing#rectangle ~filled:true ~x:0 ~y:0 ~width:200 ~height:200 (); drawing#set_foreground `BLACK; (* drawing#line x:0 y:0 x:150 y:150; drawing#polygon filled:true [10,100; 35,35; 100,10; 10, 100]; *) let n = 200 in let r = 100. in let a = 3 in let b = 5 in for i=0 to n do let theta0 = 2.*.m_pi*.(float (i-1))/. (float n) in let x0 = 100 + (truncate (r*.sin ((float a)*.theta0))) in let y0 = 100 - (truncate (r*.cos ((float b)*.(theta0+. !c)))) in let theta1 = 2.*.m_pi*.(float i)/.(float n) in let x1 = 100 + (truncate (r*.sin((float a)*.theta1))) in let y1 = 100 - (truncate (r*.cos((float b)*.(theta1+. !c)))) in drawing#line ~x:x0 ~y:y0 ~x:x1 ~y:y1 done; false in area#event#connect#expose ~callback:expose_event; let timeout _ = c := !c +. 0.01*.m_pi; expose_event (); true in Timeout.add ~ms:500 ~callback:timeout; window#show (); GMain.main () let _ = Printexc.print main()
(**************************************************************************) (* Lablgtk - Examples *) (* *) (* This code is in the public domain. *) (* You may freely copy parts of it in your application. *) (* *) (**************************************************************************)
p2p_rejection.ml
open Error_monad type error_code = int type t = | No_motive | Too_many_connections | Already_connected | Unknown_chain_name | Deprecated_distributed_db_version | Deprecated_p2p_version | Unknown_motive of error_code let pp ppf motive = match motive with | No_motive -> Format.fprintf ppf "No motive" | Too_many_connections -> Format.fprintf ppf "Too many connections" | Already_connected -> Format.fprintf ppf "Already connected/connecting" | Unknown_chain_name -> Format.fprintf ppf "Unknown chain name" | Deprecated_distributed_db_version -> Format.fprintf ppf "Running a deprecated distributed db version" | Deprecated_p2p_version -> Format.fprintf ppf "Running a deprecated p2p layer version" | Unknown_motive error_code -> Format.fprintf ppf "Rejected for unknown reason, code (%i)" error_code let pp_short ppf motive = match motive with | No_motive -> Format.fprintf ppf "No motive" | Too_many_connections -> Format.fprintf ppf "Too many connections" | Already_connected -> Format.fprintf ppf "Already connected" | Unknown_chain_name -> Format.fprintf ppf "Unknown chain name" | Deprecated_distributed_db_version -> Format.fprintf ppf "Deprecated ddb version" | Deprecated_p2p_version -> Format.fprintf ppf "Deprecated p2p version" | Unknown_motive error_code -> Format.fprintf ppf "unknown code (%i)" error_code let encoding = let open Data_encoding in conv (function | No_motive -> 0 | Too_many_connections -> 1 | Unknown_chain_name -> 2 | Deprecated_p2p_version -> 3 | Deprecated_distributed_db_version -> 4 | Already_connected -> 5 | Unknown_motive error_code -> error_code) (function | 0 -> No_motive | 1 -> Too_many_connections | 2 -> Unknown_chain_name | 3 -> Deprecated_p2p_version | 4 -> Deprecated_distributed_db_version | 5 -> Already_connected | error_code -> Unknown_motive error_code) Data_encoding.int16 type error += Rejecting of {motive : t} let () = (* Rejecting socket connection with motive *) register_error_kind `Permanent ~id:"node.p2p_socket.rejecting_incoming" ~title:"Rejecting socket connection" ~description:"Rejecting peer connection with motive." ~pp:(fun ppf motive -> Format.fprintf ppf "Rejecting peer connection. Cause : %a." pp motive) Data_encoding.(obj1 (req "motive" encoding)) (function Rejecting {motive} -> Some motive | _ -> None) (fun motive -> Rejecting {motive}) let rejecting motive = Result_syntax.tzfail (Rejecting {motive})
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2019 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
sandbox_mode.mli
(** How to sandbox actions *) (** This module describes the method used to sandbox actions. Choices include: - not sandboxing - sandboxing by symlinking dependencies - sandboxing by copying dependencies - sandboxing by hardlinking dependencies - sandboxing by copying dependencies, detecting changes and patching back the source tree In the last mode, Dune applies all the changes that happened in the sandbox to the source tree. This includes: - applying changes to source files that were dependencies - deleting source files that were dependencies and were deleted in the sandbox - promoting all targets - promoting all files that were created and not declared as dependencies or targets This is a dirty setting, but it is necessary to port projects to Dune that don't use a separate directory and have rules that go and create/modify random files. *) open Import type some = | Symlink | Copy | Hardlink | Patch_back_source_tree type t = some option val compare : t -> t -> Ordering.t val equal : t -> t -> bool module Dict : sig type key = t type 'a t = { none : 'a ; symlink : 'a ; copy : 'a ; hardlink : 'a ; patch_back_source_tree : 'a } val compare : ('a -> 'a -> Ordering.t) -> 'a t -> 'a t -> Ordering.t val of_func : (key -> 'a) -> 'a t val get : 'a t -> key -> 'a end module Set : sig type key = t type t = bool Dict.t val singleton : key -> t (** For rules with (mode patch-back-source-tree). *) val patch_back_source_tree_only : t val is_patch_back_source_tree_only : t -> bool val equal : t -> t -> bool val compare : t -> t -> Ordering.t val of_func : (key -> bool) -> t val mem : t -> key -> bool val inter : t -> t -> t val to_dyn : t -> Dyn.t end (** We exclude [Some Patch_back_source_tree] because selecting this mode globally via the command line or the config file seems like a terrible choice. Also, we want to get rid of this mode eventually. *) val all_except_patch_back_source_tree : t list val all : t list val none : t val symlink : t val copy : t val hardlink : t val decode : t Dune_lang.Decoder.t val to_string : t -> string val to_dyn : t -> Dyn.t
(** How to sandbox actions *)
propagate_values_tactic.h
#pragma once #include "util/params.h" class ast_manager; class tactic; tactic * mk_propagate_values_tactic(ast_manager & m, params_ref const & p = params_ref()); /* ADD_TACTIC("propagate-values", "propagate constants.", "mk_propagate_values_tactic(m, p)") */
/*++ Copyright (c) 2011 Microsoft Corporation Module Name: propagate_values_tactic.h Abstract: Propagate values using equalities of the form (= t v) where v is a value, and atoms t and (not t) Author: Leonardo de Moura (leonardo) 2011-12-28. Revision History: --*/
dune
(rule (targets ocamlc) (action (copy %{ocamlc} %{targets}))) (rule (targets ocamlopt) (action (copy %{ocamlopt} %{targets})))
dune
(library (name eqaf) (public_name eqaf) (modules unsafe eqaf)) (rule (copy %{read:../config/which-unsafe-file} unsafe.ml)) (library (name eqaf_bigstring) (public_name eqaf.bigstring) (modules eqaf_bigstring) (libraries eqaf)) (library (name eqaf_cstruct) (public_name eqaf.cstruct) (modules eqaf_cstruct) (libraries cstruct eqaf.bigstring))
dhcp_ipv4.ml
open Lwt.Infix module Make(R : Mirage_random.S) (C : Mirage_clock.MCLOCK) (Time : Mirage_time.S) (Network : Mirage_net.S) (E : Ethernet.S) (Arp : Arp.S) = struct (* for now, just wrap a static ipv4 *) module DHCP = Dhcp_client_mirage.Make(R)(Time)(Network) include Static_ipv4.Make(R)(C)(E)(Arp) let connect net ethernet arp = DHCP.connect net >>= fun dhcp -> Lwt_stream.last_new dhcp >>= fun (cidr, gateway) -> connect ~cidr ?gateway ethernet arp end
float_physical_equality.ml
(* TEST *) let a = -0. let b = +0. let _ = assert(not (a == b)) let f () = let a = -0. in let b = +0. in assert(not (a == b))
(* TEST *)
jordan_transformation.c
#include "ca_mat.h" /* The algorithm is taken from jordan_form() in Sage */ /* Find a row vector v in the row span of V but not in the row span of W. Returns the index of such a vector. Returns -1 on failure. */ static slong vector_in_difference(const ca_mat_t V, const ca_mat_t W, ca_ctx_t ctx) { ca_mat_t U; ca_ptr v; ca_t t, u; slong i, j, k, l, n, found, rank; truth_t is_zero; if (ca_mat_nrows(V) == 0) return -1; if (ca_mat_nrows(W) == 0) return 0; n = ca_mat_ncols(W); found = -1; ca_mat_init(U, ca_mat_nrows(W), n, ctx); v = _ca_vec_init(n, ctx); ca_init(t, ctx); ca_init(u, ctx); if (ca_mat_rref(&rank, U, W, ctx)) { for (i = 0; i < ca_mat_nrows(V); i++) /* for candidate v in V */ { /* Copy of v for reduction */ _ca_vec_set(v, ca_mat_entry(V, i, 0), n, ctx); /* Reduce v by the rows in W */ for (j = 0; j < rank; j++) /* for each w in W */ { for (k = 0; k < n; k++) /* find pivot element in w */ { is_zero = ca_check_is_zero(ca_mat_entry(U, j, k), ctx); if (is_zero == T_UNKNOWN) goto cleanup; /* reduce by this row */ if (is_zero == T_FALSE) { ca_div(t, v + k, ca_mat_entry(U, j, k), ctx); for (l = 0; l < n; l++) { if (l == k) ca_zero(v + l, ctx); else { ca_mul(u, t, ca_mat_entry(U, j, l), ctx); ca_sub(v + l, v + l, u, ctx); } } break; } } } is_zero = _ca_vec_check_is_zero(v, n, ctx); if (is_zero == T_UNKNOWN) goto cleanup; if (is_zero == T_FALSE) { found = i; break; } } } cleanup: ca_mat_clear(U, ctx); _ca_vec_clear(v, n, ctx); ca_clear(t, ctx); ca_clear(u, ctx); return found; } /* note: doesn't support aliasing */ static void _ca_mat_mul_vec(ca_ptr res, const ca_mat_t mat, ca_srcptr v, ca_ctx_t ctx) { slong i; for (i = 0; i < ca_mat_nrows(mat); i++) { ca_dot(res + i, NULL, 0, ca_mat_entry(mat, i, 0), 1, v, 1, ca_mat_ncols(mat), ctx); } } static void ca_mat_transpose_resize(ca_mat_t B, const ca_mat_t A, ca_ctx_t ctx) { ca_mat_t T; ca_mat_init(T, ca_mat_ncols(A), ca_mat_nrows(A), ctx); ca_mat_transpose(T, A, ctx); ca_mat_swap(B, T, ctx); ca_mat_clear(T, ctx); } /* todo: special-case num_lambda == n (diagonalization) */ /* todo: also, for each vector */ /* todo: aliasing */ int ca_mat_jordan_transformation(ca_mat_t mat, const ca_vec_t lambda, slong num_blocks, slong * block_lambda, slong * block_size, const ca_mat_t A, ca_ctx_t ctx) { slong num_lambda, i, j, k, l, m, n, output_block, column_offset; slong *sizes, *counts; ca_mat_t B, Y, V1, V2, V1ker, V2ker; slong size, num_sizes, count, y_rows, v_index; int * written; int success; n = ca_mat_nrows(A); if (n == 0) return 1; num_lambda = ca_vec_length(lambda, ctx); /* Special-case diagonalization with distinct eigenvalues. */ /* TODO: also special-case eigenvalues with multiplicity 1 below. */ if (num_lambda == n) { success = 1; ca_mat_init(B, n, n, ctx); ca_mat_init(Y, 0, 0, ctx); for (i = 0; i < n; i++) { /* B = A - lambda */ for (j = 0; j < n; j++) for (k = 0; k < n; k++) if (j == k) ca_sub(ca_mat_entry(B, j, j), ca_mat_entry(A, j, j), ca_vec_entry(lambda, block_lambda[i]), ctx); else ca_set(ca_mat_entry(B, j, k), ca_mat_entry(A, j, k), ctx); success = ca_mat_right_kernel(Y, B, ctx); if (!success) break; if (ca_mat_ncols(Y) != 1) abort(); for (j = 0; j < n; j++) ca_set(ca_mat_entry(mat, j, i), ca_mat_entry(Y, j, 0), ctx); } ca_mat_clear(B, ctx); ca_mat_clear(Y, ctx); return success; } sizes = flint_malloc(sizeof(slong) * n); counts = flint_malloc(sizeof(slong) * n); written = flint_calloc(num_blocks, sizeof(int)); ca_mat_init(B, n, n, ctx); ca_mat_init(Y, 0, n, ctx); ca_mat_init(V1, n, n, ctx); ca_mat_init(V2, n, n, ctx); ca_mat_init(V1ker, 0, 0, ctx); ca_mat_init(V2ker, 0, 0, ctx); success = 1; for (i = 0; i < num_lambda; i++) { /* B = A - lambda */ for (j = 0; j < n; j++) for (k = 0; k < n; k++) if (j == k) ca_sub(ca_mat_entry(B, j, j), ca_mat_entry(A, j, j), ca_vec_entry(lambda, i), ctx); else ca_set(ca_mat_entry(B, j, k), ca_mat_entry(A, j, k), ctx); /* Group blocks as (block size, count) */ /* Todo: does this need to be sorted? */ num_sizes = 0; for (j = 0; j < num_blocks; j++) { if (block_lambda[j] == i) { for (k = 0; k < num_sizes; k++) { if (sizes[k] == block_size[j]) { counts[k]++; break; } } if (k == num_sizes) { sizes[num_sizes] = block_size[j]; counts[num_sizes] = 1; num_sizes++; } } } /* Y = matrix of row vectors spanning the Jordan chains for this eigenvalue. */ ca_mat_clear(Y, ctx); ca_mat_init(Y, n, n, ctx); y_rows = 0; /* Iterate over (block size, count) */ for (j = 0; j < num_sizes; j++) { size = sizes[j]; count = counts[j]; if (size == 0) flint_abort(); /* Find elements in ker(B^size) - ker(B^(size-1)) */ ca_mat_pow_ui_binexp(V2, B, size - 1, ctx); ca_mat_mul(V1, B, V2, ctx); success = ca_mat_right_kernel(V1ker, V1, ctx); if (!success) goto cleanup; success = ca_mat_right_kernel(V2ker, V2, ctx); if (!success) goto cleanup; /* rows instead of columns */ ca_mat_transpose_resize(V1ker, V1ker, ctx); ca_mat_transpose_resize(V2ker, V2ker, ctx); for (k = 0; k < count; k++) { /* Concatenate V2ker with Y */ ca_mat_t V2kerY; ca_mat_init(V2kerY, ca_mat_nrows(V2ker) + y_rows, n, ctx); for (m = 0; m < ca_mat_nrows(V2ker); m++) _ca_vec_set(ca_mat_entry(V2kerY, m, 0), ca_mat_entry(V2ker, m, 0), n, ctx); for (m = 0; m < y_rows; m++) _ca_vec_set(ca_mat_entry(V2kerY, ca_mat_nrows(V2ker) + m, 0), ca_mat_entry(Y, m, 0), n, ctx); v_index = vector_in_difference(V1ker, V2kerY, ctx); ca_mat_clear(V2kerY, ctx); if (v_index == -1) { success = 0; goto cleanup; } /* Position in output matrix to write chain. */ column_offset = 0; output_block = 0; while (1) { if (block_lambda[output_block] == i && block_size[output_block] == size && !written[output_block]) { written[output_block] = 1; break; } else { column_offset += block_size[output_block]; output_block++; } } /* chain = [v, B*v, ..., B^(size-1)*v] */ _ca_vec_set(ca_mat_entry(Y, y_rows, 0), ca_mat_entry(V1ker, v_index, 0), n, ctx); for (m = 1; m < size; m++) { _ca_mat_mul_vec(ca_mat_entry(Y, y_rows + m, 0), B, ca_mat_entry(Y, y_rows + m - 1, 0), ctx); } y_rows += size; /* Insert chain in the output matrix */ for (m = 0; m < size; m++) { for (l = 0; l < n; l++) ca_set(ca_mat_entry(mat, l, column_offset + m), ca_mat_entry(Y, y_rows - 1 - m, l), ctx); } } } } cleanup: flint_free(sizes); flint_free(counts); ca_mat_clear(B, ctx); ca_mat_clear(Y, ctx); ca_mat_clear(V1, ctx); ca_mat_clear(V2, ctx); ca_mat_clear(V1ker, ctx); ca_mat_clear(V2ker, ctx); flint_free(written); return success; }
/* Copyright (C) 2020 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/>. */
slot_repr.ml
type error += Invalid_slot of int let () = register_error_kind `Permanent ~id:"slot.invalid_slot" ~title:"invalid slot" ~description:"Invalid slot" ~pp:(fun ppf x -> Format.fprintf ppf "invalid slot: %d" x) Data_encoding.(obj1 (req "bad_slot" int31)) (function Invalid_slot x -> Some x | _ -> None) (fun x -> Invalid_slot x) include Compare.Int type slot = t (* TODO? should there be some assertions to verify that slots are never too big ? Or do that in a storage module that depends on constants ? *) let encoding = Data_encoding.uint16 let pp = Format.pp_print_int let zero = 0 let to_int x = x (* We assume 2^16 slots is big enough. We could increase that, but we would need to make sure there is no big performance penalty first. *) let max_value = (1 lsl 16) - 1 let of_int_do_not_use_except_for_parameters i = i let of_int i = if Compare.Int.(i < 0 || i > max_value) then error (Invalid_slot i) else ok i let succ slot = of_int (slot + 1) module Map = Map.Make (Compare.Int) module Set = Set.Make (Compare.Int) module Range = struct (* For now, we only need full intervals. If we ever need sparse ones, we could switch this representation to interval trees. [hi] and [lo] bounds are included. *) type t = Interval of {lo : int; hi : int} let create ~min ~count = error_when (min < 0) (Invalid_slot min) >>? fun () -> error_when (min > max_value) (Invalid_slot min) >>? fun () -> error_when (count < 1) (Invalid_slot count) >>? fun () -> error_when (count > max_value) (Invalid_slot count) >>? fun () -> let max = min + count - 1 in error_when (max > max_value) (Invalid_slot max) >>? fun () -> ok (Interval {lo = min; hi = max}) let fold f init (Interval {lo; hi}) = let rec loop ~acc ~next = if Compare.Int.(next > hi) then acc else loop ~acc:(f acc next) ~next:(next + 1) in loop ~acc:(f init lo) ~next:(lo + 1) let fold_es f init (Interval {lo; hi}) = let rec loop ~acc ~next = if Compare.Int.(next > hi) then return acc else f acc next >>=? fun acc -> loop ~acc ~next:(next + 1) in f init lo >>=? fun acc -> loop ~acc ~next:(lo + 1) let rev_fold_es f init (Interval {lo; hi}) = let rec loop ~acc ~next = if Compare.Int.(next < lo) then return acc else f acc next >>=? fun acc -> loop ~acc ~next:(next - 1) in f init hi >>=? fun acc -> loop ~acc ~next:(hi - 1) 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. *) (* *) (*****************************************************************************)
dune
(library (name incremental_step_function) (public_name incremental.incremental_step_function) (libraries core) (preprocess (pps ppx_jane)))
misc.mli
(** {2 Stuff} ****************************************************************) type 'a lazyt = unit -> 'a type 'a lazy_list_t = LCons of 'a * ('a lazy_list_t tzresult Lwt.t lazyt) type 'a lazy_list = 'a lazy_list_t tzresult Lwt.t (** Include bounds *) val (-->) : int -> int -> int list val (--->) : Int32.t -> Int32.t -> Int32.t list val pp_print_paragraph : Format.formatter -> string -> unit val take: int -> 'a list -> ('a list * 'a list) option (** Some (input with [prefix] removed), if string has [prefix], else [None] **) val remove_prefix: prefix:string -> string -> string option (** [remove nb list] remove the first [nb] elements from the list [list]. *) val remove_elem_from_list: int -> 'a list -> 'a list
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
vm.ml
open Tezos_scoru_wasm open Wasm_pvm_state.Internal_state include (Wasm_vm : Wasm_vm_sig.S) let compute_until_snapshot ~max_steps ?write_debug pvm_state = Wasm_vm.compute_step_many_until ~max_steps ?write_debug (fun pvm_state -> Lwt.return @@ match pvm_state.tick_state with | Snapshot -> false | _ -> Wasm_vm.should_compute pvm_state) pvm_state let compute_fast ~reveal_builtins ~write_debug pvm_state = let open Lwt.Syntax in (* Execute! *) (* TODO: https://gitlab.com/tezos/tezos/-/issues/4123 Support performing multiple calls to [Eval.compute]. *) let* durable = Exec.compute ~reveal_builtins ~write_debug pvm_state.durable pvm_state.buffers in (* The WASM PVM does several maintenance operations at the end of each [kernel_run] call, using the very last [Padding] tick. Instead of replicating the same logic in the Fast VM, we reuse it by crafting the PVM state just before that critical tick. *) let ticks = pvm_state.max_nb_ticks in let current_tick = Z.(pred @@ add pvm_state.last_top_level_call ticks) in let pvm_state = {pvm_state with durable; current_tick; tick_state = Padding} in (* Here, we don't reuse the [write_debug] argument, because we are in the [Padding] stage of the WASM PVM execution, so there is no WASM execution during this tick. Calling [compute_step_with_debug ~write_debug] has a significant performance cost, because the host functions registry is reconstructed. As a consequence of these two facts, we call [compute_step] to avoid this penalty.*) let+ pvm_state = Wasm_vm.compute_step pvm_state in (pvm_state, Z.to_int64 ticks) let rec compute_step_many accum_ticks ?reveal_builtins ?(write_debug = Builtins.Noop) ?(after_fast_exec = fun () -> ()) ?(stop_at_snapshot = false) ~max_steps pvm_state = let open Lwt.Syntax in assert (max_steps > 0L) ; let eligible_for_fast_exec = Z.Compare.(pvm_state.max_nb_ticks <= Z.of_int64 max_steps) in let backup pvm_state = let+ pvm_state, ticks = Wasm_vm.compute_step_many ?reveal_builtins ~write_debug ~stop_at_snapshot ~max_steps pvm_state in (pvm_state, Int64.add accum_ticks ticks) in match reveal_builtins with | Some reveal_builtins when eligible_for_fast_exec -> ( let goto_snapshot_and_retry () = let* pvm_state, ticks = compute_until_snapshot ~write_debug ~max_steps pvm_state in match pvm_state.tick_state with | Snapshot when not stop_at_snapshot -> let max_steps = Int64.sub max_steps ticks in let accum_ticks = Int64.add accum_ticks ticks in let may_compute_more = Wasm_vm.should_compute pvm_state in if may_compute_more && max_steps > 0L then (compute_step_many [@tailcall]) accum_ticks ~reveal_builtins ~write_debug ~stop_at_snapshot ~after_fast_exec ~max_steps pvm_state else Lwt.return (pvm_state, accum_ticks) | _ -> Lwt.return (pvm_state, ticks) in let go_like_the_wind () = let+ pvm_state, ticks = compute_fast ~write_debug ~reveal_builtins pvm_state in after_fast_exec () ; (pvm_state, Int64.(add ticks accum_ticks)) in match pvm_state.tick_state with | Snapshot -> Lwt.catch go_like_the_wind (fun _ -> backup pvm_state) | _ -> goto_snapshot_and_retry ()) | _ -> (* The number of ticks we're asked to do is lower than the maximum number of ticks for a top-level cycle or no builtins were supplied. Fast Execution cannot be applied in this case. *) backup pvm_state let compute_step_many = compute_step_many 0L module Internal_for_tests = struct let compute_step_many_with_hooks = compute_step_many end let compute_step_many = compute_step_many ?after_fast_exec:None
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 TriliTech <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. *) (* *) (*****************************************************************************)
inference.mli
(** Errors and their pretty-printing function *) type inference_error exception Ill_typed_script of inference_error val pp_inference_error : Format.formatter -> inference_error -> unit (** Comparability tag. *) type comparability = Comparable | Not_comparable | Unconstrained (** Michelson types. *) type michelson_type = | Base_type of {repr : Type.Base.t option; comparable : comparability} | Stack_type of Type.Stack.t option type transformer = {bef : Type.Stack.t; aft : Type.Stack.t} (** State of the type inference module *) (** Store implementation for type representatives *) module Repr_store : Stores.S with type key = int and type value = michelson_type (** State monad built on [Repr_store] *) module Repr_sm : Monads.State_sig with type state = Repr_store.state and type key = int and type value = michelson_type (** Store implementation for instruction type representatives *) module Annot_instr_store : Stores.S with type key = Mikhailsky.Path.t and type value = transformer (** State monad handling annotations on instructions *) module Annot_instr_sm : Monads.State_sig with type state = Annot_instr_store.state and type value = transformer and type key = Mikhailsky.Path.t (** Store implementation for data type representatives *) module Annot_data_store : Stores.S with type key = Mikhailsky.Path.t and type value = Type.Base.t (** State monad handling annotations on data *) module Annot_data_sm : Monads.State_sig with type state = Annot_data_store.state and type value = Type.Base.t and type key = Mikhailsky.Path.t (** State of the inference module *) type state = { uf : Uf.UF.M.state; repr : Repr_sm.state; annot_instr : Annot_instr_sm.state; annot_data : Annot_data_sm.state; } (** State monad of the inference module. *) module M : sig type 'a t = state -> 'a * state val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t val empty : unit -> state val return : 'a -> 'a t val set_repr : int -> michelson_type -> unit t val get_repr_exn : int -> michelson_type t val get_instr_annot : Annot_data_sm.key -> transformer option t val get_data_annot : Annot_data_sm.key -> Type.Base.t option t val uf_lift : 'a Uf.UF.M.t -> 'a t val repr_lift : 'a Repr_sm.t -> 'a t val annot_instr_lift : 'a Annot_instr_sm.t -> 'a t val annot_data_lift : 'a Annot_data_sm.t -> 'a t val get_state : state t end (** Unifies two stack types. *) val unify : Type.Stack.t -> Type.Stack.t -> unit M.t (** Unifies two base types. *) val unify_base : Type.Base.t -> Type.Base.t -> unit M.t (** Instantiate type variables with the associated terms in a base type. *) val instantiate_base : Type.Base.t -> Type.Base.t M.t (** Instantiate type variables with the associated terms in a stack type. *) val instantiate : Type.Stack.t -> Type.Stack.t M.t (** Get comparability flag for a base type. *) val get_comparability : Type.Base.t -> comparability M.t (** Performs inference on the given Mikhailsky term and returns its type (as a pair of [before] and [after] stack) as well as the inference engine state. *) val infer_with_state : Mikhailsky.node -> (Type.Stack.t * Type.Stack.t) * state (** Performs inference on the given Mikhailsky term and throws the inference engine state away. *) val infer : Mikhailsky.node -> Type.Stack.t * Type.Stack.t (** Performs inference on a piece of Mikhailsky [data] and returns the inference engine state along the inferred type. *) val infer_data_with_state : Mikhailsky.node -> Type.Base.t * state (** Performs inference on a piece of Mikhailsky [data] and returns the inferred type, throwing the inference engine state away. *) val infer_data : Mikhailsky.node -> Type.Base.t
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
spinlock.h
#ifndef UV_SPINLOCK_H_ #define UV_SPINLOCK_H_ #include "internal.h" /* ACCESS_ONCE, UV_UNUSED */ #include "atomic-ops.h" #define UV_SPINLOCK_INITIALIZER { 0 } typedef struct { int lock; } uv_spinlock_t; UV_UNUSED(static void uv_spinlock_init(uv_spinlock_t* spinlock)); UV_UNUSED(static void uv_spinlock_lock(uv_spinlock_t* spinlock)); UV_UNUSED(static void uv_spinlock_unlock(uv_spinlock_t* spinlock)); UV_UNUSED(static int uv_spinlock_trylock(uv_spinlock_t* spinlock)); UV_UNUSED(static void uv_spinlock_init(uv_spinlock_t* spinlock)) { ACCESS_ONCE(int, spinlock->lock) = 0; } UV_UNUSED(static void uv_spinlock_lock(uv_spinlock_t* spinlock)) { while (!uv_spinlock_trylock(spinlock)) cpu_relax(); } UV_UNUSED(static void uv_spinlock_unlock(uv_spinlock_t* spinlock)) { ACCESS_ONCE(int, spinlock->lock) = 0; } UV_UNUSED(static int uv_spinlock_trylock(uv_spinlock_t* spinlock)) { /* TODO(bnoordhuis) Maybe change to a ticket lock to guarantee fair queueing. * Not really critical until we have locks that are (frequently) contended * for by several threads. */ return 0 == cmpxchgi(&spinlock->lock, 0, 1); } #endif /* UV_SPINLOCK_H_ */
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl> * * 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. */
voting_period_repr.mli
(** The voting period kinds are ordered as follows: Proposal -> Testing_vote -> Testing -> Promotion_vote -> Adoption. This order is the one used be the function [succ] below. *) type kind = | Proposal (** protocols can be proposed *) | Testing_vote (** a proposal can be voted *) | Testing (** winning proposal is forked on a testnet *) | Promotion_vote (** activation can be voted *) | Adoption (** a delay before activation *) val kind_encoding : kind Data_encoding.t (** A voting period can be of 5 kinds and is uniquely identified by a counter since the root. *) type voting_period = {index : Int32.t; kind : kind; start_position : Int32.t} type t = voting_period type info = {voting_period : t; position : Int32.t; remaining : Int32.t} val root : start_position:Int32.t -> t include Compare.S with type t := voting_period val encoding : t Data_encoding.t val info_encoding : info Data_encoding.t val pp : Format.formatter -> t -> unit val pp_info : Format.formatter -> info -> unit val pp_kind : Format.formatter -> kind -> unit (** [reset period ~start_position] increment the index by one and set the kind to Proposal which is the period kind that start the voting process. [start_position] is the level at wich this voting_period started. *) val reset : t -> start_position:Int32.t -> t (** [succ period ~start_position] increment the index by one and set the kind to its successor. [start_position] is the level at which this voting_period started. *) val succ : t -> start_position:Int32.t -> t val position_since : Level_repr.t -> t -> Int32.t val remaining_blocks : Level_repr.t -> t -> blocks_per_voting_period:Int32.t -> Int32.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. *) (* *) (*****************************************************************************)
dune
(executable (name main) (libraries opium))
int32.mli
(** 32-bit integers. This module provides operations on the type [int32] of signed 32-bit integers. Unlike the built-in [int] type, the type [int32] is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over [int32] are taken modulo 2{^32}. Performance notice: values of type [int32] occupy more memory space than values of type [int], and arithmetic operations on [int32] are generally slower than those on [int]. Use [int32] only when the application requires exact 32-bit arithmetic. Literals for 32-bit integers are suffixed by l: {[ let zero: int32 = 0l let one: int32 = 1l let m_one: int32 = -1l ]} *) val zero : int32 (** The 32-bit integer 0. *) val one : int32 (** The 32-bit integer 1. *) val minus_one : int32 (** The 32-bit integer -1. *) external neg : int32 -> int32 = "%int32_neg" (** Unary negation. *) external add : int32 -> int32 -> int32 = "%int32_add" (** Addition. *) external sub : int32 -> int32 -> int32 = "%int32_sub" (** Subtraction. *) external mul : int32 -> int32 -> int32 = "%int32_mul" (** Multiplication. *) external div : int32 -> int32 -> int32 = "%int32_div" (** Integer division. Raise [Division_by_zero] if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for {!Stdlib.(/)}. *) external rem : int32 -> int32 -> int32 = "%int32_mod" (** Integer remainder. If [y] is not zero, the result of [Int32.rem x y] satisfies the following property: [x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)]. If [y = 0], [Int32.rem x y] raises [Division_by_zero]. *) val succ : int32 -> int32 (** Successor. [Int32.succ x] is [Int32.add x Int32.one]. *) val pred : int32 -> int32 (** Predecessor. [Int32.pred x] is [Int32.sub x Int32.one]. *) val abs : int32 -> int32 (** Return the absolute value of its argument. *) val max_int : int32 (** The greatest representable 32-bit integer, 2{^31} - 1. *) val min_int : int32 (** The smallest representable 32-bit integer, -2{^31}. *) external logand : int32 -> int32 -> int32 = "%int32_and" (** Bitwise logical and. *) external logor : int32 -> int32 -> int32 = "%int32_or" (** Bitwise logical or. *) external logxor : int32 -> int32 -> int32 = "%int32_xor" (** Bitwise logical exclusive or. *) val lognot : int32 -> int32 (** Bitwise logical negation. *) external shift_left : int32 -> int -> int32 = "%int32_lsl" (** [Int32.shift_left x y] shifts [x] to the left by [y] bits. The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right : int32 -> int -> int32 = "%int32_asr" (** [Int32.shift_right x y] shifts [x] to the right by [y] bits. This is an arithmetic shift: the sign bit of [x] is replicated and inserted in the vacated bits. The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right_logical : int32 -> int -> int32 = "%int32_lsr" (** [Int32.shift_right_logical x y] shifts [x] to the right by [y] bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of [x]. The result is unspecified if [y < 0] or [y >= 32]. *) external of_int : int -> int32 = "%int32_of_int" (** Convert the given integer (type [int]) to a 32-bit integer (type [int32]). On 64-bit platforms, the argument is taken modulo 2{^32}. *) external to_int : int32 -> int = "%int32_to_int" (** Convert the given 32-bit integer (type [int32]) to an integer (type [int]). On 32-bit platforms, the 32-bit integer is taken modulo 2{^31}, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. *) val of_string_opt: string -> int32 option (** Same as [of_string], but return [None] instead of raising. @since 4.05 *) val to_string : int32 -> string (** Return the string representation of its argument, in signed decimal. *) type t = int32 (** An alias for the type of 32-bit integers. *) val compare: t -> t -> int (** The comparison function for 32-bit integers, with the same specification as {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [Int32] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val equal: t -> t -> bool (** The equal function for int32s. @since 4.03.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. *) (* *) (**************************************************************************)
dune
(executable (name main) (modules main) (libraries uring bechamel bechamel_csv)) (executable (name readv) (modules readv) (libraries uring)) (executable (name cptest) (modules cptest) (libraries urcp_fixed_lib urcp_lib lwtcp_lib uring bechamel bechamel_csv)) (rule (alias runbenchmark) (package uring) (action (run ./cptest.exe)))
script_map.mli
(** Functions to ease the manipulation of Michelson maps. A map in Michelson is a type-homegeneous, partial function of keys to values, along with the functions that operate on the structure (through a first-class module). *) open Script_typed_ir val make : (module Boxed_map with type key = 'key and type value = 'value) -> ('key, 'value) map val get_module : ('key, 'value) map -> (module Boxed_map with type key = 'key and type value = 'value) (** [empty cmp_ty] creates a map module where keys have size [Gas_comparable_input_size.size_of_comparable_value cmp_ty] and are compared with [Script_comparable.compare_comparable cmp_ty] (used for sorting keys, which ensures a reasonable complexity of the map functions). The function returns an empty map packaged as a first-class map module. *) val empty : 'a comparable_ty -> ('a, 'b) map (** [empty_from map] creates an empty map module where the size of keys and the comparison function are those of [map]. *) val empty_from : ('a, 'b) map -> ('a, 'c) map val fold : ('key -> 'value -> 'acc -> 'acc) -> ('key, 'value) map -> 'acc -> 'acc val fold_es : ('key -> 'value -> 'acc -> 'acc tzresult Lwt.t) -> ('key, 'value) map -> 'acc -> 'acc tzresult Lwt.t (** [update k (Some v) map] associates [v] to [k] in [map] (overwriting the previous value, if any), and [update k None map] removes the potential association to [k] in [map]. *) val update : 'a -> 'b option -> ('a, 'b) map -> ('a, 'b) map val mem : 'key -> ('key, 'value) map -> bool val get : 'key -> ('key, 'value) map -> 'value option val size : ('a, 'b) map -> Script_int.n Script_int.num val map_es_in_context : ('context -> 'key -> 'value1 -> ('value2 * 'context) tzresult Lwt.t) -> 'context -> ('key, 'value1) map -> (('key, 'value2) map * 'context) tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *) (* 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. *) (* *) (*****************************************************************************)
irmin_fs.mli
(** Disk persistence. *) val config : ?config:Irmin.config -> string -> Irmin.config (** [config ?config root] is the configuration [config] augmented with the key {!Irmin.Config.root} set to [root]. If not specified, [config] is {!Irmin.Config.empty}. *) module type IO = sig (** {1 File-system abstractions} *) type path = string (** The type for paths. *) (** {2 Read operations} *) val rec_files : path -> string list Lwt.t (** [rec_files dir] is the list of files recursively present in [dir] and all of its sub-directories. Return filenames prefixed by [dir]. *) val file_exists : path -> bool Lwt.t (** [file_exist f] is true if [f] exists. *) val read_file : path -> string option Lwt.t (** Read the contents of a file using mmap. *) (** {2 Write Operations} *) val mkdir : path -> unit Lwt.t (** Create a directory. *) type lock (** The type for file locks. *) val lock_file : path -> lock (** [lock_file f] is the lock associated to the file [f]. *) val write_file : ?temp_dir:path -> ?lock:lock -> path -> string -> unit Lwt.t (** Atomic writes. *) val test_and_set_file : ?temp_dir:string -> lock:lock -> path -> test:string option -> set:string option -> bool Lwt.t (** Test and set. *) val remove_file : ?lock:lock -> path -> unit Lwt.t (** Remove a file or directory (even if non-empty). *) end module Append_only (IO : IO) : Irmin.APPEND_ONLY_STORE_MAKER module Atomic_write (IO : IO) : Irmin.ATOMIC_WRITE_STORE_MAKER module Make (IO : IO) : Irmin.S_MAKER module KV (IO : IO) : Irmin.KV_MAKER (** {2 Advanced configuration} *) module type Config = sig (** Same as [Config] but gives more control on the file hierarchy. *) val dir : string -> string (** [dir root] is the sub-directory to look for the keys. *) val file_of_key : string -> string (** Convert a key to a filename. *) val key_of_file : string -> string (** Convert a filename to a key. *) end module Append_only_ext (IO : IO) (C : Config) : Irmin.APPEND_ONLY_STORE_MAKER module Atomic_write_ext (IO : IO) (C : Config) : Irmin.ATOMIC_WRITE_STORE_MAKER module Make_ext (IO : IO) (Obj : Config) (Ref : Config) : Irmin.S_MAKER (** {1 In-memory IO mocks} *) module IO_mem : sig include IO val clear : unit -> unit Lwt.t val set_listen_hook : unit -> unit end
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
time_repr.mli
include module type of struct include Time end type time = t val pp : Format.formatter -> t -> unit val of_seconds_string : string -> time option val to_seconds_string : time -> string val ( +? ) : time -> Period_repr.t -> time tzresult val ( -? ) : time -> time -> Period_repr.t tzresult
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
mdx.mli
(** MDX integration *) open Import type t val enabled_if : t -> Blang.t type Stanza.t += T of t (** Generates the rules to handle the given mdx stanza *) val gen_rules : t -> sctx:Super_context.t -> dir:Path.Build.t -> scope:Scope.t -> expander:Expander.t -> unit Memo.t
(** MDX integration *)
field.ml
(* The type [t] should be abstract to make the fset and set functions unavailable for private types at the level of types (and not by putting None in the field). Unfortunately, making the type abstract means that when creating fields (through a [create] function) value restriction kicks in. This is worked around by instead not making the type abstract, but forcing anyone breaking the abstraction to use the [For_generated_code] module, making it obvious to any reader that something ugly is going on. t_with_perm (and derivatives) is the type that users really use. It is a constructor because: 1. it makes type errors more readable (less aliasing) 2. the typer in ocaml 4.01 allows this: {[ module A = struct type t = {a : int} end type t = A.t let f (x : t) = x.a ]} (although with Warning 40: a is used out of scope) which means that if [t_with_perm] was really an alias on [For_generated_code.t], people could say [t.setter] and break the abstraction with no indication that something ugly is going on in the source code. The warning is (I think) for people who want to make their code compatible with previous versions of ocaml, so we may very well turn it off. The type t_with_perm could also have been a [unit -> For_generated_code.t] to work around value restriction and then [For_generated_code.t] would have been a proper abstract type, but it looks like it could impact performance (for example, a fold on a record type with 40 fields would actually allocate the 40 [For_generated_code.t]'s at every single fold.) *) module For_generated_code = struct type ('perm, 'record, 'field) t = { force_variance : 'perm -> unit ; (* force [t] to be contravariant in ['perm], because phantom type variables on concrete types don't work that well otherwise (using :> can remove them easily) *) name : string ; setter : ('record -> 'field -> unit) option ; getter : 'record -> 'field ; fset : 'record -> 'field -> 'record } let opaque_identity = Sys0.opaque_identity end type ('perm, 'record, 'field) t_with_perm = | Field of ('perm, 'record, 'field) For_generated_code.t [@@unboxed] type ('record, 'field) t = ([ `Read | `Set_and_create ], 'record, 'field) t_with_perm type ('record, 'field) readonly_t = ([ `Read ], 'record, 'field) t_with_perm let name (Field field) = field.name let get (Field field) r = field.getter r let fset (Field field) r v = field.fset r v let setter (Field field) = field.setter type ('perm, 'record, 'result) user = { f : 'field. ('perm, 'record, 'field) t_with_perm -> 'result } let map (Field field) r ~f = field.fset r (f (field.getter r)) let updater (Field field) = match field.setter with | None -> None | Some setter -> Some (fun r ~f -> setter r (f (field.getter r))) ;;
(* The type [t] should be abstract to make the fset and set functions unavailable for private types at the level of types (and not by putting None in the field). Unfortunately, making the type abstract means that when creating fields (through a [create] function) value restriction kicks in. This is worked around by instead not making the type abstract, but forcing anyone breaking the abstraction to use the [For_generated_code] module, making it obvious to any reader that something ugly is going on. t_with_perm (and derivatives) is the type that users really use. It is a constructor because: 1. it makes type errors more readable (less aliasing) 2. the typer in ocaml 4.01 allows this: {[ module A = struct type t = {a : int} end type t = A.t let f (x : t) = x.a ]} (although with Warning 40: a is used out of scope) which means that if [t_with_perm] was really an alias on [For_generated_code.t], people could say [t.setter] and break the abstraction with no indication that something ugly is going on in the source code. The warning is (I think) for people who want to make their code compatible with previous versions of ocaml, so we may very well turn it off. The type t_with_perm could also have been a [unit -> For_generated_code.t] to work around value restriction and then [For_generated_code.t] would have been a proper abstract type, but it looks like it could impact performance (for example, a fold on a record type with 40 fields would actually allocate the 40 [For_generated_code.t]'s at every single fold.) *)
dune
(library (name alcotest_engine) (public_name alcotest.engine) (libraries alcotest.stdlib_ext fmt astring cmdliner fmt.cli re stdlib-shims uutf) (preprocess future_syntax))
leaf.mli
include Leaf_intf.Leaf
(* * Copyright (c) 2021 Tarides <contact@tarides.com> * Copyright (c) 2021 Gabriel Belouze <gabriel.belouze@ens.psl.eu> * * 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. *)
free.ml
open Source open Ast module Set = Set.Make (Int32) type t = { types : Set.t; globals : Set.t; tables : Set.t; memories : Set.t; funcs : Set.t; elems : Set.t; datas : Set.t; locals : Set.t; labels : Set.t; } let empty : t = { types = Set.empty; globals = Set.empty; tables = Set.empty; memories = Set.empty; funcs = Set.empty; elems = Set.empty; datas = Set.empty; locals = Set.empty; labels = Set.empty; } let union (s1 : t) (s2 : t) : t = { types = Set.union s1.types s2.types; globals = Set.union s1.globals s2.globals; tables = Set.union s1.tables s2.tables; memories = Set.union s1.memories s2.memories; funcs = Set.union s1.funcs s2.funcs; elems = Set.union s1.elems s2.elems; datas = Set.union s1.datas s2.datas; locals = Set.union s1.locals s2.locals; labels = Set.union s1.labels s2.labels; } let types s = {empty with types = s} |> Lwt.return let globals s = {empty with globals = s} |> Lwt.return let tables s = {empty with tables = s} |> Lwt.return let memories s = {empty with memories = s} |> Lwt.return let funcs s = {empty with funcs = s} |> Lwt.return let elems s = {empty with elems = s} |> Lwt.return let datas s = {empty with datas = s} |> Lwt.return let locals s = {empty with locals = s} |> Lwt.return let labels s = {empty with labels = s} |> Lwt.return let var x = Set.singleton x.it let zero = Set.singleton 0l let shift s = Set.map (Int32.add (-1l)) (Set.remove 0l s) let ( ++* ) x y = let open Lwt.Syntax in let* x' = x in let+ y' = y in union x' y' let list free xs = List.fold_left union empty (List.map free xs) let list_s free xs = let open Lwt.Syntax in let open Tezos_lwt_result_stdlib.Lwtreslib.Bare in List.fold_left_s (fun acc s -> let+ f = free s in union acc f) empty xs (* TODO: https://gitlab.com/tezos/tezos/-/issues/3387 This function is used during parsing (`MKElaborateFunc`), hence it will load entire vectors at once. *) let vector_s free v = let open Lwt.Syntax in let rec fold acc n = if n < 0l then Lwt.return acc else let* s = Vector.get n v in let* f = free s in fold (union acc f) (Int32.pred n) in fold empty (Int32.pred (Vector.num_elements v)) let vector free v = vector_s (fun x -> Lwt.return (free x)) v let opt free xo = match xo with None -> Lwt.return empty | Some v -> free v let block_type = function | VarBlockType x -> types (var x) | ValBlockType _ -> empty |> Lwt.return let rec instr blocks (e : instr) : t Lwt.t = let empty = Lwt.return empty in match e.it with | Unreachable | Nop | Drop | Select _ -> empty | RefNull _ | RefIsNull -> empty | RefFunc x -> funcs (var x) | Const _ | Test _ | Compare _ | Unary _ | Binary _ | Convert _ -> empty | Block (bt, es) | Loop (bt, es) -> block_type bt ++* block blocks es | If (bt, es1, es2) -> block_type bt ++* block blocks es1 ++* block blocks es2 | Br x | BrIf x -> labels (var x) | BrTable (xs, x) -> list_s (fun x -> labels (var x)) (x :: xs) | Return -> empty | Call x -> funcs (var x) | CallIndirect (x, y) -> tables (var x) ++* types (var y) | LocalGet x | LocalSet x | LocalTee x -> locals (var x) | GlobalGet x | GlobalSet x -> globals (var x) | TableGet x | TableSet x | TableSize x | TableGrow x | TableFill x -> tables (var x) | TableCopy (x, y) -> tables (var x) ++* tables (var y) | TableInit (x, y) -> tables (var x) ++* elems (var y) | ElemDrop x -> elems (var x) | Load _ | Store _ | VecLoad _ | VecStore _ | VecLoadLane _ | VecStoreLane _ | MemorySize | MemoryGrow | MemoryCopy | MemoryFill -> memories zero | VecConst _ | VecTest _ | VecUnary _ | VecBinary _ | VecCompare _ | VecConvert _ | VecShift _ | VecBitmask _ | VecTestBits _ | VecUnaryBits _ | VecBinaryBits _ | VecTernaryBits _ | VecSplat _ | VecExtract _ | VecReplace _ -> memories zero | MemoryInit x -> memories zero ++* datas (var x) | DataDrop x -> datas (var x) and block blocks (Block_label es : block_label) = let open Lwt.Syntax in let* bl = Vector.get es blocks in let+ free = vector_s (instr blocks) bl in {free with labels = shift free.labels} let const blocks (c : const) = block blocks c.it let global blocks (g : global) = const blocks g.it.ginit let func blocks (f : func) = let open Lwt.Syntax in let+ body = block blocks f.it.body in {body with locals = Set.empty} let table (_ : table) = empty let memory (_ : memory) = empty let segment_mode blocks f (m : segment_mode) = match m.it with | Passive | Declarative -> empty |> Lwt.return | Active {index; offset} -> f (var index) ++* const blocks offset let elem blocks (s : elem_segment) = vector_s (const blocks) s.it.einit ++* segment_mode blocks tables s.it.emode let data blocks _data (s : data_segment) = segment_mode blocks memories s.it.dmode let type_ (_ : type_) = empty let export_desc (d : export_desc) = match d.it with | FuncExport x -> funcs (var x) | TableExport x -> tables (var x) | MemoryExport x -> memories (var x) | GlobalExport x -> globals (var x) let import_desc (d : import_desc) = match d.it with | FuncImport x -> types (var x) | TableImport _ | MemoryImport _ | GlobalImport _ -> empty |> Lwt.return let export (e : export) = export_desc e.it.edesc let import (i : import) = import_desc i.it.idesc let start (s : start) = funcs (var s.it.sfunc) let module_ (m : module_) = vector type_ m.it.types ++* vector_s (global m.it.allocations.blocks) m.it.globals ++* vector table m.it.tables ++* vector memory m.it.memories ++* vector_s (func m.it.allocations.blocks) m.it.funcs ++* opt start m.it.start ++* vector_s (elem m.it.allocations.blocks) m.it.elems ++* vector_s (data m.it.allocations.blocks m.it.allocations.datas) m.it.datas ++* vector_s import m.it.imports ++* vector_s export m.it.exports
segment.ml
open Lwt.Infix let src = Logs.Src.create "tcp.segment" ~doc:"Mirage TCP Segment module" module Log = (val Logs.src_log src : Logs.LOG) let lwt_sequence_add_l s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_l s seq in () let lwt_sequence_add_r s seq = let (_:'a Lwt_dllist.node) = Lwt_dllist.add_r s seq in () let peek_opt_l seq = match Lwt_dllist.take_opt_l seq with | None -> None | Some s -> lwt_sequence_add_l s seq; Some s let peek_l seq = match Lwt_dllist.take_opt_l seq with | None -> assert false | Some s -> let _ = Lwt_dllist.add_l s seq in s let rec reset_seq segs = match Lwt_dllist.take_opt_l segs with | None -> () | Some _ -> reset_seq segs (* The receive queue stores out-of-order segments, and can coalesece them on input and pass on an ordered list up the stack to the application. It also looks for control messages and dispatches them to the Rtx queue to ack messages or close channels. *) module Rx(Time:Mirage_time.S)(ACK: Ack.M) = struct open Tcp_packet module StateTick = State.Make(Time) (* Individual received TCP segment TODO: this will change when IP fragments work *) type segment = { header: Tcp_packet.t; payload: Cstruct.t } let pp_segment fmt {header; payload} = Format.fprintf fmt "RX seg seq=%a acknum=%a ack=%b rst=%b syn=%b fin=%b win=%d len=%d" Sequence.pp header.sequence Sequence.pp header.ack_number header.ack header.rst header.syn header.fin header.window (Cstruct.length payload) let len seg = Sequence.of_int ((Cstruct.length seg.payload) + (if seg.header.fin then 1 else 0) + (if seg.header.syn then 1 else 0)) (* Set of segments, ordered by sequence number *) module S = Set.Make(struct type t = segment let compare a b = (Sequence.compare a.header.sequence b.header.sequence) end) type t = { mutable segs: S.t; rx_data: (Cstruct.t list option * Sequence.t option) Lwt_mvar.t; (* User receive channel *) ack: ACK.t; tx_ack: (Sequence.t * int) Lwt_mvar.t; (* Acks of our transmitted segs *) wnd: Window.t; state: State.t; } let create ~rx_data ~ack ~wnd ~state ~tx_ack = let segs = S.empty in { segs; rx_data; ack; tx_ack; wnd; state } let pp fmt t = let pp_v fmt seg = Format.fprintf fmt "%a[%a]" Sequence.pp seg.header.sequence Sequence.pp (len seg) in Format.pp_print_list pp_v fmt (S.elements t.segs) (* If there is a FIN flag at the end of this segment set. TODO: should look for a FIN and chop off the rest of the set as they may be orphan segments *) let fin q = try (S.max_elt q).header.fin with Not_found -> false let is_empty q = S.is_empty q.segs let check_valid_segment q seg = if seg.header.rst then begin match State.state q.state with | State.Reset -> `Drop | _ -> if Sequence.compare seg.header.sequence (Window.rx_nxt q.wnd) = 0 then `Reset else if Window.valid q.wnd seg.header.sequence then `ChallengeAck else `Drop end else if seg.header.syn then `ChallengeAck else if Window.valid q.wnd seg.header.sequence then let min = Sequence.(sub (Window.tx_una q.wnd) (of_int32 (Window.max_tx_wnd q.wnd))) in if Sequence.between seg.header.ack_number min (Window.tx_nxt q.wnd) then `Ok else (* rfc5961 5.2 *) `ChallengeAck else `Drop let send_challenge_ack q = (* TODO: rfc5961 ACK Throttling *) ACK.pushack q.ack Sequence.zero (* Given an input segment, the window information, and a receive queue, update the window, extract any ready segments into the user receive queue, and signal any acks to the Tx queue *) let input (q:t) seg = match check_valid_segment q seg with | `Ok -> let force_ack = ref false in (* Insert the latest segment *) let segs = S.add seg q.segs in (* Walk through the set and get a list of contiguous segments *) let ready, waiting = S.fold (fun seg acc -> match Sequence.compare seg.header.sequence (Window.rx_nxt_inseq q.wnd) with | (-1) -> (* Sequence number is in the past, probably an overlapping segment. Drop it for now, but TODO segment coalescing *) force_ack := true; acc | 0 -> (* This is the next segment, so put it into the ready set and update the receive ack number *) let (ready,waiting) = acc in Window.rx_advance_inseq q.wnd (len seg); (S.add seg ready), waiting | 1 -> (* Sequence is in the future, so can't use it yet *) force_ack := true; let (ready,waiting) = acc in ready, (S.add seg waiting) | _ -> assert false ) segs (S.empty, S.empty) in q.segs <- waiting; (* If the segment has an ACK, tell the transmit side *) let tx_ack = if seg.header.ack && (Sequence.geq seg.header.ack_number (Window.ack_seq q.wnd)) then begin StateTick.tick q.state (State.Recv_ack seg.header.ack_number); let data_in_flight = Window.tx_inflight q.wnd in let ack_has_advanced = (Window.ack_seq q.wnd) <> seg.header.ack_number in let win_has_changed = (Window.ack_win q.wnd) <> seg.header.window in if ((data_in_flight && (Window.ack_serviced q.wnd || not ack_has_advanced)) || (not data_in_flight && win_has_changed)) then begin Window.set_ack_serviced q.wnd false; Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt_mvar.put q.tx_ack ((Window.ack_seq q.wnd), (Window.ack_win q.wnd)) end else begin Window.set_ack_seq_win q.wnd seg.header.ack_number seg.header.window; Lwt.return_unit end end else Lwt.return_unit in (* Inform the user application of new data *) let urx_inform = (* TODO: deal with overlapping fragments *) let elems_r, winadv = S.fold (fun seg (acc_l, acc_w) -> (if Cstruct.length seg.payload > 0 then seg.payload :: acc_l else acc_l), (Sequence.add (len seg) acc_w) ) ready ([], Sequence.zero) in let elems = List.rev elems_r in let w = if !force_ack || Sequence.(gt winadv zero) then Some winadv else None in Lwt_mvar.put q.rx_data (Some elems, w) >>= fun () -> (* If the last ready segment has a FIN, then mark the receive window as closed and tell the application *) (if fin ready then begin if S.cardinal waiting != 0 then Log.info (fun f -> f "application receive queue closed, but there are waiting segments."); Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end else Lwt.return_unit) in tx_ack <&> urx_inform | `ChallengeAck -> send_challenge_ack q | `Drop -> Lwt.return_unit | `Reset -> StateTick.tick q.state State.Recv_rst; (* Abandon our current segments *) q.segs <- S.empty; (* Signal TX side *) let txalert ack_svcd = if not ack_svcd then Lwt.return_unit else Lwt_mvar.put q.tx_ack (Window.ack_seq q.wnd, Window.ack_win q.wnd) in txalert (Window.ack_serviced q.wnd) >>= fun () -> (* Use the fin path to inform the application of end of stream *) Lwt_mvar.put q.rx_data (None, Some Sequence.zero) end (* Transmitted segments are sent in-order, and may also be marked with control flags (such as urgent, or fin to mark the end). *) type tx_flags = (* At most one of Syn/Fin/Rst/Psh allowed *) | No_flags | Syn | Fin | Rst | Psh module Tx (Time:Mirage_time.S) (Clock:Mirage_clock.MCLOCK) = struct module StateTick = State.Make(Time) module TT = Tcptimer.Make(Time) module TX = Window.Make(Clock) type ('a, 'b) xmit = flags:tx_flags -> wnd:Window.t -> options:Options.t list -> seq:Sequence.t -> Cstruct.t -> ('a, 'b) result Lwt.t type seg = { data: Cstruct.t; flags: tx_flags; seq: Sequence.t; } (* Sequence length of the segment *) let len seg = Sequence.of_int ((match seg.flags with | No_flags | Psh | Rst -> 0 | Syn | Fin -> 1) + (Cstruct.length seg.data)) (* Queue of pre-transmission segments *) type ('a, 'b) q = { segs: seg Lwt_dllist.t; (* Retransmitted segment queue *) xmit: ('a, 'b) xmit; (* Transmit packet to the wire *) rx_ack: Sequence.t Lwt_mvar.t; (* RX Ack thread that we've sent one *) wnd: Window.t; (* TCP Window information *) state: State.t; (* state of the TCP connection associated with this queue *) tx_wnd_update: int Lwt_mvar.t; (* Received updates to the transmit window *) rexmit_timer: Tcptimer.t; (* Retransmission timer for this connection *) mutable dup_acks: int; (* dup ack count for re-xmits *) } type t = T: ('a, 'b) q -> t let ack_segment _ _ = () (* Take any action to the user transmit queue due to this being successfully ACKed *) (* URG_TODO: Add sequence number to the Syn_rcvd rexmit to only rexmit most recent *) let ontimer xmit st segs wnd seq = match State.state st with | State.Syn_rcvd _ | State.Established | State.Fin_wait_1 _ | State.Close_wait | State.Closing _ | State.Last_ack _ -> begin match peek_opt_l segs with | None -> Lwt.return Tcptimer.Stoptimer | Some rexmit_seg -> match rexmit_seg.seq = seq with | false -> Log.debug (fun fmt -> fmt "PUSHING TIMER - new time=%Lu, new seq=%a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret | true -> if (Window.max_rexmits_done wnd) then ( (* TODO - include more in log msg like ipaddrs *) Log.debug (fun f -> f "Max retransmits reached: %a" Window.pp wnd); Log.info (fun fmt -> fmt "Max retransmits reached for connection - terminating"); StateTick.tick st State.Timeout; Lwt.return Tcptimer.Stoptimer ) else ( let flags = rexmit_seg.flags in let options = [] in (* TODO: put the right options *) Log.debug (fun fmt -> fmt "TCP retransmission triggered by timer! seq = %d" (Sequence.to_int rexmit_seg.seq)); Lwt.async (fun () -> xmit ~flags ~wnd ~options ~seq rexmit_seg.data (* TODO should this return value really be ignored? *) >|= fun (_: ('a,'b) result) -> () ); Window.alert_fast_rexmit wnd rexmit_seg.seq; Window.backoff_rto wnd; Log.debug (fun fmt -> fmt "Backed off! %a" Window.pp wnd); Log.debug (fun fmt -> fmt "PUSHING TIMER - new time = %Lu, new seq = %a" (Window.rto wnd) Sequence.pp rexmit_seg.seq); let ret = Tcptimer.ContinueSetPeriod (Window.rto wnd, rexmit_seg.seq) in Lwt.return ret ) end | _ -> Lwt.return Tcptimer.Stoptimer let rec clearsegs q ack_remaining segs = match Sequence.(gt ack_remaining zero) with | false -> Sequence.zero (* here we return 0l instead of ack_remaining in case the ack was an old packet in the network *) | true -> match Lwt_dllist.take_opt_l segs with | None -> Log.debug (fun f -> f "Dubious ACK received"); ack_remaining | Some s -> let seg_len = (len s) in match Sequence.lt ack_remaining seg_len with | true -> Log.debug (fun f -> f "Partial ACK received"); (* return uncleared segment to the sequence *) lwt_sequence_add_l s segs; ack_remaining | false -> ack_segment q s; clearsegs q (Sequence.sub ack_remaining seg_len) segs let rto_t q tx_ack = (* Listen for incoming TX acks from the receive queue and ACK segments in our retransmission queue *) let rec tx_ack_t () = let serviceack dupack ack_len seq win = let partleft = clearsegs q ack_len q.segs in TX.tx_ack q.wnd (Sequence.sub seq partleft) win; match dupack || Window.fast_rec q.wnd with | true -> q.dup_acks <- q.dup_acks + 1; if q.dup_acks = 3 || (Sequence.to_int32 ack_len > 0l) then begin (* alert window module to fall into fast recovery *) Window.alert_fast_rexmit q.wnd seq; (* retransmit the bottom of the unacked list of packets *) let rexmit_seg = peek_l q.segs in Log.debug (fun fmt -> fmt "TCP fast retransmission seq=%a, dupack=%a" Sequence.pp rexmit_seg.seq Sequence.pp seq); let { wnd; _ } = q in let flags=rexmit_seg.flags in let options=[] in (* TODO: put the right options *) Lwt.async (fun () -> q.xmit ~flags ~wnd ~options ~seq rexmit_seg.data (* TODO should this return value really be ignored? *) >|= fun (_: ('a,'b) result) -> () ); Lwt.return_unit end else Lwt.return_unit | false -> q.dup_acks <- 0; Lwt.return_unit in Lwt_mvar.take tx_ack >>= fun _ -> Window.set_ack_serviced q.wnd true; let seq = Window.ack_seq q.wnd in let win = Window.ack_win q.wnd in begin match State.state q.state with | State.Reset -> (* Note: This is not strictly necessary, as the PCB will be GCed later on. However, it helps removing pressure on the GC. *) reset_seq q.segs; Lwt.return_unit | _ -> let ack_len = Sequence.sub seq (Window.tx_una q.wnd) in let dupacktest () = 0l = Sequence.to_int32 ack_len && Window.tx_wnd_unscaled q.wnd = Int32.of_int win && not (Lwt_dllist.is_empty q.segs) in serviceack (dupacktest ()) ack_len seq win end >>= fun () -> (* Inform the window thread of updates to the transmit window *) Lwt_mvar.put q.tx_wnd_update win >>= fun () -> tx_ack_t () in tx_ack_t () let create ~xmit ~wnd ~state ~rx_ack ~tx_ack ~tx_wnd_update = let segs = Lwt_dllist.create () in let dup_acks = 0 in let expire = ontimer xmit state segs wnd in let period_ns = Window.rto wnd in let rexmit_timer = TT.t ~period_ns ~expire in let q = { xmit; wnd; state; rx_ack; segs; tx_wnd_update; rexmit_timer; dup_acks } in let t = rto_t q tx_ack in T q, t (* Queue a segment for transmission. May block if: - There is no transmit window available. - The wire transmit function blocks. The transmitter should check that the segment size will will not be greater than the transmit window. *) let output ?(flags=No_flags) ?(options=[]) (T q) data = (* Transmit the packet to the wire TODO: deal with transmission soft/hard errors here RFC5461 *) let { wnd; _ } = q in let ack = Window.rx_nxt wnd in let seq = Window.tx_nxt wnd in let seg = { data; flags; seq } in let seq_len = len seg in TX.tx_advance q.wnd seq_len; (* Queue up segment just sent for retransmission if needed *) let q_rexmit () = match Sequence.(gt seq_len zero) with | false -> Lwt.return_unit | true -> lwt_sequence_add_r seg q.segs; let p = Window.rto q.wnd in TT.start q.rexmit_timer ~p seg.seq in q_rexmit () >>= fun () -> q.xmit ~flags ~wnd ~options ~seq data >>= fun _ -> (* Inform the RX ack thread that we've just sent one *) Lwt_mvar.put q.rx_ack ack end
(* * Copyright (c) 2010-2011 Anil Madhavapeddy <anil@recoil.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. *)
dune
(executables (names simple reporter) (libraries win-eventlog) (preprocess no_preprocessing))
test_singletons_and_empty.ml
module H : Hashtbl.HashedType with type t = int = struct type t = int let equal = (=) let hash = Hashtbl.hash end let test_em (module EM : Vache.MAP with type key = H.t) = let c = EM.create (-1) in let () = assert (EM.length c = 0) in let () = assert (EM.capacity c = 0) in let () = assert (EM.find_opt c 0 = None) in let () = EM.replace c 0 "zero" in let () = assert (EM.length c = 0) in let () = assert (EM.find_opt c 0 = None) in () let () = test_em (module Vache.EmptyMap(H)) let test_sm (module SM : Vache.MAP with type key = H.t) = let c = SM.create (-1) in let () = assert (SM.length c = 0) in let () = assert (SM.capacity c = 1) in let () = assert (SM.find_opt c 0 = None) in let () = SM.replace c 0 "zero" in let () = assert (SM.length c = 1) in let () = assert (SM.find_opt c 0 = Some "zero") in let () = SM.replace c 0 "ziro" in let () = assert (SM.length c = 1) in let () = assert (SM.find_opt c 0 = Some "ziro") in let () = SM.replace c 1 "one" in let () = assert (SM.length c = 1) in let () = assert (SM.find_opt c 1 = Some "one") in let () = assert (SM.find_opt c 0 = None) in () let () = test_sm (module Vache.SingletonMap(H)) let test_m (module V: Vache.MAP with type key = H.t) = let module M = struct include V let create _ = create 1 end in test_sm (module M) let () = test_m (module Vache.Map (Vache.LRU_Sloppy) (Vache.Strong) (H)) let () = test_m (module Vache.Map (Vache.LRU_Sloppy) (Vache.Weak) (H)) let () = test_m (module Vache.Map (Vache.LRU_Precise) (Vache.Strong) (H)) let () = test_m (module Vache.Map (Vache.LRU_Precise) (Vache.Weak) (H)) let () = test_m (module Vache.Map (Vache.FIFO_Sloppy) (Vache.Strong) (H)) let () = test_m (module Vache.Map (Vache.FIFO_Sloppy) (Vache.Weak) (H)) let () = test_m (module Vache.Map (Vache.FIFO_Precise) (Vache.Strong) (H)) let () = test_m (module Vache.Map (Vache.FIFO_Precise) (Vache.Weak) (H)) let test_es (module ES : Vache.SET with type elt = H.t) = let c = ES.create (-1) in let () = assert (ES.length c = 0) in let () = assert (ES.capacity c = 0) in let () = assert (not (ES.mem c 0)) in let () = ES.add c 0 in let () = assert (ES.length c = 0) in let () = assert (not (ES.mem c 0)) in () let () = test_es (module Vache.EmptySet(H)) let test_ss (module SS : Vache.SET with type elt = H.t) = let c = SS.create (-1) in let () = assert (SS.length c = 0) in let () = assert (SS.capacity c = 1) in let () = assert (not (SS.mem c 0)) in let () = SS.add c 0 in let () = assert (SS.length c = 1) in let () = assert (SS.mem c 0) in let () = SS.add c 1 in let () = assert (SS.length c = 1) in let () = assert (SS.mem c 1) in let () = assert (not (SS.mem c 0)) in () let () = test_ss (module Vache.SingletonSet(H)) let test_s (module V: Vache.SET with type elt = H.t) = let module M = struct include V let create _ = create 1 end in test_ss (module M) let () = test_s (module Vache.Set (Vache.LRU_Sloppy) (Vache.Strong) (H)) let () = test_s (module Vache.Set (Vache.LRU_Sloppy) (Vache.Weak) (H)) let () = test_s (module Vache.Set (Vache.LRU_Precise) (Vache.Strong) (H)) let () = test_s (module Vache.Set (Vache.LRU_Precise) (Vache.Weak) (H)) let () = test_s (module Vache.Set (Vache.FIFO_Sloppy) (Vache.Strong) (H)) let () = test_s (module Vache.Set (Vache.FIFO_Sloppy) (Vache.Weak) (H)) let () = test_s (module Vache.Set (Vache.FIFO_Precise) (Vache.Strong) (H)) let () = test_s (module Vache.Set (Vache.FIFO_Precise) (Vache.Weak) (H))
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
smart.ml
module type COMMON = sig type hash type reference type advertised_refs = { shallow: hash list ; refs: (hash * reference * bool) list ; capabilities: Capability.t list } type shallow_update = hash Sync.shallow_update type acks = hash Sync.acks type negociation_result = NAK | ACK of hash | ERR of string type pack = [`Raw of Cstruct.t | `Out of Cstruct.t | `Err of Cstruct.t] type report_status = { unpack: (unit, string) result ; commands: (reference, reference * string) result list } type upload_request = { want: hash * hash list ; capabilities: Capability.t list ; shallow: hash list ; deep: [`Depth of int | `Timestamp of int64 | `Ref of reference] option } type request_command = [`Upload_pack | `Receive_pack | `Upload_archive] type git_proto_request = { pathname: string ; host: (string * int option) option ; request_command: request_command } type command = | Create of hash * reference | Delete of hash * reference | Update of hash * hash * reference type push_certificate = { pusher: string ; pushee: string ; nonce: string ; options: string list ; commands: command list ; gpg: string list } type update_request = { shallow: hash list ; requests: [`Raw of command * command list | `Cert of push_certificate] ; capabilities: Capability.t list } type http_upload_request = { want: hash * hash list ; capabilities: Capability.t list ; shallow: hash list ; deep: [`Depth of int | `Timestamp of int64 | `Ref of reference] option ; has: hash list } val pp_advertised_refs : advertised_refs Fmt.t val pp_shallow_update : shallow_update Fmt.t val pp_acks : acks Fmt.t val pp_negociation_result : negociation_result Fmt.t val pp_pack : pack Fmt.t val pp_report_status : report_status Fmt.t val pp_upload_request : upload_request Fmt.t val pp_request_command : request_command Fmt.t val pp_git_proto_request : git_proto_request Fmt.t val pp_command : command Fmt.t val pp_push_certificate : push_certificate Fmt.t val pp_update_request : update_request Fmt.t val pp_http_upload_request : http_upload_request Fmt.t type 'a equal = 'a -> 'a -> bool val equal_advertised_refs : advertised_refs equal val equal_shallow_update : shallow_update equal val equal_acks : acks equal val equal_negociation_result : negociation_result equal val equal_pack : pack equal val equal_report_status : report_status equal val equal_upload_request : upload_request equal val equal_request_command : request_command equal val equal_git_proto_request : git_proto_request equal val equal_command : command equal val equal_push_certificate : push_certificate equal val equal_update_request : update_request equal val equal_http_upload_request : http_upload_request equal end module Common (Hash : S.HASH) (Reference : Reference.S with module Hash := Hash) = struct type hash = Hash.t type reference = Reference.t type 'a equal = 'a -> 'a -> bool type advertised_refs = { shallow: hash list ; refs: (hash * reference * bool) list ; capabilities: Capability.t list } let pp_advertised_refs ppf {shallow; refs; capabilities} = let pp_ref ppf (hash, reference, peeled) = match peeled with | true -> Fmt.pf ppf "%a^{}:%a" Reference.pp reference Hash.pp hash | false -> Fmt.pf ppf "%a:%a" Reference.pp reference Hash.pp hash in Fmt.pf ppf "{ @[<hov>shallow = %a;@ refs = %a;@ capabilities = %a;@]}" Fmt.Dump.(list Hash.pp) shallow Fmt.Dump.(list pp_ref) refs Fmt.Dump.(list Capability.pp) capabilities let equal_advertised_refs a b = let equal_ref (hash_a, ref_a, peeled_a) (hash_b, ref_b, peeled_b) = Hash.equal hash_a hash_b && Reference.equal ref_a ref_b && peeled_a = peeled_b in let compare_ref (_, a, _) (_, b, _) = Reference.compare a b in try List.for_all2 Hash.equal (List.sort Hash.compare a.shallow) (List.sort Hash.compare b.shallow) && List.for_all2 equal_ref (List.sort compare_ref a.refs) (List.sort compare_ref b.refs) && List.for_all2 Capability.equal (List.sort Capability.compare a.capabilities) (List.sort Capability.compare b.capabilities) with Invalid_argument _ -> false type shallow_update = hash Sync.shallow_update let pp_shallow_update ppf ({shallow; unshallow} : shallow_update) = Fmt.pf ppf "{ @[<hov>shallow = %a;@ unshallow = %a;@] }" Fmt.Dump.(list Hash.pp) shallow Fmt.Dump.(list Hash.pp) unshallow let equal_shallow_update (a : shallow_update) (b : shallow_update) = try List.for_all2 Hash.equal (List.sort Hash.compare a.shallow) (List.sort Hash.compare b.shallow) && List.for_all2 Hash.equal (List.sort Hash.compare a.unshallow) (List.sort Hash.compare b.unshallow) with Invalid_argument _ -> false type acks = hash Sync.acks let pp_acks ppf ({shallow; unshallow; acks} : acks) = let pp_ack ppf (hash, ack) = match ack with | `Continue -> Fmt.pf ppf "continue:%a" Hash.pp hash | `Ready -> Fmt.pf ppf "ready:%a" Hash.pp hash | `Common -> Fmt.pf ppf "common:%a" Hash.pp hash | `ACK -> Fmt.pf ppf "ACK:%a" Hash.pp hash in Fmt.pf ppf "{ @[<hov>shallow = %a;@ unshallow = %a;@ acks = %a;@] }" Fmt.Dump.(list Hash.pp) shallow Fmt.Dump.(list Hash.pp) unshallow Fmt.Dump.(list pp_ack) acks let equal_acks (a : acks) (b : acks) = let equal_ack (hash_a, detail_a) (hash_b, detail_b) = Hash.equal hash_a hash_b && match detail_a, detail_b with | `Common, `Common -> true | `Ready, `Ready -> true | `Continue, `Continue -> true | `ACK, `ACK -> true | _, _ -> false in let compare_ack (a, _) (b, _) = Hash.compare a b in try List.for_all2 Hash.equal (List.sort Hash.compare a.shallow) (List.sort Hash.compare b.shallow) && List.for_all2 Hash.equal (List.sort Hash.compare a.unshallow) (List.sort Hash.compare b.unshallow) && List.for_all2 equal_ack (List.sort compare_ack a.acks) (List.sort compare_ack b.acks) with Invalid_argument _ -> false type negociation_result = NAK | ACK of hash | ERR of string let pp_negociation_result ppf = function | NAK -> Fmt.string ppf "NAK" | ACK hash -> Fmt.pf ppf "(ACK %a)" Hash.pp hash | ERR err -> Fmt.pf ppf "(ERR %s)" err let equal_negociation_result a b = match a, b with | NAK, NAK -> true | ACK a, ACK b -> Hash.equal a b | ERR a, ERR b -> String.equal a b | _, _ -> false type pack = [`Raw of Cstruct.t | `Out of Cstruct.t | `Err of Cstruct.t] let pp_pack ppf = function | `Raw raw -> Fmt.pf ppf "@[<5>(Raw %a)@]" (Encore.Lole.pp_scalar ~get:Cstruct.get_char ~length:Cstruct.len) raw | `Out out -> Fmt.pf ppf "@[<5>(Out %S)@]" (Cstruct.to_string out) | `Err err -> Fmt.pf ppf "@[<5>(Err %S)@]" (Cstruct.to_string err) let equal_pack a b = match a, b with | `Err a, `Err b | `Out a, `Out b | `Raw a, `Raw b -> Cstruct.equal a b | _, _ -> false type report_status = { unpack: (unit, string) result ; commands: (reference, reference * string) result list } let pp_report_status ppf {unpack; commands} = Fmt.pf ppf "{ @[<hov>unpack = %a;@ commands = %a;@] }" Fmt.(Dump.result ~ok:Fmt.nop ~error:Fmt.string) unpack Fmt.( Dump.list (Dump.result ~ok:Reference.pp ~error:(pair Reference.pp string))) commands let equal_report_status a b = let equal_result ~ok ~error a b = match a, b with | Ok a, Ok b -> ok a b | Error a, Error b -> error a b | _, _ -> false in let compare_result ~ok ~error a b = match a, b with | Ok a, Ok b -> ok a b | Error a, Error b -> error a b | Ok _, Error _ -> 1 | Error _, Ok _ -> -1 in let compare_ref_and_msg (ref_a, msg_a) (ref_b, msg_b) = let res = Reference.compare ref_a ref_b in if res = 0 then String.compare msg_a msg_b else res in let equal_ref_and_msg a b = compare_ref_and_msg a b = 0 in try equal_result ~ok:(fun () () -> true) ~error:String.equal a.unpack b.unpack && List.for_all2 (equal_result ~ok:Reference.equal ~error:equal_ref_and_msg) (List.sort (compare_result ~ok:Reference.compare ~error:compare_ref_and_msg) a.commands) (List.sort (compare_result ~ok:Reference.compare ~error:compare_ref_and_msg) b.commands) with Invalid_argument _ -> false type upload_request = { want: hash * hash list ; capabilities: Capability.t list ; shallow: hash list ; deep: [`Depth of int | `Timestamp of int64 | `Ref of reference] option } let pp_upload_request ppf {want; capabilities; shallow; deep} = let pp_deep ppf = function | `Depth n -> Fmt.pf ppf "(Depth %d)" n | `Timestamp n -> Fmt.pf ppf "(Timestamp %Ld)" n | `Ref r -> Fmt.pf ppf "(`Ref %a)" Reference.pp r in Fmt.pf ppf "{ @[<hov>want = %a;@ capabiliteis = %a;@ shallow = %a; deep = %a;@] }" Fmt.(Dump.list Hash.pp) (fst want :: snd want) Fmt.(Dump.list Capability.pp) capabilities Fmt.(Dump.list Hash.pp) shallow Fmt.(Dump.option pp_deep) deep let equal_upload_request a b = try let equal_deep a b = match a, b with | `Depth a, `Depth b -> a = b | `Timestamp a, `Timestamp b -> Int64.equal a b | `Ref a, `Ref b -> Reference.equal a b | _, _ -> false in List.for_all2 Hash.equal (List.sort Hash.compare (fst a.want :: snd a.want)) (List.sort Hash.compare (fst b.want :: snd b.want)) && List.for_all2 Capability.equal (List.sort Capability.compare a.capabilities) (List.sort Capability.compare b.capabilities) && List.for_all2 Hash.equal (List.sort Hash.compare a.shallow) (List.sort Hash.compare b.shallow) && match a.deep, b.deep with | Some a, Some b -> equal_deep a b | None, None -> true | _, _ -> false with Invalid_argument _ -> false type request_command = [`Upload_pack | `Receive_pack | `Upload_archive] let equal_request_command a b = match a, b with | `Upload_pack, `Upload_pack |`Receive_pack, `Receive_pack |`Upload_archive, `Upload_archive -> true | _, _ -> true let pp_request_command ppf = function | `Upload_pack -> Fmt.string ppf "`Upload_pack" | `Receive_pack -> Fmt.string ppf "`Receive_pack" | `Upload_archive -> Fmt.string ppf "`Upload_archive" type git_proto_request = { pathname: string ; host: (string * int option) option ; request_command: request_command } let pp_git_proto_request ppf {pathname; host; request_command} = let pp_host ppf (host, port) = match port with | Some port -> Fmt.pf ppf "%s:%d" host port | None -> Fmt.string ppf host in Fmt.pf ppf "{ @[<hov>pathname = %s;@ host = %a;@ request_command = %a;@] }" pathname Fmt.(Dump.option pp_host) host pp_request_command request_command let equal_git_proto_request a b = let equal_option equal a b = match a, b with | Some a, Some b -> equal a b | None, None -> true | _, _ -> false in let equal_host (host_a, port_a) (host_b, port_b) = String.equal host_a host_b && equal_option ( = ) port_a port_b in String.equal a.pathname b.pathname && equal_option equal_host a.host b.host && equal_request_command a.request_command b.request_command type command = | Create of hash * reference | Delete of hash * reference | Update of hash * hash * reference let pp_command ppf = function | Create (hash, reference) -> Fmt.pf ppf "(Create %a:%a)" Reference.pp reference Hash.pp hash | Delete (hash, reference) -> Fmt.pf ppf "(Delete %a:%a)" Reference.pp reference Hash.pp hash | Update (a, b, reference) -> Fmt.pf ppf "(Create %a:@[<0>%a -> %a@])" Reference.pp reference Hash.pp a Hash.pp b let equal_command a b = match a, b with | Create (hash_a, ref_a), Create (hash_b, ref_b) -> Hash.equal hash_a hash_b && Reference.equal ref_a ref_b | Delete (hash_a, ref_a), Delete (hash_b, ref_b) -> Hash.equal hash_a hash_b && Reference.equal ref_a ref_b | Update (to_a, of_a, ref_a), Update (to_b, of_b, ref_b) -> Hash.equal to_a to_b && Hash.equal of_a of_b && Reference.equal ref_a ref_b | _, _ -> false type push_certificate = { pusher: string ; pushee: string ; nonce: string ; options: string list ; commands: command list ; gpg: string list } let pp_push_certificate ppf pcert = Fmt.pf ppf "{ @[<hov>pusher = %s;@ pushee = %s;@ nonce = %S;@ options = %a;@ \ commands = %a;@ gpg = %a;@] }" pcert.pusher pcert.pushee pcert.nonce Fmt.(Dump.list string) pcert.options Fmt.(Dump.list pp_command) pcert.commands Fmt.(Dump.list (fmt "%S")) pcert.gpg let compare_command a b = match a, b with | Create (hash_a, ref_a), Create (hash_b, ref_b) |Delete (hash_a, ref_a), Delete (hash_b, ref_b) -> let res = Hash.compare hash_a hash_b in if res = 0 then Reference.compare ref_a ref_b else res | Update (to_a, of_a, ref_a), Update (to_b, of_b, ref_b) -> let res = Hash.compare to_a to_b in if res = 0 then let res = Hash.compare of_a of_b in if res = 0 then Reference.compare ref_a ref_b else res else res | Create _, _ -> 1 | Delete _, Create _ -> -1 | Update _, Create _ -> -1 | Delete _, _ -> 1 | Update _, Delete _ -> -1 let equal_push_certificate a b = try String.equal a.pusher b.pusher && String.equal a.pushee b.pushee && String.equal a.nonce b.nonce && List.for_all2 String.equal (List.sort String.compare a.options) (List.sort String.compare b.options) && List.for_all2 equal_command (List.sort compare_command a.commands) (List.sort compare_command b.commands) with Invalid_argument _ -> false type update_request = { shallow: hash list ; requests: [`Raw of command * command list | `Cert of push_certificate] ; capabilities: Capability.t list } let pp_update_request ppf {shallow; requests; capabilities} = let pp_requests ppf = function | `Raw commands -> Fmt.(Dump.list pp_command) ppf (fst commands :: snd commands) | `Cert pcert -> pp_push_certificate ppf pcert in Fmt.pf ppf "{ @[<hov>shallow = %a;@ requests = %a;@ capabilities = %a;@] }" Fmt.(Dump.list Hash.pp) shallow (Fmt.hvbox pp_requests) requests Fmt.(Dump.list Capability.pp) capabilities let equal_update_request a b = let equal_raw a b = List.for_all2 equal_command (List.sort compare_command (fst a :: snd a)) (List.sort compare_command (fst b :: snd b)) in try List.for_all2 Hash.equal (List.sort Hash.compare a.shallow) (List.sort Hash.compare b.shallow) && ( match a.requests, b.requests with | `Raw a, `Raw b -> equal_raw a b | `Cert a, `Cert b -> equal_push_certificate a b | _, _ -> false ) && List.for_all2 Capability.equal (List.sort Capability.compare a.capabilities) (List.sort Capability.compare b.capabilities) with Invalid_argument _ -> false type http_upload_request = { want: hash * hash list ; capabilities: Capability.t list ; shallow: hash list ; deep: [`Depth of int | `Timestamp of int64 | `Ref of reference] option ; has: hash list } let equal_http_upload_request a b = try equal_upload_request { want= a.want ; capabilities= a.capabilities ; shallow= a.shallow ; deep= a.deep } { want= b.want ; capabilities= b.capabilities ; shallow= b.shallow ; deep= b.deep } && List.for_all2 Hash.equal (List.sort Hash.compare a.has) (List.sort Hash.compare b.has) with Invalid_argument _ -> false let pp_http_upload_request ppf {want; capabilities; shallow; deep; has} = let pp_deep ppf = function | `Depth n -> Fmt.pf ppf "(Depth %d)" n | `Timestamp n -> Fmt.pf ppf "(Timestamp %Ld)" n | `Ref r -> Fmt.pf ppf "(`Ref %a)" Reference.pp r in Fmt.pf ppf "{ @{<hov>want = %a;@ capabilities = %a;@ shallow = %a;@ deep = %a;@ \ has = %a;@} }" Fmt.(Dump.list Hash.pp) (fst want :: snd want) Fmt.(Dump.list Capability.pp) capabilities Fmt.(Dump.list Hash.pp) shallow Fmt.(Dump.option pp_deep) deep Fmt.(Dump.list Hash.pp) has end module type DECODER = sig module Hash : S.HASH module Reference : Reference.S with module Hash := Hash module Common : COMMON with type hash := Hash.t and type reference := Reference.t type decoder val pp_decoder : decoder Fmt.t val extract_payload : decoder -> Cstruct.t type error = [ `Expected_char of char | `Unexpected_char of char | `Unexpected_flush_pkt_line | `No_assert_predicate of char -> bool | `Expected_string of string | `Unexpected_empty_pkt_line | `Malformed_pkt_line | `Unexpected_end_of_input | `Unexpected_pkt_line | `Unexpected_hashes of Hash.t * Hash.t ] val pp_error : error Fmt.t type 'a state = | Ok of 'a | Read of {buffer: Cstruct.t; off: int; len: int; continue: int -> 'a state} | Error of {err: error; buf: Cstruct.t; committed: int} type _ transaction = | HttpReferenceDiscovery : string -> (Common.advertised_refs, [ `Msg of string ]) result transaction | ReferenceDiscovery : (Common.advertised_refs, [ `Msg of string ]) result transaction | ShallowUpdate : Common.shallow_update transaction | Negociation : Hash.Set.t * ack_mode -> Common.acks transaction | NegociationResult : Common.negociation_result transaction | PACK : side_band -> flow transaction | ReportStatus : string list * side_band -> Common.report_status transaction | HttpReportStatus : string list * side_band -> Common.report_status transaction | Upload_request : Common.upload_request transaction | Git_proto_request : Common.git_proto_request transaction | Update_request : Common.update_request transaction and ack_mode = [`Ack | `Multi_ack | `Multi_ack_detailed] and flow = [`Raw of Cstruct.t | `End | `Err of Cstruct.t | `Out of Cstruct.t] and side_band = [`Side_band | `Side_band_64k | `No_multiplexe] val decode : decoder -> 'result transaction -> 'result state val decoder : unit -> decoder val of_string : string -> 'v transaction -> ('v, error * Cstruct.t * int) result end module type ENCODER = sig module Hash : S.HASH module Reference : Reference.S with module Hash := Hash module Common : COMMON with type hash := Hash.t and type reference := Reference.t type encoder val set_pos : encoder -> int -> unit val free : encoder -> Cstruct.t type 'a state = | Write of { buffer: Cstruct.t ; off: int ; len: int ; continue: int -> 'a state } | Ok of 'a type action = [ `GitProtoRequest of Common.git_proto_request | `UploadRequest of Common.upload_request | `HttpUploadRequest of [`Done | `Flush] * Common.http_upload_request | `Advertised_refs of Common.advertised_refs | `Shallow_update of Common.shallow_update | `Negociation of Common.acks | `Negociation_result of Common.negociation_result | `Report_status of [`No_multiplexe | `Side_band | `Side_band_64k] * Common.report_status | `UpdateRequest of Common.update_request | `HttpUpdateRequest of Common.update_request | `Has of Hash.Set.t | `Done | `Flush | `Shallow of Hash.t list | `PACK of int ] val encode : encoder -> action -> unit state val encoder : unit -> encoder val to_string : action -> string end module type CLIENT = sig module Hash : S.HASH module Reference : Reference.S with module Hash := Hash module Common : COMMON with type hash := Hash.t and type reference := Reference.t module Decoder : DECODER with module Hash := Hash and module Reference := Reference and module Common := Common module Encoder : ENCODER with module Hash := Hash and module Reference := Reference and module Common := Common type context type result = [ `Refs of Common.advertised_refs | `ShallowUpdate of Common.shallow_update | `Negociation of Common.acks | `NegociationResult of Common.negociation_result | `PACK of Decoder.flow | `Flush | `Nothing | `ReadyPACK of Cstruct.t | `ReportStatus of Common.report_status | `SmartError of string ] type process = [ `Read of Cstruct.t * int * int * (int -> process) | `Write of Cstruct.t * int * int * (int -> process) | `Error of Decoder.error * Cstruct.t * int | result ] type action = [ `GitProtoRequest of Common.git_proto_request | `Shallow of Hash.t list | `UploadRequest of Common.upload_request | `UpdateRequest of Common.update_request | `Has of Hash.Set.t | `Done | `Flush | `ReceivePACK | `SendPACK of int | `FinishPACK of Reference.Set.t ] val capabilities : context -> Capability.t list val set_capabilities : context -> Capability.t list -> unit val encode : Encoder.action -> (context -> process) -> context -> process val decode : 'a Decoder.transaction -> ('a -> context -> process) -> context -> process val pp_result : result Fmt.t val run : context -> action -> process val context : Common.git_proto_request -> context * process end module Decoder (Hash : S.HASH) (Reference : Reference.S with module Hash := Hash) (Common : COMMON with type hash := Hash.t and type reference := Reference.t) = struct (* XXX(dinosaure): Why this decoder? We can use Angstrom instead or another library. It's not my first library about the parsing (see Mr. MIME) and I like a lot Angstrom. But I know the limitation about Angstrom and the best case to use it. I already saw other libraries like ocaml-imap specifically to find the best way to parse an email. You need all the time to handle the performance, the re-usability, the scalability and others constraints like the memory. So, about the smart Git protocol, I have the choice between Angstrom, something similar than the PACK decoder or this decoder. - Angstrom is good to describe the smart Git protocol. The expressivity is good and the performance is another good point. A part of Angstrom is about the alteration when you have some possibilities about the input. We have some examples when we compute the format of the Git object. And the best point is to avoid any headache to handle the input buffer about any alteration. I explained this specific point in the [Helper] module (which one provide a common non-blocking interface to decode something described by Angstrom). For all of this, it's a good way to use Angstrom in this case. But it's not the best. Indeed, the smart Git protocol is think in all state about the length of the input by the /pkt-line/ format. Which one describes all the time the length of the payload and limit this payload to 65520 bytes. So the big constraint about the alteration and when we need to keep some bytes in the current input buffer to retry the next alteration if the first one fails (and have a headache to handle the input) never happens. And if it's happen, the input is wrong. - like the PACK Decoder. If you look the PACK Decoder, it's another way to decode something in the non-blocking world. The good point is to handle all aspect of your decoder and, sometimes, describe a weird semantic about your decoder which is not available in Angstrom. You can do something hacky and wrap all in a good interface « à la Daniel Bünzli ». So if you want to do something fast and hacky in some contexts (like switch between a common functional way and a imperative way easily) because you know the constraint about your protocol/format, it's a good way. But you need a long time to do this and it is not easily composable like Angstrom because it's closely specific to your protocol/format. - like ocaml-imap. The IMAP protocol is very close to the smart Git protocol in some way and the interface seems to be good to have an user-friendly interface to communicate with a Git server without a big overhead because the decoder is funded on some assertions about the protocol (like the PKT line for the smart Git protocol or the end of line for the IMAP protocol). Then, the decoder is very hacky because we don't use the continuation all the time (like Angstrom) to keep a complex state but just fuck all up by an exception. And the composition between some conveniences primitives is easy (more easy than the second way). So for all of this, I decide to use this way to decode the smart Git protocol and provide a clear interface to the user (and keep a non-blocking land about all). So enjoy it! *) module Log = struct let src = Logs.Src.create "git.smart.decoder" ~doc:"logs git's smart decoder event" include (val Logs.src_log src : Logs.LOG) end type decoder = { mutable buffer: Cstruct.t ; mutable pos: int ; mutable eop: int option (* end of packet *) ; mutable max: int } let extract_payload decoder = Cstruct.sub decoder.buffer decoder.pos (decoder.max - decoder.pos) let pp_decoder ppf {buffer; pos; eop; max} = let pp = Encore.Lole.pp_scalar ~get:Cstruct.get_char ~length:Cstruct.len in match eop with | Some eop -> Fmt.pf ppf "{ @[<hov>current = %a;@ next = %a;@] }" (Fmt.hvbox pp) (Cstruct.sub buffer pos eop) (Fmt.hvbox pp) (Cstruct.sub buffer eop max) | None -> Fmt.pf ppf "#raw" type error = [ `Expected_char of char | `Unexpected_char of char | `Unexpected_flush_pkt_line | `No_assert_predicate of char -> bool | `Expected_string of string | `Unexpected_empty_pkt_line | `Malformed_pkt_line | `Unexpected_end_of_input | `Unexpected_pkt_line | `Unexpected_hashes of Hash.t * Hash.t ] let err_unexpected_end_of_input decoder = `Unexpected_end_of_input, decoder.buffer, decoder.pos let err_expected chr decoder = `Expected_char chr, decoder.buffer, decoder.pos let err_unexpected_char chr decoder = `Unexpected_char chr, decoder.buffer, decoder.pos let err_assert_predicate predicate decoder = `No_assert_predicate predicate, decoder.buffer, decoder.pos let err_expected_string s decoder = `Expected_string s, decoder.buffer, decoder.pos let err_unexpected_empty_pkt_line decoder = `Unexpected_empty_pkt_line, decoder.buffer, decoder.pos let err_malformed_pkt_line decoder = `Malformed_pkt_line, decoder.buffer, decoder.pos let err_unexpected_flush_pkt_line decoder = `Unexpected_flush_pkt_line, decoder.buffer, decoder.pos let err_unexpected_pkt_line decoder = `Unexpected_pkt_line, decoder.buffer, decoder.pos let err_unexpected_hashes h0 h1 decoder = `Unexpected_hashes (h0, h1), decoder.buffer, decoder.pos let pp_error ppf = function | `Expected_char chr -> Fmt.pf ppf "(`Expected_char %c)" chr | `Unexpected_char chr -> Fmt.pf ppf "(`Unexpected_char %c)" chr | `No_assert_predicate _ -> Fmt.pf ppf "(`No_assert_predicate #predicate)" | `Expected_string s -> Fmt.pf ppf "(`Expected_string %s)" s | `Unexpected_empty_pkt_line -> Fmt.pf ppf "`Unexpected_empty_pkt_line" | `Malformed_pkt_line -> Fmt.pf ppf "`Malformed_pkt_line" | `Unexpected_end_of_input -> Fmt.pf ppf "`Unexpected_end_of_input" | `Unexpected_flush_pkt_line -> Fmt.pf ppf "`Unexpected_flush_pkt_line" | `Unexpected_pkt_line -> Fmt.pf ppf "`Unexpected_pkt_line" | `Unexpected_hashes (h0, h1) -> Fmt.pf ppf "(`Unexpeted_hashes (%a, %a))" Hash.pp h0 Hash.pp h1 type 'a state = | Ok of 'a | Read of {buffer: Cstruct.t; off: int; len: int; continue: int -> 'a state} | Error of {err: error; buf: Cstruct.t; committed: int} exception Leave of (error * Cstruct.t * int) let p_return (type a) (x : a) _ : a state = Ok x let p_safe k decoder : 'a state = try k decoder with Leave (err, buf, pos) -> Error {err; buf; committed= pos} let p_end_of_input decoder = match decoder.eop with Some eop -> eop | None -> decoder.max let p_peek_char decoder = if decoder.pos < p_end_of_input decoder then Some (Cstruct.get_char decoder.buffer decoder.pos) else None let p_current decoder = if decoder.pos < p_end_of_input decoder then Cstruct.get_char decoder.buffer decoder.pos else raise (Leave (err_unexpected_end_of_input decoder)) let p_junk_char decoder = if decoder.pos < p_end_of_input decoder then decoder.pos <- decoder.pos + 1 else raise (Leave (err_unexpected_end_of_input decoder)) let p_char chr decoder = match p_peek_char decoder with | Some chr' when chr' = chr -> p_junk_char decoder | Some _ -> raise (Leave (err_expected chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) let p_satisfy predicate decoder = match p_peek_char decoder with | Some chr when predicate chr -> p_junk_char decoder ; chr | Some _ -> raise (Leave (err_assert_predicate predicate decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) let p_space decoder = p_char ' ' decoder let p_null decoder = p_char '\000' decoder let p_while1 predicate decoder = let i0 = decoder.pos in while decoder.pos < p_end_of_input decoder && predicate (Cstruct.get_char decoder.buffer decoder.pos) do decoder.pos <- decoder.pos + 1 done ; if i0 < decoder.pos then Cstruct.sub decoder.buffer i0 (decoder.pos - i0) else raise (Leave (err_unexpected_char (p_current decoder) decoder)) let p_while0 predicate decoder = let i0 = decoder.pos in while decoder.pos < p_end_of_input decoder && predicate (Cstruct.get_char decoder.buffer decoder.pos) do decoder.pos <- decoder.pos + 1 done ; Cstruct.sub decoder.buffer i0 (decoder.pos - i0) let p_string s decoder = let i0 = decoder.pos in let ln = String.length s in while decoder.pos < p_end_of_input decoder && decoder.pos - i0 < ln && s.[decoder.pos - i0] = Cstruct.get_char decoder.buffer decoder.pos do decoder.pos <- decoder.pos + 1 done ; if decoder.pos - i0 = ln then Cstruct.sub decoder.buffer i0 ln else raise (Leave (err_expected_string s decoder)) let p_hexdigit decoder = match p_satisfy (function '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true | _ -> false) decoder with | '0' .. '9' as chr -> Char.code chr - 48 | 'a' .. 'f' as chr -> Char.code chr - 87 | 'A' .. 'F' as chr -> Char.code chr - 55 | _ -> assert false let p_pkt_payload ?(strict = false) k decoder expect = let pkt = if expect < 0 then `Malformed else if expect = 0 then `Empty else `Line expect in if expect <= 0 then ( decoder.eop <- Some decoder.pos ; k ~pkt decoder ) else ( (* compress *) if decoder.pos > 0 then ( Cstruct.blit decoder.buffer decoder.pos decoder.buffer 0 (decoder.max - decoder.pos) ; decoder.max <- decoder.max - decoder.pos ; decoder.pos <- 0 ) ; let rec loop rest off = if rest <= 0 then ( let off, pkt = if Cstruct.get_char decoder.buffer (off + rest - 1) = '\n' && not strict then ( if rest < 0 then Cstruct.blit decoder.buffer (off + rest) decoder.buffer (off + rest - 1) (off - (off + rest)) ; off - 1, `Line (expect - 1) ) else off, `Line expect in decoder.max <- off ; decoder.eop <- Some (off + rest) ; p_safe (k ~pkt) decoder ) else if off >= Cstruct.len decoder.buffer then raise (Invalid_argument "PKT Format: payload upper than 65520 bytes") else Read { buffer= decoder.buffer ; off ; len= Cstruct.len decoder.buffer - off ; continue= (fun n -> loop (rest - n) (off + n)) } in loop (expect - (decoder.max - decoder.pos)) decoder.max ) let p_pkt_len_safe ?(strict = false) k decoder = let a = p_hexdigit decoder in let b = p_hexdigit decoder in let c = p_hexdigit decoder in let d = p_hexdigit decoder in let expect = (a * (16 * 16 * 16)) + (b * (16 * 16)) + (c * 16) + d in if expect = 0 then ( decoder.eop <- Some decoder.pos ; k ~pkt:`Flush decoder ) else p_pkt_payload ~strict k decoder (expect - 4) let p_pkt_line ?(strict = false) k decoder = decoder.eop <- None ; if decoder.max - decoder.pos >= 4 then p_pkt_len_safe ~strict k decoder else ( (* compress *) if decoder.pos > 0 then ( Cstruct.blit decoder.buffer decoder.pos decoder.buffer 0 (decoder.max - decoder.pos) ; decoder.max <- decoder.max - decoder.pos ; decoder.pos <- 0 ) ; let rec loop off = if off - decoder.pos >= 4 then ( decoder.max <- off ; p_safe (p_pkt_len_safe ~strict k) decoder ) else if off >= Cstruct.len decoder.buffer then raise (Invalid_argument "PKT Format: payload upper than 65520 bytes") else Read { buffer= decoder.buffer ; off ; len= Cstruct.len decoder.buffer - off ; continue= (fun n -> loop (off + n)) } in loop decoder.max ) let zero_id = String.make Hash.digest_size '\000' |> Hash.of_raw_string let p_hash decoder = p_while1 (function '0' .. '9' | 'a' .. 'f' -> true | _ -> false) decoder |> Cstruct.to_string |> Hash.of_hex let p_capability decoder = let capability = p_while1 (function | '\x61' .. '\x7a' | '0' .. '9' | '-' | '_' -> true | _ -> false) decoder |> Cstruct.to_string in match p_peek_char decoder with | Some '=' -> p_junk_char decoder ; let value = p_while1 (function '\033' .. '\126' -> true | _ -> false) decoder |> Cstruct.to_string in Capability.of_string ~value capability | _ -> Capability.of_string capability let p_capabilities1 decoder = let acc = [p_capability decoder] in let rec loop acc = match p_peek_char decoder with | Some ' ' -> p_junk_char decoder ; let capability = p_capability decoder in loop (capability :: acc) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> List.rev acc in loop acc let p_reference decoder = let refname = p_while1 (function | ' ' | '~' | '^' | ':' | '?' | '*' -> false | chr -> let code = Char.code chr in if code < 31 || code > 126 then false else true) decoder in Reference.of_string (Cstruct.to_string refname) let p_first_ref decoder = let obj_id = p_hash decoder in p_space decoder ; let reference = p_reference decoder in let peeled = match p_peek_char decoder with | Some '^' -> p_char '^' decoder ; p_char '{' decoder ; p_char '}' decoder ; true | Some _ -> false | None -> raise (Leave (err_unexpected_end_of_input decoder)) in p_null decoder ; let capabilities = match p_peek_char decoder with | Some ' ' -> p_junk_char decoder ; p_capabilities1 decoder | Some _ -> p_capabilities1 decoder | None -> raise (Leave (err_unexpected_end_of_input decoder)) in if Hash.equal obj_id zero_id && Reference.to_string reference = "capabilities" && peeled then `No_ref capabilities else `Ref ((obj_id, reference, peeled), capabilities) let p_shallow decoder = let _ = p_string "shallow" decoder in p_space decoder ; let obj_id = p_hash decoder in obj_id let p_unshallow decoder = let _ = p_string "unshallow" decoder in p_space decoder ; let obj_id = p_hash decoder in obj_id let p_other_ref decoder = let obj_id = p_hash decoder in p_space decoder ; let reference = p_reference decoder in let peeled = match p_peek_char decoder with | Some '^' -> p_char '^' decoder ; p_char '{' decoder ; p_char '}' decoder ; true | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> false in obj_id, reference, peeled type no_line = [`Empty | `Malformed | `Flush] let err_expected_line decoder = function | `Empty -> raise (Leave (err_unexpected_empty_pkt_line decoder)) | `Malformed -> raise (Leave (err_malformed_pkt_line decoder)) | `Flush -> raise (Leave (err_unexpected_flush_pkt_line decoder)) type no_line_and_flush = [`Empty | `Malformed] let err_expected_line_or_flush decoder = function | #no_line as v -> err_expected_line decoder v let p_pkt_flush k decoder = p_pkt_line (fun ~pkt decoder -> match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> k decoder | `Line _ -> raise (Leave (err_unexpected_pkt_line decoder)) ) decoder let p_advertised_refs ~pkt (advertised_refs : Common.advertised_refs) decoder = let rec go_shallows ~pkt (advertised_refs : Common.advertised_refs) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return (Rresult.R.ok advertised_refs) decoder | `Line _ -> ( match p_peek_char decoder with | Some 's' -> let hash = p_shallow decoder in p_pkt_line (go_shallows {advertised_refs with shallow= hash :: advertised_refs.shallow}) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let rec go_other_refs ~pkt (advertised_refs : Common.advertised_refs) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return (Rresult.R.ok advertised_refs) decoder | `Line _ -> ( match p_peek_char decoder with | Some 's' -> go_shallows ~pkt advertised_refs decoder | Some _ -> let x = p_other_ref decoder in p_pkt_line (go_other_refs {advertised_refs with refs= x :: advertised_refs.refs}) decoder | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let go_first_ref ~pkt (advertised_refs : Common.advertised_refs) decoder = match pkt with | `Flush -> p_return (Rresult.R.ok advertised_refs) decoder (* XXX(dinosaure): this is not explained by documentation but a server can just send [0000] and leave up. In this case, we return a an empty [advertised_refs] and close socket properly. *) | #no_line as v -> err_expected_line decoder v | `Line _ -> match p_peek_char decoder with | None -> raise (Leave (err_unexpected_end_of_input decoder)) | Some 'E' -> let err = p_while0 (fun _ -> true) decoder in p_return (Rresult.R.error_msg (Cstruct.to_string err)) decoder | Some _ -> match p_first_ref decoder with | `No_ref capabilities -> p_pkt_line (go_shallows {advertised_refs with capabilities}) decoder | `Ref (first, capabilities) -> p_pkt_line (go_other_refs {advertised_refs with capabilities; refs= [first]}) decoder in go_first_ref ~pkt advertised_refs decoder let p_http_advertised_refs ~service ~pkt decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> match p_peek_char decoder with | None -> raise (Leave (err_unexpected_end_of_input decoder)) | Some '#' -> ignore @@ p_string "# service=" decoder ; ignore @@ p_string service decoder ; p_pkt_line (fun ~pkt decoder -> match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_pkt_line (p_advertised_refs {shallow= []; refs= []; capabilities= []}) decoder | `Line _ as pkt -> p_advertised_refs ~pkt {shallow= []; refs= []; capabilities= []} decoder ) decoder | Some _ -> let err = p_while0 (fun _ -> true) decoder in p_return (Rresult.R.error_msg (Cstruct.to_string err)) decoder let p_advertised_refs decoder = p_pkt_line (p_advertised_refs {shallow= []; refs= []; capabilities= []}) decoder let p_http_advertised_refs ~service decoder = p_pkt_line (p_http_advertised_refs ~service) decoder let rec p_shallow_update ~pkt (shallow_update : Common.shallow_update) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return shallow_update decoder | `Line _ -> ( match p_peek_char decoder with | Some 's' -> let x = p_shallow decoder in p_pkt_line (p_shallow_update {shallow_update with shallow= x :: shallow_update.shallow}) decoder | Some 'u' -> let x = p_unshallow decoder in p_pkt_line (p_shallow_update {shallow_update with unshallow= x :: shallow_update.unshallow}) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) let p_shallow_update decoder = p_pkt_line (p_shallow_update {shallow= []; unshallow= []}) decoder let p_multi_ack_detailed decoder = ignore @@ p_string "ACK" decoder ; p_space decoder ; let hash = p_hash decoder in let detail = match p_peek_char decoder with | None -> raise (Leave (err_unexpected_end_of_input decoder)) | Some ' ' -> ( p_junk_char decoder ; match p_peek_char decoder with | Some 'r' -> ignore @@ p_string "ready" decoder ; `Ready | Some 'c' -> ignore @@ p_string "common" decoder ; `Common | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) in hash, detail let p_multi_ack decoder = ignore @@ p_string "ACK" decoder ; p_space decoder ; let hash = p_hash decoder in p_space decoder ; ignore @@ p_string "continue" decoder ; hash let p_ack decoder = ignore @@ p_string "ACK" decoder ; p_space decoder ; let hash = p_hash decoder in hash let p_negociation_result ~pkt k decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> ( match p_peek_char decoder with | Some 'N' -> ignore @@ p_string "NAK" decoder ; k Common.NAK decoder | Some 'A' -> ignore @@ p_string "ACK" decoder ; p_space decoder ; let hash = p_hash decoder in k (Common.ACK hash) decoder | Some 'E' -> ignore @@ p_string "ERR" decoder ; p_space decoder ; let msg = Cstruct.to_string @@ p_while1 (fun _ -> true) decoder in k (Common.ERR msg) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) let p_negociation_one ~pkt ~mode k decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> ( match p_peek_char decoder, mode with | Some 's', _ -> let x = p_shallow decoder in k (`Shallow x) decoder | Some 'u', _ -> let x = p_unshallow decoder in k (`Unshallow x) decoder | Some 'A', `Multi_ack_detailed -> let hash, detail = p_multi_ack_detailed decoder in k (`Ack (hash, detail)) decoder | Some 'A', `Multi_ack -> let hash = p_multi_ack decoder in k (`Ack (hash, `Continue)) decoder | Some 'A', `Ack -> let hash = p_ack decoder in k (`Ack (hash, `ACK)) decoder | Some 'N', _ -> ignore @@ p_string "NAK" decoder ; k `Nak decoder | Some chr, _ -> raise (Leave (err_unexpected_char chr decoder)) | None, _ -> raise (Leave (err_unexpected_end_of_input decoder)) ) let p_negociation ~mode k hashes (acks : Common.acks) decoder = let rec go hashes (acks : Common.acks) v decoder = match v with | `Shallow hash -> let acks = {acks with shallow= hash :: acks.shallow} in p_pkt_line (p_negociation_one ~mode (go hashes acks)) decoder | `Unshallow hash -> let acks = {acks with unshallow= hash :: acks.unshallow} in p_pkt_line (p_negociation_one ~mode (go hashes acks)) decoder | `Ack (hash, `ACK) (* when mode = `Ack *) -> k {acks with acks= [hash, `ACK]} decoder | `Ack (hash, detail) -> let hashes = Hash.Set.remove hash hashes in let acks = {acks with acks= (hash, detail) :: acks.acks} in p_pkt_line (p_negociation_one ~mode (go hashes acks)) decoder | `Nak -> k acks decoder in p_pkt_line (p_negociation_one ~mode (go hashes acks)) decoder let p_negociation ~mode hashes decoder = p_negociation ~mode p_return hashes {shallow= []; unshallow= []; acks= []} decoder let p_pack ~pkt ~mode decoder = match pkt, mode with | (#no_line_and_flush as v), _ -> err_expected_line_or_flush decoder v | `Line n, `No_multiplexe -> let raw = Cstruct.sub decoder.buffer decoder.pos n in decoder.pos <- decoder.pos + n ; p_return (`Raw raw) decoder | `Flush, _ -> p_return `End decoder | `Line n, (`Side_band_64k | `Side_band) -> ( let raw = Cstruct.sub decoder.buffer (decoder.pos + 1) (n - 1) in match p_peek_char decoder with | Some '\001' -> decoder.pos <- decoder.pos + n ; p_return (`Raw raw) decoder | Some '\002' -> decoder.pos <- decoder.pos + n ; p_return (`Out raw) decoder | Some '\003' -> decoder.pos <- decoder.pos + n ; p_return (`Err raw) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) let p_negociation_result decoder = p_pkt_line (p_negociation_result p_return) decoder let p_pack ~mode decoder = p_pkt_line ~strict:true (p_pack ~mode) decoder let p_unpack decoder : (unit, string) result = ignore @@ p_string "unpack" decoder ; p_space decoder ; let msg = p_while1 (fun _ -> true) decoder in match Cstruct.to_string msg with "ok" -> Ok () | err -> Error err let p_command_status decoder : (Reference.t, Reference.t * string) result = let status = p_while1 (function ' ' -> false | _ -> true) decoder in match Cstruct.to_string status with | "ok" -> p_space decoder ; let reference = p_reference decoder in Ok reference | "ng" -> p_space decoder ; let reference = p_reference decoder in p_space decoder ; let msg = p_while1 (fun _ -> true) decoder |> Cstruct.to_string in Error (reference, msg) | _ -> raise (Leave (err_unexpected_char '\000' decoder)) let rec p_report_status ~pkt ~unpack ~commands ~sideband decoder = let go unpack commands sideband decoder = match p_peek_char decoder with | Some 'u' -> let unpack = p_unpack decoder in p_pkt_line (p_report_status ~unpack:(Some unpack) ~commands ~sideband) decoder | Some ('o' | 'n') -> let command = p_command_status decoder in let commands = match commands with | Some lst -> Some (command :: lst) | None -> Some [command] in p_pkt_line (p_report_status ~unpack ~commands ~sideband) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) in match pkt, sideband, unpack, commands with | (#no_line_and_flush as v), _, _, _ -> err_expected_line_or_flush decoder v | `Flush, _, Some unpack, Some (_ :: _ as commands) -> p_return {Common.unpack; commands} decoder | `Flush, _, _, _ -> raise (Leave (err_unexpected_flush_pkt_line decoder)) | `Line _, (`Side_band | `Side_band_64k), _, _ -> ( match p_peek_char decoder with | Some '\001' -> p_junk_char decoder ; (* XXX(dinosaure): [git] wraps it inside a PKT-line. *) go unpack commands sideband decoder | Some '\002' -> ignore @@ p_while0 (fun _ -> true) decoder ; p_pkt_line (p_report_status ~unpack ~commands ~sideband) decoder | Some '\003' -> ignore @@ p_while0 (fun _ -> true) decoder ; p_pkt_line (p_report_status ~unpack ~commands ~sideband) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_empty_pkt_line decoder)) ) | `Line _, `No_multiplexe, _, _ -> go unpack commands sideband decoder let rec p_http_report_status ~pkt ?unpack ?(commands = []) ~sideband ~references decoder = let go_unpack ~pkt k decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> ( match p_peek_char decoder with | Some 'u' -> let unpack = p_unpack decoder in k unpack decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let go_command ~pkt kcons kfinal decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> kfinal decoder | `Line _ -> ( match p_peek_char decoder with | Some ('o' | 'n') -> let command = p_command_status decoder in kcons command decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in match pkt, sideband, unpack with | (#no_line as v), _, _ -> err_expected_line decoder v | `Line _, (`Side_band | `Side_band_64k), unpack -> ( match p_peek_char decoder with | Some '\001' -> ( p_junk_char decoder ; match unpack with | None -> let k unpack decoder = p_pkt_line (p_report_status ~sideband:`No_multiplexe ~unpack:(Some unpack) ~commands:None) decoder in p_pkt_line (go_unpack k) decoder | Some unpack -> let kcons command decoder = p_pkt_line ~strict:true (p_http_report_status ~unpack ~sideband ~commands:(command :: commands) ~references) decoder in let kfinal decoder = p_return {Common.unpack; commands} decoder in p_pkt_line (go_command kcons kfinal) decoder ) | Some '\002' -> ignore @@ p_while0 (fun _ -> true) decoder ; p_pkt_line (p_http_report_status ?unpack ~commands ~sideband ~references) decoder | Some '\003' -> ignore @@ p_while0 (fun _ -> true) decoder ; p_pkt_line (p_http_report_status ?unpack ~commands ~sideband ~references) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) | (`Line _ as pkt), _, None -> let k unpack decoder = p_pkt_line ~strict:true (p_http_report_status ~unpack ~sideband ~commands:[] ~references) decoder in go_unpack ~pkt k decoder | (`Line _ as pkt), _, Some unpack -> let kcons command decoder = p_pkt_line ~strict:true (p_http_report_status ~unpack ~sideband ~commands:(command :: commands) ~references) decoder in let kfinal decoder = p_return {Common.unpack; commands} decoder in go_command ~pkt kcons kfinal decoder let p_http_report_status references sideband decoder = p_pkt_line ~strict:true (p_http_report_status ~references ?unpack:None ~commands:[] ~sideband) decoder let p_first_want decoder = ignore @@ p_string "want" decoder ; p_space decoder ; let obj_id = p_hash decoder in p_space decoder ; let capabilities = p_capabilities1 decoder in obj_id, capabilities let p_want decoder = ignore @@ p_string "want" decoder ; p_space decoder ; let obj_id = p_hash decoder in obj_id type 'a intl = Int : int intl | Int64 : int64 intl let p_int, p_int64 = let go : type a. a intl -> decoder -> a = fun intl decoder -> let n = Cstruct.to_string @@ p_while1 (function '0' .. '9' -> true | _ -> false) decoder in match intl with Int -> int_of_string n | Int64 -> Int64.of_string n in go Int, go Int64 let p_deepen decoder = ignore @@ p_string "deepen" decoder ; match p_peek_char decoder with | Some ' ' -> p_junk_char decoder ; `Depth (p_int decoder) | Some '-' -> ( p_junk_char decoder ; match p_peek_char decoder with | Some 's' -> ignore @@ p_string "since" decoder ; p_space decoder ; `Timestamp (p_int64 decoder) | Some 'n' -> ignore @@ p_string "not" decoder ; p_space decoder ; `Ref (p_reference decoder) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) let p_upload_request decoder = let go_deepen ~pkt (upload_request : Common.upload_request) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return upload_request decoder | `Line _ -> ( match p_peek_char decoder with | Some 'd' -> let deepen = p_deepen decoder in p_pkt_flush (p_return {upload_request with Common.deep= Some deepen}) decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let rec go_shallows ~pkt (upload_request : Common.upload_request) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return upload_request decoder | `Line _ -> ( match p_peek_char decoder with | Some 's' -> let shallow = p_shallow decoder in p_pkt_line (go_shallows { upload_request with Common.shallow= shallow :: upload_request.shallow }) decoder | Some 'd' -> go_deepen ~pkt upload_request decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let rec go_wants ~pkt (upload_request : Common.upload_request) decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> p_return upload_request decoder | `Line _ -> ( match p_peek_char decoder with | Some 'w' -> let want = p_want decoder in p_pkt_line (go_wants { upload_request with Common.want= ( fst upload_request.Common.want , want :: snd upload_request.Common.want ) }) decoder | Some 's' -> go_shallows ~pkt upload_request decoder | Some 'd' -> go_deepen ~pkt upload_request decoder | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in let go_first_want ~pkt decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> let obj_id, capabilities = p_first_want decoder in p_pkt_line (go_wants {Common.want= obj_id, []; capabilities; shallow= []; deep= None}) decoder in p_pkt_line go_first_want decoder let p_request_command decoder = ignore @@ p_string "git-" decoder ; match p_peek_char decoder with | Some 'r' -> ignore @@ p_string "receive-pack" decoder ; `Receive_pack | Some 'u' -> ( ignore @@ p_string "upload-" decoder ; match p_peek_char decoder with | Some 'p' -> ignore @@ p_string "pack" decoder ; `Upload_pack | Some 'a' -> ignore @@ p_string "archive" decoder ; `Upload_archive | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) | None -> raise (Leave (err_unexpected_end_of_input decoder)) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) let p_host decoder = match p_peek_char decoder with | None -> None | Some _ -> ( ignore @@ p_string "host=" decoder ; let host = Cstruct.to_string @@ p_while1 (function ':' | '\x00' -> false | _ -> true) decoder in match p_peek_char decoder with | Some ':' -> p_junk_char decoder ; let port = int_of_string @@ Cstruct.to_string @@ p_while1 (function '0' .. '9' -> true | _ -> false) decoder in p_junk_char decoder ; Some (host, Some port) | Some '\x00' -> p_junk_char decoder ; Some (host, None) | Some chr -> raise (Leave (err_unexpected_char chr decoder)) | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) let p_git_proto_request decoder = let request_command = p_request_command decoder in p_space decoder ; let pathname = Cstruct.to_string @@ p_while1 (function '\x00' -> false | _ -> true) decoder in p_null decoder ; let host = p_host decoder in p_return {Common.request_command; pathname; host} decoder let p_git_proto_request decoder = p_pkt_line (fun ~pkt decoder -> match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> p_git_proto_request decoder ) decoder let p_command decoder = let hash0 = p_hash decoder in p_space decoder ; let hash1 = p_hash decoder in p_space decoder ; let reference = p_reference decoder in match Hash.equal zero_id hash0, Hash.equal zero_id hash1 with | true, false -> Common.Create (hash1, reference) | false, true -> Common.Delete (hash0, reference) | false, false -> Common.Update (hash0, hash1, reference) | true, true -> raise (Leave (err_unexpected_hashes hash0 hash1 decoder)) let p_first_command decoder = let command = p_command decoder in p_null decoder ; let capabilities = p_capabilities1 decoder in command, capabilities let p_update_request decoder = let rec p_commands (first, commands) ~pkt decoder = match pkt with | #no_line_and_flush as v -> err_expected_line_or_flush decoder v | `Flush -> let shallows, first, capabilities = first in p_return { Common.shallow= shallows ; requests= `Raw (first, commands) ; capabilities } decoder | `Line _ -> let command = p_command decoder in p_pkt_line (p_commands (first, command :: commands)) decoder in let p_first_command shallows decoder = let command, capabilities = p_first_command decoder in p_pkt_line (p_commands ((shallows, command, capabilities), [])) decoder in let rec p_shallows shallows ~pkt decoder = match pkt with | #no_line as v -> err_expected_line decoder v | `Line _ -> ( match p_peek_char decoder with | Some 's' -> let shallow = p_shallow decoder in p_pkt_line (p_shallows (shallow :: shallows)) decoder | Some _ -> p_first_command shallows decoder | None -> raise (Leave (err_unexpected_end_of_input decoder)) ) in p_pkt_line (p_shallows []) decoder (* XXX(dinosaure): désolé mais ce GADT, c'est quand même la classe. *) type _ transaction = | HttpReferenceDiscovery : string -> (Common.advertised_refs, [ `Msg of string ]) result transaction | ReferenceDiscovery : (Common.advertised_refs, [ `Msg of string ]) result transaction | ShallowUpdate : Common.shallow_update transaction | Negociation : Hash.Set.t * ack_mode -> Common.acks transaction | NegociationResult : Common.negociation_result transaction | PACK : side_band -> flow transaction | ReportStatus : string list * side_band -> Common.report_status transaction | HttpReportStatus : string list * side_band -> Common.report_status transaction | Upload_request : Common.upload_request transaction | Git_proto_request : Common.git_proto_request transaction | Update_request : Common.update_request transaction and ack_mode = [`Ack | `Multi_ack | `Multi_ack_detailed] and flow = [`Raw of Cstruct.t | `End | `Err of Cstruct.t | `Out of Cstruct.t] and side_band = [`Side_band | `Side_band_64k | `No_multiplexe] let decode : type result. decoder -> result transaction -> result state = fun decoder -> function | HttpReferenceDiscovery service -> p_safe (p_http_advertised_refs ~service) decoder | ReferenceDiscovery -> p_safe p_advertised_refs decoder | ShallowUpdate -> p_safe p_shallow_update decoder | Negociation (hashes, ackmode) -> p_safe (p_negociation ~mode:ackmode hashes) decoder | NegociationResult -> p_safe p_negociation_result decoder | PACK sideband -> p_safe (p_pack ~mode:sideband) decoder | ReportStatus (refs, sideband) -> p_safe (p_http_report_status refs sideband) decoder | HttpReportStatus (refs, sideband) -> p_safe (p_http_report_status refs sideband) decoder | Upload_request -> p_safe p_upload_request decoder | Git_proto_request -> p_safe p_git_proto_request decoder | Update_request -> p_safe p_update_request decoder let decoder () = {buffer= Cstruct.create 65535; pos= 0; max= 0; eop= None} let of_string : type v. string -> v transaction -> (v, error * Cstruct.t * int) result = fun s t -> let decoder = decoder () in let rec go consumed = function | Ok v -> (Ok v : (v, error * Cstruct.t * int) result) | Read {buffer; off; len; continue} -> if consumed = String.length s then ( Error (err_unexpected_end_of_input decoder) : (v, error * Cstruct.t * int) result ) else let len = min (String.length s - consumed) len in Cstruct.blit_from_string s consumed buffer off len ; go (consumed + len) @@ continue len | Error {err; buf; committed} -> (Error (err, buf, committed) : (v, error * Cstruct.t * int) result) in go 0 @@ decode decoder t end module Encoder (Hash : S.HASH) (Reference : Reference.S with module Hash := Hash) (Common : COMMON with type hash := Hash.t and type reference := Reference.t) = struct type encoder = {mutable payload: Cstruct.t; mutable pos: int} let set_pos encoder pos = encoder.pos <- pos let free {payload; pos} = Cstruct.sub payload pos (Cstruct.len payload - pos) type 'a state = | Write of { buffer: Cstruct.t ; off: int ; len: int ; continue: int -> 'a state } | Ok of 'a let flush k encoder = if encoder.pos > 0 then let rec k1 n = if n < encoder.pos then Write { buffer= encoder.payload ; off= n ; len= encoder.pos - n ; continue= (fun m -> k1 (n + m)) } else ( encoder.pos <- 4 ; k encoder ) in k1 0 else k encoder let writes s k encoder = let _len = Cstruct.len encoder.payload in let go j l encoder = let rem = _len - encoder.pos in let len = if l > rem then rem else l in Cstruct.blit_from_string s j encoder.payload encoder.pos len ; encoder.pos <- encoder.pos + len ; if len < l then raise (Invalid_argument "PKT Format: payload upper than 65520 bytes") else k encoder in go 0 (String.length s) encoder let w_lf k e = writes "\n" k e let noop k encoder = k encoder let pkt_line ?(lf = false) writes k encoder = let pkt_len encoder = let has = encoder.pos in let hdr = Fmt.strf "%04x" has in Cstruct.blit_from_string hdr 0 encoder.payload 0 4 ; flush k encoder in writes ((if lf then w_lf else noop) @@ pkt_len) encoder let pkt_flush k encoder = Cstruct.blit_from_string "0000" 0 encoder.payload 0 4 ; flush k encoder let zero_id = String.make Hash.digest_size '\000' |> Hash.of_raw_string let w_space k encoder = writes " " k encoder let w_null k encoder = writes "\000" k encoder let w_capabilities lst k encoder = let rec loop lst encoder = match lst with | [] -> k encoder | [x] -> writes (Capability.to_string x) k encoder | x :: r -> (writes (Capability.to_string x) @@ w_space @@ loop r) encoder in loop lst encoder let w_hash hash k encoder = writes (Hash.to_hex hash) k encoder let w_first_want obj_id capabilities k encoder = ( writes "want" @@ w_space @@ w_hash obj_id @@ w_space @@ w_capabilities capabilities k ) encoder let w_want obj_id k encoder = (writes "want" @@ w_space @@ w_hash obj_id k) encoder let w_shallow obj_id k encoder = (writes "shallow" @@ w_space @@ w_hash obj_id k) encoder let w_deepen depth k encoder = (writes "deepen" @@ w_space @@ writes (Fmt.strf "%d" depth) k) encoder let w_deepen_since timestamp k encoder = (writes "deepen-since" @@ w_space @@ writes (Fmt.strf "%Ld" timestamp) k) encoder let w_deepen_not reference k encoder = (writes "deepen-not" @@ w_space @@ writes (Reference.to_string reference) k) encoder let w_first_want ?lf obj_id capabilities k encoder = pkt_line ?lf (w_first_want obj_id capabilities) k encoder let w_want ?lf obj_id k encoder = pkt_line ?lf (w_want obj_id) k encoder let w_shallow ?lf obj_id k encoder = pkt_line ?lf (w_shallow obj_id) k encoder let w_deepen ?lf depth k encoder = pkt_line ?lf (w_deepen depth) k encoder let w_deepen_since ?lf timestamp k encoder = pkt_line ?lf (w_deepen_since timestamp) k encoder let w_deepen_not ?lf reference k encoder = pkt_line ?lf (w_deepen_not reference) k encoder let w_done_and_lf k encoder = pkt_line ~lf:true (writes "done") k encoder let w_list w l k encoder = let rec aux l encoder = match l with [] -> k encoder | x :: r -> w x (aux r) encoder in aux l encoder let w_upload_request ?lf (upload_request : Common.upload_request) k encoder = let first, rest = upload_request.want in ( w_first_want ?lf first upload_request.capabilities @@ w_list (w_want ?lf) rest @@ w_list (w_shallow ?lf) upload_request.shallow @@ ( match upload_request.deep with | Some (`Depth depth) -> w_deepen ?lf depth | Some (`Timestamp t) -> w_deepen_since ?lf t | Some (`Ref reference) -> w_deepen_not ?lf reference | None -> noop ) @@ pkt_flush k ) encoder let w_has hash k encoder = (writes "have" @@ w_space @@ w_hash hash k) encoder let w_has ?lf hash k encoder = pkt_line ?lf (w_has hash) k encoder let w_http_upload_request at_the_end http_upload_request k encoder = ( w_upload_request ~lf:true { Common.want= http_upload_request.Common.want ; capabilities= http_upload_request.Common.capabilities ; shallow= http_upload_request.Common.shallow ; deep= http_upload_request.Common.deep } @@ w_list (w_has ~lf:true) http_upload_request.has @@ if at_the_end = `Done then w_done_and_lf k else pkt_flush k ) encoder let w_flush k encoder = pkt_flush k encoder let w_request_command request_command k encoder = match request_command with | `Upload_pack -> writes "git-upload-pack" k encoder | `Receive_pack -> writes "git-receive-pack" k encoder | `Upload_archive -> writes "git-upload-archive" k encoder let w_git_proto_request git_proto_request k encoder = let w_host host k encoder = match host with | Some (host, Some port) -> ( writes "host=" @@ writes host @@ writes ":" @@ writes (Fmt.strf "%d" port) @@ w_null k ) encoder | Some (host, None) -> (writes "host=" @@ writes host @@ w_null k) encoder | None -> noop k encoder in ( w_request_command git_proto_request.Common.request_command @@ w_space @@ writes git_proto_request.pathname @@ w_null @@ w_host git_proto_request.host k ) encoder let w_done k encoder = pkt_line (writes "done") k encoder let w_has hashes k encoder = let rec go l encoder = match l with | [] -> w_flush k encoder | x :: r -> (w_has x @@ go r) encoder in go (Hash.Set.elements hashes) encoder let w_git_proto_request git_proto_request k encoder = pkt_line (w_git_proto_request git_proto_request) k encoder let w_shallows l k encoder = let rec go l encoder = match l with | [] -> k encoder | x :: r -> pkt_line (fun k -> writes "shallow" @@ w_space @@ w_hash x k) (go r) encoder in go l encoder let w_command command k encoder = match command with | Common.Create (hash, reference) -> ( w_hash zero_id @@ w_space @@ w_hash hash @@ w_space @@ writes (Reference.to_string reference) k ) encoder | Common.Delete (hash, reference) -> ( w_hash hash @@ w_space @@ w_hash zero_id @@ w_space @@ writes (Reference.to_string reference) k ) encoder | Common.Update (old_id, new_id, reference) -> ( w_hash old_id @@ w_space @@ w_hash new_id @@ w_space @@ writes (Reference.to_string reference) k ) encoder let w_first_command capabilities first k encoder = (w_command first @@ w_null @@ w_capabilities capabilities k) encoder let w_first_command capabilities first k encoder = pkt_line (w_first_command capabilities first) k encoder let w_command command k encoder = pkt_line (w_command command) k encoder let w_commands capabilities (first, rest) k encoder = (w_first_command capabilities first @@ w_list w_command rest @@ pkt_flush k) encoder let w_push_certificates capabilities push_cert k encoder = (* XXX(dinosaure): clean this code, TODO! *) ( (fun k e -> pkt_line ~lf:true (fun k -> writes "push-cert" @@ w_null @@ w_capabilities capabilities k ) k e ) @@ (fun k e -> pkt_line ~lf:true (writes "certificate version 0.1") k e) @@ (fun k e -> pkt_line ~lf:true (fun k -> writes "pusher" @@ w_space @@ writes push_cert.Common.pusher k ) k e ) @@ (fun k e -> pkt_line ~lf:true (fun k -> writes "pushee" @@ w_space @@ writes push_cert.Common.pushee k ) k e ) @@ (fun k e -> pkt_line ~lf:true (fun k -> writes "nonce" @@ w_space @@ writes push_cert.Common.nonce k ) k e ) @@ (fun k e -> w_list (fun x k e -> pkt_line ~lf:true (fun k -> writes "push-option" @@ w_space @@ writes x k) k e ) push_cert.Common.options k e ) @@ (fun k e -> pkt_line ~lf:true noop k e) @@ (fun k e -> w_list (fun x k e -> pkt_line ~lf:true (w_command x) k e) push_cert.Common.commands k e ) @@ (fun k e -> w_list (fun x k e -> pkt_line ~lf:true (writes x) k e) push_cert.Common.gpg k e ) @@ (fun k e -> pkt_line ~lf:true (writes "push-cert-end") k e) @@ pkt_flush @@ k ) encoder let w_update_request (update_request : Common.update_request) k encoder = ( w_shallows update_request.Common.shallow @@ ( match update_request.Common.requests with | `Raw commands -> w_commands update_request.Common.capabilities commands | `Cert push_cert -> w_push_certificates update_request.Common.capabilities push_cert ) @@ k ) encoder let flush_pack k encoder = if encoder.pos > 0 then let rec k1 n = if n < encoder.pos then Write { buffer= encoder.payload ; off= n ; len= encoder.pos - n ; continue= (fun m -> k1 (n + m)) } else ( encoder.pos <- 0 ; k encoder ) in k1 0 else k encoder let w_pack n k encoder = encoder.pos <- encoder.pos + n ; flush_pack k encoder let w_http_update_request i k encoder = w_update_request i k encoder let w_advertised_refs (advertised_refs : Common.advertised_refs) k encoder = let w_ref (hash, reference, peeled) k encoder = ( w_hash hash @@ w_space @@ writes (Reference.to_string reference) @@ match peeled with true -> writes "^{}" k | false -> k ) encoder in match advertised_refs.Common.refs with | [] -> pkt_line (fun k -> w_hash zero_id @@ w_space @@ writes "capabilities^{}" @@ w_null @@ w_capabilities advertised_refs.Common.capabilities k ) (w_shallows advertised_refs.Common.shallow (pkt_flush k)) encoder | first :: refs -> let rec go refs encoder = match refs with | [] -> w_shallows advertised_refs.Common.shallow (pkt_flush k) encoder | reference :: refs -> pkt_line (w_ref reference) (go refs) encoder in pkt_line (fun k -> w_ref first @@ w_null @@ w_capabilities advertised_refs.Common.capabilities k ) (go refs) encoder let w_shallow hash k encoder = pkt_line (fun k -> writes "shallow" @@ w_space @@ w_hash hash k) k encoder let w_unshallow hash k encoder = pkt_line (fun k -> writes "unshallow" @@ w_space @@ w_hash hash k) k encoder let w_shallow_update (shallow_update : Common.shallow_update) k encoder = let rec go (shallow_update : Common.shallow_update) encoder = match shallow_update.shallow with | hash :: shallow -> w_shallow hash (go {shallow_update with shallow}) encoder | [] -> ( match shallow_update.unshallow with | hash :: unshallow -> w_unshallow hash (go {shallow_update with unshallow}) encoder | [] -> pkt_flush k encoder ) in go shallow_update encoder let w_negociation_one value k encoder = match value with | `Ack (hash, `Continue) -> pkt_line (fun k -> writes "ACK" @@ w_space @@ w_hash hash @@ w_space @@ writes "continue" k ) k encoder | `Ack (hash, `Common) -> pkt_line (fun k -> writes "ACK" @@ w_space @@ w_hash hash @@ w_space @@ writes "common" k ) k encoder | `Ack (hash, `Ready) -> pkt_line (fun k -> writes "ACK" @@ w_space @@ w_hash hash @@ w_space @@ writes "ready" k ) k encoder | `Ack (hash, `ACK) -> pkt_line (fun k -> writes "ACK" @@ w_space @@ w_hash hash k) k encoder | `Nak -> pkt_line (writes "NAK") k encoder let w_negociation (acks : Common.acks) k encoder = let rec go_ack acks encoder = match acks with | [] -> w_negociation_one `Nak k encoder | ack :: acks -> w_negociation_one (`Ack ack) (go_ack acks) encoder in let rec go_unshallow unshallows encoder = match unshallows with | [] -> go_ack acks.acks encoder | hash :: rest -> w_unshallow hash (go_unshallow rest) encoder in let rec go_shallow shallows encoder = match shallows with | [] -> go_unshallow acks.unshallow encoder | hash :: rest -> w_shallow hash (go_shallow rest) encoder in go_shallow acks.shallow encoder let w_negociation_result result k encoder = match result with | Common.NAK -> pkt_line (writes "NAK") k encoder | Common.ACK hash -> pkt_line (fun k -> writes "ACK" @@ w_space @@ w_hash hash k) k encoder | Common.ERR err -> pkt_line (fun k -> writes "ERR" @@ w_space @@ writes err k) k encoder let w_report_status ~sideband report_status k encoder = let w_reference reference k encoder = writes (Reference.to_string reference) k encoder in let go_command (command : (Reference.t, Reference.t * string) result) k encoder = match command with | Ok reference -> (writes "ok" @@ w_space @@ w_reference reference k) encoder | Error (reference, err) -> ( writes "ng" @@ w_space @@ w_reference reference @@ w_space @@ writes err k ) encoder in let rec go_commands commands encoder = match sideband, commands with | _, [] -> pkt_flush k encoder | `No_multiplexe, command :: commands -> pkt_line (go_command command) (go_commands commands) encoder | (`Side_band | `Side_band_64k), command :: commands -> pkt_line (fun k -> writes "\001" @@ go_command command k) (go_commands commands) encoder in let go_unpack k encoder = match report_status.Common.unpack with | Ok () -> writes "unpack ok" k encoder | Error err -> (writes "unpack" @@ w_space @@ writes err k) encoder in match sideband with | `No_multiplexe -> pkt_line go_unpack (go_commands report_status.Common.commands) encoder | `Side_band | `Side_band_64k -> pkt_line (fun k -> writes "\001" @@ go_unpack k) (go_commands report_status.Common.commands) encoder type action = [ `GitProtoRequest of Common.git_proto_request | `UploadRequest of Common.upload_request | `HttpUploadRequest of [`Done | `Flush] * Common.http_upload_request | `Advertised_refs of Common.advertised_refs | `Shallow_update of Common.shallow_update | `Negociation of Common.acks | `Negociation_result of Common.negociation_result | `Report_status of [`No_multiplexe | `Side_band | `Side_band_64k] * Common.report_status | `UpdateRequest of Common.update_request | `HttpUpdateRequest of Common.update_request | `Has of Hash.Set.t | `Done | `Flush | `PACK of int | `Shallow of Hash.t list ] let encode encoder = function | `GitProtoRequest c -> w_git_proto_request c (fun _ -> Ok ()) encoder | `UploadRequest i -> w_upload_request i (fun _ -> Ok ()) encoder | `HttpUploadRequest (v, i) -> w_http_upload_request v i (fun _ -> Ok ()) encoder | `Advertised_refs v -> w_advertised_refs v (fun _ -> Ok ()) encoder | `Shallow_update v -> w_shallow_update v (fun _ -> Ok ()) encoder | `Negociation v -> w_negociation v (fun _ -> Ok ()) encoder | `Negociation_result v -> w_negociation_result v (fun _ -> Ok ()) encoder | `Report_status (s, v) -> w_report_status ~sideband:s v (fun _ -> Ok ()) encoder | `UpdateRequest i -> w_update_request i (fun _ -> Ok ()) encoder | `HttpUpdateRequest i -> w_http_update_request i (fun _ -> Ok ()) encoder | `Has l -> w_has l (fun _ -> Ok ()) encoder | `Done -> w_done (fun _ -> Ok ()) encoder | `Flush -> w_flush (fun _ -> Ok ()) encoder | `Shallow l -> w_shallows l (fun _ -> Ok ()) encoder | `PACK n -> w_pack n (fun _ -> Ok ()) encoder let encoder () = {payload= Cstruct.create 65535; pos= 4} let to_string v = let encoder = encoder () in let result = Buffer.create 16 in let rec go = function | Write {buffer; off; len; continue} -> Buffer.add_string result (Cstruct.to_string (Cstruct.sub buffer off len)) ; go @@ continue len | Ok () -> Buffer.contents result in go @@ encode encoder v end module Client (Hash : S.HASH) (Reference : Reference.S with module Hash := Hash) = struct module Common = Common (Hash) (Reference) module Decoder = Decoder (Hash) (Reference) (Common) module Encoder = Encoder (Hash) (Reference) (Common) type context = { decoder: Decoder.decoder ; encoder: Encoder.encoder ; mutable capabilities: Capability.t list } let capabilities {capabilities; _} = capabilities let set_capabilities context capabilities = context.capabilities <- capabilities let encode x k ctx = let rec loop = function | Encoder.Write {buffer; off; len; continue} -> `Write (buffer, off, len, fun n -> loop (continue n)) | Encoder.Ok () -> k ctx in loop (Encoder.encode ctx.encoder x) let decode phase k ctx = let rec loop = function | Decoder.Ok v -> k v ctx | Decoder.Read {buffer; off; len; continue} -> `Read (buffer, off, len, fun n -> loop (continue n)) | Decoder.Error {err; buf; committed} -> `Error (err, buf, committed) in loop (Decoder.decode ctx.decoder phase) type result = [ `Refs of Common.advertised_refs | `ShallowUpdate of Common.shallow_update | `Negociation of Common.acks | `NegociationResult of Common.negociation_result | `PACK of Decoder.flow | `Flush | `Nothing | `ReadyPACK of Cstruct.t | `ReportStatus of Common.report_status | `SmartError of string ] type process = [ `Read of Cstruct.t * int * int * (int -> process) | `Write of Cstruct.t * int * int * (int -> process) | `Error of Decoder.error * Cstruct.t * int | result ] let pp_result ppf = function | `Refs refs -> Fmt.pf ppf "(`Refs %a)" (Fmt.hvbox Common.pp_advertised_refs) refs | `ShallowUpdate shallow_update -> Fmt.pf ppf "(`ShallowUpdate %a)" (Fmt.hvbox Common.pp_shallow_update) shallow_update | `Negociation acks -> Fmt.pf ppf "(`Negociation %a)" (Fmt.hvbox Common.pp_acks) acks | `NegociationResult result -> Fmt.pf ppf "(`NegociationResult %a)" (Fmt.hvbox Common.pp_negociation_result) result | `PACK (`Err _) -> Fmt.pf ppf "(`Pack stderr)" | `PACK (`Out _) -> Fmt.pf ppf "(`Pack stdout)" | `PACK (`Raw _) -> Fmt.pf ppf "(`Pack pack)" | `PACK `End -> Fmt.pf ppf "(`Pack `End)" | `Flush -> Fmt.pf ppf "`Flush" | `Nothing -> Fmt.pf ppf "`Nothing" | `ReadyPACK _ -> Fmt.pf ppf "(`ReadyPACK #raw)" | `ReportStatus status -> Fmt.pf ppf "(`ReportStatus %a)" (Fmt.hvbox Common.pp_report_status) status | `SmartError err -> Fmt.pf ppf "(`SmartError %S)" err type action = [ `GitProtoRequest of Common.git_proto_request | `Shallow of Hash.t list | `UploadRequest of Common.upload_request | `UpdateRequest of Common.update_request | `Has of Hash.Set.t | `Done | `Flush | `ReceivePACK | `SendPACK of int | `FinishPACK of Reference.Set.t ] let run context = function | `GitProtoRequest c -> encode (`GitProtoRequest c) (decode Decoder.ReferenceDiscovery (fun refs ctx -> match refs with | Ok refs -> ctx.capabilities <- refs.Common.capabilities ; `Refs refs | Error (`Msg err) -> `SmartError err)) context | `Flush -> encode `Flush (fun _ -> `Flush) context | `UploadRequest (descr : Common.upload_request) -> let common = List.filter (fun x -> List.exists (( = ) x) context.capabilities) descr.Common.capabilities in (* XXX(dinosaure): we update with the shared capabilities between the client and the server. *) context.capabilities <- common ; let next = match descr.Common.deep with | Some (`Depth n) -> if n > 0 then decode Decoder.ShallowUpdate (fun shallow_update _ -> `ShallowUpdate shallow_update ) else fun _ -> `ShallowUpdate ({shallow= []; unshallow= []} : Common.shallow_update) | _ -> fun _ -> `ShallowUpdate ({shallow= []; unshallow= []} : Common.shallow_update) in encode (`UploadRequest descr) next context | `UpdateRequest (descr : Common.update_request) -> let common = List.filter (fun x -> List.exists (( = ) x) context.capabilities) descr.Common.capabilities in (* XXX(dinosaure): same as below. *) context.capabilities <- common ; encode (`UpdateRequest descr) (fun {encoder; _} -> Encoder.set_pos encoder 0 ; let raw = Encoder.free encoder in `ReadyPACK raw ) context | `Has has -> let ackmode = if List.exists (( = ) `Multi_ack_detailed) context.capabilities then `Multi_ack_detailed else if List.exists (( = ) `Multi_ack) context.capabilities then `Multi_ack else `Ack in encode (`Has has) (decode (Decoder.Negociation (has, ackmode)) (fun status _ -> `Negociation status)) context | `Done -> encode `Done (decode Decoder.NegociationResult (fun result _ -> `NegociationResult result )) context | `ReceivePACK -> let sideband = if List.exists (( = ) `Side_band_64k) context.capabilities then `Side_band_64k else if List.exists (( = ) `Side_band) context.capabilities then `Side_band else `No_multiplexe in (decode (Decoder.PACK sideband) (fun flow _ -> `PACK flow)) context | `SendPACK w -> encode (`PACK w) (fun {encoder; _} -> Encoder.set_pos encoder 0 ; let raw = Encoder.free encoder in `ReadyPACK raw ) context | `FinishPACK refs -> let sideband = if List.exists (( = ) `Side_band_64k) context.capabilities then `Side_band_64k else if List.exists (( = ) `Side_band) context.capabilities then `Side_band else `No_multiplexe in if List.exists (( = ) `Report_status) context.capabilities then decode (Decoder.ReportStatus (List.map Reference.to_string (Reference.Set.elements refs), sideband)) (fun result _ -> `ReportStatus result) context else `Nothing (* XXX(dinosaure): the specification does not explain what the server send when we don't have the capability [report-status]. *) | `Shallow l -> encode (`Shallow l) (fun _ -> `Nothing) context let context c = let context = { decoder= Decoder.decoder () ; encoder= Encoder.encoder () ; capabilities= [] } in ( context , encode (`GitProtoRequest c) (decode Decoder.ReferenceDiscovery (fun refs ctx -> match refs with | Ok refs -> ctx.capabilities <- refs.Common.capabilities ; `Refs refs | Error (`Msg err) -> `SmartError err)) context ) end
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * and Romain Calascibetta <romain.calascibetta@gmail.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. *)
mirage_protocols.ml
module Ethernet = struct type error = [ `Exceeds_mtu ] let pp_error ppf = function | `Exceeds_mtu -> Fmt.string ppf "exceeds MTU" type proto = [ `ARP | `IPv4 | `IPv6 ] let pp_proto ppf = function | `ARP -> Fmt.string ppf "ARP" | `IPv4 -> Fmt.string ppf "IPv4" | `IPv6 -> Fmt.string ppf "IPv6" end module Ip = struct type error = [ | `No_route of string (** can't send a message to that destination *) | `Would_fragment ] let pp_error ppf = function | `No_route s -> Fmt.pf ppf "no route to destination: %s" s | `Would_fragment -> Fmt.string ppf "would fragment" type proto = [ `TCP | `UDP | `ICMP ] let pp_proto ppf = function | `TCP -> Fmt.string ppf "TCP" | `UDP -> Fmt.string ppf "UDP" | `ICMP -> Fmt.string ppf "ICMP" end module Arp = struct type error = [ | `Timeout (** Failed to establish a mapping between an IP and a link-level address *) ] let pp_error ppf = function | `Timeout -> Fmt.pf ppf "could not determine a link-level address for the IP address given" end module Tcp = struct type error = [ `Timeout | `Refused] type write_error = [ error | Mirage_flow.write_error] let pp_error ppf = function | `Timeout -> Fmt.string ppf "connection attempt timed out" | `Refused -> Fmt.string ppf "connection attempt was refused" let pp_write_error ppf = function | #Mirage_flow.write_error as e -> Mirage_flow.pp_write_error ppf e | #error as e -> pp_error ppf e end module type ETHERNET = sig type error = private [> Ethernet.error] val pp_error: error Fmt.t type buffer type macaddr include Mirage_device.S val write: t -> ?src:macaddr -> macaddr -> Ethernet.proto -> ?size:int -> (buffer -> int) -> (unit, error) result io val mac: t -> macaddr val mtu: t -> int val input: arpv4:(buffer -> unit io) -> ipv4:(buffer -> unit io) -> ipv6:(buffer -> unit io) -> t -> buffer -> unit io end module type IP = sig type error = private [> Ip.error] val pp_error: error Fmt.t type buffer type ipaddr val pp_ipaddr : ipaddr Fmt.t include Mirage_device.S type callback = src:ipaddr -> dst:ipaddr -> buffer -> unit io val input: t -> tcp:callback -> udp:callback -> default:(proto:int -> callback) -> buffer -> unit io val write: t -> ?fragment:bool -> ?ttl:int -> ?src:ipaddr -> ipaddr -> Ip.proto -> ?size:int -> (buffer -> int) -> buffer list -> (unit, error) result io val pseudoheader : t -> ?src:ipaddr -> ipaddr -> Ip.proto -> int -> buffer val src: t -> dst:ipaddr -> ipaddr val get_ip: t -> ipaddr list val mtu: t -> int end module type ARP = sig include Mirage_device.S type ipaddr type buffer type macaddr type repr type error = private [> Arp.error] val pp_error: error Fmt.t val to_repr : t -> repr io val pp : repr Fmt.t val get_ips : t -> ipaddr list val set_ips : t -> ipaddr list -> unit io val remove_ip : t -> ipaddr -> unit io val add_ip : t -> ipaddr -> unit io val query : t -> ipaddr -> (macaddr, error) result io val input : t -> buffer -> unit io end module type IPV4 = IP module type IPV6 = IP module type ICMP = sig include Mirage_device.S type ipaddr type buffer type error val pp_error: error Fmt.t val input : t -> src:ipaddr -> dst:ipaddr -> buffer -> unit io val write : t -> dst:ipaddr -> ?ttl:int -> buffer -> (unit, error) result io end module type ICMPV4 = ICMP module type UDP = sig type error val pp_error: error Fmt.t type buffer type ipaddr type ipinput include Mirage_device.S type callback = src:ipaddr -> dst:ipaddr -> src_port:int -> buffer -> unit io val input: listeners:(dst_port:int -> callback option) -> t -> ipinput val write: ?src_port:int -> ?ttl:int -> dst:ipaddr -> dst_port:int -> t -> buffer -> (unit, error) result io end module Keepalive = struct type t = { after: Duration.t; interval: Duration.t; probes: int; } end module type TCP = sig type error = private [> Tcp.error] type write_error = private [> Tcp.write_error] type buffer type ipaddr type ipinput type flow include Mirage_device.S include Mirage_flow.S with type 'a io := 'a io and type buffer := buffer and type flow := flow and type error := error and type write_error := write_error val dst: flow -> ipaddr * int val write_nodelay: flow -> buffer -> (unit, write_error) result io val writev_nodelay: flow -> buffer list -> (unit, write_error) result io val create_connection: ?keepalive:Keepalive.t -> t -> ipaddr * int -> (flow, error) result io type listener = { process: flow -> unit io; keepalive: Keepalive.t option; } val input: t -> listeners:(int -> listener option) -> ipinput end
pool.ml
open Stdune open Core open Core.O type mvar = | Done | Task of (unit -> unit t) type status = | Open | Closed type t = { mvar : mvar Mvar.t ; mutable status : status } let running t k = match t.status with | Open -> k true | Closed -> k false let create () = { mvar = Mvar.create (); status = Open } let task t ~f k = match t.status with | Closed -> Code_error.raise "pool is closed. new tasks may not be submitted" [] | Open -> Mvar.write t.mvar (Task f) k let stream t = Stream.In.create (fun () -> let+ next = Mvar.read t.mvar in match next with | Done -> None | Task task -> Some task) let stop t k = match t.status with | Closed -> k () | Open -> t.status <- Closed; Mvar.write t.mvar Done k let run t = stream t |> Stream.In.parallel_iter ~f:(fun task -> task ())
compress_z.ml
#13 "src/session/compress_z.ml" let compression_supported = true module type S = sig type out_channel val open_out: string -> out_channel val output_char: out_channel -> char -> unit val output_substring: out_channel -> string -> int -> int -> unit val output_string: out_channel -> string -> unit val close_out: out_channel -> unit type in_channel val open_in: string -> in_channel val input: in_channel -> bytes -> int -> int -> int val really_input: in_channel -> bytes -> int -> int -> unit val input_char: in_channel -> char val close_in: in_channel -> unit end module Compress_none = Stdlib module Compress_z = struct type out_channel = Gzip.out_channel let open_out fn = Gzip.open_out ~level:6 fn let output_char = Gzip.output_char let output_substring = Gzip.output_substring let output_string ch s = output_substring ch s 0 (String.length s) let close_out = Gzip.close_out type in_channel = Gzip.in_channel let open_in = Gzip.open_in let input = Gzip.input let really_input = Gzip.really_input let input_char = Gzip.input_char let close_in = Gzip.close_in end
(********************************************************************) (* *) (* The Why3 Verification Platform / The Why3 Development Team *) (* Copyright 2010-2023 -- Inria - CNRS - Paris-Saclay University *) (* *) (* This software is distributed under the terms of the GNU Lesser *) (* General Public License version 2.1, with the special exception *) (* on linking described in file LICENSE. *) (* *) (********************************************************************)
cast8.c
#include "testharness.h" /* A very surprising bug that has surfaced after 3 years */ int main() { int base = 5; unsigned long max_over_base = (unsigned long) -1 / base; unsigned long correct = ((unsigned long) -1) / base; printf("Result is %ld. Correct=%ld\n", max_over_base, correct); if(max_over_base != correct) E(1); SUCCESS; }
persistent.ml
open Stdune module type Desc = sig type t val name : string val version : int val to_dyn : t -> Dyn.t end type data = .. module type Desc_with_data = sig include Desc type data += T of t end let registry = String.Table.create 16 let max_magic_length = 128 let register (module D : Desc_with_data) = match String.Table.add registry D.name (module D : Desc_with_data) with | Ok () -> () | Error _ -> Code_error.raise "Persistent file kind registered for the second time" [ ("name", String D.name) ] module Make (D : Desc) = struct let magic = sprintf "DUNE-%sv%d:" D.name D.version let () = if String.length magic > max_magic_length then Code_error.raise "Persistent.Make: magic string too long" [ ("magic", String magic); ("max_magic_length", Int max_magic_length) ] type data += T of D.t let () = register (module struct include D type data += T = T end : Desc_with_data) let to_string (v : D.t) = Printf.sprintf "%s%s" magic (Marshal.to_string v []) let dump file (v : D.t) = Io.with_file_out file ~f:(fun oc -> output_string oc magic; Marshal.to_channel oc v []) let load file = if Path.exists file then Io.with_file_in file ~f:(fun ic -> match really_input_string ic (String.length magic) with | exception End_of_file -> None | s -> if s = magic then match (Marshal.from_channel ic : D.t) with | exception Failure f -> Log.info_user_message (User_message.make [ Pp.tag User_message.Style.Warning (Pp.textf "Failed to load corrupted file %s: %s" (Path.to_string file) f) ]); None | d -> Some d else None) else None end type t = T : (module Desc with type t = 'a) * 'a -> t let load_exn path = Io.with_file_in path ~f:(fun ic -> let buf = Buffer.create max_magic_length in let rec read_magic n = if n = max_magic_length then None else match Stdlib.input_char ic with | exception End_of_file -> None | ':' -> Some (Buffer.contents buf) | c -> Buffer.add_char buf c; read_magic (n + 1) in let magic = let open Option.O in let* s = read_magic 0 in let* s = String.drop_prefix s ~prefix:"DUNE-" in let* name, version = String.rsplit2 s ~on:'v' in let* version = Int.of_string version in Some (name, version) in match magic with | None -> User_error.raise ~loc:(Loc.in_file path) [ Pp.text "This file is not a persistent dune file." ] | Some (name, version) -> ( match String.Table.find registry name with | None -> User_error.raise ~loc:(Loc.in_file path) [ Pp.textf "Unknown type of persistent dune file: %s." (String.escaped name) ] | Some (module D : Desc_with_data) -> if D.version <> version then User_error.raise ~loc:(Loc.in_file path) [ Pp.textf "Unsupported version of dune '%s' file: %d." (String.escaped name) version ; Pp.textf "I only know how to read version %d." D.version ]; let data : D.t = Marshal.from_channel ic in T ((module D), data)))